diff --git a/python/user_packages/Python313/site-packages/chromadb-1.5.9.dist-info/licenses/LICENSE b/python/user_packages/Python313/site-packages/chromadb-1.5.9.dist-info/licenses/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..29f81d812f3e768fa89638d1f72920dbfd1413a8 --- /dev/null +++ b/python/user_packages/Python313/site-packages/chromadb-1.5.9.dist-info/licenses/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + 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/python/user_packages/Python313/site-packages/chromadb-1.5.9.dist-info/sboms/chromadb_rust_bindings.cyclonedx.json b/python/user_packages/Python313/site-packages/chromadb-1.5.9.dist-info/sboms/chromadb_rust_bindings.cyclonedx.json new file mode 100644 index 0000000000000000000000000000000000000000..c445dc33eb3e63faf054749e1908e79ff848c0ea --- /dev/null +++ b/python/user_packages/Python313/site-packages/chromadb-1.5.9.dist-info/sboms/chromadb_rust_bindings.cyclonedx.json @@ -0,0 +1,29364 @@ +{ + "bomFormat": "CycloneDX", + "specVersion": "1.5", + "version": 1, + "serialNumber": "urn:uuid:04646707-c84f-4aa4-a6f0-dab3942a0de7", + "metadata": { + "timestamp": "2026-05-05T05:38:29.561386800Z", + "tools": [ + { + "vendor": "CycloneDX", + "name": "cargo-cyclonedx", + "version": "0.5.9" + } + ], + "component": { + "type": "library", + "bom-ref": "path+file:///C:/a/chroma/chroma/rust/python_bindings#chromadb_rust_bindings@0.1.0", + "name": "chromadb_rust_bindings", + "version": "0.1.0", + "scope": "required", + "purl": "pkg:cargo/chromadb_rust_bindings@0.1.0?download_url=file://.", + "components": [ + { + "type": "library", + "bom-ref": "path+file:///C:/a/chroma/chroma/rust/python_bindings#chromadb_rust_bindings@0.1.0 bin-target-0", + "name": "chromadb_rust_bindings", + "version": "0.1.0", + "purl": "pkg:cargo/chromadb_rust_bindings@0.1.0?download_url=file://.#src/lib.rs" + } + ] + }, + "properties": [ + { + "name": "cdx:rustc:sbom:target:all_targets", + "value": "true" + } + ] + }, + "components": [ + { + "type": "library", + "bom-ref": "git+https://github.com/chroma-core/hnswlib.git?branch=master#hnswlib@0.8.2", + "name": "hnswlib", + "version": "0.8.2", + "scope": "required", + "purl": "pkg:cargo/hnswlib@0.8.2?vcs_url=git%2Bhttps://github.com/chroma-core/hnswlib.git%406868102bde454dc761136e1994490133a6a026bb" + }, + { + "type": "library", + "bom-ref": "path+file:///C:/a/chroma/chroma/rust/api-types#chroma-api-types@0.14.0", + "name": "chroma-api-types", + "version": "0.14.0", + "description": "Chroma-provided crate for api-types used in the Chroma API.", + "scope": "required", + "licenses": [ + { + "expression": "Apache-2.0" + } + ], + "purl": "pkg:cargo/chroma-api-types@0.14.0?download_url=file://..\\api-types", + "externalReferences": [ + { + "type": "vcs", + "url": "https://github.com/chroma-core/chroma" + } + ] + }, + { + "type": "library", + "bom-ref": "path+file:///C:/a/chroma/chroma/rust/blockstore#chroma-blockstore@0.1.0", + "name": "chroma-blockstore", + "version": "0.1.0", + "scope": "required", + "purl": "pkg:cargo/chroma-blockstore@0.1.0?download_url=file://..\\blockstore" + }, + { + "type": "library", + "bom-ref": "path+file:///C:/a/chroma/chroma/rust/cache#chroma-cache@0.1.0", + "name": "chroma-cache", + "version": "0.1.0", + "scope": "required", + "purl": "pkg:cargo/chroma-cache@0.1.0?download_url=file://..\\cache" + }, + { + "type": "library", + "bom-ref": "path+file:///C:/a/chroma/chroma/rust/chroma#0.14.0", + "name": "chroma", + "version": "0.14.0", + "description": "Client for Chroma, the AI-native cloud database.", + "scope": "required", + "licenses": [ + { + "expression": "Apache-2.0" + } + ], + "purl": "pkg:cargo/chroma@0.14.0?download_url=file://..\\chroma" + }, + { + "type": "library", + "bom-ref": "path+file:///C:/a/chroma/chroma/rust/cli#chroma-cli@1.4.4", + "name": "chroma-cli", + "version": "1.4.4", + "scope": "required", + "purl": "pkg:cargo/chroma-cli@1.4.4?download_url=file://..\\cli" + }, + { + "type": "library", + "bom-ref": "path+file:///C:/a/chroma/chroma/rust/config#chroma-config@0.1.0", + "name": "chroma-config", + "version": "0.1.0", + "scope": "required", + "purl": "pkg:cargo/chroma-config@0.1.0?download_url=file://..\\config" + }, + { + "type": "library", + "bom-ref": "path+file:///C:/a/chroma/chroma/rust/distance#chroma-distance@0.1.0", + "name": "chroma-distance", + "version": "0.1.0", + "scope": "required", + "purl": "pkg:cargo/chroma-distance@0.1.0?download_url=file://..\\distance" + }, + { + "type": "library", + "bom-ref": "path+file:///C:/a/chroma/chroma/rust/error#chroma-error@0.14.0", + "name": "chroma-error", + "version": "0.14.0", + "description": "Chroma-provided crate for errors returned from Chroma.", + "scope": "required", + "licenses": [ + { + "expression": "Apache-2.0" + } + ], + "purl": "pkg:cargo/chroma-error@0.14.0?download_url=file://..\\error", + "externalReferences": [ + { + "type": "vcs", + "url": "https://github.com/chroma-core/chroma" + } + ] + }, + { + "type": "library", + "bom-ref": "path+file:///C:/a/chroma/chroma/rust/frontend#chroma-frontend@1.0.0", + "name": "chroma-frontend", + "version": "1.0.0", + "scope": "required", + "purl": "pkg:cargo/chroma-frontend@1.0.0?download_url=file://..\\frontend" + }, + { + "type": "library", + "bom-ref": "path+file:///C:/a/chroma/chroma/rust/index#chroma-index@0.1.0", + "name": "chroma-index", + "version": "0.1.0", + "scope": "required", + "purl": "pkg:cargo/chroma-index@0.1.0?download_url=file://..\\index" + }, + { + "type": "library", + "bom-ref": "path+file:///C:/a/chroma/chroma/rust/log#chroma-log@0.1.0", + "name": "chroma-log", + "version": "0.1.0", + "scope": "required", + "purl": "pkg:cargo/chroma-log@0.1.0?download_url=file://..\\log" + }, + { + "type": "library", + "bom-ref": "path+file:///C:/a/chroma/chroma/rust/mdac#0.1.0", + "name": "mdac", + "version": "0.1.0", + "description": "Multi-dimensional admission control for the Chroma AI retrieval system (0.1.0 is a placeholder).", + "scope": "required", + "licenses": [ + { + "expression": "Apache-2.0" + } + ], + "purl": "pkg:cargo/mdac@0.1.0?download_url=file://..\\mdac" + }, + { + "type": "library", + "bom-ref": "path+file:///C:/a/chroma/chroma/rust/memberlist#chroma-memberlist@0.1.0", + "name": "chroma-memberlist", + "version": "0.1.0", + "scope": "required", + "purl": "pkg:cargo/chroma-memberlist@0.1.0?download_url=file://..\\memberlist" + }, + { + "type": "library", + "bom-ref": "path+file:///C:/a/chroma/chroma/rust/metering#chroma-metering@0.1.0", + "name": "chroma-metering", + "version": "0.1.0", + "scope": "required", + "purl": "pkg:cargo/chroma-metering@0.1.0?download_url=file://..\\metering" + }, + { + "type": "library", + "bom-ref": "path+file:///C:/a/chroma/chroma/rust/metering-macros#chroma-metering-macros@0.1.0", + "name": "chroma-metering-macros", + "version": "0.1.0", + "scope": "required", + "purl": "pkg:cargo/chroma-metering-macros@0.1.0?download_url=file://..\\metering-macros" + }, + { + "type": "library", + "bom-ref": "path+file:///C:/a/chroma/chroma/rust/segment#chroma-segment@0.1.0", + "name": "chroma-segment", + "version": "0.1.0", + "scope": "required", + "purl": "pkg:cargo/chroma-segment@0.1.0?download_url=file://..\\segment" + }, + { + "type": "library", + "bom-ref": "path+file:///C:/a/chroma/chroma/rust/sqlite#chroma-sqlite@0.1.0", + "name": "chroma-sqlite", + "version": "0.1.0", + "scope": "required", + "purl": "pkg:cargo/chroma-sqlite@0.1.0?download_url=file://..\\sqlite" + }, + { + "type": "library", + "bom-ref": "path+file:///C:/a/chroma/chroma/rust/storage#chroma-storage@0.1.0", + "name": "chroma-storage", + "version": "0.1.0", + "scope": "required", + "purl": "pkg:cargo/chroma-storage@0.1.0?download_url=file://..\\storage" + }, + { + "type": "library", + "bom-ref": "path+file:///C:/a/chroma/chroma/rust/sysdb#chroma-sysdb@0.1.0", + "name": "chroma-sysdb", + "version": "0.1.0", + "scope": "required", + "purl": "pkg:cargo/chroma-sysdb@0.1.0?download_url=file://..\\sysdb" + }, + { + "type": "library", + "bom-ref": "path+file:///C:/a/chroma/chroma/rust/system#chroma-system@0.1.0", + "name": "chroma-system", + "version": "0.1.0", + "scope": "required", + "purl": "pkg:cargo/chroma-system@0.1.0?download_url=file://..\\system" + }, + { + "type": "library", + "bom-ref": "path+file:///C:/a/chroma/chroma/rust/tracing#chroma-tracing@0.1.0", + "name": "chroma-tracing", + "version": "0.1.0", + "scope": "required", + "purl": "pkg:cargo/chroma-tracing@0.1.0?download_url=file://..\\tracing" + }, + { + "type": "library", + "bom-ref": "path+file:///C:/a/chroma/chroma/rust/types#chroma-types@0.14.0", + "name": "chroma-types", + "version": "0.14.0", + "description": "Chroma-provided crate for internal types used in the Chroma API.", + "scope": "required", + "licenses": [ + { + "expression": "Apache-2.0" + } + ], + "purl": "pkg:cargo/chroma-types@0.14.0?download_url=file://..\\types", + "externalReferences": [ + { + "type": "vcs", + "url": "https://github.com/chroma-core/chroma" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#adler2@2.0.1", + "author": "Jonas Schievink , oyvindln ", + "name": "adler2", + "version": "2.0.1", + "description": "A simple clean-room implementation of the Adler-32 checksum", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa" + } + ], + "licenses": [ + { + "expression": "0BSD OR MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/adler2@2.0.1", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/adler2/" + }, + { + "type": "vcs", + "url": "https://github.com/oyvindln/adler2" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#aes@0.8.4", + "author": "RustCrypto Developers", + "name": "aes", + "version": "0.8.4", + "description": "Pure Rust implementation of the Advanced Encryption Standard (a.k.a. Rijndael)", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "b169f7a6d4742236a0a00c541b845991d0ac43e546831af1249753ab4c3aa3a0" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/aes@0.8.4", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/aes" + }, + { + "type": "vcs", + "url": "https://github.com/RustCrypto/block-ciphers" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#ahash@0.8.12", + "author": "Tom Kaitchuck ", + "name": "ahash", + "version": "0.8.12", + "description": "A non-cryptographic hash function using AES-NI for high performance", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "5a15f179cd60c4584b8a8c596927aadc462e27f2ca70c04e0071964a73ba7a75" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/ahash@0.8.12", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/ahash" + }, + { + "type": "vcs", + "url": "https://github.com/tkaitchuck/ahash" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#aho-corasick@1.1.4", + "author": "Andrew Gallant ", + "name": "aho-corasick", + "version": "1.1.4", + "description": "Fast multiple substring searching.", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "ddd31a130427c27518df266943a5308ed92d4b226cc639f5a8f1002816174301" + } + ], + "licenses": [ + { + "expression": "Unlicense OR MIT" + } + ], + "purl": "pkg:cargo/aho-corasick@1.1.4", + "externalReferences": [ + { + "type": "website", + "url": "https://github.com/BurntSushi/aho-corasick" + }, + { + "type": "vcs", + "url": "https://github.com/BurntSushi/aho-corasick" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#alga@0.9.3", + "author": "Brendan Zabarauskas, Darin Morrison, Sébastien Crozet, Wadelma ", + "name": "alga", + "version": "0.9.3", + "description": "Abstract algebra for Rust", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "4f823d037a7ec6ea2197046bafd4ae150e6bc36f9ca347404f46a46823fa84f2" + } + ], + "licenses": [ + { + "expression": "Apache-2.0" + } + ], + "purl": "pkg:cargo/alga@0.9.3", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/alga" + }, + { + "type": "vcs", + "url": "https://github.com/rustsim/alga" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#alloc-no-stdlib@2.0.4", + "author": "Daniel Reiter Horn ", + "name": "alloc-no-stdlib", + "version": "2.0.4", + "description": "A dynamic allocator that may be used with or without the stdlib. This allows a package with nostd to allocate memory dynamically and be used either with a custom allocator, items on the stack, or by a package that wishes to simply use Box<>. It also provides options to use calloc or a mutable global variable for pre-zeroed memory", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "cc7bb162ec39d46ab1ca8c77bf72e890535becd1751bb45f64c597edb4c8c6b3" + } + ], + "licenses": [ + { + "expression": "BSD-3-Clause" + } + ], + "purl": "pkg:cargo/alloc-no-stdlib@2.0.4", + "externalReferences": [ + { + "type": "documentation", + "url": "https://raw.githubusercontent.com/dropbox/rust-alloc-no-stdlib/master/tests/lib.rs" + }, + { + "type": "website", + "url": "https://github.com/dropbox/rust-alloc-no-stdlib" + }, + { + "type": "vcs", + "url": "https://github.com/dropbox/rust-alloc-no-stdlib" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#alloc-stdlib@0.2.2", + "author": "Daniel Reiter Horn ", + "name": "alloc-stdlib", + "version": "0.2.2", + "description": "A dynamic allocator example that may be used with the stdlib", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "94fb8275041c72129eb51b7d0322c29b8387a0386127718b096429201a5d6ece" + } + ], + "licenses": [ + { + "expression": "BSD-3-Clause" + } + ], + "purl": "pkg:cargo/alloc-stdlib@0.2.2", + "externalReferences": [ + { + "type": "documentation", + "url": "https://raw.githubusercontent.com/dropbox/rust-alloc-no-stdlib/master/alloc-stdlib/tests/lib.rs" + }, + { + "type": "website", + "url": "https://github.com/dropbox/rust-alloc-no-stdlib" + }, + { + "type": "vcs", + "url": "https://github.com/dropbox/rust-alloc-no-stdlib" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#allocator-api2@0.2.21", + "author": "Zakarum ", + "name": "allocator-api2", + "version": "0.2.21", + "description": "Mirror of Rust's allocator API", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "683d7910e743518b0e34f1186f92494becacb047c7b6bf616c96772180fef923" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/allocator-api2@0.2.21", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/allocator-api2" + }, + { + "type": "website", + "url": "https://github.com/zakarumych/allocator-api2" + }, + { + "type": "vcs", + "url": "https://github.com/zakarumych/allocator-api2" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#anes@0.1.6", + "author": "Robert Vojta ", + "name": "anes", + "version": "0.1.6", + "description": "ANSI Escape Sequences provider & parser", + "scope": "excluded", + "hashes": [ + { + "alg": "SHA-256", + "content": "4b46cbb362ab8752921c97e041f5e366ee6297bd428a31275b9fcf1e380f7299" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/anes@0.1.6", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/anes/" + }, + { + "type": "vcs", + "url": "https://github.com/zrzka/anes-rs" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#anstream@1.0.0", + "name": "anstream", + "version": "1.0.0", + "description": "IO stream adapters for writing colored text that will gracefully degrade according to your terminal's capabilities.", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "824a212faf96e9acacdbd09febd34438f8f711fb84e09a8916013cd7815ca28d" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/anstream@1.0.0", + "externalReferences": [ + { + "type": "vcs", + "url": "https://github.com/rust-cli/anstyle.git" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#anstyle-parse@1.0.0", + "name": "anstyle-parse", + "version": "1.0.0", + "description": "Parse ANSI Style Escapes", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "52ce7f38b242319f7cabaa6813055467063ecdc9d355bbb4ce0c68908cd8130e" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/anstyle-parse@1.0.0", + "externalReferences": [ + { + "type": "vcs", + "url": "https://github.com/rust-cli/anstyle.git" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#anstyle-query@1.1.5", + "name": "anstyle-query", + "version": "1.1.5", + "description": "Look up colored console capabilities", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "40c48f72fd53cd289104fc64099abca73db4166ad86ea0b4341abe65af83dadc" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/anstyle-query@1.1.5", + "externalReferences": [ + { + "type": "vcs", + "url": "https://github.com/rust-cli/anstyle.git" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#anstyle-wincon@3.0.11", + "name": "anstyle-wincon", + "version": "3.0.11", + "description": "Styling legacy Windows terminals", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "291e6a250ff86cd4a820112fb8898808a366d8f9f58ce16d1f538353ad55747d" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/anstyle-wincon@3.0.11", + "externalReferences": [ + { + "type": "vcs", + "url": "https://github.com/rust-cli/anstyle.git" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#anstyle@1.0.14", + "name": "anstyle", + "version": "1.0.14", + "description": "ANSI text styling", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "940b3a0ca603d1eade50a4846a2afffd5ef57a9feac2c0e2ec2e14f9ead76000" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/anstyle@1.0.14", + "externalReferences": [ + { + "type": "vcs", + "url": "https://github.com/rust-cli/anstyle.git" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#anyhow@1.0.102", + "author": "David Tolnay ", + "name": "anyhow", + "version": "1.0.102", + "description": "Flexible concrete Error type built on std::error::Error", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "7f202df86484c868dbad7eaa557ef785d5c66295e41b460ef922eca0723b842c" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/anyhow@1.0.102", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/anyhow" + }, + { + "type": "vcs", + "url": "https://github.com/dtolnay/anyhow" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#approx@0.3.2", + "author": "Brendan Zabarauskas ", + "name": "approx", + "version": "0.3.2", + "description": "Approximate floating point equality comparisons and assertions.", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "f0e60b75072ecd4168020818c0107f2857bb6c4e64252d8d3983f6263b40a5c3" + } + ], + "licenses": [ + { + "expression": "Apache-2.0" + } + ], + "purl": "pkg:cargo/approx@0.3.2", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/approx" + }, + { + "type": "website", + "url": "https://github.com/brendanzab/approx" + }, + { + "type": "vcs", + "url": "https://github.com/brendanzab/approx" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#arboard@3.6.1", + "name": "arboard", + "version": "3.6.1", + "description": "Image and text handling for the OS clipboard.", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "0348a1c054491f4bfe6ab86a7b6ab1e44e45d899005de92f58b3df180b36ddaf" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/arboard@3.6.1", + "externalReferences": [ + { + "type": "vcs", + "url": "https://github.com/1Password/arboard" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#arc-swap@1.8.2", + "author": "Michal 'vorner' Vaner ", + "name": "arc-swap", + "version": "1.8.2", + "description": "Atomically swappable Arc", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "f9f3647c145568cec02c42054e07bdf9a5a698e15b466fb2341bfc393cd24aa5" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/arc-swap@1.8.2", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/arc-swap" + }, + { + "type": "vcs", + "url": "https://github.com/vorner/arc-swap" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#array-util@1.0.2", + "author": "Daniel Bloom", + "name": "array-util", + "version": "1.0.2", + "description": "no_std array helpers available without nightly", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "7e509844de8f09b90a2c3444684a2b6695f4071360e13d2fda0af9f749cc2ed6" + } + ], + "licenses": [ + { + "expression": "MIT" + } + ], + "purl": "pkg:cargo/array-util@1.0.2", + "externalReferences": [ + { + "type": "vcs", + "url": "https://github.com/Daniel-Aaron-Bloom/array-util" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#arrayvec@0.7.6", + "author": "bluss", + "name": "arrayvec", + "version": "0.7.6", + "description": "A vector with fixed capacity, backed by an array (it can be stored on the stack too). Implements fixed capacity ArrayVec and ArrayString.", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "7c02d123df017efcdfbd739ef81735b36c5ba83ec3c59c80a9d7ecc718f92e50" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/arrayvec@0.7.6", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/arrayvec/" + }, + { + "type": "vcs", + "url": "https://github.com/bluss/arrayvec" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#arrow-arith@55.2.0", + "author": "Apache Arrow ", + "name": "arrow-arith", + "version": "55.2.0", + "description": "Arrow arithmetic kernels", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "30feb679425110209ae35c3fbf82404a39a4c0436bb3ec36164d8bffed2a4ce4" + } + ], + "licenses": [ + { + "expression": "Apache-2.0" + } + ], + "purl": "pkg:cargo/arrow-arith@55.2.0", + "externalReferences": [ + { + "type": "website", + "url": "https://github.com/apache/arrow-rs" + }, + { + "type": "vcs", + "url": "https://github.com/apache/arrow-rs" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#arrow-array@55.2.0", + "author": "Apache Arrow ", + "name": "arrow-array", + "version": "55.2.0", + "description": "Array abstractions for Apache Arrow", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "70732f04d285d49054a48b72c54f791bb3424abae92d27aafdf776c98af161c8" + } + ], + "licenses": [ + { + "expression": "Apache-2.0" + } + ], + "purl": "pkg:cargo/arrow-array@55.2.0", + "externalReferences": [ + { + "type": "website", + "url": "https://github.com/apache/arrow-rs" + }, + { + "type": "vcs", + "url": "https://github.com/apache/arrow-rs" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#arrow-buffer@55.2.0", + "author": "Apache Arrow ", + "name": "arrow-buffer", + "version": "55.2.0", + "description": "Buffer abstractions for Apache Arrow", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "169b1d5d6cb390dd92ce582b06b23815c7953e9dfaaea75556e89d890d19993d" + } + ], + "licenses": [ + { + "expression": "Apache-2.0" + } + ], + "purl": "pkg:cargo/arrow-buffer@55.2.0", + "externalReferences": [ + { + "type": "website", + "url": "https://github.com/apache/arrow-rs" + }, + { + "type": "vcs", + "url": "https://github.com/apache/arrow-rs" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#arrow-cast@55.2.0", + "author": "Apache Arrow ", + "name": "arrow-cast", + "version": "55.2.0", + "description": "Cast kernel and utilities for Apache Arrow", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "e4f12eccc3e1c05a766cafb31f6a60a46c2f8efec9b74c6e0648766d30686af8" + } + ], + "licenses": [ + { + "expression": "Apache-2.0" + } + ], + "purl": "pkg:cargo/arrow-cast@55.2.0", + "externalReferences": [ + { + "type": "website", + "url": "https://github.com/apache/arrow-rs" + }, + { + "type": "vcs", + "url": "https://github.com/apache/arrow-rs" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#arrow-csv@55.2.0", + "author": "Apache Arrow ", + "name": "arrow-csv", + "version": "55.2.0", + "description": "Support for parsing CSV format to and from the Arrow format", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "012c9fef3f4a11573b2c74aec53712ff9fdae4a95f4ce452d1bbf088ee00f06b" + } + ], + "licenses": [ + { + "expression": "Apache-2.0" + } + ], + "purl": "pkg:cargo/arrow-csv@55.2.0", + "externalReferences": [ + { + "type": "website", + "url": "https://github.com/apache/arrow-rs" + }, + { + "type": "vcs", + "url": "https://github.com/apache/arrow-rs" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#arrow-data@55.2.0", + "author": "Apache Arrow ", + "name": "arrow-data", + "version": "55.2.0", + "description": "Array data abstractions for Apache Arrow", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "8de1ce212d803199684b658fc4ba55fb2d7e87b213de5af415308d2fee3619c2" + } + ], + "licenses": [ + { + "expression": "Apache-2.0" + } + ], + "purl": "pkg:cargo/arrow-data@55.2.0", + "externalReferences": [ + { + "type": "website", + "url": "https://github.com/apache/arrow-rs" + }, + { + "type": "vcs", + "url": "https://github.com/apache/arrow-rs" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#arrow-ipc@55.2.0", + "author": "Apache Arrow ", + "name": "arrow-ipc", + "version": "55.2.0", + "description": "Support for the Arrow IPC format", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "d9ea5967e8b2af39aff5d9de2197df16e305f47f404781d3230b2dc672da5d92" + } + ], + "licenses": [ + { + "expression": "Apache-2.0" + } + ], + "purl": "pkg:cargo/arrow-ipc@55.2.0", + "externalReferences": [ + { + "type": "website", + "url": "https://github.com/apache/arrow-rs" + }, + { + "type": "vcs", + "url": "https://github.com/apache/arrow-rs" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#arrow-json@55.2.0", + "author": "Apache Arrow ", + "name": "arrow-json", + "version": "55.2.0", + "description": "Support for parsing JSON format to and from the Arrow format", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "5709d974c4ea5be96d900c01576c7c0b99705f4a3eec343648cb1ca863988a9c" + } + ], + "licenses": [ + { + "expression": "Apache-2.0" + } + ], + "purl": "pkg:cargo/arrow-json@55.2.0", + "externalReferences": [ + { + "type": "website", + "url": "https://github.com/apache/arrow-rs" + }, + { + "type": "vcs", + "url": "https://github.com/apache/arrow-rs" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#arrow-ord@55.2.0", + "author": "Apache Arrow ", + "name": "arrow-ord", + "version": "55.2.0", + "description": "Ordering kernels for arrow arrays", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "6506e3a059e3be23023f587f79c82ef0bcf6d293587e3272d20f2d30b969b5a7" + } + ], + "licenses": [ + { + "expression": "Apache-2.0" + } + ], + "purl": "pkg:cargo/arrow-ord@55.2.0", + "externalReferences": [ + { + "type": "website", + "url": "https://github.com/apache/arrow-rs" + }, + { + "type": "vcs", + "url": "https://github.com/apache/arrow-rs" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#arrow-row@55.2.0", + "author": "Apache Arrow ", + "name": "arrow-row", + "version": "55.2.0", + "description": "Arrow row format", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "52bf7393166beaf79b4bed9bfdf19e97472af32ce5b6b48169d321518a08cae2" + } + ], + "licenses": [ + { + "expression": "Apache-2.0" + } + ], + "purl": "pkg:cargo/arrow-row@55.2.0", + "externalReferences": [ + { + "type": "website", + "url": "https://github.com/apache/arrow-rs" + }, + { + "type": "vcs", + "url": "https://github.com/apache/arrow-rs" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#arrow-schema@55.2.0", + "author": "Apache Arrow ", + "name": "arrow-schema", + "version": "55.2.0", + "description": "Defines the logical types for arrow arrays", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "af7686986a3bf2254c9fb130c623cdcb2f8e1f15763e7c71c310f0834da3d292" + } + ], + "licenses": [ + { + "expression": "Apache-2.0" + } + ], + "purl": "pkg:cargo/arrow-schema@55.2.0", + "externalReferences": [ + { + "type": "website", + "url": "https://github.com/apache/arrow-rs" + }, + { + "type": "vcs", + "url": "https://github.com/apache/arrow-rs" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#arrow-select@55.2.0", + "author": "Apache Arrow ", + "name": "arrow-select", + "version": "55.2.0", + "description": "Selection kernels for arrow arrays", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "dd2b45757d6a2373faa3352d02ff5b54b098f5e21dccebc45a21806bc34501e5" + } + ], + "licenses": [ + { + "expression": "Apache-2.0" + } + ], + "purl": "pkg:cargo/arrow-select@55.2.0", + "externalReferences": [ + { + "type": "website", + "url": "https://github.com/apache/arrow-rs" + }, + { + "type": "vcs", + "url": "https://github.com/apache/arrow-rs" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#arrow-string@55.2.0", + "author": "Apache Arrow ", + "name": "arrow-string", + "version": "55.2.0", + "description": "String kernels for arrow arrays", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "0377d532850babb4d927a06294314b316e23311503ed580ec6ce6a0158f49d40" + } + ], + "licenses": [ + { + "expression": "Apache-2.0" + } + ], + "purl": "pkg:cargo/arrow-string@55.2.0", + "externalReferences": [ + { + "type": "website", + "url": "https://github.com/apache/arrow-rs" + }, + { + "type": "vcs", + "url": "https://github.com/apache/arrow-rs" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#arrow@55.2.0", + "author": "Apache Arrow ", + "name": "arrow", + "version": "55.2.0", + "description": "Rust implementation of Apache Arrow", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "f3f15b4c6b148206ff3a2b35002e08929c2462467b62b9c02036d9c34f9ef994" + } + ], + "licenses": [ + { + "expression": "Apache-2.0" + } + ], + "purl": "pkg:cargo/arrow@55.2.0", + "externalReferences": [ + { + "type": "website", + "url": "https://github.com/apache/arrow-rs" + }, + { + "type": "vcs", + "url": "https://github.com/apache/arrow-rs" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#assoc@0.1.3", + "author": "", + "name": "assoc", + "version": "0.1.3", + "description": "Treat vectors like associative arrays", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "bfdc70193dadb9d7287fa4b633f15f90c876915b31f6af17da307fc59c9859a8" + } + ], + "licenses": [ + { + "expression": "MIT" + } + ], + "purl": "pkg:cargo/assoc@0.1.3", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/assoc" + }, + { + "type": "website", + "url": "https://github.com/mingyli/assoc" + }, + { + "type": "vcs", + "url": "https://github.com/mingyli/assoc" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#async-stream-impl@0.3.6", + "author": "Carl Lerche ", + "name": "async-stream-impl", + "version": "0.3.6", + "description": "proc macros for async-stream crate", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "c7c24de15d275a1ecfd47a380fb4d5ec9bfe0933f309ed5e705b775596a3574d" + } + ], + "licenses": [ + { + "expression": "MIT" + } + ], + "purl": "pkg:cargo/async-stream-impl@0.3.6", + "externalReferences": [ + { + "type": "vcs", + "url": "https://github.com/tokio-rs/async-stream" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#async-stream@0.3.6", + "author": "Carl Lerche ", + "name": "async-stream", + "version": "0.3.6", + "description": "Asynchronous streams using async & await notation", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "0b5a71a6f37880a80d1d7f19efd781e4b5de42c88f0722cc13bcb6cc2cfe8476" + } + ], + "licenses": [ + { + "expression": "MIT" + } + ], + "purl": "pkg:cargo/async-stream@0.3.6", + "externalReferences": [ + { + "type": "vcs", + "url": "https://github.com/tokio-rs/async-stream" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#async-trait@0.1.89", + "author": "David Tolnay ", + "name": "async-trait", + "version": "0.1.89", + "description": "Type erasure for async trait methods", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "9035ad2d096bed7955a320ee7e2230574d28fd3c3a0f186cbea1ff3c7eed5dbb" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/async-trait@0.1.89", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/async-trait" + }, + { + "type": "vcs", + "url": "https://github.com/dtolnay/async-trait" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#atoi@2.0.0", + "author": "Markus Klein", + "name": "atoi", + "version": "2.0.0", + "description": "Parse integers directly from `[u8]` slices in safe code", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "f28d99ec8bfea296261ca1af174f24225171fea9664ba9003cbebee704810528" + } + ], + "licenses": [ + { + "expression": "MIT" + } + ], + "purl": "pkg:cargo/atoi@2.0.0", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/atoi/" + }, + { + "type": "vcs", + "url": "https://github.com/pacman82/atoi-rs" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#atomic-waker@1.1.2", + "author": "Stjepan Glavina , Contributors to futures-rs", + "name": "atomic-waker", + "version": "1.1.2", + "description": "A synchronization primitive for task wakeup", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "1505bd5d3d116872e7271a6d4e16d81d0c8570876c8de68093a09ac269d8aac0" + } + ], + "licenses": [ + { + "expression": "Apache-2.0 OR MIT" + } + ], + "purl": "pkg:cargo/atomic-waker@1.1.2", + "externalReferences": [ + { + "type": "vcs", + "url": "https://github.com/smol-rs/atomic-waker" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#auto_enums@0.8.8", + "name": "auto_enums", + "version": "0.8.8", + "description": "A library for to allow multiple return types by automatically generated enum. ", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "65398a2893f41bce5c9259f6e1a4f03fbae40637c1bdc755b4f387f48c613b03" + } + ], + "licenses": [ + { + "expression": "Apache-2.0 OR MIT" + } + ], + "purl": "pkg:cargo/auto_enums@0.8.8", + "externalReferences": [ + { + "type": "vcs", + "url": "https://github.com/taiki-e/auto_enums" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#autocfg@1.5.0", + "author": "Josh Stone ", + "name": "autocfg", + "version": "1.5.0", + "description": "Automatic cfg for Rust compiler features", + "scope": "excluded", + "hashes": [ + { + "alg": "SHA-256", + "content": "c08606f8c3cbf4ce6ec8e28fb0014a2c086708fe954eaa885384a6165172e7e8" + } + ], + "licenses": [ + { + "expression": "Apache-2.0 OR MIT" + } + ], + "purl": "pkg:cargo/autocfg@1.5.0", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/autocfg/" + }, + { + "type": "vcs", + "url": "https://github.com/cuviper/autocfg" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#aws-config@1.8.15", + "author": "AWS Rust SDK Team , Russell Cohen ", + "name": "aws-config", + "version": "1.8.15", + "description": "AWS SDK config and credential provider implementations.", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "11493b0bad143270fb8ad284a096dd529ba91924c5409adeac856cc1bf047dbc" + } + ], + "licenses": [ + { + "expression": "Apache-2.0" + } + ], + "purl": "pkg:cargo/aws-config@1.8.15", + "externalReferences": [ + { + "type": "vcs", + "url": "https://github.com/smithy-lang/smithy-rs" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#aws-credential-types@1.2.14", + "author": "AWS Rust SDK Team ", + "name": "aws-credential-types", + "version": "1.2.14", + "description": "Types for AWS SDK credentials.", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "8f20799b373a1be121fe3005fba0c2090af9411573878f224df44b42727fcaf7" + } + ], + "licenses": [ + { + "expression": "Apache-2.0" + } + ], + "purl": "pkg:cargo/aws-credential-types@1.2.14", + "externalReferences": [ + { + "type": "vcs", + "url": "https://github.com/smithy-lang/smithy-rs" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#aws-lc-rs@1.16.2", + "author": "AWS-LibCrypto", + "name": "aws-lc-rs", + "version": "1.16.2", + "description": "aws-lc-rs is a cryptographic library using AWS-LC for its cryptographic operations. This library strives to be API-compatible with the popular Rust library named ring.", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "a054912289d18629dc78375ba2c3726a3afe3ff71b4edba9dedfca0e3446d1fc" + } + ], + "licenses": [ + { + "expression": "ISC AND (Apache-2.0 OR ISC)" + } + ], + "purl": "pkg:cargo/aws-lc-rs@1.16.2", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/crate/aws-lc-rs" + }, + { + "type": "website", + "url": "https://github.com/aws/aws-lc-rs" + }, + { + "type": "other", + "url": "aws_lc_rs_1_16_2_sys" + }, + { + "type": "vcs", + "url": "https://github.com/aws/aws-lc-rs" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#aws-lc-sys@0.39.0", + "author": "AWS-LC", + "name": "aws-lc-sys", + "version": "0.39.0", + "description": "AWS-LC is a general-purpose cryptographic library maintained by the AWS Cryptography team for AWS and their customers. It іs based on code from the Google BoringSSL project and the OpenSSL project.", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "1fa7e52a4c5c547c741610a2c6f123f3881e409b714cd27e6798ef020c514f0a" + } + ], + "licenses": [ + { + "expression": "ISC AND (Apache-2.0 OR ISC) AND Apache-2.0 AND MIT AND BSD-3-Clause AND (Apache-2.0 OR ISC OR MIT) AND (Apache-2.0 OR ISC OR MIT-0)" + } + ], + "purl": "pkg:cargo/aws-lc-sys@0.39.0", + "externalReferences": [ + { + "type": "other", + "url": "aws_lc_0_39_0" + }, + { + "type": "vcs", + "url": "https://github.com/aws/aws-lc-rs" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#aws-runtime@1.7.2", + "author": "AWS Rust SDK Team ", + "name": "aws-runtime", + "version": "1.7.2", + "description": "Runtime support code for the AWS SDK. This crate isn't intended to be used directly.", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "5fc0651c57e384202e47153c1260b84a9936e19803d747615edf199dc3b98d17" + } + ], + "licenses": [ + { + "expression": "Apache-2.0" + } + ], + "purl": "pkg:cargo/aws-runtime@1.7.2", + "externalReferences": [ + { + "type": "vcs", + "url": "https://github.com/smithy-lang/smithy-rs" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#aws-sdk-s3@1.119.0", + "author": "AWS Rust SDK Team , Russell Cohen ", + "name": "aws-sdk-s3", + "version": "1.119.0", + "description": "AWS SDK for Amazon Simple Storage Service", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "1d65fddc3844f902dfe1864acb8494db5f9342015ee3ab7890270d36fbd2e01c" + } + ], + "licenses": [ + { + "expression": "Apache-2.0" + } + ], + "purl": "pkg:cargo/aws-sdk-s3@1.119.0", + "externalReferences": [ + { + "type": "vcs", + "url": "https://github.com/awslabs/aws-sdk-rust" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#aws-sdk-sso@1.97.0", + "author": "AWS Rust SDK Team , Russell Cohen ", + "name": "aws-sdk-sso", + "version": "1.97.0", + "description": "AWS SDK for AWS Single Sign-On", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "9aadc669e184501caaa6beafb28c6267fc1baef0810fb58f9b205485ca3f2567" + } + ], + "licenses": [ + { + "expression": "Apache-2.0" + } + ], + "purl": "pkg:cargo/aws-sdk-sso@1.97.0", + "externalReferences": [ + { + "type": "vcs", + "url": "https://github.com/awslabs/aws-sdk-rust" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#aws-sdk-ssooidc@1.99.0", + "author": "AWS Rust SDK Team , Russell Cohen ", + "name": "aws-sdk-ssooidc", + "version": "1.99.0", + "description": "AWS SDK for AWS SSO OIDC", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "1342a7db8f358d3de0aed2007a0b54e875458e39848d54cc1d46700b2bfcb0a8" + } + ], + "licenses": [ + { + "expression": "Apache-2.0" + } + ], + "purl": "pkg:cargo/aws-sdk-ssooidc@1.99.0", + "externalReferences": [ + { + "type": "vcs", + "url": "https://github.com/awslabs/aws-sdk-rust" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#aws-sdk-sts@1.101.0", + "author": "AWS Rust SDK Team , Russell Cohen ", + "name": "aws-sdk-sts", + "version": "1.101.0", + "description": "AWS SDK for AWS Security Token Service", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "ab41ad64e4051ecabeea802d6a17845a91e83287e1dd249e6963ea1ba78c428a" + } + ], + "licenses": [ + { + "expression": "Apache-2.0" + } + ], + "purl": "pkg:cargo/aws-sdk-sts@1.101.0", + "externalReferences": [ + { + "type": "vcs", + "url": "https://github.com/awslabs/aws-sdk-rust" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#aws-sigv4@1.4.2", + "author": "AWS Rust SDK Team , David Barsky ", + "name": "aws-sigv4", + "version": "1.4.2", + "description": "SigV4 signer for HTTP requests and Event Stream messages.", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "b0b660013a6683ab23797778e21f1f854744fdf05f68204b4cca4c8c04b5d1f4" + } + ], + "licenses": [ + { + "expression": "Apache-2.0" + } + ], + "purl": "pkg:cargo/aws-sigv4@1.4.2", + "externalReferences": [ + { + "type": "vcs", + "url": "https://github.com/smithy-lang/smithy-rs" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#aws-smithy-async@1.2.14", + "author": "AWS Rust SDK Team , John DiSanti ", + "name": "aws-smithy-async", + "version": "1.2.14", + "description": "Async runtime agnostic abstractions for smithy-rs.", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "2ffcaf626bdda484571968400c326a244598634dc75fd451325a54ad1a59acfc" + } + ], + "licenses": [ + { + "expression": "Apache-2.0" + } + ], + "purl": "pkg:cargo/aws-smithy-async@1.2.14", + "externalReferences": [ + { + "type": "vcs", + "url": "https://github.com/smithy-lang/smithy-rs" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#aws-smithy-checksums@0.63.12", + "author": "AWS Rust SDK Team , Zelda Hessler ", + "name": "aws-smithy-checksums", + "version": "0.63.12", + "description": "Checksum calculation and verification callbacks", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "87294a084b43d649d967efe58aa1f9e0adc260e13a6938eb904c0ae9b45824ae" + } + ], + "licenses": [ + { + "expression": "Apache-2.0" + } + ], + "purl": "pkg:cargo/aws-smithy-checksums@0.63.12", + "externalReferences": [ + { + "type": "vcs", + "url": "https://github.com/smithy-lang/smithy-rs" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#aws-smithy-eventstream@0.60.20", + "author": "AWS Rust SDK Team , John DiSanti ", + "name": "aws-smithy-eventstream", + "version": "0.60.20", + "description": "Event stream logic for smithy-rs.", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "faf09d74e5e32f76b8762da505a3cd59303e367a664ca67295387baa8c1d7548" + } + ], + "licenses": [ + { + "expression": "Apache-2.0" + } + ], + "purl": "pkg:cargo/aws-smithy-eventstream@0.60.20", + "externalReferences": [ + { + "type": "vcs", + "url": "https://github.com/smithy-lang/smithy-rs" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#aws-smithy-http-client@1.1.12", + "author": "AWS Rust SDK Team ", + "name": "aws-smithy-http-client", + "version": "1.1.12", + "description": "HTTP client abstractions for generated smithy clients", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "6a2f165a7feee6f263028b899d0a181987f4fa7179a6411a32a439fba7c5f769" + } + ], + "licenses": [ + { + "expression": "Apache-2.0" + } + ], + "purl": "pkg:cargo/aws-smithy-http-client@1.1.12", + "externalReferences": [ + { + "type": "vcs", + "url": "https://github.com/smithy-lang/smithy-rs" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#aws-smithy-http@0.62.6", + "author": "AWS Rust SDK Team , Russell Cohen ", + "name": "aws-smithy-http", + "version": "0.62.6", + "description": "Smithy HTTP logic for smithy-rs.", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "826141069295752372f8203c17f28e30c464d22899a43a0c9fd9c458d469c88b" + } + ], + "licenses": [ + { + "expression": "Apache-2.0" + } + ], + "purl": "pkg:cargo/aws-smithy-http@0.62.6", + "externalReferences": [ + { + "type": "vcs", + "url": "https://github.com/smithy-lang/smithy-rs" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#aws-smithy-http@0.63.6", + "author": "AWS Rust SDK Team , Russell Cohen ", + "name": "aws-smithy-http", + "version": "0.63.6", + "description": "Smithy HTTP logic for smithy-rs.", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "ba1ab2dc1c2c3749ead27180d333c42f11be8b0e934058fb4b2258ee8dbe5231" + } + ], + "licenses": [ + { + "expression": "Apache-2.0" + } + ], + "purl": "pkg:cargo/aws-smithy-http@0.63.6", + "externalReferences": [ + { + "type": "vcs", + "url": "https://github.com/smithy-lang/smithy-rs" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#aws-smithy-json@0.61.9", + "author": "AWS Rust SDK Team , John DiSanti ", + "name": "aws-smithy-json", + "version": "0.61.9", + "description": "Token streaming JSON parser for smithy-rs.", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "49fa1213db31ac95288d981476f78d05d9cbb0353d22cdf3472cc05bb02f6551" + } + ], + "licenses": [ + { + "expression": "Apache-2.0" + } + ], + "purl": "pkg:cargo/aws-smithy-json@0.61.9", + "externalReferences": [ + { + "type": "vcs", + "url": "https://github.com/smithy-lang/smithy-rs" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#aws-smithy-json@0.62.5", + "author": "AWS Rust SDK Team , John DiSanti ", + "name": "aws-smithy-json", + "version": "0.62.5", + "description": "Token streaming JSON parser for smithy-rs.", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "9648b0bb82a2eedd844052c6ad2a1a822d1f8e3adee5fbf668366717e428856a" + } + ], + "licenses": [ + { + "expression": "Apache-2.0" + } + ], + "purl": "pkg:cargo/aws-smithy-json@0.62.5", + "externalReferences": [ + { + "type": "vcs", + "url": "https://github.com/smithy-lang/smithy-rs" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#aws-smithy-observability@0.2.6", + "author": "AWS Rust SDK Team ", + "name": "aws-smithy-observability", + "version": "0.2.6", + "description": "Smithy observability implementation.", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "a06c2315d173edbf1920da8ba3a7189695827002e4c0fc961973ab1c54abca9c" + } + ], + "licenses": [ + { + "expression": "Apache-2.0" + } + ], + "purl": "pkg:cargo/aws-smithy-observability@0.2.6", + "externalReferences": [ + { + "type": "vcs", + "url": "https://github.com/awslabs/smithy-rs" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#aws-smithy-query@0.60.15", + "author": "AWS Rust SDK Team , John DiSanti ", + "name": "aws-smithy-query", + "version": "0.60.15", + "description": "AWSQuery and EC2Query Smithy protocol logic for smithy-rs.", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "1a56d79744fb3edb5d722ef79d86081e121d3b9422cb209eb03aea6aa4f21ebd" + } + ], + "licenses": [ + { + "expression": "Apache-2.0" + } + ], + "purl": "pkg:cargo/aws-smithy-query@0.60.15", + "externalReferences": [ + { + "type": "vcs", + "url": "https://github.com/smithy-lang/smithy-rs" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#aws-smithy-runtime-api@1.11.6", + "author": "AWS Rust SDK Team , Zelda Hessler ", + "name": "aws-smithy-runtime-api", + "version": "1.11.6", + "description": "Smithy runtime types.", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "876ab3c9c29791ba4ba02b780a3049e21ec63dabda09268b175272c3733a79e6" + } + ], + "licenses": [ + { + "expression": "Apache-2.0" + } + ], + "purl": "pkg:cargo/aws-smithy-runtime-api@1.11.6", + "externalReferences": [ + { + "type": "vcs", + "url": "https://github.com/smithy-lang/smithy-rs" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#aws-smithy-runtime@1.10.3", + "author": "AWS Rust SDK Team , Zelda Hessler ", + "name": "aws-smithy-runtime", + "version": "1.10.3", + "description": "The new smithy runtime crate", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "028999056d2d2fd58a697232f9eec4a643cf73a71cf327690a7edad1d2af2110" + } + ], + "licenses": [ + { + "expression": "Apache-2.0" + } + ], + "purl": "pkg:cargo/aws-smithy-runtime@1.10.3", + "externalReferences": [ + { + "type": "vcs", + "url": "https://github.com/smithy-lang/smithy-rs" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#aws-smithy-types@1.4.7", + "author": "AWS Rust SDK Team , Russell Cohen ", + "name": "aws-smithy-types", + "version": "1.4.7", + "description": "Types for smithy-rs codegen.", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "9d73dbfbaa8e4bc57b9045137680b958d274823509a360abfd8e1d514d40c95c" + } + ], + "licenses": [ + { + "expression": "Apache-2.0" + } + ], + "purl": "pkg:cargo/aws-smithy-types@1.4.7", + "externalReferences": [ + { + "type": "vcs", + "url": "https://github.com/smithy-lang/smithy-rs" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#aws-smithy-xml@0.60.15", + "author": "AWS Rust SDK Team , Russell Cohen ", + "name": "aws-smithy-xml", + "version": "0.60.15", + "description": "XML parsing logic for Smithy protocols.", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "0ce02add1aa3677d022f8adf81dcbe3046a95f17a1b1e8979c145cd21d3d22b3" + } + ], + "licenses": [ + { + "expression": "Apache-2.0" + } + ], + "purl": "pkg:cargo/aws-smithy-xml@0.60.15", + "externalReferences": [ + { + "type": "vcs", + "url": "https://github.com/smithy-lang/smithy-rs" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#aws-types@1.3.14", + "author": "AWS Rust SDK Team , Russell Cohen ", + "name": "aws-types", + "version": "1.3.14", + "description": "Cross-service types for the AWS SDK.", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "47c8323699dd9b3c8d5b3c13051ae9cdef58fd179957c882f8374dd8725962d9" + } + ], + "licenses": [ + { + "expression": "Apache-2.0" + } + ], + "purl": "pkg:cargo/aws-types@1.3.14", + "externalReferences": [ + { + "type": "vcs", + "url": "https://github.com/smithy-lang/smithy-rs" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#axum-core@0.4.5", + "name": "axum-core", + "version": "0.4.5", + "description": "Core types and traits for axum", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "09f2bd6146b97ae3359fa0cc6d6b376d9539582c7b4220f041a33ec24c226199" + } + ], + "licenses": [ + { + "expression": "MIT" + } + ], + "purl": "pkg:cargo/axum-core@0.4.5", + "externalReferences": [ + { + "type": "website", + "url": "https://github.com/tokio-rs/axum" + }, + { + "type": "vcs", + "url": "https://github.com/tokio-rs/axum" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#axum-core@0.5.6", + "name": "axum-core", + "version": "0.5.6", + "description": "Core types and traits for axum", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "08c78f31d7b1291f7ee735c1c6780ccde7785daae9a9206026862dab7d8792d1" + } + ], + "licenses": [ + { + "expression": "MIT" + } + ], + "purl": "pkg:cargo/axum-core@0.5.6", + "externalReferences": [ + { + "type": "website", + "url": "https://github.com/tokio-rs/axum" + }, + { + "type": "vcs", + "url": "https://github.com/tokio-rs/axum" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#axum-macros@0.5.0", + "name": "axum-macros", + "version": "0.5.0", + "description": "Macros for axum", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "604fde5e028fea851ce1d8570bbdc034bec850d157f7569d10f347d06808c05c" + } + ], + "licenses": [ + { + "expression": "MIT" + } + ], + "purl": "pkg:cargo/axum-macros@0.5.0", + "externalReferences": [ + { + "type": "website", + "url": "https://github.com/tokio-rs/axum" + }, + { + "type": "vcs", + "url": "https://github.com/tokio-rs/axum" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#axum@0.7.9", + "name": "axum", + "version": "0.7.9", + "description": "Web framework that focuses on ergonomics and modularity", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "edca88bc138befd0323b20752846e6587272d3b03b0343c8ea28a6f819e6e71f" + } + ], + "licenses": [ + { + "expression": "MIT" + } + ], + "purl": "pkg:cargo/axum@0.7.9", + "externalReferences": [ + { + "type": "website", + "url": "https://github.com/tokio-rs/axum" + }, + { + "type": "vcs", + "url": "https://github.com/tokio-rs/axum" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#axum@0.8.8", + "name": "axum", + "version": "0.8.8", + "description": "Web framework that focuses on ergonomics and modularity", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "8b52af3cb4058c895d37317bb27508dccc8e5f2d39454016b297bf4a400597b8" + } + ], + "licenses": [ + { + "expression": "MIT" + } + ], + "purl": "pkg:cargo/axum@0.8.8", + "externalReferences": [ + { + "type": "website", + "url": "https://github.com/tokio-rs/axum" + }, + { + "type": "vcs", + "url": "https://github.com/tokio-rs/axum" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#backoff@0.4.0", + "author": "Tibor Benke ", + "name": "backoff", + "version": "0.4.0", + "description": "Retry operations with exponential backoff policy. ", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "b62ddb9cb1ec0a098ad4bbf9344d0713fa193ae1a80af55febcff2627b6a00c1" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/backoff@0.4.0", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/backoff" + }, + { + "type": "website", + "url": "https://github.com/ihrwein/backoff" + }, + { + "type": "vcs", + "url": "https://github.com/ihrwein/backoff" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#backon@1.6.0", + "name": "backon", + "version": "1.6.0", + "description": "Make retry like a built-in feature provided by Rust.", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "cffb0e931875b666fc4fcb20fee52e9bbd1ef836fd9e9e04ec21555f9f85f7ef" + } + ], + "licenses": [ + { + "expression": "Apache-2.0" + } + ], + "purl": "pkg:cargo/backon@1.6.0", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/backon" + }, + { + "type": "vcs", + "url": "https://github.com/Xuanwo/backon" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#base16ct@0.1.1", + "author": "RustCrypto Developers", + "name": "base16ct", + "version": "0.1.1", + "description": "Pure Rust implementation of Base16 a.k.a hexadecimal (RFC 4648) which avoids any usages of data-dependent branches/LUTs and thereby provides portable \"best effort\" constant-time operation and embedded-friendly no_std support ", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "349a06037c7bf932dd7e7d1f653678b2038b9ad46a74102f1fc7bd7872678cce" + } + ], + "licenses": [ + { + "expression": "Apache-2.0 OR MIT" + } + ], + "purl": "pkg:cargo/base16ct@0.1.1", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/base16ct" + }, + { + "type": "vcs", + "url": "https://github.com/RustCrypto/formats/tree/master/base16ct" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#base64-simd@0.8.0", + "name": "base64-simd", + "version": "0.8.0", + "description": "SIMD-accelerated base64 encoding and decoding", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "339abbe78e73178762e23bea9dfd08e697eb3f3301cd4be981c0f78ba5859195" + } + ], + "licenses": [ + { + "expression": "MIT" + } + ], + "purl": "pkg:cargo/base64-simd@0.8.0", + "externalReferences": [ + { + "type": "vcs", + "url": "https://github.com/Nugine/simd" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#base64@0.21.7", + "author": "Alice Maz , Marshall Pierce ", + "name": "base64", + "version": "0.21.7", + "description": "encodes and decodes base64 as bytes or utf8", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "9d297deb1925b89f2ccc13d7635fa0714f12c87adce1c75356b39ca9b7178567" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/base64@0.21.7", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/base64" + }, + { + "type": "vcs", + "url": "https://github.com/marshallpierce/rust-base64" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#base64@0.22.1", + "author": "Marshall Pierce ", + "name": "base64", + "version": "0.22.1", + "description": "encodes and decodes base64 as bytes or utf8", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/base64@0.22.1", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/base64" + }, + { + "type": "vcs", + "url": "https://github.com/marshallpierce/rust-base64" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#base64ct@1.8.3", + "author": "RustCrypto Developers", + "name": "base64ct", + "version": "1.8.3", + "description": "Pure Rust implementation of Base64 (RFC 4648) which avoids any usages of data-dependent branches/LUTs and thereby provides portable \"best effort\" constant-time operation and embedded-friendly no_std support ", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "2af50177e190e07a26ab74f8b1efbfe2ef87da2116221318cb1c2e82baf7de06" + } + ], + "licenses": [ + { + "expression": "Apache-2.0 OR MIT" + } + ], + "purl": "pkg:cargo/base64ct@1.8.3", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/base64ct" + }, + { + "type": "website", + "url": "https://github.com/RustCrypto/formats/tree/master/base64ct" + }, + { + "type": "vcs", + "url": "https://github.com/RustCrypto/formats" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#bincode@1.3.3", + "author": "Ty Overby , Francesco Mazzoli , David Tolnay , Zoey Riordan ", + "name": "bincode", + "version": "1.3.3", + "description": "A binary serialization / deserialization strategy that uses Serde for transforming structs into bytes and vice versa!", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "b1f45e9417d87227c7a56d22e471c6206462cba514c7590c09aff4cf6d1ddcad" + } + ], + "licenses": [ + { + "expression": "MIT" + } + ], + "purl": "pkg:cargo/bincode@1.3.3", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/bincode" + }, + { + "type": "vcs", + "url": "https://github.com/servo/bincode" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#bit-set@0.8.0", + "author": "Alexis Beingessner ", + "name": "bit-set", + "version": "0.8.0", + "description": "A set of bits", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "08807e080ed7f9d5433fa9b275196cfc35414f66a0c79d864dc51a0d825231a3" + } + ], + "licenses": [ + { + "expression": "Apache-2.0 OR MIT" + } + ], + "purl": "pkg:cargo/bit-set@0.8.0", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/bit-set/" + }, + { + "type": "website", + "url": "https://github.com/contain-rs/bit-set" + }, + { + "type": "vcs", + "url": "https://github.com/contain-rs/bit-set" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#bit-vec@0.8.0", + "author": "Alexis Beingessner ", + "name": "bit-vec", + "version": "0.8.0", + "description": "A vector of bits", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "5e764a1d40d510daf35e07be9eb06e75770908c27d411ee6c92109c9840eaaf7" + } + ], + "licenses": [ + { + "expression": "Apache-2.0 OR MIT" + } + ], + "purl": "pkg:cargo/bit-vec@0.8.0", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/bit-vec/" + }, + { + "type": "website", + "url": "https://github.com/contain-rs/bit-vec" + }, + { + "type": "vcs", + "url": "https://github.com/contain-rs/bit-vec" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#bitflags@2.11.0", + "author": "The Rust Project Developers", + "name": "bitflags", + "version": "2.11.0", + "description": "A macro to generate structures which behave like bitflags. ", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "843867be96c8daad0d758b57df9392b6d8d271134fce549de6ce169ff98a92af" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/bitflags@2.11.0", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/bitflags" + }, + { + "type": "website", + "url": "https://github.com/bitflags/bitflags" + }, + { + "type": "vcs", + "url": "https://github.com/bitflags/bitflags" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#bitpacking@0.9.3", + "author": "Paul Masurel ", + "name": "bitpacking", + "version": "0.9.3", + "description": "Fast integer compression/decompression via SIMD bit-packing. Port of simdcomp to rust.", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "96a7139abd3d9cebf8cd6f920a389cf3dc9576172e32f4563f188cae3c3eb019" + } + ], + "licenses": [ + { + "expression": "MIT" + } + ], + "purl": "pkg:cargo/bitpacking@0.9.3", + "externalReferences": [ + { + "type": "website", + "url": "https://github.com/quickwit-oss/bitpacking" + }, + { + "type": "vcs", + "url": "https://github.com/quickwit-oss/bitpacking" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#bitvec@1.0.1", + "name": "bitvec", + "version": "1.0.1", + "description": "Addresses memory by bits, for packed collections and bitfields", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "1bc2832c24239b0141d5674bb9174f9d68a8b5b3f2753311927c172ca46f7e9c" + } + ], + "licenses": [ + { + "expression": "MIT" + } + ], + "purl": "pkg:cargo/bitvec@1.0.1", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/bitvec/latest/bitvec" + }, + { + "type": "website", + "url": "https://bitvecto-rs.github.io/bitvec" + }, + { + "type": "vcs", + "url": "https://github.com/bitvecto-rs/bitvec" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#block-buffer@0.10.4", + "author": "RustCrypto Developers", + "name": "block-buffer", + "version": "0.10.4", + "description": "Buffer type for block processing of data", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "3078c7629b62d3f0439517fa394996acacc5cbc91c5a20d8c658e77abd503a71" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/block-buffer@0.10.4", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/block-buffer" + }, + { + "type": "vcs", + "url": "https://github.com/RustCrypto/utils" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#bon-macros@3.9.1", + "name": "bon-macros", + "version": "3.9.1", + "description": "This is a proc-macro crate that is supposed to be a private implementation detail of the `bon` crate ", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "519bd3116aeeb42d5372c29d982d16d0170d3d4a5ed85fc7dd91642ffff3c67c" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/bon-macros@3.9.1", + "externalReferences": [ + { + "type": "website", + "url": "https://bon-rs.com/" + }, + { + "type": "vcs", + "url": "https://github.com/elastio/bon" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#bon@3.9.1", + "name": "bon", + "version": "3.9.1", + "description": "Next-gen compile-time-checked builder generator, named function's arguments, and more!", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "f47dbe92550676ee653353c310dfb9cf6ba17ee70396e1f7cf0a2020ad49b2fe" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/bon@3.9.1", + "externalReferences": [ + { + "type": "website", + "url": "https://bon-rs.com" + }, + { + "type": "vcs", + "url": "https://github.com/elastio/bon" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#brotli-decompressor@5.0.0", + "author": "Daniel Reiter Horn , The Brotli Authors", + "name": "brotli-decompressor", + "version": "5.0.0", + "description": "A brotli decompressor that with an interface avoiding the rust stdlib. This makes it suitable for embedded devices and kernels. It is designed with a pluggable allocator so that the standard lib's allocator may be employed. The default build also includes a stdlib allocator and stream interface. Disable this with --features=no-stdlib. Alternatively, --features=unsafe turns off array bounds checks and memory initialization but provides a safe interface for the caller. Without adding the --features=unsafe argument, all included code is safe. For compression in addition to this library, download https://github.com/dropbox/rust-brotli ", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "874bb8112abecc98cbd6d81ea4fa7e94fb9449648c93cc89aa40c81c24d7de03" + } + ], + "licenses": [ + { + "expression": "BSD-3-Clause OR MIT" + } + ], + "purl": "pkg:cargo/brotli-decompressor@5.0.0", + "externalReferences": [ + { + "type": "documentation", + "url": "https://github.com/dropbox/rust-brotli-decompressor/blob/master/README.md" + }, + { + "type": "website", + "url": "https://github.com/dropbox/rust-brotli-decompressor" + }, + { + "type": "vcs", + "url": "https://github.com/dropbox/rust-brotli-decompressor" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#brotli@8.0.2", + "author": "Daniel Reiter Horn , The Brotli Authors", + "name": "brotli", + "version": "8.0.2", + "description": "A brotli compressor and decompressor that with an interface avoiding the rust stdlib. This makes it suitable for embedded devices and kernels. It is designed with a pluggable allocator so that the standard lib's allocator may be employed. The default build also includes a stdlib allocator and stream interface. Disable this with --features=no-stdlib. All included code is safe.", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "4bd8b9603c7aa97359dbd97ecf258968c95f3adddd6db2f7e7a5bef101c84560" + } + ], + "licenses": [ + { + "expression": "BSD-3-Clause AND MIT" + } + ], + "purl": "pkg:cargo/brotli@8.0.2", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/brotli/" + }, + { + "type": "website", + "url": "https://github.com/dropbox/rust-brotli" + }, + { + "type": "vcs", + "url": "https://github.com/dropbox/rust-brotli" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#bstr@1.12.1", + "author": "Andrew Gallant ", + "name": "bstr", + "version": "1.12.1", + "description": "A string type that is not required to be valid UTF-8.", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "63044e1ae8e69f3b5a92c736ca6269b8d12fa7efe39bf34ddb06d102cf0e2cab" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/bstr@1.12.1", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/bstr" + }, + { + "type": "website", + "url": "https://github.com/BurntSushi/bstr" + }, + { + "type": "vcs", + "url": "https://github.com/BurntSushi/bstr" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#bumpalo@3.20.2", + "author": "Nick Fitzgerald ", + "name": "bumpalo", + "version": "3.20.2", + "description": "A fast bump allocation arena for Rust.", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "5d20789868f4b01b2f2caec9f5c4e0213b41e3e5702a50157d699ae31ced2fcb" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/bumpalo@3.20.2", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/bumpalo" + }, + { + "type": "vcs", + "url": "https://github.com/fitzgen/bumpalo" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#bytemuck@1.25.0", + "author": "Lokathor ", + "name": "bytemuck", + "version": "1.25.0", + "description": "A crate for mucking around with piles of bytes.", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "c8efb64bd706a16a1bdde310ae86b351e4d21550d98d056f22f8a7f7a2183fec" + } + ], + "licenses": [ + { + "expression": "Zlib OR Apache-2.0 OR MIT" + } + ], + "purl": "pkg:cargo/bytemuck@1.25.0", + "externalReferences": [ + { + "type": "vcs", + "url": "https://github.com/Lokathor/bytemuck" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#bytemuck_derive@1.10.2", + "author": "Lokathor ", + "name": "bytemuck_derive", + "version": "1.10.2", + "description": "derive proc-macros for `bytemuck`", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "f9abbd1bc6865053c427f7198e6af43bfdedc55ab791faed4fbd361d789575ff" + } + ], + "licenses": [ + { + "expression": "Zlib OR Apache-2.0 OR MIT" + } + ], + "purl": "pkg:cargo/bytemuck_derive@1.10.2", + "externalReferences": [ + { + "type": "vcs", + "url": "https://github.com/Lokathor/bytemuck" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#byteorder-lite@0.1.0", + "name": "byteorder-lite", + "version": "0.1.0", + "description": "Library for reading/writing numbers in big-endian and little-endian.", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "8f1fe948ff07f4bd06c30984e69f5b4899c516a3ef74f34df92a2df2ab535495" + } + ], + "licenses": [ + { + "expression": "Unlicense OR MIT" + } + ], + "purl": "pkg:cargo/byteorder-lite@0.1.0", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/byteorder-lite" + }, + { + "type": "website", + "url": "https://github.com/image-rs/byteorder-lite" + }, + { + "type": "vcs", + "url": "https://github.com/image-rs/byteorder-lite" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#byteorder@1.5.0", + "author": "Andrew Gallant ", + "name": "byteorder", + "version": "1.5.0", + "description": "Library for reading/writing numbers in big-endian and little-endian.", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "1fd0f2584146f6f2ef48085050886acf353beff7305ebd1ae69500e27c67f64b" + } + ], + "licenses": [ + { + "expression": "Unlicense OR MIT" + } + ], + "purl": "pkg:cargo/byteorder@1.5.0", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/byteorder" + }, + { + "type": "website", + "url": "https://github.com/BurntSushi/byteorder" + }, + { + "type": "vcs", + "url": "https://github.com/BurntSushi/byteorder" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#bytes-utils@0.1.4", + "author": "Michal 'vorner' Vaner ", + "name": "bytes-utils", + "version": "0.1.4", + "description": "Additional utilities for working with the bytes crate", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "7dafe3a8757b027e2be6e4e5601ed563c55989fcf1546e933c66c8eb3a058d35" + } + ], + "licenses": [ + { + "expression": "Apache-2.0 OR MIT" + } + ], + "purl": "pkg:cargo/bytes-utils@0.1.4", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/bytes-utils" + }, + { + "type": "vcs", + "url": "https://github.com/vorner/bytes-utils" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#bytes@1.11.1", + "author": "Carl Lerche , Sean McArthur ", + "name": "bytes", + "version": "1.11.1", + "description": "Types and traits for working with bytes", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "1e748733b7cbc798e1434b6ac524f0c1ff2ab456fe201501e6497c8417a4fc33" + } + ], + "licenses": [ + { + "expression": "MIT" + } + ], + "purl": "pkg:cargo/bytes@1.11.1", + "externalReferences": [ + { + "type": "vcs", + "url": "https://github.com/tokio-rs/bytes" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#bzip2@0.6.1", + "name": "bzip2", + "version": "0.6.1", + "description": "Bindings to libbzip2 for bzip2 compression and decompression exposed as Reader/Writer streams. ", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "f3a53fac24f34a81bc9954b5d6cfce0c21e18ec6959f44f56e8e90e4bb7c346c" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/bzip2@0.6.1", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/bzip2" + }, + { + "type": "website", + "url": "https://github.com/trifectatechfoundation/bzip2-rs" + }, + { + "type": "vcs", + "url": "https://github.com/trifectatechfoundation/bzip2-rs" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#cassowary@0.3.0", + "author": "Dylan Ede ", + "name": "cassowary", + "version": "0.3.0", + "description": "A Rust implementation of the Cassowary linear constraint solving algorithm. The Cassowary algorithm is designed for naturally laying out user interfaces using linear constraints, like 'this button must line up with this text box'. ", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "df8670b8c7b9dae1793364eafadf7239c40d669904660c5960d74cfd80b46a53" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/cassowary@0.3.0", + "externalReferences": [ + { + "type": "documentation", + "url": "https://dylanede.github.io/cassowary-rs" + }, + { + "type": "website", + "url": "https://github.com/dylanede/cassowary-rs" + }, + { + "type": "vcs", + "url": "https://github.com/dylanede/cassowary-rs" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#cast@0.3.0", + "author": "Jorge Aparicio ", + "name": "cast", + "version": "0.3.0", + "description": "Ergonomic, checked cast functions for primitive types", + "scope": "excluded", + "hashes": [ + { + "alg": "SHA-256", + "content": "37b2a672a2cb129a2e41c10b1224bb368f9f37a2b16b612598138befd7b37eb5" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/cast@0.3.0", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/cast" + }, + { + "type": "vcs", + "url": "https://github.com/japaric/cast.rs" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#castaway@0.2.4", + "author": "Stephen M. Coakley ", + "name": "castaway", + "version": "0.2.4", + "description": "Safe, zero-cost downcasting for limited compile-time specialization.", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "dec551ab6e7578819132c713a93c022a05d60159dc86e7a7050223577484c55a" + } + ], + "licenses": [ + { + "expression": "MIT" + } + ], + "purl": "pkg:cargo/castaway@0.2.4", + "externalReferences": [ + { + "type": "vcs", + "url": "https://github.com/sagebind/castaway" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#cc@1.2.57", + "author": "Alex Crichton ", + "name": "cc", + "version": "1.2.57", + "description": "A build-time dependency for Cargo build scripts to assist in invoking the native C compiler to compile native C code into a static archive to be linked into Rust code. ", + "scope": "excluded", + "hashes": [ + { + "alg": "SHA-256", + "content": "7a0dd1ca384932ff3641c8718a02769f1698e7563dc6974ffd03346116310423" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/cc@1.2.57", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/cc" + }, + { + "type": "website", + "url": "https://github.com/rust-lang/cc-rs" + }, + { + "type": "vcs", + "url": "https://github.com/rust-lang/cc-rs" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#census@0.4.2", + "author": "Paul Masurel ", + "name": "census", + "version": "0.4.2", + "description": "Keeps an inventory of living objects", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "4f4c707c6a209cbe82d10abd08e1ea8995e9ea937d2550646e02798948992be0" + } + ], + "licenses": [ + { + "expression": "MIT" + } + ], + "purl": "pkg:cargo/census@0.4.2", + "externalReferences": [ + { + "type": "website", + "url": "https://github.com/quickwit-inc/census" + }, + { + "type": "vcs", + "url": "https://github.com/quickwit-inc/census" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#cfg-if@1.0.4", + "author": "Alex Crichton ", + "name": "cfg-if", + "version": "1.0.4", + "description": "A macro to ergonomically define an item depending on a large number of #[cfg] parameters. Structured like an if-else chain, the first matching branch is the item that gets emitted. ", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "9330f8b2ff13f34540b44e946ef35111825727b38d33286ef986142615121801" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/cfg-if@1.0.4", + "externalReferences": [ + { + "type": "vcs", + "url": "https://github.com/rust-lang/cfg-if" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#cfg_aliases@0.2.1", + "author": "Zicklag ", + "name": "cfg_aliases", + "version": "0.2.1", + "description": "A tiny utility to help save you a lot of effort with long winded `#[cfg()]` checks.", + "scope": "excluded", + "hashes": [ + { + "alg": "SHA-256", + "content": "613afe47fcd5fac7ccf1db93babcb082c5994d996f20b8b159f2ad1658eb5724" + } + ], + "licenses": [ + { + "expression": "MIT" + } + ], + "purl": "pkg:cargo/cfg_aliases@0.2.1", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/cfg_aliases" + }, + { + "type": "website", + "url": "https://github.com/katharostech/cfg_aliases" + }, + { + "type": "vcs", + "url": "https://github.com/katharostech/cfg_aliases" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#chacha20@0.10.0", + "author": "RustCrypto Developers", + "name": "chacha20", + "version": "0.10.0", + "description": "The ChaCha20 stream cipher (RFC 8439) implemented in pure Rust using traits from the RustCrypto `cipher` crate, with optional architecture-specific hardware acceleration (AVX2, SSE2). Additionally provides the ChaCha8, ChaCha12, XChaCha20, XChaCha12 and XChaCha8 stream ciphers, and also optional rand_core-compatible RNGs based on those ciphers. ", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "6f8d983286843e49675a4b7a2d174efe136dc93a18d69130dd18198a6c167601" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/chacha20@0.10.0", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/chacha20" + }, + { + "type": "vcs", + "url": "https://github.com/RustCrypto/stream-ciphers" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#chrono@0.4.44", + "name": "chrono", + "version": "0.4.44", + "description": "Date and time library for Rust", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "c673075a2e0e5f4a1dde27ce9dee1ea4558c7ffe648f576438a20ca1d2acc4b0" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/chrono@0.4.44", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/chrono/" + }, + { + "type": "website", + "url": "https://github.com/chronotope/chrono" + }, + { + "type": "vcs", + "url": "https://github.com/chronotope/chrono" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#ciborium-io@0.2.2", + "author": "Nathaniel McCallum ", + "name": "ciborium-io", + "version": "0.2.2", + "description": "Simplified Read/Write traits for no_std usage", + "scope": "excluded", + "hashes": [ + { + "alg": "SHA-256", + "content": "05afea1e0a06c9be33d539b876f1ce3692f4afea2cb41f740e7743225ed1c757" + } + ], + "licenses": [ + { + "expression": "Apache-2.0" + } + ], + "purl": "pkg:cargo/ciborium-io@0.2.2", + "externalReferences": [ + { + "type": "website", + "url": "https://github.com/enarx/ciborium" + }, + { + "type": "vcs", + "url": "https://github.com/enarx/ciborium" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#ciborium-ll@0.2.2", + "author": "Nathaniel McCallum ", + "name": "ciborium-ll", + "version": "0.2.2", + "description": "Low-level CBOR codec primitives", + "scope": "excluded", + "hashes": [ + { + "alg": "SHA-256", + "content": "57663b653d948a338bfb3eeba9bb2fd5fcfaecb9e199e87e1eda4d9e8b240fd9" + } + ], + "licenses": [ + { + "expression": "Apache-2.0" + } + ], + "purl": "pkg:cargo/ciborium-ll@0.2.2", + "externalReferences": [ + { + "type": "website", + "url": "https://github.com/enarx/ciborium" + }, + { + "type": "vcs", + "url": "https://github.com/enarx/ciborium" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#ciborium@0.2.2", + "author": "Nathaniel McCallum ", + "name": "ciborium", + "version": "0.2.2", + "description": "serde implementation of CBOR using ciborium-basic", + "scope": "excluded", + "hashes": [ + { + "alg": "SHA-256", + "content": "42e69ffd6f0917f5c029256a24d0161db17cea3997d185db0d35926308770f0e" + } + ], + "licenses": [ + { + "expression": "Apache-2.0" + } + ], + "purl": "pkg:cargo/ciborium@0.2.2", + "externalReferences": [ + { + "type": "website", + "url": "https://github.com/enarx/ciborium" + }, + { + "type": "vcs", + "url": "https://github.com/enarx/ciborium" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#cipher@0.4.4", + "author": "RustCrypto Developers", + "name": "cipher", + "version": "0.4.4", + "description": "Traits for describing block ciphers and stream ciphers", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "773f3b9af64447d2ce9850330c473515014aa235e6a783b02db81ff39e4a3dad" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/cipher@0.4.4", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/cipher" + }, + { + "type": "vcs", + "url": "https://github.com/RustCrypto/traits" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#clap@4.6.0", + "name": "clap", + "version": "4.6.0", + "description": "A simple to use, efficient, and full-featured Command Line Argument Parser", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "b193af5b67834b676abd72466a96c1024e6a6ad978a1f484bd90b85c94041351" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/clap@4.6.0", + "externalReferences": [ + { + "type": "vcs", + "url": "https://github.com/clap-rs/clap" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#clap_builder@4.6.0", + "name": "clap_builder", + "version": "4.6.0", + "description": "A simple to use, efficient, and full-featured Command Line Argument Parser", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "714a53001bf66416adb0e2ef5ac857140e7dc3a0c48fb28b2f10762fc4b5069f" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/clap_builder@4.6.0", + "externalReferences": [ + { + "type": "vcs", + "url": "https://github.com/clap-rs/clap" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#clap_derive@4.6.0", + "name": "clap_derive", + "version": "4.6.0", + "description": "Parse command line argument by defining a struct, derive crate.", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "1110bd8a634a1ab8cb04345d8d878267d57c3cf1b38d91b71af6686408bbca6a" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/clap_derive@4.6.0", + "externalReferences": [ + { + "type": "vcs", + "url": "https://github.com/clap-rs/clap" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#clap_lex@1.1.0", + "name": "clap_lex", + "version": "1.1.0", + "description": "Minimal, flexible command line parser", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "c8d4a3bb8b1e0c1050499d1815f5ab16d04f0959b233085fb31653fbfc9d98f9" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/clap_lex@1.1.0", + "externalReferences": [ + { + "type": "vcs", + "url": "https://github.com/clap-rs/clap" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#clipboard-win@5.4.1", + "author": "Douman ", + "name": "clipboard-win", + "version": "5.4.1", + "description": "Provides simple way to interact with Windows clipboard.", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "bde03770d3df201d4fb868f2c9c59e66a3e4e2bd06692a0fe701e7103c7e84d4" + } + ], + "licenses": [ + { + "expression": "BSL-1.0" + } + ], + "purl": "pkg:cargo/clipboard-win@5.4.1", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/crate/clipboard-win" + }, + { + "type": "vcs", + "url": "https://github.com/DoumanAsh/clipboard-win" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#cmake@0.1.57", + "author": "Alex Crichton ", + "name": "cmake", + "version": "0.1.57", + "description": "A build dependency for running `cmake` to build a native library ", + "scope": "excluded", + "hashes": [ + { + "alg": "SHA-256", + "content": "75443c44cd6b379beb8c5b45d85d0773baf31cce901fe7bb252f4eff3008ef7d" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/cmake@0.1.57", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/cmake" + }, + { + "type": "website", + "url": "https://github.com/rust-lang/cmake-rs" + }, + { + "type": "vcs", + "url": "https://github.com/rust-lang/cmake-rs" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#cmsketch@0.2.4", + "author": "MrCroxx ", + "name": "cmsketch", + "version": "0.2.4", + "description": "A count min sketch implementation in Rust", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "d7ee2cfacbd29706479902b06d75ad8f1362900836aa32799eabc7e004bfd854" + } + ], + "licenses": [ + { + "expression": "Apache-2.0" + } + ], + "purl": "pkg:cargo/cmsketch@0.2.4", + "externalReferences": [ + { + "type": "website", + "url": "https://github.com/mrcroxx/cmsketch-rs" + }, + { + "type": "vcs", + "url": "https://github.com/mrcroxx/cmsketch-rs" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#codespan-reporting@0.13.1", + "author": "Brendan Zabarauskas ", + "name": "codespan-reporting", + "version": "0.13.1", + "description": "Beautiful diagnostic reporting for text-based programming languages", + "scope": "excluded", + "hashes": [ + { + "alg": "SHA-256", + "content": "af491d569909a7e4dee0ad7db7f5341fef5c614d5b8ec8cf765732aba3cff681" + } + ], + "licenses": [ + { + "expression": "Apache-2.0" + } + ], + "purl": "pkg:cargo/codespan-reporting@0.13.1", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/codespan-reporting" + }, + { + "type": "website", + "url": "https://github.com/brendanzab/codespan" + }, + { + "type": "vcs", + "url": "https://github.com/brendanzab/codespan" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#colorchoice@1.0.5", + "name": "colorchoice", + "version": "1.0.5", + "description": "Global override of color control", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "1d07550c9036bf2ae0c684c4297d503f838287c83c53686d05370d0e139ae570" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/colorchoice@1.0.5", + "externalReferences": [ + { + "type": "vcs", + "url": "https://github.com/rust-cli/anstyle.git" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#colored@3.1.1", + "author": "Thomas Wickham ", + "name": "colored", + "version": "3.1.1", + "description": "The most simple way to add colors in your terminal", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "faf9468729b8cbcea668e36183cb69d317348c2e08e994829fb56ebfdfbaac34" + } + ], + "licenses": [ + { + "expression": "MPL-2.0" + } + ], + "purl": "pkg:cargo/colored@3.1.1", + "externalReferences": [ + { + "type": "website", + "url": "https://github.com/mackwic/colored" + }, + { + "type": "vcs", + "url": "https://github.com/mackwic/colored" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#compact_str@0.8.1", + "author": "Parker Timmerman ", + "name": "compact_str", + "version": "0.8.1", + "description": "A memory efficient string type that transparently stores strings on the stack, when possible", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "3b79c4069c6cad78e2e0cdfcbd26275770669fb39fd308a752dc110e83b9af32" + } + ], + "licenses": [ + { + "expression": "MIT" + } + ], + "purl": "pkg:cargo/compact_str@0.8.1", + "externalReferences": [ + { + "type": "website", + "url": "https://github.com/ParkMyCar/compact_str" + }, + { + "type": "vcs", + "url": "https://github.com/ParkMyCar/compact_str" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#concurrent-queue@2.5.0", + "author": "Stjepan Glavina , Taiki Endo , John Nunley ", + "name": "concurrent-queue", + "version": "2.5.0", + "description": "Concurrent multi-producer multi-consumer queue", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "4ca0197aee26d1ae37445ee532fefce43251d24cc7c166799f4d46817f1d3973" + } + ], + "licenses": [ + { + "expression": "Apache-2.0 OR MIT" + } + ], + "purl": "pkg:cargo/concurrent-queue@2.5.0", + "externalReferences": [ + { + "type": "vcs", + "url": "https://github.com/smol-rs/concurrent-queue" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#console@0.15.11", + "author": "Armin Ronacher ", + "name": "console", + "version": "0.15.11", + "description": "A terminal and console abstraction for Rust", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "054ccb5b10f9f2cbf51eb355ca1d05c2d279ce1804688d0db74b4733a5aeafd8" + } + ], + "licenses": [ + { + "expression": "MIT" + } + ], + "purl": "pkg:cargo/console@0.15.11", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/console" + }, + { + "type": "website", + "url": "https://github.com/console-rs/console" + }, + { + "type": "vcs", + "url": "https://github.com/console-rs/console" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#const-oid@0.9.6", + "author": "RustCrypto Developers", + "name": "const-oid", + "version": "0.9.6", + "description": "Const-friendly implementation of the ISO/IEC Object Identifier (OID) standard as defined in ITU X.660, with support for BER/DER encoding/decoding as well as heapless no_std (i.e. embedded) support ", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "c2459377285ad874054d797f3ccebf984978aa39129f6eafde5cdc8315b612f8" + } + ], + "licenses": [ + { + "expression": "Apache-2.0 OR MIT" + } + ], + "purl": "pkg:cargo/const-oid@0.9.6", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/const-oid" + }, + { + "type": "vcs", + "url": "https://github.com/RustCrypto/formats/tree/master/const-oid" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#const-random-macro@0.1.16", + "author": "Tom Kaitchuck ", + "name": "const-random-macro", + "version": "0.1.16", + "description": "Provides the procedural macro used by const-random", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "f9d839f2a20b0aee515dc581a6172f2321f96cab76c1a38a4c584a194955390e" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/const-random-macro@0.1.16", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/const-random" + }, + { + "type": "vcs", + "url": "https://github.com/tkaitchuck/constrandom" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#const-random@0.1.18", + "author": "Tom Kaitchuck ", + "name": "const-random", + "version": "0.1.18", + "description": "Provides compile time random number generation.", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "87e00182fe74b066627d63b85fd550ac2998d4b0bd86bfed477a0ae4c7c71359" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/const-random@0.1.18", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/const-random" + }, + { + "type": "vcs", + "url": "https://github.com/tkaitchuck/constrandom" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#constant_time_eq@0.4.2", + "author": "Cesar Eduardo Barros ", + "name": "constant_time_eq", + "version": "0.4.2", + "description": "Compares two equal-sized byte strings in constant time.", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "3d52eff69cd5e647efe296129160853a42795992097e8af39800e1060caeea9b" + } + ], + "licenses": [ + { + "expression": "CC0-1.0 OR MIT-0 OR Apache-2.0" + } + ], + "purl": "pkg:cargo/constant_time_eq@0.4.2", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/constant_time_eq" + }, + { + "type": "vcs", + "url": "https://github.com/cesarb/constant_time_eq" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#convert_case@0.10.0", + "author": "rutrum ", + "name": "convert_case", + "version": "0.10.0", + "description": "Convert strings into any case", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "633458d4ef8c78b72454de2d54fd6ab2e60f9e02be22f3c6104cdc8a4e0fceb9" + } + ], + "licenses": [ + { + "expression": "MIT" + } + ], + "purl": "pkg:cargo/convert_case@0.10.0", + "externalReferences": [ + { + "type": "vcs", + "url": "https://github.com/rutrum/convert-case" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#cpufeatures@0.2.17", + "author": "RustCrypto Developers", + "name": "cpufeatures", + "version": "0.2.17", + "description": "Lightweight runtime CPU feature detection for aarch64, loongarch64, and x86/x86_64 targets, with no_std support and support for mobile targets including Android and iOS ", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "59ed5838eebb26a2bb2e58f6d5b5316989ae9d08bab10e0e6d103e656d1b0280" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/cpufeatures@0.2.17", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/cpufeatures" + }, + { + "type": "vcs", + "url": "https://github.com/RustCrypto/utils" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#cpufeatures@0.3.0", + "author": "RustCrypto Developers", + "name": "cpufeatures", + "version": "0.3.0", + "description": "Lightweight runtime CPU feature detection for aarch64, loongarch64, and x86/x86_64 targets, with no_std support and support for mobile targets including Android and iOS ", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "8b2a41393f66f16b0823bb79094d54ac5fbd34ab292ddafb9a0456ac9f87d201" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/cpufeatures@0.3.0", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/cpufeatures" + }, + { + "type": "vcs", + "url": "https://github.com/RustCrypto/utils" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#crc-catalog@2.4.0", + "author": "Akhil Velagapudi ", + "name": "crc-catalog", + "version": "2.4.0", + "description": "Catalog of CRC algorithms (generated from http://reveng.sourceforge.net/crc-catalogue) expressed as simple Rust structs.", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "19d374276b40fb8bbdee95aef7c7fa6b5316ec764510eb64b8dd0e2ed0d7e7f5" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/crc-catalog@2.4.0", + "externalReferences": [ + { + "type": "vcs", + "url": "https://github.com/akhilles/crc-catalog.git" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#crc-fast@1.6.0", + "author": "Don MacAskill", + "name": "crc-fast", + "version": "1.6.0", + "description": "World's fastest generic CRC32 and CRC64 calculator using SIMD. Supplies a C-compatible shared library for use in other languages.", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "6ddc2d09feefeee8bd78101665bd8645637828fa9317f9f292496dbbd8c65ff3" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/crc-fast@1.6.0", + "externalReferences": [ + { + "type": "vcs", + "url": "https://github.com/awesomized/crc-fast-rust" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#crc32fast@1.5.0", + "author": "Sam Rijs , Alex Crichton ", + "name": "crc32fast", + "version": "1.5.0", + "description": "Fast, SIMD-accelerated CRC32 (IEEE) checksum computation", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "9481c1c90cbf2ac953f07c8d4a58aa3945c425b7185c9154d67a65e4230da511" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/crc32fast@1.5.0", + "externalReferences": [ + { + "type": "vcs", + "url": "https://github.com/srijs/rust-crc32fast" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#crc@3.4.0", + "author": "Rui Hu , Akhil Velagapudi <4@4khil.com>", + "name": "crc", + "version": "3.4.0", + "description": "Rust implementation of CRC with support of various standards", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "5eb8a2a1cd12ab0d987a5d5e825195d372001a4094a0376319d5a0ad71c1ba0d" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/crc@3.4.0", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/crc" + }, + { + "type": "vcs", + "url": "https://github.com/mrhooray/crc-rs.git" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#criterion-plot@0.6.0", + "author": "Jorge Aparicio , Brook Heisler ", + "name": "criterion-plot", + "version": "0.6.0", + "description": "Criterion's plotting library", + "scope": "excluded", + "hashes": [ + { + "alg": "SHA-256", + "content": "9b1bcc0dc7dfae599d84ad0b1a55f80cde8af3725da8313b528da95ef783e338" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/criterion-plot@0.6.0", + "externalReferences": [ + { + "type": "vcs", + "url": "https://github.com/bheisler/criterion.rs" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#criterion@0.7.0", + "author": "Jorge Aparicio , Brook Heisler ", + "name": "criterion", + "version": "0.7.0", + "description": "Statistics-driven micro-benchmarking library", + "scope": "excluded", + "hashes": [ + { + "alg": "SHA-256", + "content": "e1c047a62b0cc3e145fa84415a3191f628e980b194c2755aa12300a4e6cbd928" + } + ], + "licenses": [ + { + "expression": "Apache-2.0 OR MIT" + } + ], + "purl": "pkg:cargo/criterion@0.7.0", + "externalReferences": [ + { + "type": "website", + "url": "https://bheisler.github.io/criterion.rs/book/index.html" + }, + { + "type": "vcs", + "url": "https://github.com/bheisler/criterion.rs" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#crossbeam-channel@0.5.15", + "name": "crossbeam-channel", + "version": "0.5.15", + "description": "Multi-producer multi-consumer channels for message passing", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "82b8f8f868b36967f9606790d1903570de9ceaf870a7bf9fbbd3016d636a2cb2" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/crossbeam-channel@0.5.15", + "externalReferences": [ + { + "type": "website", + "url": "https://github.com/crossbeam-rs/crossbeam/tree/master/crossbeam-channel" + }, + { + "type": "vcs", + "url": "https://github.com/crossbeam-rs/crossbeam" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#crossbeam-deque@0.8.6", + "name": "crossbeam-deque", + "version": "0.8.6", + "description": "Concurrent work-stealing deque", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "9dd111b7b7f7d55b72c0a6ae361660ee5853c9af73f70c3c2ef6858b950e2e51" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/crossbeam-deque@0.8.6", + "externalReferences": [ + { + "type": "website", + "url": "https://github.com/crossbeam-rs/crossbeam/tree/master/crossbeam-deque" + }, + { + "type": "vcs", + "url": "https://github.com/crossbeam-rs/crossbeam" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#crossbeam-epoch@0.9.18", + "name": "crossbeam-epoch", + "version": "0.9.18", + "description": "Epoch-based garbage collection", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "5b82ac4a3c2ca9c3460964f020e1402edd5753411d7737aa39c3714ad1b5420e" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/crossbeam-epoch@0.9.18", + "externalReferences": [ + { + "type": "website", + "url": "https://github.com/crossbeam-rs/crossbeam/tree/master/crossbeam-epoch" + }, + { + "type": "vcs", + "url": "https://github.com/crossbeam-rs/crossbeam" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#crossbeam-queue@0.3.12", + "name": "crossbeam-queue", + "version": "0.3.12", + "description": "Concurrent queues", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "0f58bbc28f91df819d0aa2a2c00cd19754769c2fad90579b3592b1c9ba7a3115" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/crossbeam-queue@0.3.12", + "externalReferences": [ + { + "type": "website", + "url": "https://github.com/crossbeam-rs/crossbeam/tree/master/crossbeam-queue" + }, + { + "type": "vcs", + "url": "https://github.com/crossbeam-rs/crossbeam" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#crossbeam-utils@0.8.21", + "name": "crossbeam-utils", + "version": "0.8.21", + "description": "Utilities for concurrent programming", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "d0a5c400df2834b80a4c3327b3aad3a4c4cd4de0629063962b03235697506a28" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/crossbeam-utils@0.8.21", + "externalReferences": [ + { + "type": "website", + "url": "https://github.com/crossbeam-rs/crossbeam/tree/master/crossbeam-utils" + }, + { + "type": "vcs", + "url": "https://github.com/crossbeam-rs/crossbeam" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#crossterm@0.28.1", + "author": "T. Post", + "name": "crossterm", + "version": "0.28.1", + "description": "A crossplatform terminal library for manipulating terminals.", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "829d955a0bb380ef178a640b91779e3987da38c9aea133b20614cfed8cdea9c6" + } + ], + "licenses": [ + { + "expression": "MIT" + } + ], + "purl": "pkg:cargo/crossterm@0.28.1", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/crossterm/" + }, + { + "type": "vcs", + "url": "https://github.com/crossterm-rs/crossterm" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#crossterm@0.29.0", + "author": "T. Post", + "name": "crossterm", + "version": "0.29.0", + "description": "A crossplatform terminal library for manipulating terminals.", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "d8b9f2e4c67f833b660cdb0a3523065869fb35570177239812ed4c905aeff87b" + } + ], + "licenses": [ + { + "expression": "MIT" + } + ], + "purl": "pkg:cargo/crossterm@0.29.0", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/crossterm/" + }, + { + "type": "vcs", + "url": "https://github.com/crossterm-rs/crossterm" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#crossterm_winapi@0.9.1", + "author": "T. Post", + "name": "crossterm_winapi", + "version": "0.9.1", + "description": "WinAPI wrapper that provides some basic simple abstractions around common WinAPI calls", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "acdd7c62a3665c7f6830a51635d9ac9b23ed385797f70a83bb8bafe9c572ab2b" + } + ], + "licenses": [ + { + "expression": "MIT" + } + ], + "purl": "pkg:cargo/crossterm_winapi@0.9.1", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/crossterm_winapi/" + }, + { + "type": "vcs", + "url": "https://github.com/crossterm-rs/crossterm-winapi" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#crunchy@0.2.4", + "author": "Eira Fransham ", + "name": "crunchy", + "version": "0.2.4", + "description": "Crunchy unroller: deterministically unroll constant loops", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "460fbee9c2c2f33933d720630a6a0bac33ba7053db5344fac858d4b8952d77d5" + } + ], + "licenses": [ + { + "expression": "MIT" + } + ], + "purl": "pkg:cargo/crunchy@0.2.4", + "externalReferences": [ + { + "type": "website", + "url": "https://github.com/eira-fransham/crunchy" + }, + { + "type": "vcs", + "url": "https://github.com/eira-fransham/crunchy" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#crypto-bigint@0.4.9", + "author": "RustCrypto Developers", + "name": "crypto-bigint", + "version": "0.4.9", + "description": "Pure Rust implementation of a big integer library which has been designed from the ground-up for use in cryptographic applications. Provides constant-time, no_std-friendly implementations of modern formulas using const generics. ", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "ef2b4b23cddf68b89b8f8069890e8c270d54e2d5fe1b143820234805e4cb17ef" + } + ], + "licenses": [ + { + "expression": "Apache-2.0 OR MIT" + } + ], + "purl": "pkg:cargo/crypto-bigint@0.4.9", + "externalReferences": [ + { + "type": "vcs", + "url": "https://github.com/RustCrypto/crypto-bigint" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#crypto-bigint@0.5.5", + "author": "RustCrypto Developers", + "name": "crypto-bigint", + "version": "0.5.5", + "description": "Pure Rust implementation of a big integer library which has been designed from the ground-up for use in cryptographic applications. Provides constant-time, no_std-friendly implementations of modern formulas using const generics. ", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "0dc92fb57ca44df6db8059111ab3af99a63d5d0f8375d9972e319a379c6bab76" + } + ], + "licenses": [ + { + "expression": "Apache-2.0 OR MIT" + } + ], + "purl": "pkg:cargo/crypto-bigint@0.5.5", + "externalReferences": [ + { + "type": "vcs", + "url": "https://github.com/RustCrypto/crypto-bigint" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#crypto-common@0.1.7", + "author": "RustCrypto Developers", + "name": "crypto-common", + "version": "0.1.7", + "description": "Common cryptographic traits", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "78c8292055d1c1df0cce5d180393dc8cce0abec0a7102adb6c7b1eef6016d60a" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/crypto-common@0.1.7", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/crypto-common" + }, + { + "type": "vcs", + "url": "https://github.com/RustCrypto/traits" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#csv-core@0.1.13", + "author": "Andrew Gallant ", + "name": "csv-core", + "version": "0.1.13", + "description": "Bare bones CSV parsing with no_std support.", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "704a3c26996a80471189265814dbc2c257598b96b8a7feae2d31ace646bb9782" + } + ], + "licenses": [ + { + "expression": "Unlicense OR MIT" + } + ], + "purl": "pkg:cargo/csv-core@0.1.13", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/csv-core" + }, + { + "type": "website", + "url": "https://github.com/BurntSushi/rust-csv" + }, + { + "type": "vcs", + "url": "https://github.com/BurntSushi/rust-csv" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#csv@1.4.0", + "author": "Andrew Gallant ", + "name": "csv", + "version": "1.4.0", + "description": "Fast CSV parsing with support for serde.", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "52cd9d68cf7efc6ddfaaee42e7288d3a99d613d4b50f76ce9827ae0c6e14f938" + } + ], + "licenses": [ + { + "expression": "Unlicense OR MIT" + } + ], + "purl": "pkg:cargo/csv@1.4.0", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/csv" + }, + { + "type": "website", + "url": "https://github.com/BurntSushi/rust-csv" + }, + { + "type": "vcs", + "url": "https://github.com/BurntSushi/rust-csv" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#cxx-build@1.0.194", + "author": "David Tolnay ", + "name": "cxx-build", + "version": "1.0.194", + "description": "C++ code generator for integrating `cxx` crate into a Cargo build.", + "scope": "excluded", + "hashes": [ + { + "alg": "SHA-256", + "content": "b0f4697d190a142477b16aef7da8a99bfdc41e7e8b1687583c0d23a79c7afc1e" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/cxx-build@1.0.194", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/cxx-build" + }, + { + "type": "website", + "url": "https://cxx.rs" + }, + { + "type": "vcs", + "url": "https://github.com/dtolnay/cxx" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#cxx@1.0.194", + "author": "David Tolnay ", + "name": "cxx", + "version": "1.0.194", + "description": "Safe interop between Rust and C++", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "747d8437319e3a2f43d93b341c137927ca70c0f5dabeea7a005a73665e247c7e" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/cxx@1.0.194", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/cxx" + }, + { + "type": "website", + "url": "https://cxx.rs" + }, + { + "type": "other", + "url": "cxxbridge1" + }, + { + "type": "vcs", + "url": "https://github.com/dtolnay/cxx" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#cxxbridge-flags@1.0.194", + "author": "David Tolnay ", + "name": "cxxbridge-flags", + "version": "1.0.194", + "description": "Compiler configuration of the `cxx` crate (implementation detail)", + "scope": "excluded", + "hashes": [ + { + "alg": "SHA-256", + "content": "23384a836ab4f0ad98ace7e3955ad2de39de42378ab487dc28d3990392cb283a" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/cxxbridge-flags@1.0.194", + "externalReferences": [ + { + "type": "vcs", + "url": "https://github.com/dtolnay/cxx" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#cxxbridge-macro@1.0.194", + "author": "David Tolnay ", + "name": "cxxbridge-macro", + "version": "1.0.194", + "description": "Implementation detail of the `cxx` crate.", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "e6acc6b5822b9526adfb4fc377b67128fdd60aac757cc4a741a6278603f763cf" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/cxxbridge-macro@1.0.194", + "externalReferences": [ + { + "type": "website", + "url": "https://cxx.rs" + }, + { + "type": "vcs", + "url": "https://github.com/dtolnay/cxx" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#darling@0.20.11", + "author": "Ted Driggs ", + "name": "darling", + "version": "0.20.11", + "description": "A proc-macro library for reading attributes into structs when implementing custom derives. ", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "fc7f46116c46ff9ab3eb1597a45688b6715c6e628b5c133e288e709a29bcb4ee" + } + ], + "licenses": [ + { + "expression": "MIT" + } + ], + "purl": "pkg:cargo/darling@0.20.11", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/darling/0.20.11" + }, + { + "type": "vcs", + "url": "https://github.com/TedDriggs/darling" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#darling@0.23.0", + "author": "Ted Driggs ", + "name": "darling", + "version": "0.23.0", + "description": "A proc-macro library for reading attributes into structs when implementing custom derives. ", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "25ae13da2f202d56bd7f91c25fba009e7717a1e4a1cc98a76d844b65ae912e9d" + } + ], + "licenses": [ + { + "expression": "MIT" + } + ], + "purl": "pkg:cargo/darling@0.23.0", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/darling/0.23.0" + }, + { + "type": "vcs", + "url": "https://github.com/TedDriggs/darling" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#darling_core@0.20.11", + "author": "Ted Driggs ", + "name": "darling_core", + "version": "0.20.11", + "description": "Helper crate for proc-macro library for reading attributes into structs when implementing custom derives. Use https://crates.io/crates/darling in your code. ", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "0d00b9596d185e565c2207a0b01f8bd1a135483d02d9b7b0a54b11da8d53412e" + } + ], + "licenses": [ + { + "expression": "MIT" + } + ], + "purl": "pkg:cargo/darling_core@0.20.11", + "externalReferences": [ + { + "type": "vcs", + "url": "https://github.com/TedDriggs/darling" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#darling_core@0.23.0", + "author": "Ted Driggs ", + "name": "darling_core", + "version": "0.23.0", + "description": "Helper crate for proc-macro library for reading attributes into structs when implementing custom derives. Use https://crates.io/crates/darling in your code. ", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "9865a50f7c335f53564bb694ef660825eb8610e0a53d3e11bf1b0d3df31e03b0" + } + ], + "licenses": [ + { + "expression": "MIT" + } + ], + "purl": "pkg:cargo/darling_core@0.23.0", + "externalReferences": [ + { + "type": "vcs", + "url": "https://github.com/TedDriggs/darling" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#darling_macro@0.20.11", + "author": "Ted Driggs ", + "name": "darling_macro", + "version": "0.20.11", + "description": "Internal support for a proc-macro library for reading attributes into structs when implementing custom derives. Use https://crates.io/crates/darling in your code. ", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "fc34b93ccb385b40dc71c6fceac4b2ad23662c7eeb248cf10d529b7e055b6ead" + } + ], + "licenses": [ + { + "expression": "MIT" + } + ], + "purl": "pkg:cargo/darling_macro@0.20.11", + "externalReferences": [ + { + "type": "vcs", + "url": "https://github.com/TedDriggs/darling" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#darling_macro@0.23.0", + "author": "Ted Driggs ", + "name": "darling_macro", + "version": "0.23.0", + "description": "Internal support for a proc-macro library for reading attributes into structs when implementing custom derives. Use https://crates.io/crates/darling in your code. ", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "ac3984ec7bd6cfa798e62b4a642426a5be0e68f9401cfc2a01e3fa9ea2fcdb8d" + } + ], + "licenses": [ + { + "expression": "MIT" + } + ], + "purl": "pkg:cargo/darling_macro@0.23.0", + "externalReferences": [ + { + "type": "vcs", + "url": "https://github.com/TedDriggs/darling" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#dashmap@6.1.0", + "author": "Acrimon ", + "name": "dashmap", + "version": "6.1.0", + "description": "Blazing fast concurrent HashMap for Rust.", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "5041cc499144891f3790297212f32a74fb938e5136a14943f338ef9e0ae276cf" + } + ], + "licenses": [ + { + "expression": "MIT" + } + ], + "purl": "pkg:cargo/dashmap@6.1.0", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/dashmap" + }, + { + "type": "website", + "url": "https://github.com/xacrimon/dashmap" + }, + { + "type": "vcs", + "url": "https://github.com/xacrimon/dashmap" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#defer@0.2.1", + "author": "Andrew Hickman , Zakarum ", + "name": "defer", + "version": "0.2.1", + "description": "Utility to defer excecution of code, inspired by go's defer statement.", + "scope": "excluded", + "hashes": [ + { + "alg": "SHA-256", + "content": "930c7171c8df9fb1782bdf9b918ed9ed2d33d1d22300abb754f9085bc48bf8e8" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/defer@0.2.1", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/defer/" + }, + { + "type": "vcs", + "url": "https://github.com/andrewhickman/defer/" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#deflate64@0.1.11", + "author": "anatawa12 ", + "name": "deflate64", + "version": "0.1.11", + "description": "Deflate64 implementation based on .NET's implementation", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "807800ff3288b621186fe0a8f3392c4652068257302709c24efd918c3dffcdc2" + } + ], + "licenses": [ + { + "expression": "MIT" + } + ], + "purl": "pkg:cargo/deflate64@0.1.11", + "externalReferences": [ + { + "type": "website", + "url": "https://github.com/anatawa12/deflate64-rs#readme" + }, + { + "type": "vcs", + "url": "https://github.com/anatawa12/deflate64-rs" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#der@0.6.1", + "author": "RustCrypto Developers", + "name": "der", + "version": "0.6.1", + "description": "Pure Rust embedded-friendly implementation of the Distinguished Encoding Rules (DER) for Abstract Syntax Notation One (ASN.1) as described in ITU X.690 with full support for heapless no_std targets ", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "f1a467a65c5e759bce6e65eaf91cc29f466cdc57cb65777bd646872a8a1fd4de" + } + ], + "licenses": [ + { + "expression": "Apache-2.0 OR MIT" + } + ], + "purl": "pkg:cargo/der@0.6.1", + "externalReferences": [ + { + "type": "vcs", + "url": "https://github.com/RustCrypto/formats/tree/master/der" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#der@0.7.10", + "author": "RustCrypto Developers", + "name": "der", + "version": "0.7.10", + "description": "Pure Rust embedded-friendly implementation of the Distinguished Encoding Rules (DER) for Abstract Syntax Notation One (ASN.1) as described in ITU X.690 with full support for heapless no_std targets ", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "e7c1832837b905bbfb5101e07cc24c8deddf52f93225eee6ead5f4d63d53ddcb" + } + ], + "licenses": [ + { + "expression": "Apache-2.0 OR MIT" + } + ], + "purl": "pkg:cargo/der@0.7.10", + "externalReferences": [ + { + "type": "vcs", + "url": "https://github.com/RustCrypto/formats/tree/master/der" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#deranged@0.5.8", + "author": "Jacob Pratt ", + "name": "deranged", + "version": "0.5.8", + "description": "Ranged integers", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "7cd812cc2bc1d69d4764bd80df88b4317eaef9e773c75226407d9bc0876b211c" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/deranged@0.5.8", + "externalReferences": [ + { + "type": "vcs", + "url": "https://github.com/jhpratt/deranged" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#derivative@2.2.0", + "author": "mcarton ", + "name": "derivative", + "version": "2.2.0", + "description": "A set of alternative `derive` attributes for Rust", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "fcc3dd5e9e9c0b295d6e1e4d811fb6f157d5ffd784b8d202fc62eac8035a770b" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/derivative@2.2.0", + "externalReferences": [ + { + "type": "documentation", + "url": "https://mcarton.github.io/rust-derivative/" + }, + { + "type": "vcs", + "url": "https://github.com/mcarton/rust-derivative" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#derive_more-impl@2.1.1", + "author": "Jelte Fennema ", + "name": "derive_more-impl", + "version": "2.1.1", + "description": "Internal implementation of `derive_more` crate", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "799a97264921d8623a957f6c3b9011f3b5492f557bbb7a5a19b7fa6d06ba8dcb" + } + ], + "licenses": [ + { + "expression": "MIT" + } + ], + "purl": "pkg:cargo/derive_more-impl@2.1.1", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/derive_more" + }, + { + "type": "vcs", + "url": "https://github.com/JelteF/derive_more" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#derive_more@2.1.1", + "author": "Jelte Fennema ", + "name": "derive_more", + "version": "2.1.1", + "description": "Adds #[derive(x)] macros for more traits", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "d751e9e49156b02b44f9c1815bcb94b984cdcc4396ecc32521c739452808b134" + } + ], + "licenses": [ + { + "expression": "MIT" + } + ], + "purl": "pkg:cargo/derive_more@2.1.1", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/derive_more" + }, + { + "type": "vcs", + "url": "https://github.com/JelteF/derive_more" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#derive_utils@0.15.1", + "name": "derive_utils", + "version": "0.15.1", + "description": "A procedural macro helper for easily writing derive macros for enums. ", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "362f47930db19fe7735f527e6595e4900316b893ebf6d48ad3d31be928d57dd6" + } + ], + "licenses": [ + { + "expression": "Apache-2.0 OR MIT" + } + ], + "purl": "pkg:cargo/derive_utils@0.15.1", + "externalReferences": [ + { + "type": "vcs", + "url": "https://github.com/taiki-e/derive_utils" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#dialoguer@0.11.0", + "author": "Armin Ronacher , Pavan Kumar Sunkara ", + "name": "dialoguer", + "version": "0.11.0", + "description": "A command line prompting library.", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "658bce805d770f407bc62102fca7c2c64ceef2fbcb2b8bd19d2765ce093980de" + } + ], + "licenses": [ + { + "expression": "MIT" + } + ], + "purl": "pkg:cargo/dialoguer@0.11.0", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/dialoguer" + }, + { + "type": "website", + "url": "https://github.com/console-rs/dialoguer" + }, + { + "type": "vcs", + "url": "https://github.com/console-rs/dialoguer" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#digest@0.10.7", + "author": "RustCrypto Developers", + "name": "digest", + "version": "0.10.7", + "description": "Traits for cryptographic hash functions and message authentication codes", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/digest@0.10.7", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/digest" + }, + { + "type": "vcs", + "url": "https://github.com/RustCrypto/traits" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#dirs-sys@0.5.0", + "author": "Simon Ochsenreither ", + "name": "dirs-sys", + "version": "0.5.0", + "description": "System-level helper functions for the dirs and directories crates.", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "e01a3366d27ee9890022452ee61b2b63a67e6f13f58900b651ff5665f0bb1fab" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/dirs-sys@0.5.0", + "externalReferences": [ + { + "type": "vcs", + "url": "https://github.com/dirs-dev/dirs-sys-rs" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#dirs@6.0.0", + "author": "Simon Ochsenreither ", + "name": "dirs", + "version": "6.0.0", + "description": "A tiny low-level library that provides platform-specific standard locations of directories for config, cache and other data on Linux, Windows, macOS and Redox by leveraging the mechanisms defined by the XDG base/user directory specifications on Linux, the Known Folder API on Windows, and the Standard Directory guidelines on macOS.", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "c3e8aa94d75141228480295a7d0e7feb620b1a5ad9f12bc40be62411e38cce4e" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/dirs@6.0.0", + "externalReferences": [ + { + "type": "vcs", + "url": "https://github.com/soc/dirs-rs" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#displaydoc@0.2.5", + "author": "Jane Lusby ", + "name": "displaydoc", + "version": "0.2.5", + "description": "A derive macro for implementing the display Trait via a doc comment and string interpolation ", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "97369cbbc041bc366949bc74d34658d6cda5621039731c6310521892a3a20ae0" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/displaydoc@0.2.5", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/displaydoc" + }, + { + "type": "website", + "url": "https://github.com/yaahc/displaydoc" + }, + { + "type": "vcs", + "url": "https://github.com/yaahc/displaydoc" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#document-features@0.2.12", + "author": "Slint Developers ", + "name": "document-features", + "version": "0.2.12", + "description": "Extract documentation for the feature flags from comments in Cargo.toml", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "d4b8a88685455ed29a21542a33abd9cb6510b6b129abadabdcef0f4c55bc8f61" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/document-features@0.2.12", + "externalReferences": [ + { + "type": "website", + "url": "https://slint.rs" + }, + { + "type": "vcs", + "url": "https://github.com/slint-ui/document-features" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#dotenvy@0.15.7", + "author": "Noemi Lapresta , Craig Hills , Mike Piccolo , Alice Maz , Sean Griffin , Adam Sharp , Arpad Borsos , Allan Zhang ", + "name": "dotenvy", + "version": "0.15.7", + "description": "A well-maintained fork of the dotenv crate", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "1aaf95b3e5c8f23aa320147307562d361db0ae0d51242340f558153b4eb2439b" + } + ], + "licenses": [ + { + "expression": "MIT" + } + ], + "purl": "pkg:cargo/dotenvy@0.15.7", + "externalReferences": [ + { + "type": "website", + "url": "https://github.com/allan2/dotenvy" + }, + { + "type": "vcs", + "url": "https://github.com/allan2/dotenvy" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#downcast-rs@1.2.1", + "author": "Ashish Myles , Runji Wang ", + "name": "downcast-rs", + "version": "1.2.1", + "description": "Trait object downcasting support using only safe Rust. It supports type parameters, associated types, and type constraints. ", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "75b325c5dbd37f80359721ad39aca5a29fb04c89279657cffdda8736d0c0b9d2" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/downcast-rs@1.2.1", + "externalReferences": [ + { + "type": "vcs", + "url": "https://github.com/marcianx/downcast-rs" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#dunce@1.0.5", + "author": "Kornel ", + "name": "dunce", + "version": "1.0.5", + "description": "Normalize Windows paths to the most compatible format, avoiding UNC where possible", + "scope": "excluded", + "hashes": [ + { + "alg": "SHA-256", + "content": "92773504d58c093f6de2459af4af33faa518c13451eb8f2b5698ed3d36e7c813" + } + ], + "licenses": [ + { + "expression": "CC0-1.0 OR MIT-0 OR Apache-2.0" + } + ], + "purl": "pkg:cargo/dunce@1.0.5", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/dunce" + }, + { + "type": "website", + "url": "https://lib.rs/crates/dunce" + }, + { + "type": "vcs", + "url": "https://gitlab.com/kornelski/dunce" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#dyn-clone@1.0.20", + "author": "David Tolnay ", + "name": "dyn-clone", + "version": "1.0.20", + "description": "Clone trait that is dyn-compatible", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "d0881ea181b1df73ff77ffaaf9c7544ecc11e82fba9b5f27b262a3c73a332555" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/dyn-clone@1.0.20", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/dyn-clone" + }, + { + "type": "vcs", + "url": "https://github.com/dtolnay/dyn-clone" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#dyn-stack-macros@0.1.3", + "author": "sarah quiñones", + "name": "dyn-stack-macros", + "version": "0.1.3", + "description": "Dynamic stack wrapper for unsized allocations", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "e1d926b4d407d372f141f93bb444696142c29d32962ccbd3531117cf3aa0bfa9" + } + ], + "licenses": [ + { + "expression": "MIT" + } + ], + "purl": "pkg:cargo/dyn-stack-macros@0.1.3", + "externalReferences": [ + { + "type": "vcs", + "url": "https://github.com/kitegi/dynstack/" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#dyn-stack@0.13.2", + "author": "sarah <>", + "name": "dyn-stack", + "version": "0.13.2", + "description": "Dynamic stack wrapper for unsized allocations", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "1c4713e43e2886ba72b8271aa66c93d722116acf7a75555cce11dcde84388fe8" + } + ], + "licenses": [ + { + "expression": "MIT" + } + ], + "purl": "pkg:cargo/dyn-stack@0.13.2", + "externalReferences": [ + { + "type": "vcs", + "url": "https://codeberg.org/sarah-quinones/dyn-stack" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#ecdsa@0.14.8", + "author": "RustCrypto Developers", + "name": "ecdsa", + "version": "0.14.8", + "description": "Pure Rust implementation of the Elliptic Curve Digital Signature Algorithm (ECDSA) as specified in FIPS 186-4 (Digital Signature Standard), providing RFC6979 deterministic signatures as well as support for added entropy ", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "413301934810f597c1d19ca71c8710e99a3f1ba28a0d2ebc01551a2daeea3c5c" + } + ], + "licenses": [ + { + "expression": "Apache-2.0 OR MIT" + } + ], + "purl": "pkg:cargo/ecdsa@0.14.8", + "externalReferences": [ + { + "type": "vcs", + "url": "https://github.com/RustCrypto/signatures/tree/master/ecdsa" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#either@1.15.0", + "author": "bluss", + "name": "either", + "version": "1.15.0", + "description": "The enum `Either` with variants `Left` and `Right` is a general purpose sum type with two cases. ", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "48c757948c5ede0e46177b7add2e67155f70e33c07fea8284df6576da70b3719" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/either@1.15.0", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/either/1/" + }, + { + "type": "vcs", + "url": "https://github.com/rayon-rs/either" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#elliptic-curve@0.12.3", + "author": "RustCrypto Developers", + "name": "elliptic-curve", + "version": "0.12.3", + "description": "General purpose Elliptic Curve Cryptography (ECC) support, including types and traits for representing various elliptic curve forms, scalars, points, and public/secret keys composed thereof. ", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "e7bb888ab5300a19b8e5bceef25ac745ad065f3c9f7efc6de1b91958110891d3" + } + ], + "licenses": [ + { + "expression": "Apache-2.0 OR MIT" + } + ], + "purl": "pkg:cargo/elliptic-curve@0.12.3", + "externalReferences": [ + { + "type": "vcs", + "url": "https://github.com/RustCrypto/traits/tree/master/elliptic-curve" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#encode_unicode@1.0.0", + "author": "Torbjørn Birch Moltu ", + "name": "encode_unicode", + "version": "1.0.0", + "description": "UTF-8 and UTF-16 character types, iterators and related methods for char, u8 and u16. ", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "34aa73646ffb006b8f5147f3dc182bd4bcb190227ce861fc4a4844bf8e3cb2c0" + } + ], + "licenses": [ + { + "expression": "Apache-2.0 OR MIT" + } + ], + "purl": "pkg:cargo/encode_unicode@1.0.0", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/encode_unicode/" + }, + { + "type": "vcs", + "url": "https://github.com/tormol/encode_unicode" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#encoding_rs@0.8.35", + "author": "Henri Sivonen ", + "name": "encoding_rs", + "version": "0.8.35", + "description": "A Gecko-oriented implementation of the Encoding Standard", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "75030f3c4f45dafd7586dd6780965a8c7e8e285a5ecb86713e63a79c5b2766f3" + } + ], + "licenses": [ + { + "expression": "(Apache-2.0 OR MIT) AND BSD-3-Clause" + } + ], + "purl": "pkg:cargo/encoding_rs@0.8.35", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/encoding_rs/" + }, + { + "type": "website", + "url": "https://docs.rs/encoding_rs/" + }, + { + "type": "vcs", + "url": "https://github.com/hsivonen/encoding_rs" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#equator-macro@0.2.1", + "author": "sarah <>", + "name": "equator-macro", + "version": "0.2.1", + "description": "Composable assertion library", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "3bf679796c0322556351f287a51b49e48f7c4986e727b5dd78c972d30e2e16cc" + } + ], + "licenses": [ + { + "expression": "MIT" + } + ], + "purl": "pkg:cargo/equator-macro@0.2.1", + "externalReferences": [ + { + "type": "vcs", + "url": "https://github.com/sarah-ek/equator/" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#equator-macro@0.6.0", + "author": "sarah <>", + "name": "equator-macro", + "version": "0.6.0", + "description": "Composable assertion library", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "2b14b339eb76d07f052cdbad76ca7c1310e56173a138095d3bf42a23c06ef5d8" + } + ], + "licenses": [ + { + "expression": "MIT" + } + ], + "purl": "pkg:cargo/equator-macro@0.6.0", + "externalReferences": [ + { + "type": "vcs", + "url": "https://github.com/sarah-ek/equator/" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#equator@0.2.2", + "author": "sarah <>", + "name": "equator", + "version": "0.2.2", + "description": "Composable assertion library", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "c35da53b5a021d2484a7cc49b2ac7f2d840f8236a286f84202369bd338d761ea" + } + ], + "licenses": [ + { + "expression": "MIT" + } + ], + "purl": "pkg:cargo/equator@0.2.2", + "externalReferences": [ + { + "type": "vcs", + "url": "https://github.com/sarah-ek/equator/" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#equator@0.6.0", + "author": "sarah <>", + "name": "equator", + "version": "0.6.0", + "description": "Composable assertion library", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "02da895aab06bbebefb6b2595f6d637b18c9ff629b4cd840965bb3164e4194b0" + } + ], + "licenses": [ + { + "expression": "MIT" + } + ], + "purl": "pkg:cargo/equator@0.6.0", + "externalReferences": [ + { + "type": "vcs", + "url": "https://github.com/sarah-ek/equator/" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#equivalent@1.0.2", + "name": "equivalent", + "version": "1.0.2", + "description": "Traits for key comparison in maps.", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "877a4ace8713b0bcf2a4e7eec82529c029f1d0619886d18145fea96c3ffe5c0f" + } + ], + "licenses": [ + { + "expression": "Apache-2.0 OR MIT" + } + ], + "purl": "pkg:cargo/equivalent@1.0.2", + "externalReferences": [ + { + "type": "vcs", + "url": "https://github.com/indexmap-rs/equivalent" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#error-code@3.3.2", + "author": "Douman ", + "name": "error-code", + "version": "3.3.2", + "description": "Error code", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "dea2df4cf52843e0452895c455a1a2cfbb842a1e7329671acf418fdc53ed4c59" + } + ], + "licenses": [ + { + "expression": "BSL-1.0" + } + ], + "purl": "pkg:cargo/error-code@3.3.2", + "externalReferences": [ + { + "type": "vcs", + "url": "https://github.com/DoumanAsh/error-code" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#etcetera@0.8.0", + "name": "etcetera", + "version": "0.8.0", + "description": "An unopinionated library for obtaining configuration, data, cache, & other directories", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "136d1b5283a1ab77bd9257427ffd09d8667ced0570b6f938942bc7568ed5b943" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/etcetera@0.8.0", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/etcetera" + }, + { + "type": "website", + "url": "https://github.com/lunacookies/etcetera" + }, + { + "type": "vcs", + "url": "https://github.com/lunacookies/etcetera" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#event-listener@5.4.1", + "author": "Stjepan Glavina , John Nunley ", + "name": "event-listener", + "version": "5.4.1", + "description": "Notify async tasks or threads", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "e13b66accf52311f30a0db42147dadea9850cb48cd070028831ae5f5d4b856ab" + } + ], + "licenses": [ + { + "expression": "Apache-2.0 OR MIT" + } + ], + "purl": "pkg:cargo/event-listener@5.4.1", + "externalReferences": [ + { + "type": "vcs", + "url": "https://github.com/smol-rs/event-listener" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#faer-traits@0.24.0", + "author": "sarah quiñones ", + "name": "faer-traits", + "version": "0.24.0", + "description": "linear algebra library", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "b87d23ed7ab1f26c0cba0e5b9e061a796fbb7dc170fa8bee6970055a1308bb0f" + } + ], + "licenses": [ + { + "expression": "MIT" + } + ], + "purl": "pkg:cargo/faer-traits@0.24.0", + "externalReferences": [ + { + "type": "vcs", + "url": "https://codeberg.org/sarah-quinones/faer" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#faer@0.24.0", + "author": "sarah quiñones ", + "name": "faer", + "version": "0.24.0", + "description": "linear algebra library", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "02d2ecfb80b6f8b0c569e36988a052e64b14d8def9d372390b014e8bf79f299a" + } + ], + "licenses": [ + { + "expression": "MIT" + } + ], + "purl": "pkg:cargo/faer@0.24.0", + "externalReferences": [ + { + "type": "vcs", + "url": "https://codeberg.org/sarah-quinones/faer" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#failsafe@1.3.0", + "author": "Dmitry Galinsky ", + "name": "failsafe", + "version": "1.3.0", + "description": "A circuit breaker implementation", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "a6b1dc7c28e66a8f5dc32b7043b735e93d9eea8ea6e7be5507dae5850ab7ac70" + } + ], + "licenses": [ + { + "expression": "MIT" + } + ], + "purl": "pkg:cargo/failsafe@1.3.0", + "externalReferences": [ + { + "type": "vcs", + "url": "https://github.com/dmexe/failsafe-rs" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#fastant@0.1.11", + "name": "fastant", + "version": "0.1.11", + "description": "A drop-in replacement for `std::time::Instant` that measures time with high performance and high accuracy powered by Time Stamp Counter (TSC).", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "2e825441bfb2d831c47c97d05821552db8832479f44c571b97fededbf0099c07" + } + ], + "licenses": [ + { + "expression": "MIT" + } + ], + "purl": "pkg:cargo/fastant@0.1.11", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/fastant" + }, + { + "type": "website", + "url": "https://github.com/fast/fastant" + }, + { + "type": "vcs", + "url": "https://github.com/fast/fastant" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#fastbloom@0.17.0", + "author": "tomtomwombat", + "name": "fastbloom", + "version": "0.17.0", + "description": "The fastest Bloom filter in Rust. No accuracy compromises. Full concurrency support and compatible with any hasher.", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "ef975e30683b2d965054bb0a836f8973857c4ebf6acf274fe46617cd285060d8" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/fastbloom@0.17.0", + "externalReferences": [ + { + "type": "website", + "url": "https://github.com/tomtomwombat/fastbloom/" + }, + { + "type": "vcs", + "url": "https://github.com/tomtomwombat/fastbloom/" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#fastdivide@0.4.2", + "author": "Paul Masurel ", + "name": "fastdivide", + "version": "0.4.2", + "description": "Fastdivide is a partial port of libdivide. It makes it possible to reduce the cost of divisions.", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "9afc2bd4d5a73106dd53d10d73d3401c2f32730ba2c0b93ddb888a8983680471" + } + ], + "licenses": [ + { + "expression": "zlib-acknowledgement OR MIT" + } + ], + "purl": "pkg:cargo/fastdivide@0.4.2", + "externalReferences": [ + { + "type": "vcs", + "url": "https://github.com/fulmicoton/fastdivide" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#fastrace-macro@0.7.17", + "name": "fastrace-macro", + "version": "0.7.17", + "description": "Attribute procedural macro for fastrace", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "0b35f67e02527fca6515ff61f922360df781f477daf6a806fff16bd59525dee5" + } + ], + "licenses": [ + { + "expression": "Apache-2.0" + } + ], + "purl": "pkg:cargo/fastrace-macro@0.7.17", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/fastrace-macro" + }, + { + "type": "vcs", + "url": "https://github.com/fast/fastrace" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#fastrace-opentelemetry@0.8.1", + "name": "fastrace-opentelemetry", + "version": "0.8.1", + "description": "Opentelemetry reporter for fastrace", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "beef82b9b66d159544235a372fd723b86a436f19ea8a28cb58f292951055d3a9" + } + ], + "licenses": [ + { + "expression": "Apache-2.0" + } + ], + "purl": "pkg:cargo/fastrace-opentelemetry@0.8.1", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/fastrace-opentelemetry" + }, + { + "type": "vcs", + "url": "https://github.com/fast/fastrace" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#fastrace@0.7.8", + "name": "fastrace", + "version": "0.7.8", + "description": "A high-performance timeline tracing library for Rust", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "773324bb245e34a32d704c2256871377f9d7cdb4acff10c555e0dc068d6ddb55" + } + ], + "licenses": [ + { + "expression": "Apache-2.0" + } + ], + "purl": "pkg:cargo/fastrace@0.7.8", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/fastrace" + }, + { + "type": "vcs", + "url": "https://github.com/fast/fastrace" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#fastrand@2.3.0", + "author": "Stjepan Glavina ", + "name": "fastrand", + "version": "2.3.0", + "description": "A simple and fast random number generator", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "37909eebbb50d72f9059c3b6d82c0463f2ff062c9e95845c43a6c9c0355411be" + } + ], + "licenses": [ + { + "expression": "Apache-2.0 OR MIT" + } + ], + "purl": "pkg:cargo/fastrand@2.3.0", + "externalReferences": [ + { + "type": "vcs", + "url": "https://github.com/smol-rs/fastrand" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#fax@0.2.6", + "author": "Sebastian K ", + "name": "fax", + "version": "0.2.6", + "description": "Decoder and Encoder for CCITT Group 3 and 4 bi-level image encodings used by fax machines TIFF and PDF.", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "f05de7d48f37cd6730705cbca900770cab77a89f413d23e100ad7fad7795a0ab" + } + ], + "licenses": [ + { + "expression": "MIT" + } + ], + "purl": "pkg:cargo/fax@0.2.6", + "externalReferences": [ + { + "type": "vcs", + "url": "https://github.com/pdf-rs/fax" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#fax_derive@0.2.0", + "author": "Sebastian K ", + "name": "fax_derive", + "version": "0.2.0", + "description": "Bitstream matcher for the fax crate", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "a0aca10fb742cb43f9e7bb8467c91aa9bcb8e3ffbc6a6f7389bb93ffc920577d" + } + ], + "licenses": [ + { + "expression": "MIT" + } + ], + "purl": "pkg:cargo/fax_derive@0.2.0", + "externalReferences": [ + { + "type": "vcs", + "url": "https://github.com/pdf-rs/fax" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#fdeflate@0.3.7", + "author": "The image-rs Developers", + "name": "fdeflate", + "version": "0.3.7", + "description": "Fast specialized deflate implementation", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "1e6853b52649d4ac5c0bd02320cddc5ba956bdb407c4b75a2c6b75bf51500f8c" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/fdeflate@0.3.7", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/fdeflate" + }, + { + "type": "website", + "url": "https://github.com/image-rs/fdeflate" + }, + { + "type": "vcs", + "url": "https://github.com/image-rs/fdeflate" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#ff@0.12.1", + "author": "Sean Bowe , Jack Grigg ", + "name": "ff", + "version": "0.12.1", + "description": "Library for building and interfacing with finite fields", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "d013fc25338cc558c5c2cfbad646908fb23591e2404481826742b651c9af7160" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/ff@0.12.1", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/ff/" + }, + { + "type": "website", + "url": "https://github.com/zkcrypto/ff" + }, + { + "type": "vcs", + "url": "https://github.com/zkcrypto/ff" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#figment@0.10.19", + "author": "Sergio Benitez ", + "name": "figment", + "version": "0.10.19", + "description": "A configuration library so con-free, it's unreal.", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "8cb01cd46b0cf372153850f4c6c272d9cbea2da513e07538405148f95bd789f3" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/figment@0.10.19", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/figment/0.10" + }, + { + "type": "vcs", + "url": "https://github.com/SergioBenitez/Figment" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#find-msvc-tools@0.1.9", + "name": "find-msvc-tools", + "version": "0.1.9", + "description": "Find windows-specific tools, read MSVC versions from the registry and from COM interfaces", + "scope": "excluded", + "hashes": [ + { + "alg": "SHA-256", + "content": "5baebc0774151f905a1a2cc41989300b1e6fbb29aff0ceffa1064fdd3088d582" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/find-msvc-tools@0.1.9", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/find-msvc-tools" + }, + { + "type": "vcs", + "url": "https://github.com/rust-lang/cc-rs" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#fixedbitset@0.5.7", + "author": "bluss", + "name": "fixedbitset", + "version": "0.5.7", + "description": "FixedBitSet is a simple bitset collection", + "scope": "excluded", + "hashes": [ + { + "alg": "SHA-256", + "content": "1d674e81391d1e1ab681a28d99df07927c6d4aa5b027d7da16ba32d1d21ecd99" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/fixedbitset@0.5.7", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/fixedbitset/" + }, + { + "type": "vcs", + "url": "https://github.com/petgraph/fixedbitset" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#flatbuffers@25.12.19", + "author": "Robert Winslow , FlatBuffers Maintainers", + "name": "flatbuffers", + "version": "25.12.19", + "description": "Official FlatBuffers Rust runtime library.", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "35f6839d7b3b98adde531effaf34f0c2badc6f4735d26fe74709d8e513a96ef3" + } + ], + "licenses": [ + { + "expression": "Apache-2.0" + } + ], + "purl": "pkg:cargo/flatbuffers@25.12.19", + "externalReferences": [ + { + "type": "website", + "url": "https://google.github.io/flatbuffers/" + }, + { + "type": "vcs", + "url": "https://github.com/google/flatbuffers" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#flate2@1.1.9", + "author": "Alex Crichton , Josh Triplett ", + "name": "flate2", + "version": "1.1.9", + "description": "DEFLATE compression and decompression exposed as Read/BufRead/Write streams. Supports miniz_oxide and multiple zlib implementations. Supports zlib, gzip, and raw deflate streams. ", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "843fba2746e448b37e26a819579957415c8cef339bf08564fe8b7ddbd959573c" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/flate2@1.1.9", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/flate2" + }, + { + "type": "website", + "url": "https://github.com/rust-lang/flate2-rs" + }, + { + "type": "vcs", + "url": "https://github.com/rust-lang/flate2-rs" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#flume@0.11.1", + "author": "Joshua Barretto ", + "name": "flume", + "version": "0.11.1", + "description": "A blazingly fast multi-producer channel", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "da0e4dd2a88388a1f4ccc7c9ce104604dab68d9f408dc34cd45823d5a9069095" + } + ], + "licenses": [ + { + "expression": "Apache-2.0 OR MIT" + } + ], + "purl": "pkg:cargo/flume@0.11.1", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/flume" + }, + { + "type": "vcs", + "url": "https://github.com/zesterer/flume" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#fnv@1.0.7", + "author": "Alex Crichton ", + "name": "fnv", + "version": "1.0.7", + "description": "Fowler–Noll–Vo hash function", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "3f9eec918d3f24069decb9af1554cad7c880e2da24a9afd88aca000531ab82c1" + } + ], + "licenses": [ + { + "expression": "Apache-2.0 OR MIT" + } + ], + "purl": "pkg:cargo/fnv@1.0.7", + "externalReferences": [ + { + "type": "documentation", + "url": "https://doc.servo.org/fnv/" + }, + { + "type": "vcs", + "url": "https://github.com/servo/rust-fnv" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#foldhash@0.1.5", + "author": "Orson Peters ", + "name": "foldhash", + "version": "0.1.5", + "description": "A fast, non-cryptographic, minimally DoS-resistant hashing algorithm.", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "d9c4f5dac5e15c24eb999c26181a6ca40b39fe946cbe4c263c7209467bc83af2" + } + ], + "licenses": [ + { + "expression": "Zlib" + } + ], + "purl": "pkg:cargo/foldhash@0.1.5", + "externalReferences": [ + { + "type": "vcs", + "url": "https://github.com/orlp/foldhash" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#foldhash@0.2.0", + "author": "Orson Peters ", + "name": "foldhash", + "version": "0.2.0", + "description": "A fast, non-cryptographic, minimally DoS-resistant hashing algorithm.", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "77ce24cb58228fbb8aa041425bb1050850ac19177686ea6e0f41a70416f56fdb" + } + ], + "licenses": [ + { + "expression": "Zlib" + } + ], + "purl": "pkg:cargo/foldhash@0.2.0", + "externalReferences": [ + { + "type": "vcs", + "url": "https://github.com/orlp/foldhash" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#form_urlencoded@1.2.2", + "author": "The rust-url developers", + "name": "form_urlencoded", + "version": "1.2.2", + "description": "Parser and serializer for the application/x-www-form-urlencoded syntax, as used by HTML forms.", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "cb4cb245038516f5f85277875cdaa4f7d2c9a0fa0468de06ed190163b1581fcf" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/form_urlencoded@1.2.2", + "externalReferences": [ + { + "type": "vcs", + "url": "https://github.com/servo/rust-url" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#foyer-common@0.17.4", + "author": "MrCroxx ", + "name": "foyer-common", + "version": "0.17.4", + "description": "common components for foyer - Hybrid cache for Rust", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "dbf63fd16ba6227de0004472156048338ad7544280d1200c27e4b4a82ca6f075" + } + ], + "licenses": [ + { + "expression": "Apache-2.0" + } + ], + "purl": "pkg:cargo/foyer-common@0.17.4", + "externalReferences": [ + { + "type": "website", + "url": "https://foyer.rs" + }, + { + "type": "vcs", + "url": "https://github.com/foyer-rs/foyer" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#foyer-intrusive-collections@0.10.0-dev", + "author": "Amanieu d'Antras ", + "name": "foyer-intrusive-collections", + "version": "0.10.0-dev", + "description": "Intrusive collections for Rust (linked list and red-black tree)", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "6e4fee46bea69e0596130e3210e65d3424e0ac1e6df3bde6636304bdf1ca4a3b" + } + ], + "licenses": [ + { + "expression": "Apache-2.0 OR MIT" + } + ], + "purl": "pkg:cargo/foyer-intrusive-collections@0.10.0-dev", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/foyer-intrusive-collections" + }, + { + "type": "vcs", + "url": "https://github.com/foyer-rs/intrusive-rs" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#foyer-memory@0.17.4", + "author": "MrCroxx ", + "name": "foyer-memory", + "version": "0.17.4", + "description": "memory cache for foyer - Hybrid cache for Rust", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "3ae8a1c8e263f91cf3abca38bbf6b8f82f34b6cf20fa3a249c90ebfa795e5631" + } + ], + "licenses": [ + { + "expression": "Apache-2.0" + } + ], + "purl": "pkg:cargo/foyer-memory@0.17.4", + "externalReferences": [ + { + "type": "website", + "url": "https://foyer.rs" + }, + { + "type": "vcs", + "url": "https://github.com/foyer-rs/foyer" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#foyer-storage@0.17.4", + "author": "MrCroxx ", + "name": "foyer-storage", + "version": "0.17.4", + "description": "storage engine for foyer - Hybrid cache for Rust", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "d387ab178f8bcb03fe4981766c9f436007234d8ca73080e3ad2c370d8d75113b" + } + ], + "licenses": [ + { + "expression": "Apache-2.0" + } + ], + "purl": "pkg:cargo/foyer-storage@0.17.4", + "externalReferences": [ + { + "type": "website", + "url": "https://foyer.rs" + }, + { + "type": "vcs", + "url": "https://github.com/foyer-rs/foyer" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#foyer@0.17.4", + "author": "MrCroxx ", + "name": "foyer", + "version": "0.17.4", + "description": "foyer - Hybrid cache for Rust", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "0618db36554a0a5db538d7ff04427571b1f668d3e86a764aabe17985c02ea14c" + } + ], + "licenses": [ + { + "expression": "Apache-2.0" + } + ], + "purl": "pkg:cargo/foyer@0.17.4", + "externalReferences": [ + { + "type": "website", + "url": "https://foyer.rs" + }, + { + "type": "vcs", + "url": "https://github.com/foyer-rs/foyer" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#fs4@0.13.1", + "author": "Dan Burkert , Al Liu ", + "name": "fs4", + "version": "0.13.1", + "description": "No libc, pure Rust cross-platform file locks. Original fs2, now supports async and replace libc by rustix.", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "8640e34b88f7652208ce9e88b1a37a2ae95227d84abec377ccd3c5cfeb141ed4" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/fs4@0.13.1", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/fs4" + }, + { + "type": "vcs", + "url": "https://github.com/al8n/fs4-rs" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#fs4@0.8.4", + "author": "Dan Burkert , Al Liu ", + "name": "fs4", + "version": "0.8.4", + "description": "No libc, pure Rust cross-platform file locks. Original fs2, now supports async and replace libc by rustix.", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "f7e180ac76c23b45e767bd7ae9579bc0bb458618c4bc71835926e098e61d15f8" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/fs4@0.8.4", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/fs4" + }, + { + "type": "vcs", + "url": "https://github.com/al8n/fs4-rs" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#fs_extra@1.3.0", + "author": "Denis Kurilenko ", + "name": "fs_extra", + "version": "1.3.0", + "description": "Expanding std::fs and std::io. Recursively copy folders with information about process and much more.", + "scope": "excluded", + "hashes": [ + { + "alg": "SHA-256", + "content": "42703706b716c37f96a77aea830392ad231f44c9e9a67872fa5548707e11b11c" + } + ], + "licenses": [ + { + "expression": "MIT" + } + ], + "purl": "pkg:cargo/fs_extra@1.3.0", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/fs_extra" + }, + { + "type": "website", + "url": "https://github.com/webdesus/fs_extra" + }, + { + "type": "vcs", + "url": "https://github.com/webdesus/fs_extra" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#funty@2.0.0", + "author": "myrrlyn ", + "name": "funty", + "version": "2.0.0", + "description": "Trait generalization over the primitive types", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "e6d5a32815ae3f33302d95fdcb2ce17862f8c65363dcfd29360480ba1001fc9c" + } + ], + "licenses": [ + { + "expression": "MIT" + } + ], + "purl": "pkg:cargo/funty@2.0.0", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/funty" + }, + { + "type": "vcs", + "url": "https://github.com/myrrlyn/funty" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#futures-channel@0.3.32", + "name": "futures-channel", + "version": "0.3.32", + "description": "Channels for asynchronous communication using futures-rs. ", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "07bbe89c50d7a535e539b8c17bc0b49bdb77747034daa8087407d655f3f7cc1d" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/futures-channel@0.3.32", + "externalReferences": [ + { + "type": "website", + "url": "https://rust-lang.github.io/futures-rs" + }, + { + "type": "vcs", + "url": "https://github.com/rust-lang/futures-rs" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#futures-core@0.3.32", + "name": "futures-core", + "version": "0.3.32", + "description": "The core traits and types in for the `futures` library. ", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "7e3450815272ef58cec6d564423f6e755e25379b217b0bc688e295ba24df6b1d" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/futures-core@0.3.32", + "externalReferences": [ + { + "type": "website", + "url": "https://rust-lang.github.io/futures-rs" + }, + { + "type": "vcs", + "url": "https://github.com/rust-lang/futures-rs" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#futures-executor@0.3.32", + "name": "futures-executor", + "version": "0.3.32", + "description": "Executors for asynchronous tasks based on the futures-rs library. ", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "baf29c38818342a3b26b5b923639e7b1f4a61fc5e76102d4b1981c6dc7a7579d" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/futures-executor@0.3.32", + "externalReferences": [ + { + "type": "website", + "url": "https://rust-lang.github.io/futures-rs" + }, + { + "type": "vcs", + "url": "https://github.com/rust-lang/futures-rs" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#futures-intrusive@0.5.0", + "author": "Matthias Einwag ", + "name": "futures-intrusive", + "version": "0.5.0", + "description": "Futures based on intrusive data structures - for std and no-std environments. ", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "1d930c203dd0b6ff06e0201a4a2fe9149b43c684fd4420555b26d21b1a02956f" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/futures-intrusive@0.5.0", + "externalReferences": [ + { + "type": "website", + "url": "https://github.com/Matthias247/futures-intrusive" + }, + { + "type": "vcs", + "url": "https://github.com/Matthias247/futures-intrusive" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#futures-io@0.3.32", + "name": "futures-io", + "version": "0.3.32", + "description": "The `AsyncRead`, `AsyncWrite`, `AsyncSeek`, and `AsyncBufRead` traits for the futures-rs library. ", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "cecba35d7ad927e23624b22ad55235f2239cfa44fd10428eecbeba6d6a717718" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/futures-io@0.3.32", + "externalReferences": [ + { + "type": "website", + "url": "https://rust-lang.github.io/futures-rs" + }, + { + "type": "vcs", + "url": "https://github.com/rust-lang/futures-rs" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#futures-macro@0.3.32", + "name": "futures-macro", + "version": "0.3.32", + "description": "The futures-rs procedural macro implementations. ", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "e835b70203e41293343137df5c0664546da5745f82ec9b84d40be8336958447b" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/futures-macro@0.3.32", + "externalReferences": [ + { + "type": "website", + "url": "https://rust-lang.github.io/futures-rs" + }, + { + "type": "vcs", + "url": "https://github.com/rust-lang/futures-rs" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#futures-sink@0.3.32", + "name": "futures-sink", + "version": "0.3.32", + "description": "The asynchronous `Sink` trait for the futures-rs library. ", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "c39754e157331b013978ec91992bde1ac089843443c49cbc7f46150b0fad0893" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/futures-sink@0.3.32", + "externalReferences": [ + { + "type": "website", + "url": "https://rust-lang.github.io/futures-rs" + }, + { + "type": "vcs", + "url": "https://github.com/rust-lang/futures-rs" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#futures-task@0.3.32", + "name": "futures-task", + "version": "0.3.32", + "description": "Tools for working with tasks. ", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "037711b3d59c33004d3856fbdc83b99d4ff37a24768fa1be9ce3538a1cde4393" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/futures-task@0.3.32", + "externalReferences": [ + { + "type": "website", + "url": "https://rust-lang.github.io/futures-rs" + }, + { + "type": "vcs", + "url": "https://github.com/rust-lang/futures-rs" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#futures-util@0.3.32", + "name": "futures-util", + "version": "0.3.32", + "description": "Common utilities and extension traits for the futures-rs library. ", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "389ca41296e6190b48053de0321d02a77f32f8a5d2461dd38762c0593805c6d6" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/futures-util@0.3.32", + "externalReferences": [ + { + "type": "website", + "url": "https://rust-lang.github.io/futures-rs" + }, + { + "type": "vcs", + "url": "https://github.com/rust-lang/futures-rs" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#futures@0.3.32", + "name": "futures", + "version": "0.3.32", + "description": "An implementation of futures and streams featuring zero allocations, composability, and iterator-like interfaces. ", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "8b147ee9d1f6d097cef9ce628cd2ee62288d963e16fb287bd9286455b241382d" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/futures@0.3.32", + "externalReferences": [ + { + "type": "website", + "url": "https://rust-lang.github.io/futures-rs" + }, + { + "type": "vcs", + "url": "https://github.com/rust-lang/futures-rs" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#gemm-c32@0.19.0", + "author": "sarah <>", + "name": "gemm-c32", + "version": "0.19.0", + "description": "Playground for matrix multiplication algorithms", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "086936dbdcb99e37aad81d320f98f670e53c1e55a98bee70573e83f95beb128c" + } + ], + "licenses": [ + { + "expression": "MIT" + } + ], + "purl": "pkg:cargo/gemm-c32@0.19.0", + "externalReferences": [ + { + "type": "vcs", + "url": "https://github.com/sarah-ek/gemm/" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#gemm-c64@0.19.0", + "author": "sarah <>", + "name": "gemm-c64", + "version": "0.19.0", + "description": "Playground for matrix multiplication algorithms", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "20c8aeeeec425959bda4d9827664029ba1501a90a0d1e6228e48bef741db3a3f" + } + ], + "licenses": [ + { + "expression": "MIT" + } + ], + "purl": "pkg:cargo/gemm-c64@0.19.0", + "externalReferences": [ + { + "type": "vcs", + "url": "https://github.com/sarah-ek/gemm/" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#gemm-common@0.19.0", + "author": "sarah <>", + "name": "gemm-common", + "version": "0.19.0", + "description": "Playground for matrix multiplication algorithms", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "88027625910cc9b1085aaaa1c4bc46bb3a36aad323452b33c25b5e4e7c8e2a3e" + } + ], + "licenses": [ + { + "expression": "MIT" + } + ], + "purl": "pkg:cargo/gemm-common@0.19.0", + "externalReferences": [ + { + "type": "vcs", + "url": "https://github.com/sarah-ek/gemm/" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#gemm-f16@0.19.0", + "author": "sarah <>", + "name": "gemm-f16", + "version": "0.19.0", + "description": "Playground for matrix multiplication algorithms", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "e3df7a55202e6cd6739d82ae3399c8e0c7e1402859b30e4cb780e61525d9486e" + } + ], + "licenses": [ + { + "expression": "MIT" + } + ], + "purl": "pkg:cargo/gemm-f16@0.19.0", + "externalReferences": [ + { + "type": "vcs", + "url": "https://github.com/sarah-ek/gemm/" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#gemm-f32@0.19.0", + "author": "sarah <>", + "name": "gemm-f32", + "version": "0.19.0", + "description": "Playground for matrix multiplication algorithms", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "02e0b8c9da1fbec6e3e3ab2ce6bc259ef18eb5f6f0d3e4edf54b75f9fd41a81c" + } + ], + "licenses": [ + { + "expression": "MIT" + } + ], + "purl": "pkg:cargo/gemm-f32@0.19.0", + "externalReferences": [ + { + "type": "vcs", + "url": "https://github.com/sarah-ek/gemm/" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#gemm-f64@0.19.0", + "author": "sarah <>", + "name": "gemm-f64", + "version": "0.19.0", + "description": "Playground for matrix multiplication algorithms", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "056131e8f2a521bfab322f804ccd652520c79700d81209e9d9275bbdecaadc6a" + } + ], + "licenses": [ + { + "expression": "MIT" + } + ], + "purl": "pkg:cargo/gemm-f64@0.19.0", + "externalReferences": [ + { + "type": "vcs", + "url": "https://github.com/sarah-ek/gemm/" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#gemm@0.19.0", + "author": "sarah <>", + "name": "gemm", + "version": "0.19.0", + "description": "Playground for matrix multiplication algorithms", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "aa0673db364b12263d103b68337a68fbecc541d6f6b61ba72fe438654709eacb" + } + ], + "licenses": [ + { + "expression": "MIT" + } + ], + "purl": "pkg:cargo/gemm@0.19.0", + "externalReferences": [ + { + "type": "vcs", + "url": "https://github.com/sarah-ek/gemm/" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#generativity@1.1.0", + "name": "generativity", + "version": "1.1.0", + "description": "Generation of unique invariant lifetimes", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "5881e4c3c2433fe4905bb19cfd2b5d49d4248274862b68c27c33d9ba4e13f9ec" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/generativity@1.1.0", + "externalReferences": [ + { + "type": "vcs", + "url": "https://github.com/CAD97/generativity" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#generator@0.8.8", + "author": "Xudong Huang ", + "name": "generator", + "version": "0.8.8", + "description": "Stackfull Generator Library in Rust", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "52f04ae4152da20c76fe800fa48659201d5cf627c5149ca0b707b69d7eef6cf9" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/generator@0.8.8", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/generator" + }, + { + "type": "website", + "url": "https://github.com/Xudong-Huang/generator-rs.git" + }, + { + "type": "vcs", + "url": "https://github.com/Xudong-Huang/generator-rs.git" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#generic-array@0.14.7", + "author": "Bartłomiej Kamiński , Aaron Trent ", + "name": "generic-array", + "version": "0.14.7", + "description": "Generic types implementing functionality of arrays", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "85649ca51fd72272d7821adaf274ad91c288277713d9c18820d8499a7ff69e9a" + } + ], + "licenses": [ + { + "expression": "MIT" + } + ], + "purl": "pkg:cargo/generic-array@0.14.7", + "externalReferences": [ + { + "type": "documentation", + "url": "http://fizyk20.github.io/generic-array/generic_array/" + }, + { + "type": "vcs", + "url": "https://github.com/fizyk20/generic-array.git" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#getrandom@0.2.17", + "author": "The Rand Project Developers", + "name": "getrandom", + "version": "0.2.17", + "description": "A small cross-platform library for retrieving random data from system source", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "ff2abc00be7fca6ebc474524697ae276ad847ad0a6b3faa4bcb027e9a4614ad0" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/getrandom@0.2.17", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/getrandom" + }, + { + "type": "vcs", + "url": "https://github.com/rust-random/getrandom" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#getrandom@0.3.4", + "author": "The Rand Project Developers", + "name": "getrandom", + "version": "0.3.4", + "description": "A small cross-platform library for retrieving random data from system source", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "899def5c37c4fd7b2664648c28120ecec138e4d395b459e5ca34f9cce2dd77fd" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/getrandom@0.3.4", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/getrandom" + }, + { + "type": "vcs", + "url": "https://github.com/rust-random/getrandom" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#getrandom@0.4.2", + "author": "The Rand Project Developers", + "name": "getrandom", + "version": "0.4.2", + "description": "A small cross-platform library for retrieving random data from system source", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "0de51e6874e94e7bf76d726fc5d13ba782deca734ff60d5bb2fb2607c7406555" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/getrandom@0.4.2", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/getrandom" + }, + { + "type": "vcs", + "url": "https://github.com/rust-random/getrandom" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#glob@0.3.3", + "author": "The Rust Project Developers", + "name": "glob", + "version": "0.3.3", + "description": "Support for matching file paths against Unix shell style patterns. ", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "0cc23270f6e1808e30a928bdc84dea0b9b4136a8bc82338574f23baf47bbd280" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/glob@0.3.3", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/glob" + }, + { + "type": "website", + "url": "https://github.com/rust-lang/glob" + }, + { + "type": "vcs", + "url": "https://github.com/rust-lang/glob" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#globset@0.4.18", + "author": "Andrew Gallant ", + "name": "globset", + "version": "0.4.18", + "description": "Cross platform single glob and glob set matching. Glob set matching is the process of matching one or more glob patterns against a single candidate path simultaneously, and returning all of the globs that matched. ", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "52dfc19153a48bde0cbd630453615c8151bce3a5adfac7a0aebfbf0a1e1f57e3" + } + ], + "licenses": [ + { + "expression": "Unlicense OR MIT" + } + ], + "purl": "pkg:cargo/globset@0.4.18", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/globset" + }, + { + "type": "website", + "url": "https://github.com/BurntSushi/ripgrep/tree/master/crates/globset" + }, + { + "type": "vcs", + "url": "https://github.com/BurntSushi/ripgrep/tree/master/crates/globset" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#group@0.12.1", + "author": "Sean Bowe , Jack Grigg ", + "name": "group", + "version": "0.12.1", + "description": "Elliptic curve group traits and utilities", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "5dfbfb3a6cfbd390d5c9564ab283a0349b9b9fcd46a706c1eb10e0db70bfbac7" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/group@0.12.1", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/group/" + }, + { + "type": "website", + "url": "https://github.com/zkcrypto/group" + }, + { + "type": "vcs", + "url": "https://github.com/zkcrypto/group" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#h2@0.3.27", + "author": "Carl Lerche , Sean McArthur ", + "name": "h2", + "version": "0.3.27", + "description": "An HTTP/2 client and server", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "0beca50380b1fc32983fc1cb4587bfa4bb9e78fc259aad4a0032d2080309222d" + } + ], + "licenses": [ + { + "expression": "MIT" + } + ], + "purl": "pkg:cargo/h2@0.3.27", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/h2" + }, + { + "type": "vcs", + "url": "https://github.com/hyperium/h2" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#h2@0.4.13", + "author": "Carl Lerche , Sean McArthur ", + "name": "h2", + "version": "0.4.13", + "description": "An HTTP/2 client and server", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "2f44da3a8150a6703ed5d34e164b875fd14c2cdab9af1252a9a1020bde2bdc54" + } + ], + "licenses": [ + { + "expression": "MIT" + } + ], + "purl": "pkg:cargo/h2@0.4.13", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/h2" + }, + { + "type": "vcs", + "url": "https://github.com/hyperium/h2" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#half@2.7.1", + "author": "Kathryn Long ", + "name": "half", + "version": "2.7.1", + "description": "Half-precision floating point f16 and bf16 types for Rust implementing the IEEE 754-2008 standard binary16 and bfloat16 types.", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "6ea2d84b969582b4b1864a92dc5d27cd2b77b622a8d79306834f1be5ba20d84b" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/half@2.7.1", + "externalReferences": [ + { + "type": "vcs", + "url": "https://github.com/VoidStarKat/half-rs" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#hashbrown@0.12.3", + "author": "Amanieu d'Antras ", + "name": "hashbrown", + "version": "0.12.3", + "description": "A Rust port of Google's SwissTable hash map", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "8a9ee70c43aaf417c914396645a0fa852624801b24ebb7ae78fe8272889ac888" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/hashbrown@0.12.3", + "externalReferences": [ + { + "type": "vcs", + "url": "https://github.com/rust-lang/hashbrown" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#hashbrown@0.13.2", + "author": "Amanieu d'Antras ", + "name": "hashbrown", + "version": "0.13.2", + "description": "A Rust port of Google's SwissTable hash map", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "43a3c133739dddd0d2990f9a4bdf8eb4b21ef50e4851ca85ab661199821d510e" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/hashbrown@0.13.2", + "externalReferences": [ + { + "type": "vcs", + "url": "https://github.com/rust-lang/hashbrown" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#hashbrown@0.14.5", + "author": "Amanieu d'Antras ", + "name": "hashbrown", + "version": "0.14.5", + "description": "A Rust port of Google's SwissTable hash map", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "e5274423e17b7c9fc20b6e7e208532f9b19825d82dfd615708b70edd83df41f1" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/hashbrown@0.14.5", + "externalReferences": [ + { + "type": "vcs", + "url": "https://github.com/rust-lang/hashbrown" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#hashbrown@0.15.5", + "author": "Amanieu d'Antras ", + "name": "hashbrown", + "version": "0.15.5", + "description": "A Rust port of Google's SwissTable hash map", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "9229cfe53dfd69f0609a49f65461bd93001ea1ef889cd5529dd176593f5338a1" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/hashbrown@0.15.5", + "externalReferences": [ + { + "type": "vcs", + "url": "https://github.com/rust-lang/hashbrown" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#hashbrown@0.16.1", + "author": "Amanieu d'Antras ", + "name": "hashbrown", + "version": "0.16.1", + "description": "A Rust port of Google's SwissTable hash map", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "841d1cc9bed7f9236f321df977030373f4a4163ae1a7dbfe1a51a2c1a51d9100" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/hashbrown@0.16.1", + "externalReferences": [ + { + "type": "vcs", + "url": "https://github.com/rust-lang/hashbrown" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#hashlink@0.10.0", + "author": "kyren ", + "name": "hashlink", + "version": "0.10.0", + "description": "HashMap-like containers that hold their key-value pairs in a user controllable order", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "7382cf6263419f2d8df38c55d7da83da5c18aef87fc7a7fc1fb1e344edfe14c1" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/hashlink@0.10.0", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/hashlink" + }, + { + "type": "vcs", + "url": "https://github.com/kyren/hashlink" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#heck@0.4.1", + "author": "Without Boats ", + "name": "heck", + "version": "0.4.1", + "description": "heck is a case conversion library.", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "95505c38b4572b2d910cecb0281560f54b440a19336cbbcb27bf6ce6adc6f5a8" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/heck@0.4.1", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/heck" + }, + { + "type": "website", + "url": "https://github.com/withoutboats/heck" + }, + { + "type": "vcs", + "url": "https://github.com/withoutboats/heck" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#heck@0.5.0", + "name": "heck", + "version": "0.5.0", + "description": "heck is a case conversion library.", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/heck@0.5.0", + "externalReferences": [ + { + "type": "vcs", + "url": "https://github.com/withoutboats/heck" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#hex@0.4.3", + "author": "KokaKiwi ", + "name": "hex", + "version": "0.4.3", + "description": "Encoding and decoding data into/from hexadecimal representation.", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/hex@0.4.3", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/hex/" + }, + { + "type": "vcs", + "url": "https://github.com/KokaKiwi/rust-hex" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#hkdf@0.12.4", + "author": "RustCrypto Developers", + "name": "hkdf", + "version": "0.12.4", + "description": "HMAC-based Extract-and-Expand Key Derivation Function (HKDF)", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "7b5f8eb2ad728638ea2c7d47a21db23b7b58a72ed6a38256b8a1849f15fbbdf7" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/hkdf@0.12.4", + "externalReferences": [ + { + "type": "website", + "url": "https://github.com/RustCrypto/KDFs/" + }, + { + "type": "vcs", + "url": "https://github.com/RustCrypto/KDFs/" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#hmac@0.12.1", + "author": "RustCrypto Developers", + "name": "hmac", + "version": "0.12.1", + "description": "Generic implementation of Hash-based Message Authentication Code (HMAC)", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "6c49c37c09c17a53d937dfbb742eb3a961d65a994e6bcdcf37e7399d0cc8ab5e" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/hmac@0.12.1", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/hmac" + }, + { + "type": "vcs", + "url": "https://github.com/RustCrypto/MACs" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#home@0.5.12", + "author": "Brian Anderson ", + "name": "home", + "version": "0.5.12", + "description": "Shared definitions of home directories.", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "cc627f471c528ff0c4a49e1d5e60450c8f6461dd6d10ba9dcd3a61d3dff7728d" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/home@0.5.12", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/home" + }, + { + "type": "website", + "url": "https://github.com/rust-lang/cargo" + }, + { + "type": "vcs", + "url": "https://github.com/rust-lang/cargo" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#htmlescape@0.3.1", + "author": "Viktor Dahl ", + "name": "htmlescape", + "version": "0.3.1", + "description": "A library for HTML entity encoding and decoding", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "e9025058dae765dee5070ec375f591e2ba14638c63feff74f13805a72e523163" + } + ], + "licenses": [ + { + "expression": "Apache-2.0 OR MIT OR MPL-2.0" + } + ], + "purl": "pkg:cargo/htmlescape@0.3.1", + "externalReferences": [ + { + "type": "vcs", + "url": "https://github.com/veddan/rust-htmlescape" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#http-body-util@0.1.3", + "author": "Carl Lerche , Lucio Franco , Sean McArthur ", + "name": "http-body-util", + "version": "0.1.3", + "description": "Combinators and adapters for HTTP request or response bodies. ", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "b021d93e26becf5dc7e1b75b1bed1fd93124b374ceb73f43d4d4eafec896a64a" + } + ], + "licenses": [ + { + "expression": "MIT" + } + ], + "purl": "pkg:cargo/http-body-util@0.1.3", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/http-body-util" + }, + { + "type": "vcs", + "url": "https://github.com/hyperium/http-body" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#http-body@0.4.6", + "author": "Carl Lerche , Lucio Franco , Sean McArthur ", + "name": "http-body", + "version": "0.4.6", + "description": "Trait representing an asynchronous, streaming, HTTP request or response body. ", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "7ceab25649e9960c0311ea418d17bee82c0dcec1bd053b5f9a66e265a693bed2" + } + ], + "licenses": [ + { + "expression": "MIT" + } + ], + "purl": "pkg:cargo/http-body@0.4.6", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/http-body" + }, + { + "type": "vcs", + "url": "https://github.com/hyperium/http-body" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#http-body@1.0.1", + "author": "Carl Lerche , Lucio Franco , Sean McArthur ", + "name": "http-body", + "version": "1.0.1", + "description": "Trait representing an asynchronous, streaming, HTTP request or response body. ", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "1efedce1fb8e6913f23e0c92de8e62cd5b772a67e7b3946df930a62566c93184" + } + ], + "licenses": [ + { + "expression": "MIT" + } + ], + "purl": "pkg:cargo/http-body@1.0.1", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/http-body" + }, + { + "type": "vcs", + "url": "https://github.com/hyperium/http-body" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#http-range-header@0.3.1", + "name": "http-range-header", + "version": "0.3.1", + "description": "No-dep range header parser", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "add0ab9360ddbd88cfeb3bd9574a1d85cfdfa14db10b3e21d3700dbc4328758f" + } + ], + "licenses": [ + { + "expression": "MIT" + } + ], + "purl": "pkg:cargo/http-range-header@0.3.1", + "externalReferences": [ + { + "type": "website", + "url": "https://github.com/MarcusGrass/parse-range-headers" + }, + { + "type": "vcs", + "url": "https://github.com/MarcusGrass/parse-range-headers" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#http@0.2.12", + "author": "Alex Crichton , Carl Lerche , Sean McArthur ", + "name": "http", + "version": "0.2.12", + "description": "A set of types for representing HTTP requests and responses. ", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "601cbb57e577e2f5ef5be8e7b83f0f63994f25aa94d673e54a92d5c516d101f1" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/http@0.2.12", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/http" + }, + { + "type": "vcs", + "url": "https://github.com/hyperium/http" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#http@1.4.0", + "author": "Alex Crichton , Carl Lerche , Sean McArthur ", + "name": "http", + "version": "1.4.0", + "description": "A set of types for representing HTTP requests and responses. ", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "e3ba2a386d7f85a81f119ad7498ebe444d2e22c2af0b86b069416ace48b3311a" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/http@1.4.0", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/http" + }, + { + "type": "vcs", + "url": "https://github.com/hyperium/http" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#httparse@1.10.1", + "author": "Sean McArthur ", + "name": "httparse", + "version": "1.10.1", + "description": "A tiny, safe, speedy, zero-copy HTTP/1.x parser.", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "6dbf3de79e51f3d586ab4cb9d5c3e2c14aa28ed23d180cf89b4df0454a69cc87" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/httparse@1.10.1", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/httparse" + }, + { + "type": "vcs", + "url": "https://github.com/seanmonstar/httparse" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#httpdate@1.0.3", + "author": "Pyfisch ", + "name": "httpdate", + "version": "1.0.3", + "description": "HTTP date parsing and formatting", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "df3b46402a9d5adb4c86a0cf463f42e19994e3ee891101b1841f30a545cb49a9" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/httpdate@1.0.3", + "externalReferences": [ + { + "type": "vcs", + "url": "https://github.com/pyfisch/httpdate" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#humantime@2.3.0", + "name": "humantime", + "version": "2.3.0", + "description": "A parser and formatter for std::time::{Duration, SystemTime}", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "135b12329e5e3ce057a9f972339ea52bc954fe1e9358ef27f95e89716fbc5424" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/humantime@2.3.0", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/humantime" + }, + { + "type": "website", + "url": "https://github.com/chronotope/humantime" + }, + { + "type": "vcs", + "url": "https://github.com/chronotope/humantime" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#hyper-rustls@0.24.2", + "name": "hyper-rustls", + "version": "0.24.2", + "description": "Rustls+hyper integration for pure rust HTTPS", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "ec3efd23720e2049821a693cbc7e65ea87c72f1c58ff2f9522ff332b1491e590" + } + ], + "licenses": [ + { + "expression": "Apache-2.0 OR ISC OR MIT" + } + ], + "purl": "pkg:cargo/hyper-rustls@0.24.2", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/hyper-rustls/" + }, + { + "type": "website", + "url": "https://github.com/rustls/hyper-rustls" + }, + { + "type": "vcs", + "url": "https://github.com/rustls/hyper-rustls" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#hyper-rustls@0.27.7", + "name": "hyper-rustls", + "version": "0.27.7", + "description": "Rustls+hyper integration for pure rust HTTPS", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "e3c93eb611681b207e1fe55d5a71ecf91572ec8a6705cdb6857f7d8d5242cf58" + } + ], + "licenses": [ + { + "expression": "Apache-2.0 OR ISC OR MIT" + } + ], + "purl": "pkg:cargo/hyper-rustls@0.27.7", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/hyper-rustls/" + }, + { + "type": "website", + "url": "https://github.com/rustls/hyper-rustls" + }, + { + "type": "vcs", + "url": "https://github.com/rustls/hyper-rustls" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#hyper-timeout@0.4.1", + "author": "Herman J. Radtke III ", + "name": "hyper-timeout", + "version": "0.4.1", + "description": "A connect, read and write timeout aware connector to be used with hyper Client.", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "bbb958482e8c7be4bc3cf272a766a2b0bf1a6755e7a6ae777f017a31d11b13b1" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/hyper-timeout@0.4.1", + "externalReferences": [ + { + "type": "documentation", + "url": "https://github.com/hjr3/hyper-timeout" + }, + { + "type": "website", + "url": "https://github.com/hjr3/hyper-timeout" + }, + { + "type": "vcs", + "url": "https://github.com/hjr3/hyper-timeout" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#hyper-timeout@0.5.2", + "author": "Herman J. Radtke III ", + "name": "hyper-timeout", + "version": "0.5.2", + "description": "A connect, read and write timeout aware connector to be used with hyper Client.", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "2b90d566bffbce6a75bd8b09a05aa8c2cb1fabb6cb348f8840c9e4c90a0d83b0" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/hyper-timeout@0.5.2", + "externalReferences": [ + { + "type": "documentation", + "url": "https://github.com/hjr3/hyper-timeout" + }, + { + "type": "website", + "url": "https://github.com/hjr3/hyper-timeout" + }, + { + "type": "vcs", + "url": "https://github.com/hjr3/hyper-timeout" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#hyper-tls@0.6.0", + "author": "Sean McArthur ", + "name": "hyper-tls", + "version": "0.6.0", + "description": "Default TLS implementation for use with hyper", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "70206fc6890eaca9fde8a0bf71caa2ddfc9fe045ac9e5c70df101a7dbde866e0" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/hyper-tls@0.6.0", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/hyper-tls" + }, + { + "type": "website", + "url": "https://hyper.rs" + }, + { + "type": "vcs", + "url": "https://github.com/hyperium/hyper-tls" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#hyper-util@0.1.20", + "author": "Sean McArthur ", + "name": "hyper-util", + "version": "0.1.20", + "description": "hyper utilities", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "96547c2556ec9d12fb1578c4eaf448b04993e7fb79cbaad930a656880a6bdfa0" + } + ], + "licenses": [ + { + "expression": "MIT" + } + ], + "purl": "pkg:cargo/hyper-util@0.1.20", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/hyper-util" + }, + { + "type": "website", + "url": "https://hyper.rs" + }, + { + "type": "vcs", + "url": "https://github.com/hyperium/hyper-util" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#hyper@0.14.32", + "author": "Sean McArthur ", + "name": "hyper", + "version": "0.14.32", + "description": "A fast and correct HTTP library.", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "41dfc780fdec9373c01bae43289ea34c972e40ee3c9f6b3c8801a35f35586ce7" + } + ], + "licenses": [ + { + "expression": "MIT" + } + ], + "purl": "pkg:cargo/hyper@0.14.32", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/hyper" + }, + { + "type": "website", + "url": "https://hyper.rs" + }, + { + "type": "vcs", + "url": "https://github.com/hyperium/hyper" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#hyper@1.8.1", + "author": "Sean McArthur ", + "name": "hyper", + "version": "1.8.1", + "description": "A protective and efficient HTTP library for all.", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "2ab2d4f250c3d7b1c9fcdff1cece94ea4e2dfbec68614f7b87cb205f24ca9d11" + } + ], + "licenses": [ + { + "expression": "MIT" + } + ], + "purl": "pkg:cargo/hyper@1.8.1", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/hyper" + }, + { + "type": "website", + "url": "https://hyper.rs" + }, + { + "type": "vcs", + "url": "https://github.com/hyperium/hyper" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#icu_collections@2.1.1", + "author": "The ICU4X Project Developers", + "name": "icu_collections", + "version": "2.1.1", + "description": "Collection of API for use in ICU libraries.", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "4c6b649701667bbe825c3b7e6388cb521c23d88644678e83c0c4d0a621a34b43" + } + ], + "licenses": [ + { + "expression": "Unicode-3.0" + } + ], + "purl": "pkg:cargo/icu_collections@2.1.1", + "externalReferences": [ + { + "type": "website", + "url": "https://icu4x.unicode.org" + }, + { + "type": "vcs", + "url": "https://github.com/unicode-org/icu4x" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#icu_locale_core@2.1.1", + "author": "The ICU4X Project Developers", + "name": "icu_locale_core", + "version": "2.1.1", + "description": "API for managing Unicode Language and Locale Identifiers", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "edba7861004dd3714265b4db54a3c390e880ab658fec5f7db895fae2046b5bb6" + } + ], + "licenses": [ + { + "expression": "Unicode-3.0" + } + ], + "purl": "pkg:cargo/icu_locale_core@2.1.1", + "externalReferences": [ + { + "type": "website", + "url": "https://icu4x.unicode.org" + }, + { + "type": "vcs", + "url": "https://github.com/unicode-org/icu4x" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#icu_normalizer@2.1.1", + "author": "The ICU4X Project Developers", + "name": "icu_normalizer", + "version": "2.1.1", + "description": "API for normalizing text into Unicode Normalization Forms", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "5f6c8828b67bf8908d82127b2054ea1b4427ff0230ee9141c54251934ab1b599" + } + ], + "licenses": [ + { + "expression": "Unicode-3.0" + } + ], + "purl": "pkg:cargo/icu_normalizer@2.1.1", + "externalReferences": [ + { + "type": "website", + "url": "https://icu4x.unicode.org" + }, + { + "type": "vcs", + "url": "https://github.com/unicode-org/icu4x" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#icu_normalizer_data@2.1.1", + "author": "The ICU4X Project Developers", + "name": "icu_normalizer_data", + "version": "2.1.1", + "description": "Data for the icu_normalizer crate", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "7aedcccd01fc5fe81e6b489c15b247b8b0690feb23304303a9e560f37efc560a" + } + ], + "licenses": [ + { + "expression": "Unicode-3.0" + } + ], + "purl": "pkg:cargo/icu_normalizer_data@2.1.1", + "externalReferences": [ + { + "type": "website", + "url": "https://icu4x.unicode.org" + }, + { + "type": "vcs", + "url": "https://github.com/unicode-org/icu4x" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#icu_properties@2.1.2", + "author": "The ICU4X Project Developers", + "name": "icu_properties", + "version": "2.1.2", + "description": "Definitions for Unicode properties", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "020bfc02fe870ec3a66d93e677ccca0562506e5872c650f893269e08615d74ec" + } + ], + "licenses": [ + { + "expression": "Unicode-3.0" + } + ], + "purl": "pkg:cargo/icu_properties@2.1.2", + "externalReferences": [ + { + "type": "website", + "url": "https://icu4x.unicode.org" + }, + { + "type": "vcs", + "url": "https://github.com/unicode-org/icu4x" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#icu_properties_data@2.1.2", + "author": "The ICU4X Project Developers", + "name": "icu_properties_data", + "version": "2.1.2", + "description": "Data for the icu_properties crate", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "616c294cf8d725c6afcd8f55abc17c56464ef6211f9ed59cccffe534129c77af" + } + ], + "licenses": [ + { + "expression": "Unicode-3.0" + } + ], + "purl": "pkg:cargo/icu_properties_data@2.1.2", + "externalReferences": [ + { + "type": "website", + "url": "https://icu4x.unicode.org" + }, + { + "type": "vcs", + "url": "https://github.com/unicode-org/icu4x" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#icu_provider@2.1.1", + "author": "The ICU4X Project Developers", + "name": "icu_provider", + "version": "2.1.1", + "description": "Trait and struct definitions for the ICU data provider", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "85962cf0ce02e1e0a629cc34e7ca3e373ce20dda4c4d7294bbd0bf1fdb59e614" + } + ], + "licenses": [ + { + "expression": "Unicode-3.0" + } + ], + "purl": "pkg:cargo/icu_provider@2.1.1", + "externalReferences": [ + { + "type": "website", + "url": "https://icu4x.unicode.org" + }, + { + "type": "vcs", + "url": "https://github.com/unicode-org/icu4x" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#ident_case@1.0.1", + "author": "Ted Driggs ", + "name": "ident_case", + "version": "1.0.1", + "description": "Utility for applying case rules to Rust identifiers.", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "b9e0384b61958566e926dc50660321d12159025e767c18e043daf26b70104c39" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/ident_case@1.0.1", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/ident_case/1.0.1" + }, + { + "type": "vcs", + "url": "https://github.com/TedDriggs/ident_case" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#idna@1.1.0", + "author": "The rust-url developers", + "name": "idna", + "version": "1.1.0", + "description": "IDNA (Internationalizing Domain Names in Applications) and Punycode.", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "3b0875f23caa03898994f6ddc501886a45c7d3d62d04d2d90788d47be1b1e4de" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/idna@1.1.0", + "externalReferences": [ + { + "type": "vcs", + "url": "https://github.com/servo/rust-url/" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#idna_adapter@1.2.1", + "author": "The rust-url developers", + "name": "idna_adapter", + "version": "1.2.1", + "description": "Back end adapter for idna", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "3acae9609540aa318d1bc588455225fb2085b9ed0c4f6bd0d9d5bcd86f1a0344" + } + ], + "licenses": [ + { + "expression": "Apache-2.0 OR MIT" + } + ], + "purl": "pkg:cargo/idna_adapter@1.2.1", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/idna_adapter/latest/idna_adapter/" + }, + { + "type": "website", + "url": "https://docs.rs/crate/idna_adapter/latest" + }, + { + "type": "vcs", + "url": "https://github.com/hsivonen/idna_adapter" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#image@0.25.10", + "author": "The image-rs Developers", + "name": "image", + "version": "0.25.10", + "description": "Imaging library. Provides basic image processing and encoders/decoders for common image formats.", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "85ab80394333c02fe689eaf900ab500fbd0c2213da414687ebf995a65d5a6104" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/image@0.25.10", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/image" + }, + { + "type": "website", + "url": "https://github.com/image-rs/image" + }, + { + "type": "vcs", + "url": "https://github.com/image-rs/image" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#indexmap@1.9.3", + "name": "indexmap", + "version": "1.9.3", + "description": "A hash table with consistent order and fast iteration.", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "bd070e393353796e801d209ad339e89596eb4c8d430d18ede6a1cced8fafbd99" + } + ], + "licenses": [ + { + "expression": "Apache-2.0 OR MIT" + } + ], + "purl": "pkg:cargo/indexmap@1.9.3", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/indexmap/" + }, + { + "type": "vcs", + "url": "https://github.com/bluss/indexmap" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#indexmap@2.13.0", + "name": "indexmap", + "version": "2.13.0", + "description": "A hash table with consistent order and fast iteration.", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "7714e70437a7dc3ac8eb7e6f8df75fd8eb422675fc7678aff7364301092b1017" + } + ], + "licenses": [ + { + "expression": "Apache-2.0 OR MIT" + } + ], + "purl": "pkg:cargo/indexmap@2.13.0", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/indexmap/" + }, + { + "type": "vcs", + "url": "https://github.com/indexmap-rs/indexmap" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#indicatif@0.17.11", + "name": "indicatif", + "version": "0.17.11", + "description": "A progress bar and cli reporting library for Rust", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "183b3088984b400f4cfac3620d5e076c84da5364016b4f49473de574b2586235" + } + ], + "licenses": [ + { + "expression": "MIT" + } + ], + "purl": "pkg:cargo/indicatif@0.17.11", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/indicatif" + }, + { + "type": "vcs", + "url": "https://github.com/console-rs/indicatif" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#indoc@2.0.7", + "author": "David Tolnay ", + "name": "indoc", + "version": "2.0.7", + "description": "Indented document literals", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "79cf5c93f93228cf8efb3ba362535fb11199ac548a09ce117c9b1adc3030d706" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/indoc@2.0.7", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/indoc" + }, + { + "type": "vcs", + "url": "https://github.com/dtolnay/indoc" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#inherent@1.0.13", + "author": "David Tolnay ", + "name": "inherent", + "version": "1.0.13", + "description": "Make trait methods callable without the trait in scope", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "c727f80bfa4a6c6e2508d2f05b6f4bfce242030bd88ed15ae5331c5b5d30fba7" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/inherent@1.0.13", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/inherent" + }, + { + "type": "vcs", + "url": "https://github.com/dtolnay/inherent" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#inlinable_string@0.1.15", + "author": "Nick Fitzgerald ", + "name": "inlinable_string", + "version": "0.1.15", + "description": "The `inlinable_string` crate provides the `InlinableString` type -- an owned, grow-able UTF-8 string that stores small strings inline and avoids heap-allocation -- and the `StringExt` trait which abstracts string operations over both `std::string::String` and `InlinableString` (or even your own custom string type).", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "c8fae54786f62fb2918dcfae3d568594e50eb9b5c25bf04371af6fe7516452fb" + } + ], + "licenses": [ + { + "expression": "Apache-2.0 OR MIT" + } + ], + "purl": "pkg:cargo/inlinable_string@0.1.15", + "externalReferences": [ + { + "type": "documentation", + "url": "http://fitzgen.github.io/inlinable_string/inlinable_string/index.html" + }, + { + "type": "vcs", + "url": "https://github.com/fitzgen/inlinable_string" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#inout@0.1.4", + "author": "RustCrypto Developers", + "name": "inout", + "version": "0.1.4", + "description": "Custom reference types for code generic over in-place and buffer-to-buffer modes of operation.", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "879f10e63c20629ecabbb64a8010319738c66a5cd0c29b02d63d272b03751d01" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/inout@0.1.4", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/inout" + }, + { + "type": "vcs", + "url": "https://github.com/RustCrypto/utils" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#instability@0.3.12", + "author": "Stephen M. Coakley , The Ratatui Developers", + "name": "instability", + "version": "0.3.12", + "description": "Rust API stability attributes for the rest of us. A fork of the `stability` crate.", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "5eb2d60ef19920a3a9193c3e371f726ec1dafc045dac788d0fb3704272458971" + } + ], + "licenses": [ + { + "expression": "MIT" + } + ], + "purl": "pkg:cargo/instability@0.3.12", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/instability/" + }, + { + "type": "vcs", + "url": "https://github.com/ratatui/instability" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#instant@0.1.13", + "author": "sebcrozet ", + "name": "instant", + "version": "0.1.13", + "description": "Unmaintained, consider using web-time instead - A partial replacement for std::time::Instant that works on WASM to.", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "e0242819d153cba4b4b05a5a8f2a7e9bbf97b6055b2a002b395c96b5ff3c0222" + } + ], + "licenses": [ + { + "expression": "BSD-3-Clause" + } + ], + "purl": "pkg:cargo/instant@0.1.13", + "externalReferences": [ + { + "type": "vcs", + "url": "https://github.com/sebcrozet/instant" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#integer-encoding@3.0.4", + "author": "Lewin Bormann ", + "name": "integer-encoding", + "version": "3.0.4", + "description": "varint+zigzag and fixedint integer encoding/decoding (https://developers.google.com/protocol-buffers/docs/encoding)", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "8bb03732005da905c88227371639bf1ad885cc712789c011c31c5fb3ab3ccf02" + } + ], + "licenses": [ + { + "expression": "MIT" + } + ], + "purl": "pkg:cargo/integer-encoding@3.0.4", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/integer-encoding/" + }, + { + "type": "vcs", + "url": "https://github.com/dermesser/integer-encoding-rs" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#interpol@0.2.1", + "author": "Hideyuki Tanaka ", + "name": "interpol", + "version": "0.2.1", + "description": "String interpolation macros", + "scope": "excluded", + "hashes": [ + { + "alg": "SHA-256", + "content": "eb58032ba748f4010d15912a1855a8a0b1ba9eaad3395b0c171c09b3b356ae50" + } + ], + "licenses": [ + { + "expression": "MIT" + } + ], + "purl": "pkg:cargo/interpol@0.2.1", + "externalReferences": [ + { + "type": "vcs", + "url": "https://github.com/tanakh/interpol" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#ipnet@2.12.0", + "author": "Kris Price ", + "name": "ipnet", + "version": "2.12.0", + "description": "Provides types and useful methods for working with IPv4 and IPv6 network addresses, commonly called IP prefixes. The new `IpNet`, `Ipv4Net`, and `Ipv6Net` types build on the existing `IpAddr`, `Ipv4Addr`, and `Ipv6Addr` types already provided in Rust's standard library and align to their design to stay consistent. The module also provides useful traits that extend `Ipv4Addr` and `Ipv6Addr` with methods for `Add`, `Sub`, `BitAnd`, and `BitOr` operations. The module only uses stable feature so it is guaranteed to compile using the stable toolchain.", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "d98f6fed1fde3f8c21bc40a1abb88dd75e67924f9cffc3ef95607bad8017f8e2" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/ipnet@2.12.0", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/ipnet" + }, + { + "type": "vcs", + "url": "https://github.com/krisprice/ipnet" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#iri-string@0.7.10", + "author": "YOSHIOKA Takuma ", + "name": "iri-string", + "version": "0.7.10", + "description": "IRI as string types", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "c91338f0783edbd6195decb37bae672fd3b165faffb89bf7b9e6942f8b1a731a" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/iri-string@0.7.10", + "externalReferences": [ + { + "type": "vcs", + "url": "https://github.com/lo48576/iri-string" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#is_ci@1.2.0", + "author": "Kat Marchán ", + "name": "is_ci", + "version": "1.2.0", + "description": "Super lightweight CI environment checker. Just tells you if you're in CI or not without much fuss.", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "7655c9839580ee829dfacba1d1278c2b7883e50a277ff7541299489d6bdfdc45" + } + ], + "licenses": [ + { + "expression": "ISC" + } + ], + "purl": "pkg:cargo/is_ci@1.2.0", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/is_ci" + }, + { + "type": "vcs", + "url": "https://github.com/zkat/is_ci" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#is_terminal_polyfill@1.70.2", + "name": "is_terminal_polyfill", + "version": "1.70.2", + "description": "Polyfill for `is_terminal` stdlib feature for use with older MSRVs", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "a6cb138bb79a146c1bd460005623e142ef0181e3d0219cb493e02f7d08a35695" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/is_terminal_polyfill@1.70.2", + "externalReferences": [ + { + "type": "vcs", + "url": "https://github.com/polyfill-rs/is_terminal_polyfill" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#iter-read@1.1.0", + "author": "Georg Brandl ", + "name": "iter-read", + "version": "1.1.0", + "description": "A Read implementation for iterators over u8 and related types", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "071ed4cc1afd86650602c7b11aa2e1ce30762a1c27193201cb5cee9c6ebb1294" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/iter-read@1.1.0", + "externalReferences": [ + { + "type": "vcs", + "url": "https://github.com/birkenfeld/iter-read" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#itertools@0.12.1", + "author": "bluss", + "name": "itertools", + "version": "0.12.1", + "description": "Extra iterator adaptors, iterator methods, free functions, and macros.", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "ba291022dbbd398a455acf126c1e341954079855bc60dfdda641363bd6922569" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/itertools@0.12.1", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/itertools/" + }, + { + "type": "vcs", + "url": "https://github.com/rust-itertools/itertools" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#itertools@0.13.0", + "author": "bluss", + "name": "itertools", + "version": "0.13.0", + "description": "Extra iterator adaptors, iterator methods, free functions, and macros.", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "413ee7dfc52ee1a4949ceeb7dbc8a33f2d6c088194d9f922fb8318faf1f01186" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/itertools@0.13.0", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/itertools/" + }, + { + "type": "vcs", + "url": "https://github.com/rust-itertools/itertools" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#itertools@0.14.0", + "author": "bluss", + "name": "itertools", + "version": "0.14.0", + "description": "Extra iterator adaptors, iterator methods, free functions, and macros.", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "2b192c782037fadd9cfa75548310488aabdbf3d2da73885b31bd0abd03351285" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/itertools@0.14.0", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/itertools/" + }, + { + "type": "vcs", + "url": "https://github.com/rust-itertools/itertools" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#itoa@1.0.18", + "author": "David Tolnay ", + "name": "itoa", + "version": "1.0.18", + "description": "Fast integer primitive to string conversion", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/itoa@1.0.18", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/itoa" + }, + { + "type": "vcs", + "url": "https://github.com/dtolnay/itoa" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#jobserver@0.1.34", + "author": "Alex Crichton ", + "name": "jobserver", + "version": "0.1.34", + "description": "An implementation of the GNU Make jobserver for Rust. ", + "scope": "excluded", + "hashes": [ + { + "alg": "SHA-256", + "content": "9afb3de4395d6b3e67a780b6de64b51c978ecf11cb9a462c66be7d4ca9039d33" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/jobserver@0.1.34", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/jobserver" + }, + { + "type": "website", + "url": "https://github.com/rust-lang/jobserver-rs" + }, + { + "type": "vcs", + "url": "https://github.com/rust-lang/jobserver-rs" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#json-patch@1.4.0", + "author": "Ivan Dubrov ", + "name": "json-patch", + "version": "1.4.0", + "description": "RFC 6902, JavaScript Object Notation (JSON) Patch", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "ec9ad60d674508f3ca8f380a928cfe7b096bc729c4e2dbfe3852bc45da3ab30b" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/json-patch@1.4.0", + "externalReferences": [ + { + "type": "vcs", + "url": "https://github.com/idubrov/json-patch" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#jsonpath-rust@0.3.5", + "author": "BorisZhguchev ", + "name": "jsonpath-rust", + "version": "0.3.5", + "description": "The library provides the basic functionality to find the set of the data according to the filtering query.", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "06cc127b7c3d270be504572364f9569761a180b981919dd0d87693a7f5fb7829" + } + ], + "licenses": [ + { + "license": { + "name": "Unknown", + "text": { + "encoding": "base64", + "content": "TUlUIExpY2Vuc2UKCkNvcHlyaWdodCAoYykgWzIwMjFdIFtCb3JpcyBaaGd1Y2hldl0KClBlcm1pc3Npb24gaXMgaGVyZWJ5IGdyYW50ZWQsIGZyZWUgb2YgY2hhcmdlLCB0byBhbnkgcGVyc29uIG9idGFpbmluZyBhIGNvcHkKb2YgdGhpcyBzb2Z0d2FyZSBhbmQgYXNzb2NpYXRlZCBkb2N1bWVudGF0aW9uIGZpbGVzICh0aGUgIlNvZnR3YXJlIiksIHRvIGRlYWwKaW4gdGhlIFNvZnR3YXJlIHdpdGhvdXQgcmVzdHJpY3Rpb24sIGluY2x1ZGluZyB3aXRob3V0IGxpbWl0YXRpb24gdGhlIHJpZ2h0cwp0byB1c2UsIGNvcHksIG1vZGlmeSwgbWVyZ2UsIHB1Ymxpc2gsIGRpc3RyaWJ1dGUsIHN1YmxpY2Vuc2UsIGFuZC9vciBzZWxsCmNvcGllcyBvZiB0aGUgU29mdHdhcmUsIGFuZCB0byBwZXJtaXQgcGVyc29ucyB0byB3aG9tIHRoZSBTb2Z0d2FyZSBpcwpmdXJuaXNoZWQgdG8gZG8gc28sIHN1YmplY3QgdG8gdGhlIGZvbGxvd2luZyBjb25kaXRpb25zOgoKVGhlIGFib3ZlIGNvcHlyaWdodCBub3RpY2UgYW5kIHRoaXMgcGVybWlzc2lvbiBub3RpY2Ugc2hhbGwgYmUgaW5jbHVkZWQgaW4gYWxsCmNvcGllcyBvciBzdWJzdGFudGlhbCBwb3J0aW9ucyBvZiB0aGUgU29mdHdhcmUuCgpUSEUgU09GVFdBUkUgSVMgUFJPVklERUQgIkFTIElTIiwgV0lUSE9VVCBXQVJSQU5UWSBPRiBBTlkgS0lORCwgRVhQUkVTUyBPUgpJTVBMSUVELCBJTkNMVURJTkcgQlVUIE5PVCBMSU1JVEVEIFRPIFRIRSBXQVJSQU5USUVTIE9GIE1FUkNIQU5UQUJJTElUWSwKRklUTkVTUyBGT1IgQSBQQVJUSUNVTEFSIFBVUlBPU0UgQU5EIE5PTklORlJJTkdFTUVOVC4gSU4gTk8gRVZFTlQgU0hBTEwgVEhFCkFVVEhPUlMgT1IgQ09QWVJJR0hUIEhPTERFUlMgQkUgTElBQkxFIEZPUiBBTlkgQ0xBSU0sIERBTUFHRVMgT1IgT1RIRVIKTElBQklMSVRZLCBXSEVUSEVSIElOIEFOIEFDVElPTiBPRiBDT05UUkFDVCwgVE9SVCBPUiBPVEhFUldJU0UsIEFSSVNJTkcgRlJPTSwKT1VUIE9GIE9SIElOIENPTk5FQ1RJT04gV0lUSCBUSEUgU09GVFdBUkUgT1IgVEhFIFVTRSBPUiBPVEhFUiBERUFMSU5HUyBJTiBUSEUKU09GVFdBUkUu" + } + } + } + ], + "purl": "pkg:cargo/jsonpath-rust@0.3.5", + "externalReferences": [ + { + "type": "website", + "url": "https://github.com/besok/jsonpath-rust" + }, + { + "type": "vcs", + "url": "https://github.com/besok/jsonpath-rust" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#k8s-openapi@0.20.0", + "author": "Arnav Singh ", + "name": "k8s-openapi", + "version": "0.20.0", + "description": "Bindings for the Kubernetes client API", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "edc3606fd16aca7989db2f84bb25684d0270c6d6fa1dbcd0025af7b4130523a6" + } + ], + "licenses": [ + { + "expression": "Apache-2.0" + } + ], + "purl": "pkg:cargo/k8s-openapi@0.20.0", + "externalReferences": [ + { + "type": "documentation", + "url": "https://arnavion.github.io/k8s-openapi/v0.20.x/k8s_openapi/" + }, + { + "type": "other", + "url": "k8s-openapi-0.20.0" + }, + { + "type": "vcs", + "url": "https://github.com/Arnavion/k8s-openapi" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#kube-client@0.87.2", + "author": "clux , Natalie Klestrup Röijezon , kazk ", + "name": "kube-client", + "version": "0.87.2", + "description": "Kubernetes client", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "033450dfa0762130565890dadf2f8835faedf749376ca13345bcd8ecd6b5f29f" + } + ], + "licenses": [ + { + "expression": "Apache-2.0" + } + ], + "purl": "pkg:cargo/kube-client@0.87.2", + "externalReferences": [ + { + "type": "vcs", + "url": "https://github.com/kube-rs/kube" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#kube-core@0.87.2", + "author": "clux , kazk ", + "name": "kube-core", + "version": "0.87.2", + "description": "Kube shared types, traits and client-less behavior", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "b5bba93d054786eba7994d03ce522f368ef7d48c88a1826faa28478d85fb63ae" + } + ], + "licenses": [ + { + "expression": "Apache-2.0" + } + ], + "purl": "pkg:cargo/kube-core@0.87.2", + "externalReferences": [ + { + "type": "vcs", + "url": "https://github.com/kube-rs/kube" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#kube-derive@0.87.2", + "author": "clux , kazk ", + "name": "kube-derive", + "version": "0.87.2", + "description": "Custom derives for the kube kubernetes crates", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "91e98dd5e5767c7b894c1f0e41fd628b145f808e981feb8b08ed66455d47f1a4" + } + ], + "licenses": [ + { + "expression": "Apache-2.0" + } + ], + "purl": "pkg:cargo/kube-derive@0.87.2", + "externalReferences": [ + { + "type": "vcs", + "url": "https://github.com/kube-rs/kube" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#kube-runtime@0.87.2", + "author": "Natalie Klestrup Röijezon , clux ", + "name": "kube-runtime", + "version": "0.87.2", + "description": "Kubernetes futures controller runtime", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "2d8893eb18fbf6bb6c80ef6ee7dd11ec32b1dc3c034c988ac1b3a84d46a230ae" + } + ], + "licenses": [ + { + "expression": "Apache-2.0" + } + ], + "purl": "pkg:cargo/kube-runtime@0.87.2", + "externalReferences": [ + { + "type": "vcs", + "url": "https://github.com/kube-rs/kube" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#kube@0.87.2", + "author": "clux , Natalie Klestrup Röijezon , kazk ", + "name": "kube", + "version": "0.87.2", + "description": "Kubernetes client and async controller runtime", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "3499c8d60c763246c7a213f51caac1e9033f46026904cb89bc8951ae8601f26e" + } + ], + "licenses": [ + { + "expression": "Apache-2.0" + } + ], + "purl": "pkg:cargo/kube@0.87.2", + "externalReferences": [ + { + "type": "vcs", + "url": "https://github.com/kube-rs/kube" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#lazy_static@1.5.0", + "author": "Marvin Löbel ", + "name": "lazy_static", + "version": "1.5.0", + "description": "A macro for declaring lazily evaluated statics in Rust.", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "bbd2bcb4c963f2ddae06a2efc7e9f3591312473c50c6685e1f298068316e66fe" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/lazy_static@1.5.0", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/lazy_static" + }, + { + "type": "vcs", + "url": "https://github.com/rust-lang-nursery/lazy-static.rs" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#levenshtein_automata@0.2.1", + "author": "Paul Masurel ", + "name": "levenshtein_automata", + "version": "0.2.1", + "description": "Creates Levenshtein Automata in an efficient manner.", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "0c2cdeb66e45e9f36bfad5bbdb4d2384e70936afbee843c6f6543f0c551ebb25" + } + ], + "licenses": [ + { + "expression": "MIT" + } + ], + "purl": "pkg:cargo/levenshtein_automata@0.2.1", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/levenshtein-automata/" + }, + { + "type": "website", + "url": "https://github.com/tantivy-search/levenshtein-automata" + }, + { + "type": "vcs", + "url": "https://github.com/tantivy-search/levenshtein-automata" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#lexical-core@1.0.6", + "author": "Alex Huszagh ", + "name": "lexical-core", + "version": "1.0.6", + "description": "Lexical, to- and from-string conversion routines.", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "7d8d125a277f807e55a77304455eb7b1cb52f2b18c143b60e766c120bd64a594" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/lexical-core@1.0.6", + "externalReferences": [ + { + "type": "vcs", + "url": "https://github.com/Alexhuszagh/rust-lexical" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#lexical-parse-float@1.0.6", + "author": "Alex Huszagh ", + "name": "lexical-parse-float", + "version": "1.0.6", + "description": "Efficient parsing of floats from strings.", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "52a9f232fbd6f550bc0137dcb5f99ab674071ac2d690ac69704593cb4abbea56" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/lexical-parse-float@1.0.6", + "externalReferences": [ + { + "type": "vcs", + "url": "https://github.com/Alexhuszagh/rust-lexical" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#lexical-parse-integer@1.0.6", + "author": "Alex Huszagh ", + "name": "lexical-parse-integer", + "version": "1.0.6", + "description": "Efficient parsing of integers from strings.", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "9a7a039f8fb9c19c996cd7b2fcce303c1b2874fe1aca544edc85c4a5f8489b34" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/lexical-parse-integer@1.0.6", + "externalReferences": [ + { + "type": "vcs", + "url": "https://github.com/Alexhuszagh/rust-lexical" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#lexical-util@1.0.7", + "author": "Alex Huszagh ", + "name": "lexical-util", + "version": "1.0.7", + "description": "Shared utilities for lexical creates.", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "2604dd126bb14f13fb5d1bd6a66155079cb9fa655b37f875b3a742c705dbed17" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/lexical-util@1.0.7", + "externalReferences": [ + { + "type": "vcs", + "url": "https://github.com/Alexhuszagh/rust-lexical" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#lexical-write-float@1.0.6", + "author": "Alex Huszagh ", + "name": "lexical-write-float", + "version": "1.0.6", + "description": "Efficient formatting of floats to strings.", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "50c438c87c013188d415fbabbb1dceb44249ab81664efbd31b14ae55dabb6361" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/lexical-write-float@1.0.6", + "externalReferences": [ + { + "type": "vcs", + "url": "https://github.com/Alexhuszagh/rust-lexical" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#lexical-write-integer@1.0.6", + "author": "Alex Huszagh ", + "name": "lexical-write-integer", + "version": "1.0.6", + "description": "Efficient formatting of integers to strings.", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "409851a618475d2d5796377cad353802345cba92c867d9fbcde9cf4eac4e14df" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/lexical-write-integer@1.0.6", + "externalReferences": [ + { + "type": "vcs", + "url": "https://github.com/Alexhuszagh/rust-lexical" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#libbz2-rs-sys@0.2.2", + "name": "libbz2-rs-sys", + "version": "0.2.2", + "description": "a drop-in compatible rust bzip2 implementation", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "2c4a545a15244c7d945065b5d392b2d2d7f21526fba56ce51467b06ed445e8f7" + } + ], + "licenses": [ + { + "expression": "bzip2-1.0.6" + } + ], + "purl": "pkg:cargo/libbz2-rs-sys@0.2.2", + "externalReferences": [ + { + "type": "website", + "url": "https://github.com/trifectatechfoundation/libbzip2-rs" + }, + { + "type": "vcs", + "url": "https://github.com/trifectatechfoundation/libbzip2-rs" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#libc@0.2.183", + "author": "The Rust Project Developers", + "name": "libc", + "version": "0.2.183", + "description": "Raw FFI bindings to platform libraries like libc.", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "b5b646652bf6661599e1da8901b3b9522896f01e736bad5f723fe7a3a27f899d" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/libc@0.2.183", + "externalReferences": [ + { + "type": "vcs", + "url": "https://github.com/rust-lang/libc" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#libm@0.2.16", + "author": "Alex Crichton , Amanieu d'Antras , Jorge Aparicio , Trevor Gross ", + "name": "libm", + "version": "0.2.16", + "description": "libm in pure Rust", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "b6d2cec3eae94f9f509c767b45932f1ada8350c4bdb85af2fcab4a3c14807981" + } + ], + "licenses": [ + { + "expression": "MIT" + } + ], + "purl": "pkg:cargo/libm@0.2.16", + "externalReferences": [ + { + "type": "vcs", + "url": "https://github.com/rust-lang/compiler-builtins" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#libsqlite3-sys@0.30.1", + "author": "The rusqlite developers", + "name": "libsqlite3-sys", + "version": "0.30.1", + "description": "Native bindings to the libsqlite3 library", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "2e99fb7a497b1e3339bc746195567ed8d3e24945ecd636e3619d20b9de9e9149" + } + ], + "licenses": [ + { + "expression": "MIT" + } + ], + "purl": "pkg:cargo/libsqlite3-sys@0.30.1", + "externalReferences": [ + { + "type": "other", + "url": "sqlite3" + }, + { + "type": "vcs", + "url": "https://github.com/rusqlite/rusqlite" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#link-cplusplus@1.0.12", + "author": "David Tolnay ", + "name": "link-cplusplus", + "version": "1.0.12", + "description": "Link libstdc++ or libc++ automatically or manually", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "7f78c730aaa7d0b9336a299029ea49f9ee53b0ed06e9202e8cb7db9bae7b8c82" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/link-cplusplus@1.0.12", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/link-cplusplus" + }, + { + "type": "other", + "url": "cplusplus" + }, + { + "type": "vcs", + "url": "https://github.com/dtolnay/link-cplusplus" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#litemap@0.8.1", + "author": "The ICU4X Project Developers", + "name": "litemap", + "version": "0.8.1", + "description": "A key-value Map implementation based on a flat, sorted Vec.", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "6373607a59f0be73a39b6fe456b8192fcc3585f602af20751600e974dd455e77" + } + ], + "licenses": [ + { + "expression": "Unicode-3.0" + } + ], + "purl": "pkg:cargo/litemap@0.8.1", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/litemap" + }, + { + "type": "vcs", + "url": "https://github.com/unicode-org/icu4x" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#litrs@1.0.0", + "author": "Lukas Kalbertodt ", + "name": "litrs", + "version": "1.0.0", + "description": "Parse and inspect Rust literals (i.e. tokens in the Rust programming language representing fixed values). Particularly useful for proc macros, but can also be used outside of a proc-macro context. ", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "11d3d7f243d5c5a8b9bb5d6dd2b1602c0cb0b9db1621bafc7ed66e35ff9fe092" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/litrs@1.0.0", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/litrs" + }, + { + "type": "vcs", + "url": "https://github.com/LukasKalbertodt/litrs" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#lock_api@0.4.14", + "author": "Amanieu d'Antras ", + "name": "lock_api", + "version": "0.4.14", + "description": "Wrappers to create fully-featured Mutex and RwLock types. Compatible with no_std.", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "224399e74b87b5f3557511d98dff8b14089b3dadafcab6bb93eab67d3aace965" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/lock_api@0.4.14", + "externalReferences": [ + { + "type": "vcs", + "url": "https://github.com/Amanieu/parking_lot" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#log@0.4.29", + "author": "The Rust Project Developers", + "name": "log", + "version": "0.4.29", + "description": "A lightweight logging facade for Rust ", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "5e5032e24019045c762d3c0f28f5b6b8bbf38563a65908389bf7978758920897" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/log@0.4.29", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/log" + }, + { + "type": "vcs", + "url": "https://github.com/rust-lang/log" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#lru-slab@0.1.2", + "author": "Benjamin Saunders ", + "name": "lru-slab", + "version": "0.1.2", + "description": "Pre-allocated storage with constant-time LRU tracking", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "112b39cec0b298b6c1999fee3e31427f74f676e4cb9879ed1a121b43661a4154" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0 OR Zlib" + } + ], + "purl": "pkg:cargo/lru-slab@0.1.2", + "externalReferences": [ + { + "type": "vcs", + "url": "https://github.com/Ralith/lru-slab" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#lru@0.12.5", + "author": "Jerome Froelich ", + "name": "lru", + "version": "0.12.5", + "description": "A LRU cache implementation", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "234cf4f4a04dc1f57e24b96cc0cd600cf2af460d4161ac5ecdd0af8e1f3b2a38" + } + ], + "licenses": [ + { + "expression": "MIT" + } + ], + "purl": "pkg:cargo/lru@0.12.5", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/lru/" + }, + { + "type": "website", + "url": "https://github.com/jeromefroe/lru-rs" + }, + { + "type": "vcs", + "url": "https://github.com/jeromefroe/lru-rs.git" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#lz4-sys@1.11.1+lz4-1.10.0", + "author": "Jens Heyens , Artem V. Navrotskiy , Patrick Marks ", + "name": "lz4-sys", + "version": "1.11.1+lz4-1.10.0", + "description": "Rust LZ4 sys package.", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "6bd8c0d6c6ed0cd30b3652886bb8711dc4bb01d637a68105a3d5158039b418e6" + } + ], + "licenses": [ + { + "expression": "MIT" + } + ], + "purl": "pkg:cargo/lz4-sys@1.11.1+lz4-1.10.0", + "externalReferences": [ + { + "type": "other", + "url": "lz4" + }, + { + "type": "vcs", + "url": "https://github.com/10xGenomics/lz4-rs" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#lz4@1.28.1", + "author": "Jens Heyens , Artem V. Navrotskiy , Patrick Marks ", + "name": "lz4", + "version": "1.28.1", + "description": "Rust LZ4 bindings library.", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "a20b523e860d03443e98350ceaac5e71c6ba89aea7d960769ec3ce37f4de5af4" + } + ], + "licenses": [ + { + "expression": "MIT" + } + ], + "purl": "pkg:cargo/lz4@1.28.1", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/lz4" + }, + { + "type": "vcs", + "url": "https://github.com/10xGenomics/lz4-rs" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#lz4_flex@0.11.6", + "author": "Pascal Seitz , Arthur Silva , ticki ", + "name": "lz4_flex", + "version": "0.11.6", + "description": "Fastest LZ4 implementation in Rust, no unsafe by default.", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "373f5eceeeab7925e0c1098212f2fbc4d416adec9d35051a6ab251e824c1854a" + } + ], + "licenses": [ + { + "expression": "MIT" + } + ], + "purl": "pkg:cargo/lz4_flex@0.11.6", + "externalReferences": [ + { + "type": "website", + "url": "https://github.com/pseitz/lz4_flex" + }, + { + "type": "vcs", + "url": "https://github.com/pseitz/lz4_flex" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#lzma-rust2@0.16.2", + "name": "lzma-rust2", + "version": "0.16.2", + "description": "LZMA / LZMA2 / LZIP / XZ compression ported from 'tukaani xz for java'", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "47bb1e988e6fb779cf720ad431242d3f03167c1b3f2b1aae7f1a94b2495b36ae" + } + ], + "licenses": [ + { + "expression": "Apache-2.0" + } + ], + "purl": "pkg:cargo/lzma-rust2@0.16.2", + "externalReferences": [ + { + "type": "website", + "url": "https://github.com/hasenbanck/lzma-rust2/" + }, + { + "type": "vcs", + "url": "https://github.com/hasenbanck/lzma-rust2/" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#matchers@0.2.0", + "author": "Eliza Weisman ", + "name": "matchers", + "version": "0.2.0", + "description": "Regex matching on character and byte streams. ", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "d1525a2a28c7f4fa0fc98bb91ae755d1e2d1505079e05539e35bc876b5d65ae9" + } + ], + "licenses": [ + { + "expression": "MIT" + } + ], + "purl": "pkg:cargo/matchers@0.2.0", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/matchers/" + }, + { + "type": "website", + "url": "https://github.com/hawkw/matchers" + }, + { + "type": "vcs", + "url": "https://github.com/hawkw/matchers" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#matchit@0.7.3", + "author": "Ibraheem Ahmed ", + "name": "matchit", + "version": "0.7.3", + "description": "A high performance, zero-copy URL router.", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "0e7465ac9959cc2b1404e8e2367b43684a6d13790fe23056cc8c6c5a6b7bcb94" + } + ], + "licenses": [ + { + "expression": "MIT AND BSD-3-Clause" + } + ], + "purl": "pkg:cargo/matchit@0.7.3", + "externalReferences": [ + { + "type": "vcs", + "url": "https://github.com/ibraheemdev/matchit" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#matchit@0.8.4", + "author": "Ibraheem Ahmed ", + "name": "matchit", + "version": "0.8.4", + "description": "A high performance, zero-copy URL router.", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "47e1ffaa40ddd1f3ed91f717a33c8c0ee23fff369e3aa8772b9605cc1d22f4c3" + } + ], + "licenses": [ + { + "expression": "MIT AND BSD-3-Clause" + } + ], + "purl": "pkg:cargo/matchit@0.8.4", + "externalReferences": [ + { + "type": "vcs", + "url": "https://github.com/ibraheemdev/matchit" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#matrixmultiply@0.3.10", + "author": "bluss, R. Janis Goldschmidt", + "name": "matrixmultiply", + "version": "0.3.10", + "description": "General matrix multiplication for f32 and f64 matrices. Operates on matrices with general layout (they can use arbitrary row and column stride). Detects and uses AVX or SSE2 on x86 platforms transparently for higher performance. Uses a microkernel strategy, so that the implementation is easy to parallelize and optimize. Supports multithreading.", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "a06de3016e9fae57a36fd14dba131fccf49f74b40b7fbdb472f96e361ec71a08" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/matrixmultiply@0.3.10", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/matrixmultiply/" + }, + { + "type": "vcs", + "url": "https://github.com/bluss/matrixmultiply/" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#md-5@0.10.6", + "author": "RustCrypto Developers", + "name": "md-5", + "version": "0.10.6", + "description": "MD5 hash function", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "d89e7ee0cfbedfc4da3340218492196241d89eefb6dab27de5df917a6d2e78cf" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/md-5@0.10.6", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/md-5" + }, + { + "type": "vcs", + "url": "https://github.com/RustCrypto/hashes" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#md5@0.7.0", + "author": "Ivan Ukhov , Kamal Ahmad , Konstantin Stepanov , Lukas Kalbertodt , Nathan Musoke , Scott Mabin , Tony Arcieri , Wim de With , Yosef Dinerstein ", + "name": "md5", + "version": "0.7.0", + "description": "The package provides the MD5 hash function.", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "490cc448043f947bae3cbee9c203358d62dbee0db12107a74be5c30ccfd09771" + } + ], + "licenses": [ + { + "expression": "Apache-2.0 OR MIT" + } + ], + "purl": "pkg:cargo/md5@0.7.0", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/md5" + }, + { + "type": "website", + "url": "https://github.com/stainless-steel/md5" + }, + { + "type": "vcs", + "url": "https://github.com/stainless-steel/md5" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#measure_time@0.8.3", + "author": "Pascal Seitz ", + "name": "measure_time", + "version": "0.8.3", + "description": "Provices macros to measure the time until end of scope. ", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "dbefd235b0aadd181626f281e1d684e116972988c14c264e42069d5e8a5775cc" + } + ], + "licenses": [ + { + "expression": "MIT" + } + ], + "purl": "pkg:cargo/measure_time@0.8.3", + "externalReferences": [ + { + "type": "website", + "url": "https://github.com/PSeitz/rust_measure_time" + }, + { + "type": "vcs", + "url": "https://github.com/PSeitz/rust_measure_time" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#memchr@2.8.0", + "author": "Andrew Gallant , bluss", + "name": "memchr", + "version": "2.8.0", + "description": "Provides extremely fast (uses SIMD on x86_64, aarch64 and wasm32) routines for 1, 2 or 3 byte search and single substring search. ", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "f8ca58f447f06ed17d5fc4043ce1b10dd205e060fb3ce5b979b8ed8e59ff3f79" + } + ], + "licenses": [ + { + "expression": "Unlicense OR MIT" + } + ], + "purl": "pkg:cargo/memchr@2.8.0", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/memchr/" + }, + { + "type": "website", + "url": "https://github.com/BurntSushi/memchr" + }, + { + "type": "vcs", + "url": "https://github.com/BurntSushi/memchr" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#memmap2@0.9.10", + "author": "Dan Burkert , Yevhenii Reizner , The Contributors", + "name": "memmap2", + "version": "0.9.10", + "description": "Cross-platform Rust API for memory-mapped file IO", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "714098028fe011992e1c3962653c96b2d578c4b4bce9036e15ff220319b1e0e3" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/memmap2@0.9.10", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/memmap2" + }, + { + "type": "vcs", + "url": "https://github.com/RazrFalcon/memmap2-rs" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#memoffset@0.9.1", + "author": "Gilad Naaman ", + "name": "memoffset", + "version": "0.9.1", + "description": "offset_of functionality for Rust structs.", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "488016bfae457b036d996092f6cb448677611ce4449e970ceaf42695203f218a" + } + ], + "licenses": [ + { + "expression": "MIT" + } + ], + "purl": "pkg:cargo/memoffset@0.9.1", + "externalReferences": [ + { + "type": "vcs", + "url": "https://github.com/Gilnaa/memoffset" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#mime@0.3.17", + "author": "Sean McArthur ", + "name": "mime", + "version": "0.3.17", + "description": "Strongly Typed Mimes", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "6877bb514081ee2a7ff5ef9de3281f14a4dd4bceac4c09388074a6b5df8a139a" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/mime@0.3.17", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/mime" + }, + { + "type": "vcs", + "url": "https://github.com/hyperium/mime" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#mime_guess@2.0.5", + "author": "Austin Bonander ", + "name": "mime_guess", + "version": "2.0.5", + "description": "A simple crate for detection of a file's MIME type by its extension.", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "f7c44f8e672c00fe5308fa235f821cb4198414e1c77935c1ab6948d3fd78550e" + } + ], + "licenses": [ + { + "expression": "MIT" + } + ], + "purl": "pkg:cargo/mime_guess@2.0.5", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/mime_guess/" + }, + { + "type": "vcs", + "url": "https://github.com/abonander/mime_guess" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#minimal-lexical@0.2.1", + "author": "Alex Huszagh ", + "name": "minimal-lexical", + "version": "0.2.1", + "description": "Fast float parsing conversion routines.", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "68354c5c6bd36d73ff3feceb05efa59b6acb7626617f4962be322a825e61f79a" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/minimal-lexical@0.2.1", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/minimal-lexical" + }, + { + "type": "vcs", + "url": "https://github.com/Alexhuszagh/minimal-lexical" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#miniz_oxide@0.8.9", + "author": "Frommi , oyvindln , Rich Geldreich richgel99@gmail.com", + "name": "miniz_oxide", + "version": "0.8.9", + "description": "DEFLATE compression and decompression library rewritten in Rust based on miniz", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "1fa76a2c86f704bdb222d66965fb3d63269ce38518b83cb0575fca855ebb6316" + } + ], + "licenses": [ + { + "expression": "MIT OR Zlib OR Apache-2.0" + } + ], + "purl": "pkg:cargo/miniz_oxide@0.8.9", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/miniz_oxide" + }, + { + "type": "website", + "url": "https://github.com/Frommi/miniz_oxide/tree/master/miniz_oxide" + }, + { + "type": "vcs", + "url": "https://github.com/Frommi/miniz_oxide/tree/master/miniz_oxide" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#mio@1.1.1", + "author": "Carl Lerche , Thomas de Zeeuw , Tokio Contributors ", + "name": "mio", + "version": "1.1.1", + "description": "Lightweight non-blocking I/O.", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "a69bcab0ad47271a0234d9422b131806bf3968021e5dc9328caf2d4cd58557fc" + } + ], + "licenses": [ + { + "expression": "MIT" + } + ], + "purl": "pkg:cargo/mio@1.1.1", + "externalReferences": [ + { + "type": "website", + "url": "https://github.com/tokio-rs/mio" + }, + { + "type": "vcs", + "url": "https://github.com/tokio-rs/mio" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#mixtrics@0.1.0", + "author": "MrCroxx ", + "name": "mixtrics", + "version": "0.1.0", + "description": "One crate for all metrics.", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "749ed12bab176c8a42c13a679dd2de12876d5ad4abe7525548e31ae001a9ebbf" + } + ], + "licenses": [ + { + "expression": "Apache-2.0" + } + ], + "purl": "pkg:cargo/mixtrics@0.1.0", + "externalReferences": [ + { + "type": "website", + "url": "https://github.com/foyer-rs/mixtrics" + }, + { + "type": "vcs", + "url": "https://github.com/foyer-rs/mixtrics" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#moxcms@0.8.1", + "author": "Radzivon Bartoshyk", + "name": "moxcms", + "version": "0.8.1", + "description": "Simple Color Management in Rust", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "bb85c154ba489f01b25c0d36ae69a87e4a1c73a72631fc6c0eb6dde34a73e44b" + } + ], + "licenses": [ + { + "expression": "BSD-3-Clause OR Apache-2.0" + } + ], + "purl": "pkg:cargo/moxcms@0.8.1", + "externalReferences": [ + { + "type": "documentation", + "url": "https://github.com/awxkee/moxcms" + }, + { + "type": "website", + "url": "https://github.com/awxkee/moxcms" + }, + { + "type": "vcs", + "url": "https://github.com/awxkee/moxcms.git" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#multimap@0.10.1", + "author": "Håvar Nøvik ", + "name": "multimap", + "version": "0.10.1", + "description": "A multimap implementation.", + "scope": "excluded", + "hashes": [ + { + "alg": "SHA-256", + "content": "1d87ecb2933e8aeadb3e3a02b828fed80a7528047e68b4f424523a0981a3a084" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/multimap@0.10.1", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/multimap" + }, + { + "type": "vcs", + "url": "https://github.com/havarnov/multimap" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#murmur3@0.5.2", + "author": "Stu Small ", + "name": "murmur3", + "version": "0.5.2", + "description": "A rust implementation of Murmur3 hash", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "9252111cf132ba0929b6f8e030cac2a24b507f3a4d6db6fb2896f27b354c714b" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/murmur3@0.5.2", + "externalReferences": [ + { + "type": "vcs", + "url": "https://github.com/stusmall/murmur3" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#murmurhash32@0.3.1", + "author": "Paul Masurel ", + "name": "murmurhash32", + "version": "0.3.1", + "description": "A simple implementation of murmurhash32_2", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "2195bf6aa996a481483b29d62a7663eed3fe39600c460e323f8ff41e90bdd89b" + } + ], + "licenses": [ + { + "expression": "MIT" + } + ], + "purl": "pkg:cargo/murmurhash32@0.3.1", + "externalReferences": [ + { + "type": "vcs", + "url": "https://github.com/quickwit-inc/murmurhash32" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#nano-gemm-c32@0.2.1", + "author": "sarah <>", + "name": "nano-gemm-c32", + "version": "0.2.1", + "description": "Small matrix multiplication", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "0775b1e2520e64deee8fc78b7732e3091fb7585017c0b0f9f4b451757bbbc562" + } + ], + "licenses": [ + { + "expression": "MIT" + } + ], + "purl": "pkg:cargo/nano-gemm-c32@0.2.1", + "externalReferences": [ + { + "type": "vcs", + "url": "https://github.com/sarah-ek/nano-gemm/" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#nano-gemm-c64@0.2.1", + "author": "sarah <>", + "name": "nano-gemm-c64", + "version": "0.2.1", + "description": "Small matrix multiplication", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "9af49a20d58816e6b5ee65f64142e50edb5eba152678d4bb7377fcbf63f8437a" + } + ], + "licenses": [ + { + "expression": "MIT" + } + ], + "purl": "pkg:cargo/nano-gemm-c64@0.2.1", + "externalReferences": [ + { + "type": "vcs", + "url": "https://github.com/sarah-ek/nano-gemm/" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#nano-gemm-codegen@0.2.1", + "author": "sarah <>", + "name": "nano-gemm-codegen", + "version": "0.2.1", + "description": "Small matrix multiplication", + "scope": "excluded", + "hashes": [ + { + "alg": "SHA-256", + "content": "6cc8d495c791627779477a2cf5df60049f5b165342610eb0d76bee5ff5c5d74c" + } + ], + "licenses": [ + { + "expression": "MIT" + } + ], + "purl": "pkg:cargo/nano-gemm-codegen@0.2.1", + "externalReferences": [ + { + "type": "vcs", + "url": "https://github.com/sarah-ek/nano-gemm/" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#nano-gemm-core@0.2.1", + "author": "sarah <>", + "name": "nano-gemm-core", + "version": "0.2.1", + "description": "Small matrix multiplication", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "d998dfa644de87a0f8660e5ea511d7cb5c33b5a2d9847b7af57a2565105089f0" + } + ], + "licenses": [ + { + "expression": "MIT" + } + ], + "purl": "pkg:cargo/nano-gemm-core@0.2.1", + "externalReferences": [ + { + "type": "vcs", + "url": "https://github.com/sarah-ek/nano-gemm/" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#nano-gemm-f32@0.2.1", + "author": "sarah <>", + "name": "nano-gemm-f32", + "version": "0.2.1", + "description": "Small matrix multiplication", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "879d962e79bc8952e4ad21ca4845a21132540ed3f5e01184b2ff7f720e666523" + } + ], + "licenses": [ + { + "expression": "MIT" + } + ], + "purl": "pkg:cargo/nano-gemm-f32@0.2.1", + "externalReferences": [ + { + "type": "vcs", + "url": "https://github.com/sarah-ek/nano-gemm/" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#nano-gemm-f64@0.2.1", + "author": "sarah <>", + "name": "nano-gemm-f64", + "version": "0.2.1", + "description": "Small matrix multiplication", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "b9a513473dce7dc00c7e7c318481ca4494034e76997218d8dad51bd9f007a815" + } + ], + "licenses": [ + { + "expression": "MIT" + } + ], + "purl": "pkg:cargo/nano-gemm-f64@0.2.1", + "externalReferences": [ + { + "type": "vcs", + "url": "https://github.com/sarah-ek/nano-gemm/" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#nano-gemm@0.2.2", + "name": "nano-gemm", + "version": "0.2.2", + "description": "Small matrix multiplication", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "9e04345dc84b498ff89fe0d38543d1f170da9e43a2c2bcee73a0f9069f72d081" + } + ], + "licenses": [ + { + "expression": "MIT" + } + ], + "purl": "pkg:cargo/nano-gemm@0.2.2", + "externalReferences": [ + { + "type": "vcs", + "url": "https://github.com/sarah-ek/nano-gemm/" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#nanorand@0.7.0", + "author": "Lucy ", + "name": "nanorand", + "version": "0.7.0", + "description": "A tiny, fast, zero-dep library for random number generation.", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "6a51313c5820b0b02bd422f4b44776fbf47961755c74ce64afc73bfad10226c3" + } + ], + "licenses": [ + { + "expression": "Zlib" + } + ], + "purl": "pkg:cargo/nanorand@0.7.0", + "externalReferences": [ + { + "type": "vcs", + "url": "https://github.com/Absolucy/nanorand-rs" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#native-tls@0.2.18", + "author": "Steven Fackler ", + "name": "native-tls", + "version": "0.2.18", + "description": "A wrapper over a platform's native TLS implementation", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "465500e14ea162429d264d44189adc38b199b62b1c21eea9f69e4b73cb03bbf2" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/native-tls@0.2.18", + "externalReferences": [ + { + "type": "website", + "url": "https://lib.rs/crates/native-tls" + }, + { + "type": "vcs", + "url": "https://github.com/rust-native-tls/rust-native-tls" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#ndarray@0.17.2", + "author": "Ulrik Sverdrup \"bluss\", Jim Turner", + "name": "ndarray", + "version": "0.17.2", + "description": "An n-dimensional array for general elements and for numerics. Lightweight array views and slicing; views support chunking and splitting.", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "520080814a7a6b4a6e9070823bb24b4531daac8c4627e08ba5de8c5ef2f2752d" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/ndarray@0.17.2", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/ndarray/" + }, + { + "type": "vcs", + "url": "https://github.com/rust-ndarray/ndarray" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#nom@7.1.3", + "author": "contact@geoffroycouprie.com", + "name": "nom", + "version": "7.1.3", + "description": "A byte-oriented, zero-copy, parser combinators library", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "d273983c5a657a70a3e8f2a01329822f3b8c8172b73826411a55751e404a0a4a" + } + ], + "licenses": [ + { + "expression": "MIT" + } + ], + "purl": "pkg:cargo/nom@7.1.3", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/nom" + }, + { + "type": "vcs", + "url": "https://github.com/Geal/nom" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#nu-ansi-term@0.50.3", + "author": "ogham@bsago.me, Ryan Scheel (Havvy) , Josh Triplett , The Nushell Project Developers", + "name": "nu-ansi-term", + "version": "0.50.3", + "description": "Library for ANSI terminal colors and styles (bold, underline)", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "7957b9740744892f114936ab4a57b3f487491bbeafaf8083688b16841a4240e5" + } + ], + "licenses": [ + { + "expression": "MIT" + } + ], + "purl": "pkg:cargo/nu-ansi-term@0.50.3", + "externalReferences": [ + { + "type": "vcs", + "url": "https://github.com/nushell/nu-ansi-term" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#num-bigint-dig@0.8.6", + "author": "dignifiedquire , The Rust Project Developers", + "name": "num-bigint-dig", + "version": "0.8.6", + "description": "Big integer implementation for Rust", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "e661dda6640fad38e827a6d4a310ff4763082116fe217f279885c97f511bb0b7" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/num-bigint-dig@0.8.6", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/num-bigint-dig" + }, + { + "type": "website", + "url": "https://github.com/dignifiedquire/num-bigint" + }, + { + "type": "vcs", + "url": "https://github.com/dignifiedquire/num-bigint" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#num-bigint@0.4.6", + "author": "The Rust Project Developers", + "name": "num-bigint", + "version": "0.4.6", + "description": "Big integer implementation for Rust", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "a5e44f723f1133c9deac646763579fdb3ac745e418f2a7af9cd0c431da1f20b9" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/num-bigint@0.4.6", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/num-bigint" + }, + { + "type": "website", + "url": "https://github.com/rust-num/num-bigint" + }, + { + "type": "vcs", + "url": "https://github.com/rust-num/num-bigint" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#num-complex@0.2.4", + "author": "The Rust Project Developers", + "name": "num-complex", + "version": "0.2.4", + "description": "Complex numbers implementation for Rust", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "b6b19411a9719e753aff12e5187b74d60d3dc449ec3f4dc21e3989c3f554bc95" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/num-complex@0.2.4", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/num-complex" + }, + { + "type": "website", + "url": "https://github.com/rust-num/num-complex" + }, + { + "type": "vcs", + "url": "https://github.com/rust-num/num-complex" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#num-complex@0.4.6", + "author": "The Rust Project Developers", + "name": "num-complex", + "version": "0.4.6", + "description": "Complex numbers implementation for Rust", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "73f88a1307638156682bada9d7604135552957b7818057dcef22705b4d509495" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/num-complex@0.4.6", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/num-complex" + }, + { + "type": "website", + "url": "https://github.com/rust-num/num-complex" + }, + { + "type": "vcs", + "url": "https://github.com/rust-num/num-complex" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#num-conv@0.2.0", + "author": "Jacob Pratt ", + "name": "num-conv", + "version": "0.2.0", + "description": "`num_conv` is a crate to convert between integer types without using `as` casts. This provides better certainty when refactoring, makes the exact behavior of code more explicit, and allows using turbofish syntax. ", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "cf97ec579c3c42f953ef76dbf8d55ac91fb219dde70e49aa4a6b7d74e9919050" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/num-conv@0.2.0", + "externalReferences": [ + { + "type": "vcs", + "url": "https://github.com/jhpratt/num-conv" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#num-integer@0.1.46", + "author": "The Rust Project Developers", + "name": "num-integer", + "version": "0.1.46", + "description": "Integer traits and functions", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "7969661fd2958a5cb096e56c8e1ad0444ac2bbcd0061bd28660485a44879858f" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/num-integer@0.1.46", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/num-integer" + }, + { + "type": "website", + "url": "https://github.com/rust-num/num-integer" + }, + { + "type": "vcs", + "url": "https://github.com/rust-num/num-integer" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#num-iter@0.1.45", + "author": "The Rust Project Developers", + "name": "num-iter", + "version": "0.1.45", + "description": "External iterators for generic mathematics", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "1429034a0490724d0075ebb2bc9e875d6503c3cf69e235a8941aa757d83ef5bf" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/num-iter@0.1.45", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/num-iter" + }, + { + "type": "website", + "url": "https://github.com/rust-num/num-iter" + }, + { + "type": "vcs", + "url": "https://github.com/rust-num/num-iter" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#num-rational@0.4.2", + "author": "The Rust Project Developers", + "name": "num-rational", + "version": "0.4.2", + "description": "Rational numbers implementation for Rust", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "f83d14da390562dca69fc84082e73e548e1ad308d24accdedd2720017cb37824" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/num-rational@0.4.2", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/num-rational" + }, + { + "type": "website", + "url": "https://github.com/rust-num/num-rational" + }, + { + "type": "vcs", + "url": "https://github.com/rust-num/num-rational" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#num-traits@0.2.19", + "author": "The Rust Project Developers", + "name": "num-traits", + "version": "0.2.19", + "description": "Numeric traits for generic mathematics", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/num-traits@0.2.19", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/num-traits" + }, + { + "type": "website", + "url": "https://github.com/rust-num/num-traits" + }, + { + "type": "vcs", + "url": "https://github.com/rust-num/num-traits" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#num@0.4.3", + "author": "The Rust Project Developers", + "name": "num", + "version": "0.4.3", + "description": "A collection of numeric types and traits for Rust, including bigint, complex, rational, range iterators, generic integers, and more! ", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "35bd024e8b2ff75562e5f34e7f4905839deb4b22955ef5e73d2fea1b9813cb23" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/num@0.4.3", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/num" + }, + { + "type": "website", + "url": "https://github.com/rust-num/num" + }, + { + "type": "vcs", + "url": "https://github.com/rust-num/num" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#num_cpus@1.17.0", + "author": "Sean McArthur ", + "name": "num_cpus", + "version": "1.17.0", + "description": "Get the number of CPUs on a machine.", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "91df4bbde75afed763b708b7eee1e8e7651e02d97f6d5dd763e89367e957b23b" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/num_cpus@1.17.0", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/num_cpus" + }, + { + "type": "vcs", + "url": "https://github.com/seanmonstar/num_cpus" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#number_prefix@0.4.0", + "author": "Benjamin Sago ", + "name": "number_prefix", + "version": "0.4.0", + "description": "Library for numeric prefixes (kilo, giga, kibi).", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "830b246a0e5f20af87141b25c173cd1b609bd7779a4617d6ec582abaf90870f3" + } + ], + "licenses": [ + { + "expression": "MIT" + } + ], + "purl": "pkg:cargo/number_prefix@0.4.0", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/number_prefix" + }, + { + "type": "vcs", + "url": "https://github.com/ogham/rust-number-prefix" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#object_store@0.12.5", + "name": "object_store", + "version": "0.12.5", + "description": "A generic object store interface for uniformly interacting with AWS S3, Google Cloud Storage, Azure Blob Storage and local files.", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "fbfbfff40aeccab00ec8a910b57ca8ecf4319b335c542f2edcd19dd25a1e2a00" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/object_store@0.12.5", + "externalReferences": [ + { + "type": "vcs", + "url": "https://github.com/apache/arrow-rs-object-store" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#once_cell@1.21.4", + "author": "Aleksey Kladov ", + "name": "once_cell", + "version": "1.21.4", + "description": "Single assignment cells and lazy values.", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/once_cell@1.21.4", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/once_cell" + }, + { + "type": "vcs", + "url": "https://github.com/matklad/once_cell" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#once_cell_polyfill@1.70.2", + "name": "once_cell_polyfill", + "version": "1.70.2", + "description": "Polyfill for `OnceCell` stdlib feature for use with older MSRVs", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "384b8ab6d37215f3c5301a95a4accb5d64aa607f1fcb26a11b5303878451b4fe" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/once_cell_polyfill@1.70.2", + "externalReferences": [ + { + "type": "vcs", + "url": "https://github.com/polyfill-rs/once_cell_polyfill" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#oneshot@0.1.13", + "author": "Linus Färnstrand ", + "name": "oneshot", + "version": "0.1.13", + "description": "Oneshot spsc channel with (potentially) lock-free non-blocking send, and a receiver supporting both thread blocking receive operations as well as Future based async polling. ", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "269bca4c2591a28585d6bf10d9ed0332b7d76900a1b02bec41bdc3a2cdcda107" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/oneshot@0.1.13", + "externalReferences": [ + { + "type": "vcs", + "url": "https://github.com/faern/oneshot" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#oorandom@11.1.5", + "author": "Simon Heath ", + "name": "oorandom", + "version": "11.1.5", + "description": "A tiny, robust PRNG implementation.", + "scope": "excluded", + "hashes": [ + { + "alg": "SHA-256", + "content": "d6790f58c7ff633d8771f42965289203411a5e5c68388703c06e14f24770b41e" + } + ], + "licenses": [ + { + "expression": "MIT" + } + ], + "purl": "pkg:cargo/oorandom@11.1.5", + "externalReferences": [ + { + "type": "vcs", + "url": "https://hg.sr.ht/~icefox/oorandom" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#opentelemetry-http@0.27.0", + "name": "opentelemetry-http", + "version": "0.27.0", + "description": "Helper implementations for sending HTTP requests. Uses include propagating and extracting context over http, exporting telemetry, requesting sampling strategies.", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "10a8a7f5f6ba7c1b286c2fbca0454eaba116f63bbe69ed250b642d36fbb04d80" + } + ], + "licenses": [ + { + "expression": "Apache-2.0" + } + ], + "purl": "pkg:cargo/opentelemetry-http@0.27.0", + "externalReferences": [ + { + "type": "website", + "url": "https://github.com/open-telemetry/opentelemetry-rust" + }, + { + "type": "vcs", + "url": "https://github.com/open-telemetry/opentelemetry-rust" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#opentelemetry-otlp@0.27.0", + "name": "opentelemetry-otlp", + "version": "0.27.0", + "description": "Exporter for the OpenTelemetry Collector", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "91cf61a1868dacc576bf2b2a1c3e9ab150af7272909e80085c3173384fe11f76" + } + ], + "licenses": [ + { + "expression": "Apache-2.0" + } + ], + "purl": "pkg:cargo/opentelemetry-otlp@0.27.0", + "externalReferences": [ + { + "type": "website", + "url": "https://github.com/open-telemetry/opentelemetry-rust/tree/main/opentelemetry-otlp" + }, + { + "type": "vcs", + "url": "https://github.com/open-telemetry/opentelemetry-rust/tree/main/opentelemetry-otlp" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#opentelemetry-proto@0.27.0", + "name": "opentelemetry-proto", + "version": "0.27.0", + "description": "Protobuf generated files and transformations.", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "a6e05acbfada5ec79023c85368af14abd0b307c015e9064d249b2a950ef459a6" + } + ], + "licenses": [ + { + "expression": "Apache-2.0" + } + ], + "purl": "pkg:cargo/opentelemetry-proto@0.27.0", + "externalReferences": [ + { + "type": "website", + "url": "https://github.com/open-telemetry/opentelemetry-rust/tree/main/opentelemetry-proto" + }, + { + "type": "vcs", + "url": "https://github.com/open-telemetry/opentelemetry-rust/tree/main/opentelemetry-proto" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#opentelemetry@0.27.1", + "name": "opentelemetry", + "version": "0.27.1", + "description": "OpenTelemetry API for Rust", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "ab70038c28ed37b97d8ed414b6429d343a8bbf44c9f79ec854f3a643029ba6d7" + } + ], + "licenses": [ + { + "expression": "Apache-2.0" + } + ], + "purl": "pkg:cargo/opentelemetry@0.27.1", + "externalReferences": [ + { + "type": "website", + "url": "https://github.com/open-telemetry/opentelemetry-rust" + }, + { + "type": "vcs", + "url": "https://github.com/open-telemetry/opentelemetry-rust" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#opentelemetry_sdk@0.27.1", + "name": "opentelemetry_sdk", + "version": "0.27.1", + "description": "The SDK for the OpenTelemetry metrics collection and distributed tracing framework", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "231e9d6ceef9b0b2546ddf52335785ce41252bc7474ee8ba05bfad277be13ab8" + } + ], + "licenses": [ + { + "expression": "Apache-2.0" + } + ], + "purl": "pkg:cargo/opentelemetry_sdk@0.27.1", + "externalReferences": [ + { + "type": "website", + "url": "https://github.com/open-telemetry/opentelemetry-rust" + }, + { + "type": "vcs", + "url": "https://github.com/open-telemetry/opentelemetry-rust" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#option-ext@0.2.0", + "author": "Simon Ochsenreither ", + "name": "option-ext", + "version": "0.2.0", + "description": "Extends `Option` with additional operations", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "04744f49eae99ab78e0d5c0b603ab218f515ea8cfe5a456d7629ad883a3b6e7d" + } + ], + "licenses": [ + { + "expression": "MPL-2.0" + } + ], + "purl": "pkg:cargo/option-ext@0.2.0", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/option-ext/" + }, + { + "type": "website", + "url": "https://github.com/soc/option-ext" + }, + { + "type": "vcs", + "url": "https://github.com/soc/option-ext.git" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#ordered-float@2.10.1", + "author": "Jonathan Reem , Matt Brubeck ", + "name": "ordered-float", + "version": "2.10.1", + "description": "Wrappers for total ordering on floats", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "68f19d67e5a2795c94e73e0bb1cc1a7edeb2e28efd39e2e1c9b7a40c1108b11c" + } + ], + "licenses": [ + { + "expression": "MIT" + } + ], + "purl": "pkg:cargo/ordered-float@2.10.1", + "externalReferences": [ + { + "type": "vcs", + "url": "https://github.com/reem/rust-ordered-float" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#ordered_hash_map@0.4.0", + "author": "William Correia ", + "name": "ordered_hash_map", + "version": "0.4.0", + "description": "HashMap which preserves insertion order", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "ab0e5f22bf6dd04abd854a8874247813a8fa2c8c1260eba6fbb150270ce7c176" + } + ], + "licenses": [ + { + "expression": "BSD-2-Clause" + } + ], + "purl": "pkg:cargo/ordered_hash_map@0.4.0", + "externalReferences": [ + { + "type": "vcs", + "url": "https://gitlab.com/kelderon/rs-collections" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#outref@0.5.2", + "name": "outref", + "version": "0.5.2", + "description": "Out reference", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "1a80800c0488c3a21695ea981a54918fbb37abf04f4d0720c453632255e2ff0e" + } + ], + "licenses": [ + { + "expression": "MIT" + } + ], + "purl": "pkg:cargo/outref@0.5.2", + "externalReferences": [ + { + "type": "vcs", + "url": "https://github.com/Nugine/outref" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#ownedbytes@0.7.0", + "author": "Paul Masurel , Pascal Seitz ", + "name": "ownedbytes", + "version": "0.7.0", + "description": "Expose data as static slice", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "c3a059efb063b8f425b948e042e6b9bd85edfe60e913630ed727b23e2dfcc558" + } + ], + "licenses": [ + { + "expression": "MIT" + } + ], + "purl": "pkg:cargo/ownedbytes@0.7.0", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/ownedbytes/" + }, + { + "type": "website", + "url": "https://github.com/quickwit-oss/tantivy" + }, + { + "type": "vcs", + "url": "https://github.com/quickwit-oss/tantivy" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#owo-colors@3.5.0", + "author": "jam1garner <8260240+jam1garner@users.noreply.github.com>", + "name": "owo-colors", + "version": "3.5.0", + "description": "Zero-allocation terminal colors that'll make people go owo", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "c1b04fb49957986fdce4d6ee7a65027d55d4b6d2265e5848bbb507b58ccfdb6f" + } + ], + "licenses": [ + { + "expression": "MIT" + } + ], + "purl": "pkg:cargo/owo-colors@3.5.0", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/owo-colors" + }, + { + "type": "vcs", + "url": "https://github.com/jam1garner/owo-colors" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#p256@0.11.1", + "author": "RustCrypto Developers", + "name": "p256", + "version": "0.11.1", + "description": "Pure Rust implementation of the NIST P-256 (a.k.a. secp256r1, prime256v1) elliptic curve with support for ECDH, ECDSA signing/verification, and general purpose curve arithmetic ", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "51f44edd08f51e2ade572f141051021c5af22677e42b7dd28a88155151c33594" + } + ], + "licenses": [ + { + "expression": "Apache-2.0 OR MIT" + } + ], + "purl": "pkg:cargo/p256@0.11.1", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/p256" + }, + { + "type": "vcs", + "url": "https://github.com/RustCrypto/elliptic-curves/tree/master/p256" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#parking@2.2.1", + "author": "Stjepan Glavina , The Rust Project Developers", + "name": "parking", + "version": "2.2.1", + "description": "Thread parking and unparking", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "f38d5652c16fde515bb1ecef450ab0f6a219d619a7274976324d5e377f7dceba" + } + ], + "licenses": [ + { + "expression": "Apache-2.0 OR MIT" + } + ], + "purl": "pkg:cargo/parking@2.2.1", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/parking" + }, + { + "type": "website", + "url": "https://github.com/smol-rs/parking" + }, + { + "type": "vcs", + "url": "https://github.com/smol-rs/parking" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#parking_lot@0.12.5", + "author": "Amanieu d'Antras ", + "name": "parking_lot", + "version": "0.12.5", + "description": "More compact and efficient implementations of the standard synchronization primitives.", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "93857453250e3077bd71ff98b6a65ea6621a19bb0f559a85248955ac12c45a1a" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/parking_lot@0.12.5", + "externalReferences": [ + { + "type": "vcs", + "url": "https://github.com/Amanieu/parking_lot" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#parking_lot_core@0.9.12", + "author": "Amanieu d'Antras ", + "name": "parking_lot_core", + "version": "0.9.12", + "description": "An advanced API for creating custom synchronization primitives.", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "2621685985a2ebf1c516881c026032ac7deafcda1a2c9b7850dc81e3dfcb64c1" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/parking_lot_core@0.9.12", + "externalReferences": [ + { + "type": "vcs", + "url": "https://github.com/Amanieu/parking_lot" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#parquet@55.2.0", + "author": "Apache Arrow ", + "name": "parquet", + "version": "55.2.0", + "description": "Apache Parquet implementation in Rust", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "b17da4150748086bd43352bc77372efa9b6e3dbd06a04831d2a98c041c225cfa" + } + ], + "licenses": [ + { + "expression": "Apache-2.0" + } + ], + "purl": "pkg:cargo/parquet@55.2.0", + "externalReferences": [ + { + "type": "website", + "url": "https://github.com/apache/arrow-rs" + }, + { + "type": "vcs", + "url": "https://github.com/apache/arrow-rs" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#paste@1.0.15", + "author": "David Tolnay ", + "name": "paste", + "version": "1.0.15", + "description": "Macros for all your token pasting needs", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "57c0d7b74b563b49d38dae00a0c37d4d6de9b432382b2892f0574ddcae73fd0a" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/paste@1.0.15", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/paste" + }, + { + "type": "vcs", + "url": "https://github.com/dtolnay/paste" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#pbkdf2@0.12.2", + "author": "RustCrypto Developers", + "name": "pbkdf2", + "version": "0.12.2", + "description": "Generic implementation of PBKDF2", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "f8ed6a7761f76e3b9f92dfb0a60a6a6477c61024b775147ff0973a02653abaf2" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/pbkdf2@0.12.2", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/pbkdf2" + }, + { + "type": "vcs", + "url": "https://github.com/RustCrypto/password-hashes/tree/master/pbkdf2" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#pear@0.2.9", + "author": "Sergio Benitez ", + "name": "pear", + "version": "0.2.9", + "description": "A pear is a fruit.", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "bdeeaa00ce488657faba8ebf44ab9361f9365a97bd39ffb8a60663f57ff4b467" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/pear@0.2.9", + "externalReferences": [ + { + "type": "vcs", + "url": "https://github.com/SergioBenitez/Pear" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#pear_codegen@0.2.9", + "author": "Sergio Benitez ", + "name": "pear_codegen", + "version": "0.2.9", + "description": "A (codegen) pear is a fruit.", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "4bab5b985dc082b345f812b7df84e1bef27e7207b39e448439ba8bd69c93f147" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/pear_codegen@0.2.9", + "externalReferences": [ + { + "type": "vcs", + "url": "https://github.com/SergioBenitez/Pear" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#pem-rfc7468@0.7.0", + "author": "RustCrypto Developers", + "name": "pem-rfc7468", + "version": "0.7.0", + "description": "PEM Encoding (RFC 7468) for PKIX, PKCS, and CMS Structures, implementing a strict subset of the original Privacy-Enhanced Mail encoding intended specifically for use with cryptographic keys, certificates, and other messages. Provides a no_std-friendly, constant-time implementation suitable for use with cryptographic private keys. ", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "88b39c9bfcfc231068454382784bb460aae594343fb030d46e9f50a645418412" + } + ], + "licenses": [ + { + "expression": "Apache-2.0 OR MIT" + } + ], + "purl": "pkg:cargo/pem-rfc7468@0.7.0", + "externalReferences": [ + { + "type": "vcs", + "url": "https://github.com/RustCrypto/formats/tree/master/pem-rfc7468" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#pem@3.0.6", + "author": "Jonathan Creekmore ", + "name": "pem", + "version": "3.0.6", + "description": "Parse and encode PEM-encoded data.", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "1d30c53c26bc5b31a98cd02d20f25a7c8567146caf63ed593a9d87b2775291be" + } + ], + "licenses": [ + { + "expression": "MIT" + } + ], + "purl": "pkg:cargo/pem@3.0.6", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/pem/" + }, + { + "type": "website", + "url": "https://github.com/jcreekmore/pem-rs.git" + }, + { + "type": "vcs", + "url": "https://github.com/jcreekmore/pem-rs.git" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#percent-encoding@2.3.2", + "author": "The rust-url developers", + "name": "percent-encoding", + "version": "2.3.2", + "description": "Percent encoding and decoding", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/percent-encoding@2.3.2", + "externalReferences": [ + { + "type": "vcs", + "url": "https://github.com/servo/rust-url/" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#pest@2.8.6", + "author": "Dragoș Tiselice ", + "name": "pest", + "version": "2.8.6", + "description": "The Elegant Parser", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "e0848c601009d37dfa3430c4666e147e49cdcf1b92ecd3e63657d8a5f19da662" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/pest@2.8.6", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/pest" + }, + { + "type": "website", + "url": "https://pest.rs/" + }, + { + "type": "vcs", + "url": "https://github.com/pest-parser/pest" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#pest_derive@2.8.6", + "author": "Dragoș Tiselice ", + "name": "pest_derive", + "version": "2.8.6", + "description": "pest's derive macro", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "11f486f1ea21e6c10ed15d5a7c77165d0ee443402f0780849d1768e7d9d6fe77" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/pest_derive@2.8.6", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/pest" + }, + { + "type": "website", + "url": "https://pest.rs/" + }, + { + "type": "vcs", + "url": "https://github.com/pest-parser/pest" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#pest_generator@2.8.6", + "author": "Dragoș Tiselice ", + "name": "pest_generator", + "version": "2.8.6", + "description": "pest code generator", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "8040c4647b13b210a963c1ed407c1ff4fdfa01c31d6d2a098218702e6664f94f" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/pest_generator@2.8.6", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/pest" + }, + { + "type": "website", + "url": "https://pest.rs/" + }, + { + "type": "vcs", + "url": "https://github.com/pest-parser/pest" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#pest_meta@2.8.6", + "author": "Dragoș Tiselice ", + "name": "pest_meta", + "version": "2.8.6", + "description": "pest meta language parser and validator", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "89815c69d36021a140146f26659a81d6c2afa33d216d736dd4be5381a7362220" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/pest_meta@2.8.6", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/pest" + }, + { + "type": "website", + "url": "https://pest.rs/" + }, + { + "type": "vcs", + "url": "https://github.com/pest-parser/pest" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#petgraph@0.8.3", + "author": "bluss, mitchmindtree", + "name": "petgraph", + "version": "0.8.3", + "description": "Graph data structure library. Provides graph types and graph algorithms.", + "scope": "excluded", + "hashes": [ + { + "alg": "SHA-256", + "content": "8701b58ea97060d5e5b155d383a69952a60943f0e6dfe30b04c287beb0b27455" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/petgraph@0.8.3", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/petgraph/" + }, + { + "type": "vcs", + "url": "https://github.com/petgraph/petgraph" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#pin-project-internal@1.1.11", + "name": "pin-project-internal", + "version": "1.1.11", + "description": "Implementation detail of the `pin-project` crate. ", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "d9b20ed30f105399776b9c883e68e536ef602a16ae6f596d2c473591d6ad64c6" + } + ], + "licenses": [ + { + "expression": "Apache-2.0 OR MIT" + } + ], + "purl": "pkg:cargo/pin-project-internal@1.1.11", + "externalReferences": [ + { + "type": "vcs", + "url": "https://github.com/taiki-e/pin-project" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#pin-project-lite@0.2.17", + "name": "pin-project-lite", + "version": "0.2.17", + "description": "A lightweight version of pin-project written with declarative macros. ", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd" + } + ], + "licenses": [ + { + "expression": "Apache-2.0 OR MIT" + } + ], + "purl": "pkg:cargo/pin-project-lite@0.2.17", + "externalReferences": [ + { + "type": "vcs", + "url": "https://github.com/taiki-e/pin-project-lite" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#pin-project@1.1.11", + "name": "pin-project", + "version": "1.1.11", + "description": "A crate for safe and ergonomic pin-projection. ", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "f1749c7ed4bcaf4c3d0a3efc28538844fb29bcdd7d2b67b2be7e20ba861ff517" + } + ], + "licenses": [ + { + "expression": "Apache-2.0 OR MIT" + } + ], + "purl": "pkg:cargo/pin-project@1.1.11", + "externalReferences": [ + { + "type": "vcs", + "url": "https://github.com/taiki-e/pin-project" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#pin-utils@0.1.0", + "author": "Josef Brandl ", + "name": "pin-utils", + "version": "0.1.0", + "description": "Utilities for pinning ", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "8b870d8c151b6f2fb93e84a13146138f05d02ed11c7e7c54f8826aaaf7c9f184" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/pin-utils@0.1.0", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/pin-utils" + }, + { + "type": "vcs", + "url": "https://github.com/rust-lang-nursery/pin-utils" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#pkcs1@0.7.5", + "author": "RustCrypto Developers", + "name": "pkcs1", + "version": "0.7.5", + "description": "Pure Rust implementation of Public-Key Cryptography Standards (PKCS) #1: RSA Cryptography Specifications Version 2.2 (RFC 8017) ", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "c8ffb9f10fa047879315e6625af03c164b16962a5368d724ed16323b68ace47f" + } + ], + "licenses": [ + { + "expression": "Apache-2.0 OR MIT" + } + ], + "purl": "pkg:cargo/pkcs1@0.7.5", + "externalReferences": [ + { + "type": "vcs", + "url": "https://github.com/RustCrypto/formats/tree/master/pkcs1" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#pkcs8@0.10.2", + "author": "RustCrypto Developers", + "name": "pkcs8", + "version": "0.10.2", + "description": "Pure Rust implementation of Public-Key Cryptography Standards (PKCS) #8: Private-Key Information Syntax Specification (RFC 5208), with additional support for PKCS#8v2 asymmetric key packages (RFC 5958) ", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "f950b2377845cebe5cf8b5165cb3cc1a5e0fa5cfa3e1f7f55707d8fd82e0a7b7" + } + ], + "licenses": [ + { + "expression": "Apache-2.0 OR MIT" + } + ], + "purl": "pkg:cargo/pkcs8@0.10.2", + "externalReferences": [ + { + "type": "vcs", + "url": "https://github.com/RustCrypto/formats/tree/master/pkcs8" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#pkcs8@0.9.0", + "author": "RustCrypto Developers", + "name": "pkcs8", + "version": "0.9.0", + "description": "Pure Rust implementation of Public-Key Cryptography Standards (PKCS) #8: Private-Key Information Syntax Specification (RFC 5208), with additional support for PKCS#8v2 asymmetric key packages (RFC 5958) ", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "9eca2c590a5f85da82668fa685c09ce2888b9430e83299debf1f34b65fd4a4ba" + } + ], + "licenses": [ + { + "expression": "Apache-2.0 OR MIT" + } + ], + "purl": "pkg:cargo/pkcs8@0.9.0", + "externalReferences": [ + { + "type": "vcs", + "url": "https://github.com/RustCrypto/formats/tree/master/pkcs8" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#pkg-config@0.3.32", + "author": "Alex Crichton ", + "name": "pkg-config", + "version": "0.3.32", + "description": "A library to run the pkg-config system tool at build time in order to be used in Cargo build scripts. ", + "scope": "excluded", + "hashes": [ + { + "alg": "SHA-256", + "content": "7edddbd0b52d732b21ad9a5fab5c704c14cd949e5e9a1ec5929a24fded1b904c" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/pkg-config@0.3.32", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/pkg-config" + }, + { + "type": "vcs", + "url": "https://github.com/rust-lang/pkg-config-rs" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#plotters-backend@0.3.7", + "author": "Hao Hou ", + "name": "plotters-backend", + "version": "0.3.7", + "description": "Plotters Backend API", + "scope": "excluded", + "hashes": [ + { + "alg": "SHA-256", + "content": "df42e13c12958a16b3f7f4386b9ab1f3e7933914ecea48da7139435263a4172a" + } + ], + "licenses": [ + { + "expression": "MIT" + } + ], + "purl": "pkg:cargo/plotters-backend@0.3.7", + "externalReferences": [ + { + "type": "website", + "url": "https://plotters-rs.github.io" + }, + { + "type": "vcs", + "url": "https://github.com/plotters-rs/plotters" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#plotters-svg@0.3.7", + "author": "Hao Hou ", + "name": "plotters-svg", + "version": "0.3.7", + "description": "Plotters SVG backend", + "scope": "excluded", + "hashes": [ + { + "alg": "SHA-256", + "content": "51bae2ac328883f7acdfea3d66a7c35751187f870bc81f94563733a154d7a670" + } + ], + "licenses": [ + { + "expression": "MIT" + } + ], + "purl": "pkg:cargo/plotters-svg@0.3.7", + "externalReferences": [ + { + "type": "website", + "url": "https://plotters-rs.github.io" + }, + { + "type": "vcs", + "url": "https://github.com/plotters-rs/plotters.git" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#plotters@0.3.7", + "author": "Hao Hou ", + "name": "plotters", + "version": "0.3.7", + "description": "A Rust drawing library focus on data plotting for both WASM and native applications", + "scope": "excluded", + "hashes": [ + { + "alg": "SHA-256", + "content": "5aeb6f403d7a4911efb1e33402027fc44f29b5bf6def3effcc22d7bb75f2b747" + } + ], + "licenses": [ + { + "expression": "MIT" + } + ], + "purl": "pkg:cargo/plotters@0.3.7", + "externalReferences": [ + { + "type": "website", + "url": "https://plotters-rs.github.io/" + }, + { + "type": "vcs", + "url": "https://github.com/plotters-rs/plotters" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#png@0.18.1", + "author": "The image-rs Developers", + "name": "png", + "version": "0.18.1", + "description": "PNG decoding and encoding library in pure Rust", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "60769b8b31b2a9f263dae2776c37b1b28ae246943cf719eb6946a1db05128a61" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/png@0.18.1", + "externalReferences": [ + { + "type": "vcs", + "url": "https://github.com/image-rs/image-png" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#pollster@0.4.0", + "author": "Joshua Barretto ", + "name": "pollster", + "version": "0.4.0", + "description": "Synchronously block the thread until a future completes", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "2f3a9f18d041e6d0e102a0a46750538147e5e8992d3b4873aaafee2520b00ce3" + } + ], + "licenses": [ + { + "expression": "Apache-2.0 OR MIT" + } + ], + "purl": "pkg:cargo/pollster@0.4.0", + "externalReferences": [ + { + "type": "vcs", + "url": "https://github.com/zesterer/pollster" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#portable-atomic@1.13.1", + "name": "portable-atomic", + "version": "1.13.1", + "description": "Portable atomic types including support for 128-bit atomics, atomic float, etc. ", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "c33a9471896f1c69cecef8d20cbe2f7accd12527ce60845ff44c153bb2a21b49" + } + ], + "licenses": [ + { + "expression": "Apache-2.0 OR MIT" + } + ], + "purl": "pkg:cargo/portable-atomic@1.13.1", + "externalReferences": [ + { + "type": "vcs", + "url": "https://github.com/taiki-e/portable-atomic" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#potential_utf@0.1.4", + "author": "The ICU4X Project Developers", + "name": "potential_utf", + "version": "0.1.4", + "description": "Unvalidated string and character types", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "b73949432f5e2a09657003c25bca5e19a0e9c84f8058ca374f49e0ebe605af77" + } + ], + "licenses": [ + { + "expression": "Unicode-3.0" + } + ], + "purl": "pkg:cargo/potential_utf@0.1.4", + "externalReferences": [ + { + "type": "website", + "url": "https://icu4x.unicode.org" + }, + { + "type": "vcs", + "url": "https://github.com/unicode-org/icu4x" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#powerfmt@0.2.0", + "author": "Jacob Pratt ", + "name": "powerfmt", + "version": "0.2.0", + "description": " `powerfmt` is a library that provides utilities for formatting values. This crate makes it significantly easier to support filling to a minimum width with alignment, avoid heap allocation, and avoid repetitive calculations. ", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "439ee305def115ba05938db6eb1644ff94165c5ab5e9420d1c1bcedbba909391" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/powerfmt@0.2.0", + "externalReferences": [ + { + "type": "vcs", + "url": "https://github.com/jhpratt/powerfmt" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#ppmd-rust@1.4.0", + "name": "ppmd-rust", + "version": "1.4.0", + "description": "PPMd compression / decompression", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "efca4c95a19a79d1c98f791f10aebd5c1363b473244630bb7dbde1dc98455a24" + } + ], + "licenses": [ + { + "expression": "CC0-1.0 OR MIT-0" + } + ], + "purl": "pkg:cargo/ppmd-rust@1.4.0", + "externalReferences": [ + { + "type": "website", + "url": "https://github.com/hasenbanck/ppmd-rust" + }, + { + "type": "vcs", + "url": "https://github.com/hasenbanck/ppmd-rust" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#ppv-lite86@0.2.21", + "author": "The CryptoCorrosion Contributors", + "name": "ppv-lite86", + "version": "0.2.21", + "description": "Cross-platform cryptography-oriented low-level SIMD library.", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "85eae3c4ed2f50dcfe72643da4befc30deadb458a9b590d720cde2f2b1e97da9" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/ppv-lite86@0.2.21", + "externalReferences": [ + { + "type": "vcs", + "url": "https://github.com/cryptocorrosion/cryptocorrosion" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#prettyplease@0.2.37", + "author": "David Tolnay ", + "name": "prettyplease", + "version": "0.2.37", + "description": "A minimal `syn` syntax tree pretty-printer", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "479ca8adacdd7ce8f1fb39ce9ecccbfe93a3f1344b3d0d97f20bc0196208f62b" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/prettyplease@0.2.37", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/prettyplease" + }, + { + "type": "other", + "url": "prettyplease02" + }, + { + "type": "vcs", + "url": "https://github.com/dtolnay/prettyplease" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#private-gemm-x86@0.1.20", + "author": "sarah quiñones ", + "name": "private-gemm-x86", + "version": "0.1.20", + "description": "x86-64 matmul impl", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "0af8c3e5087969c323f667ccb4b789fa0954f5aa650550e38e81cf9108be21b5" + } + ], + "licenses": [ + { + "expression": "MIT" + } + ], + "purl": "pkg:cargo/private-gemm-x86@0.1.20", + "externalReferences": [ + { + "type": "vcs", + "url": "https://github.com/sarah-quinones/gemm-x64-v2/" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#proc-macro-error-attr2@2.0.0", + "author": "CreepySkeleton , GnomedDev ", + "name": "proc-macro-error-attr2", + "version": "2.0.0", + "description": "Attribute macro for the proc-macro-error2 crate", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "96de42df36bb9bba5542fe9f1a054b8cc87e172759a1868aa05c1f3acc89dfc5" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/proc-macro-error-attr2@2.0.0", + "externalReferences": [ + { + "type": "vcs", + "url": "https://github.com/GnomedDev/proc-macro-error-2" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#proc-macro-error2@2.0.1", + "author": "CreepySkeleton , GnomedDev ", + "name": "proc-macro-error2", + "version": "2.0.1", + "description": "Almost drop-in replacement to panics in proc-macros", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "11ec05c52be0a07b08061f7dd003e7d7092e0472bc731b4af7bb1ef876109802" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/proc-macro-error2@2.0.1", + "externalReferences": [ + { + "type": "vcs", + "url": "https://github.com/GnomedDev/proc-macro-error-2" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#proc-macro2-diagnostics@0.10.1", + "author": "Sergio Benitez ", + "name": "proc-macro2-diagnostics", + "version": "0.10.1", + "description": "Diagnostics for proc-macro2.", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "af066a9c399a26e020ada66a034357a868728e72cd426f3adcd35f80d88d88c8" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/proc-macro2-diagnostics@0.10.1", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/proc-macro2-diagnostics" + }, + { + "type": "website", + "url": "https://github.com/SergioBenitez/proc-macro2-diagnostics" + }, + { + "type": "vcs", + "url": "https://github.com/SergioBenitez/proc-macro2-diagnostics" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#proc-macro2@1.0.106", + "author": "David Tolnay , Alex Crichton ", + "name": "proc-macro2", + "version": "1.0.106", + "description": "A substitute implementation of the compiler's `proc_macro` API to decouple token-based libraries from the procedural macro use case.", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "8fd00f0bb2e90d81d1044c2b32617f68fcb9fa3bb7640c23e9c748e53fb30934" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/proc-macro2@1.0.106", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/proc-macro2" + }, + { + "type": "vcs", + "url": "https://github.com/dtolnay/proc-macro2" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#proptest-derive@0.5.1", + "author": "Mazdak Farrokhzad ", + "name": "proptest-derive", + "version": "0.5.1", + "description": "Custom-derive for the Arbitrary trait of proptest. ", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "4ee1c9ac207483d5e7db4940700de86a9aae46ef90c48b57f99fe7edb8345e49" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/proptest-derive@0.5.1", + "externalReferences": [ + { + "type": "documentation", + "url": "https://proptest-rs.github.io/proptest/proptest-derive/index.html" + }, + { + "type": "website", + "url": "https://proptest-rs.github.io/proptest/proptest-derive/index.html" + }, + { + "type": "vcs", + "url": "https://github.com/proptest-rs/proptest" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#proptest@1.10.0", + "author": "Jason Lingle", + "name": "proptest", + "version": "1.10.0", + "description": "Hypothesis-like property-based testing and shrinking. ", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "37566cb3fdacef14c0737f9546df7cfeadbfbc9fef10991038bf5015d0c80532" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/proptest@1.10.0", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/proptest/latest/proptest/" + }, + { + "type": "website", + "url": "https://proptest-rs.github.io/proptest/proptest/index.html" + }, + { + "type": "vcs", + "url": "https://github.com/proptest-rs/proptest" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#prost-build@0.14.3", + "author": "Dan Burkert , Lucio Franco , Casper Meijn , Tokio Contributors ", + "name": "prost-build", + "version": "0.14.3", + "description": "Generate Prost annotated Rust types from Protocol Buffers files.", + "scope": "excluded", + "hashes": [ + { + "alg": "SHA-256", + "content": "343d3bd7056eda839b03204e68deff7d1b13aba7af2b2fd16890697274262ee7" + } + ], + "licenses": [ + { + "expression": "Apache-2.0" + } + ], + "purl": "pkg:cargo/prost-build@0.14.3", + "externalReferences": [ + { + "type": "vcs", + "url": "https://github.com/tokio-rs/prost" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#prost-derive@0.13.5", + "author": "Dan Burkert , Lucio Franco , Casper Meijn , Tokio Contributors ", + "name": "prost-derive", + "version": "0.13.5", + "description": "Generate encoding and decoding implementations for Prost annotated types.", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "8a56d757972c98b346a9b766e3f02746cde6dd1cd1d1d563472929fdd74bec4d" + } + ], + "licenses": [ + { + "expression": "Apache-2.0" + } + ], + "purl": "pkg:cargo/prost-derive@0.13.5", + "externalReferences": [ + { + "type": "vcs", + "url": "https://github.com/tokio-rs/prost" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#prost-derive@0.14.3", + "author": "Dan Burkert , Lucio Franco , Casper Meijn , Tokio Contributors ", + "name": "prost-derive", + "version": "0.14.3", + "description": "Generate encoding and decoding implementations for Prost annotated types.", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "27c6023962132f4b30eb4c172c91ce92d933da334c59c23cddee82358ddafb0b" + } + ], + "licenses": [ + { + "expression": "Apache-2.0" + } + ], + "purl": "pkg:cargo/prost-derive@0.14.3", + "externalReferences": [ + { + "type": "vcs", + "url": "https://github.com/tokio-rs/prost" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#prost-types@0.14.3", + "author": "Dan Burkert , Lucio Franco , Casper Meijn , Tokio Contributors ", + "name": "prost-types", + "version": "0.14.3", + "description": "Prost definitions of Protocol Buffers well known types.", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "8991c4cbdb8bc5b11f0b074ffe286c30e523de90fee5ba8132f1399f23cb3dd7" + } + ], + "licenses": [ + { + "expression": "Apache-2.0" + } + ], + "purl": "pkg:cargo/prost-types@0.14.3", + "externalReferences": [ + { + "type": "vcs", + "url": "https://github.com/tokio-rs/prost" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#prost@0.13.5", + "author": "Dan Burkert , Lucio Franco , Casper Meijn , Tokio Contributors ", + "name": "prost", + "version": "0.13.5", + "description": "A Protocol Buffers implementation for the Rust Language.", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "2796faa41db3ec313a31f7624d9286acf277b52de526150b7e69f3debf891ee5" + } + ], + "licenses": [ + { + "expression": "Apache-2.0" + } + ], + "purl": "pkg:cargo/prost@0.13.5", + "externalReferences": [ + { + "type": "vcs", + "url": "https://github.com/tokio-rs/prost" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#prost@0.14.3", + "author": "Dan Burkert , Lucio Franco , Casper Meijn , Tokio Contributors ", + "name": "prost", + "version": "0.14.3", + "description": "A Protocol Buffers implementation for the Rust Language.", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "d2ea70524a2f82d518bce41317d0fae74151505651af45faf1ffbd6fd33f0568" + } + ], + "licenses": [ + { + "expression": "Apache-2.0" + } + ], + "purl": "pkg:cargo/prost@0.14.3", + "externalReferences": [ + { + "type": "vcs", + "url": "https://github.com/tokio-rs/prost" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#pulldown-cmark-to-cmark@22.0.0", + "author": "Sebastian Thiel , Dylan Owen , Alessandro Ogier , Zixian Cai <2891235+caizixian@users.noreply.github.com>, Andrew Lyjak ", + "name": "pulldown-cmark-to-cmark", + "version": "22.0.0", + "description": "Convert pulldown-cmark Events back to the string they were parsed from", + "scope": "excluded", + "hashes": [ + { + "alg": "SHA-256", + "content": "50793def1b900256624a709439404384204a5dc3a6ec580281bfaac35e882e90" + } + ], + "licenses": [ + { + "expression": "Apache-2.0" + } + ], + "purl": "pkg:cargo/pulldown-cmark-to-cmark@22.0.0", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/crate/pulldown-cmark-to-cmark" + }, + { + "type": "website", + "url": "https://github.com/Byron/pulldown-cmark-to-cmark" + }, + { + "type": "vcs", + "url": "https://github.com/Byron/pulldown-cmark-to-cmark" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#pulldown-cmark@0.13.1", + "author": "Raph Levien , Marcus Klaas de Vries ", + "name": "pulldown-cmark", + "version": "0.13.1", + "description": "A pull parser for CommonMark", + "scope": "excluded", + "hashes": [ + { + "alg": "SHA-256", + "content": "83c41efbf8f90ac44de7f3a868f0867851d261b56291732d0cbf7cceaaeb55a6" + } + ], + "licenses": [ + { + "expression": "MIT" + } + ], + "purl": "pkg:cargo/pulldown-cmark@0.13.1", + "externalReferences": [ + { + "type": "vcs", + "url": "https://github.com/raphlinus/pulldown-cmark" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#pulp-wasm-simd-flag@0.1.0", + "author": "sarah quiñones ", + "name": "pulp-wasm-simd-flag", + "version": "0.1.0", + "description": "safe generic simd", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "40e24eee682d89fb193496edf918a7f407d30175b2e785fe057e4392dfd182e0" + } + ], + "licenses": [ + { + "expression": "MIT" + } + ], + "purl": "pkg:cargo/pulp-wasm-simd-flag@0.1.0", + "externalReferences": [ + { + "type": "vcs", + "url": "https://github.com/sarah-quinones/pulp/" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#pulp@0.22.2", + "author": "sarah quiñones ", + "name": "pulp", + "version": "0.22.2", + "description": "safe generic simd", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "2e205bb30d5b916c55e584c22201771bcf2bad9aabd5d4127f38387140c38632" + } + ], + "licenses": [ + { + "expression": "MIT" + } + ], + "purl": "pkg:cargo/pulp@0.22.2", + "externalReferences": [ + { + "type": "vcs", + "url": "https://github.com/sarah-quinones/pulp/" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#pxfm@0.1.28", + "author": "Radzivon Bartoshyk", + "name": "pxfm", + "version": "0.1.28", + "description": "Fast and accurate math", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "b5a041e753da8b807c9255f28de81879c78c876392ff2469cde94799b2896b9d" + } + ], + "licenses": [ + { + "expression": "BSD-3-Clause OR Apache-2.0" + } + ], + "purl": "pkg:cargo/pxfm@0.1.28", + "externalReferences": [ + { + "type": "documentation", + "url": "https://github.com/awxkee/pxfm" + }, + { + "type": "vcs", + "url": "https://github.com/awxkee/pxfm" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#pyo3-build-config@0.24.2", + "author": "PyO3 Project and Contributors ", + "name": "pyo3-build-config", + "version": "0.24.2", + "description": "Build configuration for the PyO3 ecosystem", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "99636d423fa2ca130fa5acde3059308006d46f98caac629418e53f7ebb1e9999" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/pyo3-build-config@0.24.2", + "externalReferences": [ + { + "type": "website", + "url": "https://github.com/pyo3/pyo3" + }, + { + "type": "vcs", + "url": "https://github.com/pyo3/pyo3" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#pyo3-ffi@0.24.2", + "author": "PyO3 Project and Contributors ", + "name": "pyo3-ffi", + "version": "0.24.2", + "description": "Python-API bindings for the PyO3 ecosystem", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "78f9cf92ba9c409279bc3305b5409d90db2d2c22392d443a87df3a1adad59e33" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/pyo3-ffi@0.24.2", + "externalReferences": [ + { + "type": "website", + "url": "https://github.com/pyo3/pyo3" + }, + { + "type": "other", + "url": "python" + }, + { + "type": "vcs", + "url": "https://github.com/pyo3/pyo3" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#pyo3-macros-backend@0.24.2", + "author": "PyO3 Project and Contributors ", + "name": "pyo3-macros-backend", + "version": "0.24.2", + "description": "Code generation for PyO3 package", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "822ece1c7e1012745607d5cf0bcb2874769f0f7cb34c4cde03b9358eb9ef911a" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/pyo3-macros-backend@0.24.2", + "externalReferences": [ + { + "type": "website", + "url": "https://github.com/pyo3/pyo3" + }, + { + "type": "vcs", + "url": "https://github.com/pyo3/pyo3" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#pyo3-macros@0.24.2", + "author": "PyO3 Project and Contributors ", + "name": "pyo3-macros", + "version": "0.24.2", + "description": "Proc macros for PyO3 package", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "0b999cb1a6ce21f9a6b147dcf1be9ffedf02e0043aec74dc390f3007047cecd9" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/pyo3-macros@0.24.2", + "externalReferences": [ + { + "type": "website", + "url": "https://github.com/pyo3/pyo3" + }, + { + "type": "vcs", + "url": "https://github.com/pyo3/pyo3" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#pyo3@0.24.2", + "author": "PyO3 Project and Contributors ", + "name": "pyo3", + "version": "0.24.2", + "description": "Bindings to Python interpreter", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "e5203598f366b11a02b13aa20cab591229ff0a89fd121a308a5df751d5fc9219" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/pyo3@0.24.2", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/crate/pyo3/" + }, + { + "type": "website", + "url": "https://github.com/pyo3/pyo3" + }, + { + "type": "vcs", + "url": "https://github.com/pyo3/pyo3" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#qd@0.8.0", + "author": "sarah <>", + "name": "qd", + "version": "0.8.0", + "description": "Extended precision floating point arithmetic", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "15f1304a5aecdcfe9ee72fbba90aa37b3aa067a69d14cb7f3d9deada0be7c07c" + } + ], + "licenses": [ + { + "expression": "MIT" + } + ], + "purl": "pkg:cargo/qd@0.8.0", + "externalReferences": [ + { + "type": "vcs", + "url": "https://github.com/sarah-quinones/qd/" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#quick-error@1.2.3", + "author": "Paul Colomiets , Colin Kiegel ", + "name": "quick-error", + "version": "1.2.3", + "description": " A macro which makes error types pleasant to write. ", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "a1d01941d82fa2ab50be1e79e6714289dd7cde78eba4c074bc5a4374f650dfe0" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/quick-error@1.2.3", + "externalReferences": [ + { + "type": "documentation", + "url": "http://docs.rs/quick-error" + }, + { + "type": "website", + "url": "http://github.com/tailhook/quick-error" + }, + { + "type": "vcs", + "url": "http://github.com/tailhook/quick-error" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#quick-error@2.0.1", + "author": "Paul Colomiets , Colin Kiegel ", + "name": "quick-error", + "version": "2.0.1", + "description": " A macro which makes error types pleasant to write. ", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "a993555f31e5a609f617c12db6250dedcac1b0a85076912c436e6fc9b2c8e6a3" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/quick-error@2.0.1", + "externalReferences": [ + { + "type": "documentation", + "url": "http://docs.rs/quick-error" + }, + { + "type": "website", + "url": "http://github.com/tailhook/quick-error" + }, + { + "type": "vcs", + "url": "http://github.com/tailhook/quick-error" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#quick-xml@0.38.4", + "name": "quick-xml", + "version": "0.38.4", + "description": "High performance xml reader and writer", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "b66c2058c55a409d601666cffe35f04333cf1013010882cec174a7467cd4e21c" + } + ], + "licenses": [ + { + "expression": "MIT" + } + ], + "purl": "pkg:cargo/quick-xml@0.38.4", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/quick-xml" + }, + { + "type": "vcs", + "url": "https://github.com/tafia/quick-xml" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#quinn-proto@0.11.14", + "name": "quinn-proto", + "version": "0.11.14", + "description": "State machine for the QUIC transport protocol", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "434b42fec591c96ef50e21e886936e66d3cc3f737104fdb9b737c40ffb94c098" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/quinn-proto@0.11.14", + "externalReferences": [ + { + "type": "vcs", + "url": "https://github.com/quinn-rs/quinn" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#quinn-udp@0.5.14", + "name": "quinn-udp", + "version": "0.5.14", + "description": "UDP sockets with ECN information for the QUIC transport protocol", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "addec6a0dcad8a8d96a771f815f0eaf55f9d1805756410b39f5fa81332574cbd" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/quinn-udp@0.5.14", + "externalReferences": [ + { + "type": "vcs", + "url": "https://github.com/quinn-rs/quinn" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#quinn@0.11.9", + "name": "quinn", + "version": "0.11.9", + "description": "Versatile QUIC transport protocol implementation", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "b9e20a958963c291dc322d98411f541009df2ced7b5a4f2bd52337638cfccf20" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/quinn@0.11.9", + "externalReferences": [ + { + "type": "vcs", + "url": "https://github.com/quinn-rs/quinn" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#quote@1.0.45", + "author": "David Tolnay ", + "name": "quote", + "version": "1.0.45", + "description": "Quasi-quoting macro quote!(...)", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "41f2619966050689382d2b44f664f4bc593e129785a36d6ee376ddf37259b924" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/quote@1.0.45", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/quote/" + }, + { + "type": "vcs", + "url": "https://github.com/dtolnay/quote" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#radium@0.7.0", + "author": "Nika Layzell , myrrlyn ", + "name": "radium", + "version": "0.7.0", + "description": "Portable interfaces for maybe-atomic types", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "dc33ff2d4973d518d823d61aa239014831e521c75da58e3df4840d3f47749d09" + } + ], + "licenses": [ + { + "expression": "MIT" + } + ], + "purl": "pkg:cargo/radium@0.7.0", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/radium" + }, + { + "type": "website", + "url": "https://github.com/bitvecto-rs/radium" + }, + { + "type": "vcs", + "url": "https://github.com/bitvecto-rs/radium" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#rand@0.10.0", + "author": "The Rand Project Developers, The Rust Project Developers", + "name": "rand", + "version": "0.10.0", + "description": "Random number generators and other randomness functionality. ", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "bc266eb313df6c5c09c1c7b1fbe2510961e5bcd3add930c1e31f7ed9da0feff8" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/rand@0.10.0", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/rand" + }, + { + "type": "website", + "url": "https://rust-random.github.io/book" + }, + { + "type": "vcs", + "url": "https://github.com/rust-random/rand" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#rand@0.8.5", + "author": "The Rand Project Developers, The Rust Project Developers", + "name": "rand", + "version": "0.8.5", + "description": "Random number generators and other randomness functionality. ", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "34af8d1a0e25924bc5b7c43c079c942339d8f0a8b57c39049bef581b46327404" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/rand@0.8.5", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/rand" + }, + { + "type": "website", + "url": "https://rust-random.github.io/book" + }, + { + "type": "vcs", + "url": "https://github.com/rust-random/rand" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#rand@0.9.2", + "author": "The Rand Project Developers, The Rust Project Developers", + "name": "rand", + "version": "0.9.2", + "description": "Random number generators and other randomness functionality. ", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "6db2770f06117d490610c7488547d543617b21bfa07796d7a12f6f1bd53850d1" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/rand@0.9.2", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/rand" + }, + { + "type": "website", + "url": "https://rust-random.github.io/book" + }, + { + "type": "vcs", + "url": "https://github.com/rust-random/rand" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#rand_chacha@0.3.1", + "author": "The Rand Project Developers, The Rust Project Developers, The CryptoCorrosion Contributors", + "name": "rand_chacha", + "version": "0.3.1", + "description": "ChaCha random number generator ", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "e6c10a63a0fa32252be49d21e7709d4d4baf8d231c2dbce1eaa8141b9b127d88" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/rand_chacha@0.3.1", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/rand_chacha" + }, + { + "type": "website", + "url": "https://rust-random.github.io/book" + }, + { + "type": "vcs", + "url": "https://github.com/rust-random/rand" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#rand_chacha@0.9.0", + "author": "The Rand Project Developers, The Rust Project Developers, The CryptoCorrosion Contributors", + "name": "rand_chacha", + "version": "0.9.0", + "description": "ChaCha random number generator ", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "d3022b5f1df60f26e1ffddd6c66e8aa15de382ae63b3a0c1bfc0e4d3e3f325cb" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/rand_chacha@0.9.0", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/rand_chacha" + }, + { + "type": "website", + "url": "https://rust-random.github.io/book" + }, + { + "type": "vcs", + "url": "https://github.com/rust-random/rand" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#rand_core@0.10.0", + "author": "The Rand Project Developers", + "name": "rand_core", + "version": "0.10.0", + "description": "Core random number generation traits and tools for implementation.", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "0c8d0fd677905edcbeedbf2edb6494d676f0e98d54d5cf9bda0b061cb8fb8aba" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/rand_core@0.10.0", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/rand_core" + }, + { + "type": "website", + "url": "https://rust-random.github.io/book" + }, + { + "type": "vcs", + "url": "https://github.com/rust-random/rand_core" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#rand_core@0.6.4", + "author": "The Rand Project Developers, The Rust Project Developers", + "name": "rand_core", + "version": "0.6.4", + "description": "Core random number generator traits and tools for implementation. ", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "ec0be4795e2f6a28069bec0b5ff3e2ac9bafc99e6a9a7dc3547996c5c816922c" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/rand_core@0.6.4", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/rand_core" + }, + { + "type": "website", + "url": "https://rust-random.github.io/book" + }, + { + "type": "vcs", + "url": "https://github.com/rust-random/rand" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#rand_core@0.9.5", + "author": "The Rand Project Developers, The Rust Project Developers", + "name": "rand_core", + "version": "0.9.5", + "description": "Core random number generator traits and tools for implementation. ", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "76afc826de14238e6e8c374ddcc1fa19e374fd8dd986b0d2af0d02377261d83c" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/rand_core@0.9.5", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/rand_core" + }, + { + "type": "website", + "url": "https://rust-random.github.io/book" + }, + { + "type": "vcs", + "url": "https://github.com/rust-random/rand" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#rand_distr@0.4.3", + "author": "The Rand Project Developers", + "name": "rand_distr", + "version": "0.4.3", + "description": "Sampling from random number distributions ", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "32cb0b9bc82b0a0876c2dd994a7e7a2683d3e7390ca40e6886785ef0c7e3ee31" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/rand_distr@0.4.3", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/rand_distr" + }, + { + "type": "website", + "url": "https://rust-random.github.io/book" + }, + { + "type": "vcs", + "url": "https://github.com/rust-random/rand" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#rand_distr@0.5.1", + "author": "The Rand Project Developers", + "name": "rand_distr", + "version": "0.5.1", + "description": "Sampling from random number distributions ", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "6a8615d50dcf34fa31f7ab52692afec947c4dd0ab803cc87cb3b0b4570ff7463" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/rand_distr@0.5.1", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/rand_distr" + }, + { + "type": "website", + "url": "https://rust-random.github.io/book" + }, + { + "type": "vcs", + "url": "https://github.com/rust-random/rand_distr" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#rand_pcg@0.3.1", + "author": "The Rand Project Developers", + "name": "rand_pcg", + "version": "0.3.1", + "description": "Selected PCG random number generators ", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "59cad018caf63deb318e5a4586d99a24424a364f40f1e5778c29aca23f4fc73e" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/rand_pcg@0.3.1", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/rand_pcg" + }, + { + "type": "website", + "url": "https://rust-random.github.io/book" + }, + { + "type": "vcs", + "url": "https://github.com/rust-random/rand" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#rand_xorshift@0.4.0", + "author": "The Rand Project Developers, The Rust Project Developers", + "name": "rand_xorshift", + "version": "0.4.0", + "description": "Xorshift random number generator ", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "513962919efc330f829edb2535844d1b912b0fbe2ca165d613e4e8788bb05a5a" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/rand_xorshift@0.4.0", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/rand_xorshift" + }, + { + "type": "website", + "url": "https://rust-random.github.io/book" + }, + { + "type": "vcs", + "url": "https://github.com/rust-random/rngs" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#ratatui@0.29.0", + "author": "Florian Dehau , The Ratatui Developers", + "name": "ratatui", + "version": "0.29.0", + "description": "A library that's all about cooking up terminal user interfaces", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "eabd94c2f37801c20583fc49dd5cd6b0ba68c716787c2dd6ed18571e1e63117b" + } + ], + "licenses": [ + { + "expression": "MIT" + } + ], + "purl": "pkg:cargo/ratatui@0.29.0", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/ratatui/latest/ratatui/" + }, + { + "type": "website", + "url": "https://ratatui.rs" + }, + { + "type": "vcs", + "url": "https://github.com/ratatui/ratatui" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#raw-cpuid@11.6.0", + "author": "Gerd Zellweger ", + "name": "raw-cpuid", + "version": "11.6.0", + "description": "A library to parse the x86 CPUID instruction, written in rust with no external dependencies. The implementation closely resembles the Intel CPUID manual description. The library does only depend on libcore.", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "498cd0dc59d73224351ee52a95fee0f1a617a2eae0e7d9d720cc622c73a54186" + } + ], + "licenses": [ + { + "expression": "MIT" + } + ], + "purl": "pkg:cargo/raw-cpuid@11.6.0", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/raw-cpuid/" + }, + { + "type": "website", + "url": "https://github.com/gz/rust-cpuid" + }, + { + "type": "vcs", + "url": "https://github.com/gz/rust-cpuid" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#rawpointer@0.2.1", + "author": "bluss", + "name": "rawpointer", + "version": "0.2.1", + "description": "Extra methods for raw pointers and `NonNull`. For example `.post_inc()` and `.pre_dec()` (c.f. `ptr++` and `--ptr`), `offset` and `add` for `NonNull`, and the function `ptrdistance`. ", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "60a357793950651c4ed0f3f52338f53b2f809f32d83a07f72909fa13e4c6c1e3" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/rawpointer@0.2.1", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/rawpointer/" + }, + { + "type": "vcs", + "url": "https://github.com/bluss/rawpointer/" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#rayon-core@1.13.0", + "name": "rayon-core", + "version": "1.13.0", + "description": "Core APIs for Rayon", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "22e18b0f0062d30d4230b2e85ff77fdfe4326feb054b9783a3460d8435c8ab91" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/rayon-core@1.13.0", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/rayon-core/" + }, + { + "type": "other", + "url": "rayon-core" + }, + { + "type": "vcs", + "url": "https://github.com/rayon-rs/rayon" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#rayon@1.11.0", + "name": "rayon", + "version": "1.11.0", + "description": "Simple work-stealing parallelism for Rust", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "368f01d005bf8fd9b1206fb6fa653e6c4a81ceb1466406b81792d87c5677a58f" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/rayon@1.11.0", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/rayon/" + }, + { + "type": "vcs", + "url": "https://github.com/rayon-rs/rayon" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#reborrow@0.5.5", + "author": "sarah <>", + "name": "reborrow", + "version": "0.5.5", + "description": "Emulate reborrowing for user types.", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "03251193000f4bd3b042892be858ee50e8b3719f2b08e5833ac4353724632430" + } + ], + "licenses": [ + { + "expression": "MIT" + } + ], + "purl": "pkg:cargo/reborrow@0.5.5", + "externalReferences": [ + { + "type": "vcs", + "url": "https://github.com/sarah-ek/reborrow/" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#regex-automata@0.4.14", + "author": "The Rust Project Developers, Andrew Gallant ", + "name": "regex-automata", + "version": "0.4.14", + "description": "Automata construction and matching using regular expressions.", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "6e1dd4122fc1595e8162618945476892eefca7b88c52820e74af6262213cae8f" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/regex-automata@0.4.14", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/regex-automata" + }, + { + "type": "website", + "url": "https://github.com/rust-lang/regex/tree/master/regex-automata" + }, + { + "type": "vcs", + "url": "https://github.com/rust-lang/regex" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#regex-lite@0.1.9", + "author": "The Rust Project Developers, Andrew Gallant ", + "name": "regex-lite", + "version": "0.1.9", + "description": "A lightweight regex engine that optimizes for binary size and compilation time. ", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "cab834c73d247e67f4fae452806d17d3c7501756d98c8808d7c9c7aa7d18f973" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/regex-lite@0.1.9", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/regex-lite" + }, + { + "type": "website", + "url": "https://github.com/rust-lang/regex/tree/master/regex-lite" + }, + { + "type": "vcs", + "url": "https://github.com/rust-lang/regex" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#regex-syntax@0.8.10", + "author": "The Rust Project Developers, Andrew Gallant ", + "name": "regex-syntax", + "version": "0.8.10", + "description": "A regular expression parser.", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "dc897dd8d9e8bd1ed8cdad82b5966c3e0ecae09fb1907d58efaa013543185d0a" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/regex-syntax@0.8.10", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/regex-syntax" + }, + { + "type": "website", + "url": "https://github.com/rust-lang/regex/tree/master/regex-syntax" + }, + { + "type": "vcs", + "url": "https://github.com/rust-lang/regex" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#regex@1.12.3", + "author": "The Rust Project Developers, Andrew Gallant ", + "name": "regex", + "version": "1.12.3", + "description": "An implementation of regular expressions for Rust. This implementation uses finite automata and guarantees linear time matching on all inputs. ", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "e10754a14b9137dd7b1e3e5b0493cc9171fdd105e0ab477f51b72e7f3ac0e276" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/regex@1.12.3", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/regex" + }, + { + "type": "website", + "url": "https://github.com/rust-lang/regex" + }, + { + "type": "vcs", + "url": "https://github.com/rust-lang/regex" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#reqwest@0.12.28", + "author": "Sean McArthur ", + "name": "reqwest", + "version": "0.12.28", + "description": "higher level HTTP client library", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "eddd3ca559203180a307f12d114c268abf583f59b03cb906fd0b3ff8646c1147" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/reqwest@0.12.28", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/reqwest" + }, + { + "type": "vcs", + "url": "https://github.com/seanmonstar/reqwest" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#reqwest@0.13.2", + "author": "Sean McArthur ", + "name": "reqwest", + "version": "0.13.2", + "description": "higher level HTTP client library", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "ab3f43e3283ab1488b624b44b0e988d0acea0b3214e694730a055cb6b2efa801" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/reqwest@0.13.2", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/reqwest" + }, + { + "type": "vcs", + "url": "https://github.com/seanmonstar/reqwest" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#rfc6979@0.3.1", + "author": "RustCrypto Developers", + "name": "rfc6979", + "version": "0.3.1", + "description": "Pure Rust implementation of RFC6979: Deterministic Usage of the Digital Signature Algorithm (DSA) and Elliptic Curve Digital Signature Algorithm (ECDSA) ", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "7743f17af12fa0b03b803ba12cd6a8d9483a587e89c69445e3909655c0b9fabb" + } + ], + "licenses": [ + { + "expression": "Apache-2.0 OR MIT" + } + ], + "purl": "pkg:cargo/rfc6979@0.3.1", + "externalReferences": [ + { + "type": "vcs", + "url": "https://github.com/RustCrypto/signatures/tree/master/rfc6979" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#ring@0.17.14", + "name": "ring", + "version": "0.17.14", + "description": "An experiment.", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "a4689e6c2294d81e88dc6261c768b63bc4fcdb852be6d1352498b114f61383b7" + } + ], + "licenses": [ + { + "expression": "Apache-2.0 AND ISC" + } + ], + "purl": "pkg:cargo/ring@0.17.14", + "externalReferences": [ + { + "type": "other", + "url": "ring_core_0_17_14_" + }, + { + "type": "vcs", + "url": "https://github.com/briansmith/ring" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#roaring@0.10.12", + "author": "Wim Looman , Kerollmops ", + "name": "roaring", + "version": "0.10.12", + "description": "A better compressed bitset - pure Rust implementation", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "19e8d2cfa184d94d0726d650a9f4a1be7f9b76ac9fdb954219878dc00c1c1e7b" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/roaring@0.10.12", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/roaring" + }, + { + "type": "vcs", + "url": "https://github.com/RoaringBitmap/roaring-rs" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#rsa@0.9.10", + "author": "RustCrypto Developers, dignifiedquire ", + "name": "rsa", + "version": "0.9.10", + "description": "Pure Rust RSA implementation", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "b8573f03f5883dcaebdfcf4725caa1ecb9c15b2ef50c43a07b816e06799bb12d" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/rsa@0.9.10", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/rsa" + }, + { + "type": "vcs", + "url": "https://github.com/RustCrypto/RSA" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#rtrb@0.3.3", + "author": "Stjepan Glavina , Matthias Geier ", + "name": "rtrb", + "version": "0.3.3", + "description": "A realtime-safe single-producer single-consumer ring buffer", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "7204ed6420f698836b76d4d5c2ec5dec7585fd5c3a788fd1cde855d1de598239" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/rtrb@0.3.3", + "externalReferences": [ + { + "type": "vcs", + "url": "https://github.com/mgeier/rtrb" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#rust-embed-impl@8.11.0", + "author": "pyrossh", + "name": "rust-embed-impl", + "version": "8.11.0", + "description": "Rust Custom Derive Macro which loads files into the rust binary at compile time during release and loads the file from the fs during dev", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "da0902e4c7c8e997159ab384e6d0fc91c221375f6894346ae107f47dd0f3ccaa" + } + ], + "licenses": [ + { + "expression": "MIT" + } + ], + "purl": "pkg:cargo/rust-embed-impl@8.11.0", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/rust-embed" + }, + { + "type": "vcs", + "url": "https://pyrossh.dev/repos/rust-embed" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#rust-embed-utils@8.11.0", + "author": "pyrossh", + "name": "rust-embed-utils", + "version": "8.11.0", + "description": "Utilities for rust-embed", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "5bcdef0be6fe7f6fa333b1073c949729274b05f123a0ad7efcb8efd878e5c3b1" + } + ], + "licenses": [ + { + "expression": "MIT" + } + ], + "purl": "pkg:cargo/rust-embed-utils@8.11.0", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/rust-embed" + }, + { + "type": "vcs", + "url": "https://pyrossh.dev/repos/rust-embed" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#rust-embed@8.11.0", + "author": "pyrossh", + "name": "rust-embed", + "version": "8.11.0", + "description": "Rust Custom Derive Macro which loads files into the rust binary at compile time during release and loads the file from the fs during dev", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "04113cb9355a377d83f06ef1f0a45b8ab8cd7d8b1288160717d66df5c7988d27" + } + ], + "licenses": [ + { + "expression": "MIT" + } + ], + "purl": "pkg:cargo/rust-embed@8.11.0", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/rust-embed" + }, + { + "type": "vcs", + "url": "https://pyrossh.dev/repos/rust-embed" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#rust-stemmers@1.2.0", + "author": "Jakob Demler , CurrySoftware ", + "name": "rust-stemmers", + "version": "1.2.0", + "description": "A rust implementation of some popular snowball stemming algorithms", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "e46a2036019fdb888131db7a4c847a1063a7493f971ed94ea82c67eada63ca54" + } + ], + "licenses": [ + { + "expression": "MIT OR BSD-3-Clause" + } + ], + "purl": "pkg:cargo/rust-stemmers@1.2.0", + "externalReferences": [ + { + "type": "vcs", + "url": "https://github.com/CurrySoftware/rust-stemmers" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#rustc-hash@1.1.0", + "author": "The Rust Project Developers", + "name": "rustc-hash", + "version": "1.1.0", + "description": "speed, non-cryptographic hash used in rustc", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "08d43f7aa6b08d49f382cde6a7982047c3426db949b1424bc4b7ec9ae12c6ce2" + } + ], + "licenses": [ + { + "expression": "Apache-2.0 OR MIT" + } + ], + "purl": "pkg:cargo/rustc-hash@1.1.0", + "externalReferences": [ + { + "type": "vcs", + "url": "https://github.com/rust-lang-nursery/rustc-hash" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#rustc-hash@2.1.1", + "author": "The Rust Project Developers", + "name": "rustc-hash", + "version": "2.1.1", + "description": "A speedy, non-cryptographic hashing algorithm used by rustc", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "357703d41365b4b27c590e3ed91eabb1b663f07c4c084095e60cbed4362dff0d" + } + ], + "licenses": [ + { + "expression": "Apache-2.0 OR MIT" + } + ], + "purl": "pkg:cargo/rustc-hash@2.1.1", + "externalReferences": [ + { + "type": "vcs", + "url": "https://github.com/rust-lang/rustc-hash" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#rustc_version@0.4.1", + "name": "rustc_version", + "version": "0.4.1", + "description": "A library for querying the version of a installed rustc compiler", + "scope": "excluded", + "hashes": [ + { + "alg": "SHA-256", + "content": "cfcb3a22ef46e85b45de6ee7e79d063319ebb6594faafcf1c225ea92ab6e9b92" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/rustc_version@0.4.1", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/rustc_version/" + }, + { + "type": "vcs", + "url": "https://github.com/djc/rustc-version-rs" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#rustls-native-certs@0.6.3", + "name": "rustls-native-certs", + "version": "0.6.3", + "description": "rustls-native-certs allows rustls to use the platform native certificate store", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "a9aace74cb666635c918e9c12bc0d348266037aa8eb599b5cba565709a8dff00" + } + ], + "licenses": [ + { + "expression": "Apache-2.0 OR ISC OR MIT" + } + ], + "purl": "pkg:cargo/rustls-native-certs@0.6.3", + "externalReferences": [ + { + "type": "website", + "url": "https://github.com/ctz/rustls-native-certs" + }, + { + "type": "vcs", + "url": "https://github.com/ctz/rustls-native-certs" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#rustls-native-certs@0.8.3", + "name": "rustls-native-certs", + "version": "0.8.3", + "description": "rustls-native-certs allows rustls to use the platform native certificate store", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "612460d5f7bea540c490b2b6395d8e34a953e52b491accd6c86c8164c5932a63" + } + ], + "licenses": [ + { + "expression": "Apache-2.0 OR ISC OR MIT" + } + ], + "purl": "pkg:cargo/rustls-native-certs@0.8.3", + "externalReferences": [ + { + "type": "website", + "url": "https://github.com/rustls/rustls-native-certs" + }, + { + "type": "vcs", + "url": "https://github.com/rustls/rustls-native-certs" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#rustls-pemfile@1.0.4", + "name": "rustls-pemfile", + "version": "1.0.4", + "description": "Basic .pem file parser for keys and certificates", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "1c74cae0a4cf6ccbbf5f359f08efdf8ee7e1dc532573bf0db71968cb56b1448c" + } + ], + "licenses": [ + { + "expression": "Apache-2.0 OR ISC OR MIT" + } + ], + "purl": "pkg:cargo/rustls-pemfile@1.0.4", + "externalReferences": [ + { + "type": "website", + "url": "https://github.com/rustls/pemfile" + }, + { + "type": "vcs", + "url": "https://github.com/rustls/pemfile" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#rustls-pemfile@2.2.0", + "name": "rustls-pemfile", + "version": "2.2.0", + "description": "Basic .pem file parser for keys and certificates", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "dce314e5fee3f39953d46bb63bb8a46d40c2f8fb7cc5a3b6cab2bde9721d6e50" + } + ], + "licenses": [ + { + "expression": "Apache-2.0 OR ISC OR MIT" + } + ], + "purl": "pkg:cargo/rustls-pemfile@2.2.0", + "externalReferences": [ + { + "type": "website", + "url": "https://github.com/rustls/pemfile" + }, + { + "type": "vcs", + "url": "https://github.com/rustls/pemfile" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#rustls-pki-types@1.14.0", + "name": "rustls-pki-types", + "version": "1.14.0", + "description": "Shared types for the rustls PKI ecosystem", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "be040f8b0a225e40375822a563fa9524378b9d63112f53e19ffff34df5d33fdd" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/rustls-pki-types@1.14.0", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/rustls-pki-types" + }, + { + "type": "website", + "url": "https://github.com/rustls/pki-types" + }, + { + "type": "vcs", + "url": "https://github.com/rustls/pki-types" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#rustls-platform-verifier@0.6.2", + "name": "rustls-platform-verifier", + "version": "0.6.2", + "description": "rustls-platform-verifier supports verifying TLS certificates in rustls with the operating system verifier", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "1d99feebc72bae7ab76ba994bb5e121b8d83d910ca40b36e0921f53becc41784" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/rustls-platform-verifier@0.6.2", + "externalReferences": [ + { + "type": "vcs", + "url": "https://github.com/rustls/rustls-platform-verifier" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#rustls-webpki@0.101.7", + "name": "rustls-webpki", + "version": "0.101.7", + "description": "Web PKI X.509 Certificate Verification.", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "8b6275d1ee7a1cd780b64aca7726599a1dbc893b1e64144529e55c3c2f745765" + } + ], + "licenses": [ + { + "expression": "ISC" + } + ], + "purl": "pkg:cargo/rustls-webpki@0.101.7", + "externalReferences": [ + { + "type": "vcs", + "url": "https://github.com/rustls/webpki" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#rustls-webpki@0.103.9", + "name": "rustls-webpki", + "version": "0.103.9", + "description": "Web PKI X.509 Certificate Verification.", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "d7df23109aa6c1567d1c575b9952556388da57401e4ace1d15f79eedad0d8f53" + } + ], + "licenses": [ + { + "expression": "ISC" + } + ], + "purl": "pkg:cargo/rustls-webpki@0.103.9", + "externalReferences": [ + { + "type": "vcs", + "url": "https://github.com/rustls/webpki" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#rustls@0.21.12", + "name": "rustls", + "version": "0.21.12", + "description": "Rustls is a modern TLS library written in Rust.", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "3f56a14d1f48b391359b22f731fd4bd7e43c97f3c50eee276f3aa09c94784d3e" + } + ], + "licenses": [ + { + "expression": "Apache-2.0 OR ISC OR MIT" + } + ], + "purl": "pkg:cargo/rustls@0.21.12", + "externalReferences": [ + { + "type": "website", + "url": "https://github.com/rustls/rustls" + }, + { + "type": "vcs", + "url": "https://github.com/rustls/rustls" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#rustls@0.23.37", + "name": "rustls", + "version": "0.23.37", + "description": "Rustls is a modern TLS library written in Rust.", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "758025cb5fccfd3bc2fd74708fd4682be41d99e5dff73c377c0646c6012c73a4" + } + ], + "licenses": [ + { + "expression": "Apache-2.0 OR ISC OR MIT" + } + ], + "purl": "pkg:cargo/rustls@0.23.37", + "externalReferences": [ + { + "type": "website", + "url": "https://github.com/rustls/rustls" + }, + { + "type": "vcs", + "url": "https://github.com/rustls/rustls" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#rustversion@1.0.22", + "author": "David Tolnay ", + "name": "rustversion", + "version": "1.0.22", + "description": "Conditional compilation according to rustc compiler version", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "b39cdef0fa800fc44525c84ccb54a029961a8215f9619753635a9c0d2538d46d" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/rustversion@1.0.22", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/rustversion" + }, + { + "type": "vcs", + "url": "https://github.com/dtolnay/rustversion" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#rusty-fork@0.3.1", + "author": "Jason Lingle", + "name": "rusty-fork", + "version": "0.3.1", + "description": "Cross-platform library for running Rust tests in sub-processes using a fork-like interface. ", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "cc6bf79ff24e648f6da1f8d1f011e9cac26491b619e6b9280f2b47f1774e6ee2" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/rusty-fork@0.3.1", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/rusty-fork" + }, + { + "type": "vcs", + "url": "https://github.com/altsysrq/rusty-fork" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#ryu@1.0.23", + "author": "David Tolnay ", + "name": "ryu", + "version": "1.0.23", + "description": "Fast floating point to string conversion", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "9774ba4a74de5f7b1c1451ed6cd5285a32eddb5cccb8cc655a4e50009e06477f" + } + ], + "licenses": [ + { + "expression": "Apache-2.0 OR BSL-1.0" + } + ], + "purl": "pkg:cargo/ryu@1.0.23", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/ryu" + }, + { + "type": "vcs", + "url": "https://github.com/dtolnay/ryu" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#same-file@1.0.6", + "author": "Andrew Gallant ", + "name": "same-file", + "version": "1.0.6", + "description": "A simple crate for determining whether two file paths point to the same file. ", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "93fc1dc3aaa9bfed95e02e6eadabb4baf7e3078b0bd1b4d7b6b0b68378900502" + } + ], + "licenses": [ + { + "expression": "Unlicense OR MIT" + } + ], + "purl": "pkg:cargo/same-file@1.0.6", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/same-file" + }, + { + "type": "website", + "url": "https://github.com/BurntSushi/same-file" + }, + { + "type": "vcs", + "url": "https://github.com/BurntSushi/same-file" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#schannel@0.1.29", + "author": "Steven Fackler , Steffen Butzer ", + "name": "schannel", + "version": "0.1.29", + "description": "Schannel bindings for rust, allowing SSL/TLS (e.g. https) without openssl", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "91c1b7e4904c873ef0710c1f407dde2e6287de2bebc1bbbf7d430bb7cbffd939" + } + ], + "licenses": [ + { + "expression": "MIT" + } + ], + "purl": "pkg:cargo/schannel@0.1.29", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/schannel/0.1.19/schannel/" + }, + { + "type": "vcs", + "url": "https://github.com/steffengy/schannel-rs" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#schemars@0.8.22", + "author": "Graham Esau ", + "name": "schemars", + "version": "0.8.22", + "description": "Generate JSON Schemas from Rust code", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "3fbf2ae1b8bc8e02df939598064d22402220cd5bbcca1c76f7d6a310974d5615" + } + ], + "licenses": [ + { + "expression": "MIT" + } + ], + "purl": "pkg:cargo/schemars@0.8.22", + "externalReferences": [ + { + "type": "website", + "url": "https://graham.cool/schemars/" + }, + { + "type": "vcs", + "url": "https://github.com/GREsau/schemars" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#schemars_derive@0.8.22", + "author": "Graham Esau ", + "name": "schemars_derive", + "version": "0.8.22", + "description": "Macros for #[derive(JsonSchema)], for use with schemars", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "32e265784ad618884abaea0600a9adf15393368d840e0222d101a072f3f7534d" + } + ], + "licenses": [ + { + "expression": "MIT" + } + ], + "purl": "pkg:cargo/schemars_derive@0.8.22", + "externalReferences": [ + { + "type": "website", + "url": "https://graham.cool/schemars/" + }, + { + "type": "vcs", + "url": "https://github.com/GREsau/schemars" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#scoped-tls@1.0.1", + "author": "Alex Crichton ", + "name": "scoped-tls", + "version": "1.0.1", + "description": "Library implementation of the standard library's old `scoped_thread_local!` macro for providing scoped access to thread local storage (TLS) so any type can be stored into TLS. ", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "e1cf6437eb19a8f4a6cc0f7dca544973b0b78843adbfeb3683d1a94a0024a294" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/scoped-tls@1.0.1", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/scoped-tls" + }, + { + "type": "website", + "url": "https://github.com/alexcrichton/scoped-tls" + }, + { + "type": "vcs", + "url": "https://github.com/alexcrichton/scoped-tls" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#scopeguard@1.2.0", + "author": "bluss", + "name": "scopeguard", + "version": "1.2.0", + "description": "A RAII scope guard that will run a given closure when it goes out of scope, even if the code between panics (assuming unwinding panic). Defines the macros `defer!`, `defer_on_unwind!`, `defer_on_success!` as shorthands for guards with one of the implemented strategies. ", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/scopeguard@1.2.0", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/scopeguard/" + }, + { + "type": "vcs", + "url": "https://github.com/bluss/scopeguard" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#scratch@1.0.9", + "author": "David Tolnay ", + "name": "scratch", + "version": "1.0.9", + "description": "Compile-time temporary directory shared by multiple crates and erased by `cargo clean`", + "scope": "excluded", + "hashes": [ + { + "alg": "SHA-256", + "content": "d68f2ec51b097e4c1a75b681a8bec621909b5e91f15bb7b840c4f2f7b01148b2" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/scratch@1.0.9", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/scratch" + }, + { + "type": "vcs", + "url": "https://github.com/dtolnay/scratch" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#sct@0.7.1", + "author": "Joseph Birr-Pixton ", + "name": "sct", + "version": "0.7.1", + "description": "Certificate transparency SCT verification library", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "da046153aa2352493d6cb7da4b6e5c0c057d8a1d0a9aa8560baffdd945acd414" + } + ], + "licenses": [ + { + "expression": "Apache-2.0 OR ISC OR MIT" + } + ], + "purl": "pkg:cargo/sct@0.7.1", + "externalReferences": [ + { + "type": "website", + "url": "https://github.com/rustls/sct.rs" + }, + { + "type": "vcs", + "url": "https://github.com/rustls/sct.rs" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#sea-query-binder@0.7.0", + "author": "Valentin Tolmer , Ivan Krivosheev ", + "name": "sea-query-binder", + "version": "0.7.0", + "description": "Driver library for using SeaQuery with SQLx", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "b0019f47430f7995af63deda77e238c17323359af241233ec768aba1faea7608" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/sea-query-binder@0.7.0", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/sea-query" + }, + { + "type": "vcs", + "url": "https://github.com/SeaQL/sea-query" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#sea-query-derive@0.4.3", + "author": "Follpvosten , Rene Leveille ", + "name": "sea-query-derive", + "version": "0.4.3", + "description": "Derive macro for sea-query's Iden trait", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "bae0cbad6ab996955664982739354128c58d16e126114fe88c2a493642502aab" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/sea-query-derive@0.4.3", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/sea-query" + }, + { + "type": "vcs", + "url": "https://github.com/SeaQL/sea-query" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#sea-query@0.32.7", + "author": "Chris Tsang , Billy Chan , Ivan Krivosheev ", + "name": "sea-query", + "version": "0.32.7", + "description": "🔱 A dynamic query builder for MySQL, Postgres and SQLite", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "8a5d1c518eaf5eda38e5773f902b26ab6d5e9e9e2bb2349ca6c64cf96f80448c" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/sea-query@0.32.7", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/sea-query" + }, + { + "type": "vcs", + "url": "https://github.com/SeaQL/sea-query" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#sec1@0.3.0", + "author": "RustCrypto Developers", + "name": "sec1", + "version": "0.3.0", + "description": "Pure Rust implementation of SEC1: Elliptic Curve Cryptography encoding formats including ASN.1 DER-serialized private keys as well as the Elliptic-Curve-Point-to-Octet-String encoding ", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "3be24c1842290c45df0a7bf069e0c268a747ad05a192f2fd7dcfdbc1cba40928" + } + ], + "licenses": [ + { + "expression": "Apache-2.0 OR MIT" + } + ], + "purl": "pkg:cargo/sec1@0.3.0", + "externalReferences": [ + { + "type": "vcs", + "url": "https://github.com/RustCrypto/formats/tree/master/sec1" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#secrecy@0.8.0", + "author": "Tony Arcieri ", + "name": "secrecy", + "version": "0.8.0", + "description": "Wrapper types and traits for secret management which help ensure they aren't accidentally copied, logged, or otherwise exposed (as much as possible), and also ensure secrets are securely wiped from memory when dropped. ", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "9bd1c54ea06cfd2f6b63219704de0b9b4f72dcc2b8fdef820be6cd799780e91e" + } + ], + "licenses": [ + { + "expression": "Apache-2.0 OR MIT" + } + ], + "purl": "pkg:cargo/secrecy@0.8.0", + "externalReferences": [ + { + "type": "website", + "url": "https://github.com/iqlusioninc/crates/" + }, + { + "type": "vcs", + "url": "https://github.com/iqlusioninc/crates/tree/main/secrecy" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#semver@1.0.27", + "author": "David Tolnay ", + "name": "semver", + "version": "1.0.27", + "description": "Parser and evaluator for Cargo's flavor of Semantic Versioning", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "d767eb0aabc880b29956c35734170f26ed551a859dbd361d140cdbeca61ab1e2" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/semver@1.0.27", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/semver" + }, + { + "type": "vcs", + "url": "https://github.com/dtolnay/semver" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#seq-macro@0.3.6", + "author": "David Tolnay ", + "name": "seq-macro", + "version": "0.3.6", + "description": "Macro to repeat sequentially indexed copies of a fragment of code.", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "1bc711410fbe7399f390ca1c3b60ad0f53f80e95c5eb935e52268a0e2cd49acc" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/seq-macro@0.3.6", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/seq-macro" + }, + { + "type": "vcs", + "url": "https://github.com/dtolnay/seq-macro" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#serde-pickle@1.2.0", + "author": "Georg Brandl ", + "name": "serde-pickle", + "version": "1.2.0", + "description": "A serde-based serialization library for Python's pickle format", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "b641fdc8bcf2781ee78b30c599700d64ad4f412976143e4c5d0b9df906bb4843" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/serde-pickle@1.2.0", + "externalReferences": [ + { + "type": "documentation", + "url": "http://docs.rs/serde-pickle" + }, + { + "type": "vcs", + "url": "https://github.com/birkenfeld/serde-pickle" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#serde-value@0.7.0", + "author": "arcnmx", + "name": "serde-value", + "version": "0.7.0", + "description": "Serialization value trees", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "f3a1a3341211875ef120e117ea7fd5228530ae7e7036a779fdc9117be6b3282c" + } + ], + "licenses": [ + { + "expression": "MIT" + } + ], + "purl": "pkg:cargo/serde-value@0.7.0", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/serde-value/*/serde_value/" + }, + { + "type": "vcs", + "url": "https://github.com/arcnmx/serde-value" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#serde@1.0.228", + "author": "Erick Tryzelaar , David Tolnay ", + "name": "serde", + "version": "1.0.228", + "description": "A generic serialization/deserialization framework", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "9a8e94ea7f378bd32cbbd37198a4a91436180c5bb472411e48b5ec2e2124ae9e" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/serde@1.0.228", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/serde" + }, + { + "type": "website", + "url": "https://serde.rs" + }, + { + "type": "vcs", + "url": "https://github.com/serde-rs/serde" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#serde_bytes@0.11.19", + "author": "David Tolnay ", + "name": "serde_bytes", + "version": "0.11.19", + "description": "Optimized handling of `&[u8]` and `Vec` for Serde", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "a5d440709e79d88e51ac01c4b72fc6cb7314017bb7da9eeff678aa94c10e3ea8" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/serde_bytes@0.11.19", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/serde_bytes" + }, + { + "type": "vcs", + "url": "https://github.com/serde-rs/bytes" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#serde_core@1.0.228", + "author": "Erick Tryzelaar , David Tolnay ", + "name": "serde_core", + "version": "1.0.228", + "description": "Serde traits only, with no support for derive -- use the `serde` crate instead", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "41d385c7d4ca58e59fc732af25c3983b67ac852c1a25000afe1175de458b67ad" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/serde_core@1.0.228", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/serde_core" + }, + { + "type": "website", + "url": "https://serde.rs" + }, + { + "type": "vcs", + "url": "https://github.com/serde-rs/serde" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#serde_derive@1.0.228", + "author": "Erick Tryzelaar , David Tolnay ", + "name": "serde_derive", + "version": "1.0.228", + "description": "Macros 1.1 implementation of #[derive(Serialize, Deserialize)]", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "d540f220d3187173da220f885ab66608367b6574e925011a9353e4badda91d79" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/serde_derive@1.0.228", + "externalReferences": [ + { + "type": "documentation", + "url": "https://serde.rs/derive.html" + }, + { + "type": "website", + "url": "https://serde.rs" + }, + { + "type": "vcs", + "url": "https://github.com/serde-rs/serde" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#serde_derive_internals@0.29.1", + "author": "Erick Tryzelaar , David Tolnay ", + "name": "serde_derive_internals", + "version": "0.29.1", + "description": "AST representation used by Serde derive macros. Unstable.", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "18d26a20a969b9e3fdf2fc2d9f21eda6c40e2de84c9408bb5d3b05d499aae711" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/serde_derive_internals@0.29.1", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/serde_derive_internals" + }, + { + "type": "website", + "url": "https://serde.rs" + }, + { + "type": "vcs", + "url": "https://github.com/serde-rs/serde" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#serde_json@1.0.149", + "author": "Erick Tryzelaar , David Tolnay ", + "name": "serde_json", + "version": "1.0.149", + "description": "A JSON serialization file format", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "83fc039473c5595ace860d8c4fafa220ff474b3fc6bfdb4293327f1a37e94d86" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/serde_json@1.0.149", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/serde_json" + }, + { + "type": "vcs", + "url": "https://github.com/serde-rs/json" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#serde_path_to_error@0.1.20", + "author": "David Tolnay ", + "name": "serde_path_to_error", + "version": "0.1.20", + "description": "Path to the element that failed to deserialize", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "10a9ff822e371bb5403e391ecd83e182e0e77ba7f6fe0160b795797109d1b457" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/serde_path_to_error@0.1.20", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/serde_path_to_error" + }, + { + "type": "vcs", + "url": "https://github.com/dtolnay/path-to-error" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#serde_spanned@0.6.9", + "name": "serde_spanned", + "version": "0.6.9", + "description": "Serde-compatible spanned Value", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "bf41e0cfaf7226dca15e8197172c295a782857fcb97fad1808a166870dee75a3" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/serde_spanned@0.6.9", + "externalReferences": [ + { + "type": "vcs", + "url": "https://github.com/toml-rs/toml" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#serde_urlencoded@0.7.1", + "author": "Anthony Ramine ", + "name": "serde_urlencoded", + "version": "0.7.1", + "description": "`x-www-form-urlencoded` meets Serde", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "d3491c14715ca2294c4d6a88f15e84739788c1d030eed8c110436aafdaa2f3fd" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/serde_urlencoded@0.7.1", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/serde_urlencoded/0.7.1/serde_urlencoded/" + }, + { + "type": "vcs", + "url": "https://github.com/nox/serde_urlencoded" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#serde_yaml@0.9.34+deprecated", + "author": "David Tolnay ", + "name": "serde_yaml", + "version": "0.9.34+deprecated", + "description": "YAML data format for Serde", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "6a8b1a1a2ebf674015cc02edccce75287f1a0130d394307b36743c2f5d504b47" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/serde_yaml@0.9.34+deprecated", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/serde_yaml/" + }, + { + "type": "vcs", + "url": "https://github.com/dtolnay/serde-yaml" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#sha1@0.10.6", + "author": "RustCrypto Developers", + "name": "sha1", + "version": "0.10.6", + "description": "SHA-1 hash function", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "e3bf829a2d51ab4a5ddf1352d8470c140cadc8301b2ae1789db023f01cedd6ba" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/sha1@0.10.6", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/sha1" + }, + { + "type": "vcs", + "url": "https://github.com/RustCrypto/hashes" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#sha2@0.10.9", + "author": "RustCrypto Developers", + "name": "sha2", + "version": "0.10.9", + "description": "Pure Rust implementation of the SHA-2 hash function family including SHA-224, SHA-256, SHA-384, and SHA-512. ", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "a7507d819769d01a365ab707794a4084392c824f54a7a6a7862f8c3d0892b283" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/sha2@0.10.9", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/sha2" + }, + { + "type": "vcs", + "url": "https://github.com/RustCrypto/hashes" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#sharded-slab@0.1.7", + "author": "Eliza Weisman ", + "name": "sharded-slab", + "version": "0.1.7", + "description": "A lock-free concurrent slab. ", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "f40ca3c46823713e0d4209592e8d6e826aa57e928f09752619fc696c499637f6" + } + ], + "licenses": [ + { + "expression": "MIT" + } + ], + "purl": "pkg:cargo/sharded-slab@0.1.7", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/sharded-slab/" + }, + { + "type": "website", + "url": "https://github.com/hawkw/sharded-slab" + }, + { + "type": "vcs", + "url": "https://github.com/hawkw/sharded-slab" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#shell-words@1.1.1", + "author": "Tomasz Miąsko ", + "name": "shell-words", + "version": "1.1.1", + "description": "Process command line according to parsing rules of UNIX shell", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "dc6fe69c597f9c37bfeeeeeb33da3530379845f10be461a66d16d03eca2ded77" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/shell-words@1.1.1", + "externalReferences": [ + { + "type": "vcs", + "url": "https://github.com/tmiasko/shell-words" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#shlex@1.3.0", + "author": "comex , Fenhl , Adrian Taylor , Alex Touchet , Daniel Parks , Garrett Berg ", + "name": "shlex", + "version": "1.3.0", + "description": "Split a string into shell words, like Python's shlex.", + "scope": "excluded", + "hashes": [ + { + "alg": "SHA-256", + "content": "0fda2ff0d084019ba4d7c6f371c95d8fd75ce3524c3cb8fb653a3023f6323e64" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/shlex@1.3.0", + "externalReferences": [ + { + "type": "vcs", + "url": "https://github.com/comex/rust-shlex" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#shuttle@0.7.1", + "name": "shuttle", + "version": "0.7.1", + "description": "A library for testing concurrent Rust code", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "2d9a8db61a44e2b663f169a08206a789bcbd22ba32011e14951562848e7b9c98" + } + ], + "licenses": [ + { + "expression": "Apache-2.0" + } + ], + "purl": "pkg:cargo/shuttle@0.7.1", + "externalReferences": [ + { + "type": "vcs", + "url": "https://github.com/awslabs/shuttle" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#signature@1.6.4", + "author": "RustCrypto Developers", + "name": "signature", + "version": "1.6.4", + "description": "Traits for cryptographic signature algorithms (e.g. ECDSA, Ed25519)", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "74233d3b3b2f6d4b006dc19dee745e73e2a6bfb6f93607cd3b02bd5b00797d7c" + } + ], + "licenses": [ + { + "expression": "Apache-2.0 OR MIT" + } + ], + "purl": "pkg:cargo/signature@1.6.4", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/signature" + }, + { + "type": "vcs", + "url": "https://github.com/RustCrypto/traits/tree/master/signature" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#signature@2.2.0", + "author": "RustCrypto Developers", + "name": "signature", + "version": "2.2.0", + "description": "Traits for cryptographic signature algorithms (e.g. ECDSA, Ed25519)", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "77549399552de45a898a580c1b41d445bf730df867cc44e6c0233bbc4b8329de" + } + ], + "licenses": [ + { + "expression": "Apache-2.0 OR MIT" + } + ], + "purl": "pkg:cargo/signature@2.2.0", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/signature" + }, + { + "type": "vcs", + "url": "https://github.com/RustCrypto/traits/tree/master/signature" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#simd-adler32@0.3.8", + "author": "Marvin Countryman ", + "name": "simd-adler32", + "version": "0.3.8", + "description": "A SIMD-accelerated Adler-32 hash algorithm implementation.", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "e320a6c5ad31d271ad523dcf3ad13e2767ad8b1cb8f047f75a8aeaf8da139da2" + } + ], + "licenses": [ + { + "expression": "MIT" + } + ], + "purl": "pkg:cargo/simd-adler32@0.3.8", + "externalReferences": [ + { + "type": "vcs", + "url": "https://github.com/mcountryman/simd-adler32" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#simdutf8@0.1.5", + "author": "Hans Kratz ", + "name": "simdutf8", + "version": "0.1.5", + "description": "SIMD-accelerated UTF-8 validation.", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "e3a9fe34e3e7a50316060351f37187a3f546bce95496156754b601a5fa71b76e" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/simdutf8@0.1.5", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/simdutf8/" + }, + { + "type": "website", + "url": "https://github.com/rusticstuff/simdutf8" + }, + { + "type": "vcs", + "url": "https://github.com/rusticstuff/simdutf8" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#simsimd@6.5.16", + "author": "Ash Vardanian <1983160+ashvardanian@users.noreply.github.com>", + "name": "simsimd", + "version": "6.5.16", + "description": "Portable mixed-precision BLAS-like vector math library for x86 and ARM", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "f4fb3bc3cdce07a7d7d4caa4c54f8aa967f6be41690482b54b24100a2253fa70" + } + ], + "licenses": [ + { + "expression": "Apache-2.0" + } + ], + "purl": "pkg:cargo/simsimd@6.5.16", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/simsimd" + }, + { + "type": "website", + "url": "https://ashvardanian.com/posts/simsimd-faster-scipy" + }, + { + "type": "vcs", + "url": "https://github.com/ashvardanian/SimSIMD" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#siphasher@1.0.2", + "author": "Frank Denis ", + "name": "siphasher", + "version": "1.0.2", + "description": "SipHash-2-4, SipHash-1-3 and 128-bit variants in pure Rust", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "b2aa850e253778c88a04c3d7323b043aeda9d3e30d5971937c1855769763678e" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/siphasher@1.0.2", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/siphasher" + }, + { + "type": "website", + "url": "https://docs.rs/siphasher" + }, + { + "type": "vcs", + "url": "https://github.com/jedisct1/rust-siphash" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#sketches-ddsketch@0.2.2", + "author": "Mike Heffner ", + "name": "sketches-ddsketch", + "version": "0.2.2", + "description": "A direct port of the Golang DDSketch implementation. ", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "85636c14b73d81f541e525f585c0a2109e6744e1565b5c1668e31c70c10ed65c" + } + ], + "licenses": [ + { + "expression": "Apache-2.0" + } + ], + "purl": "pkg:cargo/sketches-ddsketch@0.2.2", + "externalReferences": [ + { + "type": "website", + "url": "https://github.com/mheffner/rust-sketches-ddsketch" + }, + { + "type": "vcs", + "url": "https://github.com/mheffner/rust-sketches-ddsketch" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#slab@0.4.12", + "author": "Carl Lerche ", + "name": "slab", + "version": "0.4.12", + "description": "Pre-allocated storage for a uniform data type", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5" + } + ], + "licenses": [ + { + "expression": "MIT" + } + ], + "purl": "pkg:cargo/slab@0.4.12", + "externalReferences": [ + { + "type": "vcs", + "url": "https://github.com/tokio-rs/slab" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#small_ctor@0.1.2", + "author": "Armin Ronacher ", + "name": "small_ctor", + "version": "0.1.2", + "description": "A minimal, dependency free version of the ctor crate", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "88414a5ca1f85d82cc34471e975f0f74f6aa54c40f062efa42c0080e7f763f81" + } + ], + "licenses": [ + { + "expression": "Apache-2.0" + } + ], + "purl": "pkg:cargo/small_ctor@0.1.2", + "externalReferences": [ + { + "type": "vcs", + "url": "https://github.com/mitsuhiko/small-ctor" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#smallvec@1.15.1", + "author": "The Servo Project Developers", + "name": "smallvec", + "version": "1.15.1", + "description": "'Small vector' optimization: store up to a small number of items on the stack", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "67b1b7a3b5fe4f1376887184045fcf45c69e92af734b7aaddc05fb777b6fbd03" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/smallvec@1.15.1", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/smallvec/" + }, + { + "type": "vcs", + "url": "https://github.com/servo/rust-smallvec" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#smawk@0.3.2", + "author": "Martin Geisler ", + "name": "smawk", + "version": "0.3.2", + "description": "Functions for finding row-minima in a totally monotone matrix.", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "b7c388c1b5e93756d0c740965c41e8822f866621d41acbdf6336a6a168f8840c" + } + ], + "licenses": [ + { + "expression": "MIT" + } + ], + "purl": "pkg:cargo/smawk@0.3.2", + "externalReferences": [ + { + "type": "vcs", + "url": "https://github.com/mgeisler/smawk" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#snap@1.1.1", + "author": "Andrew Gallant ", + "name": "snap", + "version": "1.1.1", + "description": "A pure Rust implementation of the Snappy compression algorithm. Includes streaming compression and decompression. ", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "1b6b67fb9a61334225b5b790716f609cd58395f895b3fe8b328786812a40bc3b" + } + ], + "licenses": [ + { + "expression": "BSD-3-Clause" + } + ], + "purl": "pkg:cargo/snap@1.1.1", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/snap" + }, + { + "type": "website", + "url": "https://github.com/BurntSushi/rust-snappy" + }, + { + "type": "vcs", + "url": "https://github.com/BurntSushi/rust-snappy" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#socket2@0.5.10", + "author": "Alex Crichton , Thomas de Zeeuw ", + "name": "socket2", + "version": "0.5.10", + "description": "Utilities for handling networking sockets with a maximal amount of configuration possible intended. ", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "e22376abed350d73dd1cd119b57ffccad95b4e585a7cda43e286245ce23c0678" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/socket2@0.5.10", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/socket2" + }, + { + "type": "website", + "url": "https://github.com/rust-lang/socket2" + }, + { + "type": "vcs", + "url": "https://github.com/rust-lang/socket2" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#socket2@0.6.3", + "author": "Alex Crichton , Thomas de Zeeuw ", + "name": "socket2", + "version": "0.6.3", + "description": "Utilities for handling networking sockets with a maximal amount of configuration possible intended. ", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "3a766e1110788c36f4fa1c2b71b387a7815aa65f88ce0229841826633d93723e" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/socket2@0.6.3", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/socket2" + }, + { + "type": "website", + "url": "https://github.com/rust-lang/socket2" + }, + { + "type": "vcs", + "url": "https://github.com/rust-lang/socket2" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#spin@0.9.8", + "author": "Mathijs van de Nes , John Ericson , Joshua Barretto ", + "name": "spin", + "version": "0.9.8", + "description": "Spin-based synchronization primitives", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "6980e8d7511241f8acf4aebddbb1ff938df5eebe98691418c4468d0b72a96a67" + } + ], + "licenses": [ + { + "expression": "MIT" + } + ], + "purl": "pkg:cargo/spin@0.9.8", + "externalReferences": [ + { + "type": "vcs", + "url": "https://github.com/mvdnes/spin-rs.git" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#spki@0.6.0", + "author": "RustCrypto Developers", + "name": "spki", + "version": "0.6.0", + "description": "X.509 Subject Public Key Info (RFC5280) describing public keys as well as their associated AlgorithmIdentifiers (i.e. OIDs) ", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "67cf02bbac7a337dc36e4f5a693db6c21e7863f45070f7064577eb4367a3212b" + } + ], + "licenses": [ + { + "expression": "Apache-2.0 OR MIT" + } + ], + "purl": "pkg:cargo/spki@0.6.0", + "externalReferences": [ + { + "type": "vcs", + "url": "https://github.com/RustCrypto/formats/tree/master/spki" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#spki@0.7.3", + "author": "RustCrypto Developers", + "name": "spki", + "version": "0.7.3", + "description": "X.509 Subject Public Key Info (RFC5280) describing public keys as well as their associated AlgorithmIdentifiers (i.e. OIDs) ", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "d91ed6c858b01f942cd56b37a94b3e0a1798290327d1236e4d9cf4eaca44d29d" + } + ], + "licenses": [ + { + "expression": "Apache-2.0 OR MIT" + } + ], + "purl": "pkg:cargo/spki@0.7.3", + "externalReferences": [ + { + "type": "vcs", + "url": "https://github.com/RustCrypto/formats/tree/master/spki" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#sprs@0.11.4", + "author": "Vincent Barrielle ", + "name": "sprs", + "version": "0.11.4", + "description": "A sparse matrix library", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "6dca58a33be2188d4edc71534f8bafa826e787cc28ca1c47f31be3423f0d6e55" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/sprs@0.11.4", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/sprs" + }, + { + "type": "vcs", + "url": "https://github.com/sparsemat/sprs" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#sqlx-core@0.8.6", + "author": "Ryan Leckey , Austin Bonander , Chloe Ross , Daniel Akhterov ", + "name": "sqlx-core", + "version": "0.8.6", + "description": "Core of SQLx, the rust SQL toolkit. Not intended to be used directly.", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "ee6798b1838b6a0f69c007c133b8df5866302197e404e8b6ee8ed3e3a5e68dc6" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/sqlx-core@0.8.6", + "externalReferences": [ + { + "type": "vcs", + "url": "https://github.com/launchbadge/sqlx" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#sqlx-macros-core@0.8.6", + "author": "Ryan Leckey , Austin Bonander , Chloe Ross , Daniel Akhterov ", + "name": "sqlx-macros-core", + "version": "0.8.6", + "description": "Macro support core for SQLx, the Rust SQL toolkit. Not intended to be used directly.", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "19a9c1841124ac5a61741f96e1d9e2ec77424bf323962dd894bdb93f37d5219b" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/sqlx-macros-core@0.8.6", + "externalReferences": [ + { + "type": "vcs", + "url": "https://github.com/launchbadge/sqlx" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#sqlx-macros@0.8.6", + "author": "Ryan Leckey , Austin Bonander , Chloe Ross , Daniel Akhterov ", + "name": "sqlx-macros", + "version": "0.8.6", + "description": "Macros for SQLx, the rust SQL toolkit. Not intended to be used directly.", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "a2d452988ccaacfbf5e0bdbc348fb91d7c8af5bee192173ac3636b5fb6e6715d" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/sqlx-macros@0.8.6", + "externalReferences": [ + { + "type": "vcs", + "url": "https://github.com/launchbadge/sqlx" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#sqlx-mysql@0.8.6", + "author": "Ryan Leckey , Austin Bonander , Chloe Ross , Daniel Akhterov ", + "name": "sqlx-mysql", + "version": "0.8.6", + "description": "MySQL driver implementation for SQLx. Not for direct use; see the `sqlx` crate for details.", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "aa003f0038df784eb8fecbbac13affe3da23b45194bd57dba231c8f48199c526" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/sqlx-mysql@0.8.6", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/sqlx" + }, + { + "type": "vcs", + "url": "https://github.com/launchbadge/sqlx" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#sqlx-postgres@0.8.6", + "author": "Ryan Leckey , Austin Bonander , Chloe Ross , Daniel Akhterov ", + "name": "sqlx-postgres", + "version": "0.8.6", + "description": "PostgreSQL driver implementation for SQLx. Not for direct use; see the `sqlx` crate for details.", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "db58fcd5a53cf07c184b154801ff91347e4c30d17a3562a635ff028ad5deda46" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/sqlx-postgres@0.8.6", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/sqlx" + }, + { + "type": "vcs", + "url": "https://github.com/launchbadge/sqlx" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#sqlx-sqlite@0.8.6", + "author": "Ryan Leckey , Austin Bonander , Chloe Ross , Daniel Akhterov ", + "name": "sqlx-sqlite", + "version": "0.8.6", + "description": "SQLite driver implementation for SQLx. Not for direct use; see the `sqlx` crate for details.", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "c2d12fe70b2c1b4401038055f90f151b78208de1f9f89a7dbfd41587a10c3eea" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/sqlx-sqlite@0.8.6", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/sqlx" + }, + { + "type": "vcs", + "url": "https://github.com/launchbadge/sqlx" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#sqlx@0.8.6", + "author": "Ryan Leckey , Austin Bonander , Chloe Ross , Daniel Akhterov ", + "name": "sqlx", + "version": "0.8.6", + "description": "🧰 The Rust SQL Toolkit. An async, pure Rust SQL crate featuring compile-time checked queries without a DSL. Supports PostgreSQL, MySQL, and SQLite.", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "1fefb893899429669dcdd979aff487bd78f4064e5e7907e4269081e0ef7d97dc" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/sqlx@0.8.6", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/sqlx" + }, + { + "type": "vcs", + "url": "https://github.com/launchbadge/sqlx" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#stable_deref_trait@1.2.1", + "author": "Robert Grosse ", + "name": "stable_deref_trait", + "version": "1.2.1", + "description": "An unsafe marker trait for types like Box and Rc that dereference to a stable address even when moved, and hence can be used with libraries such as owning_ref and rental. ", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "6ce2be8dc25455e1f91df71bfa12ad37d7af1092ae736f3a6cd0e37bc7810596" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/stable_deref_trait@1.2.1", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/stable_deref_trait/1.2.1/stable_deref_trait" + }, + { + "type": "vcs", + "url": "https://github.com/storyyeller/stable_deref_trait" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#static_assertions@1.1.0", + "author": "Nikolai Vazquez", + "name": "static_assertions", + "version": "1.1.0", + "description": "Compile-time assertions to ensure that invariants are met.", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "a2eb9349b6444b326872e140eb1cf5e7c522154d69e7a0ffb0fb81c06b37543f" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/static_assertions@1.1.0", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/static_assertions/" + }, + { + "type": "website", + "url": "https://github.com/nvzqz/static-assertions-rs" + }, + { + "type": "vcs", + "url": "https://github.com/nvzqz/static-assertions-rs" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#stringprep@0.1.5", + "author": "Steven Fackler ", + "name": "stringprep", + "version": "0.1.5", + "description": "An implementation of the stringprep algorithm", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "7b4df3d392d81bd458a8a621b8bffbd2302a12ffe288a9d931670948749463b1" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/stringprep@0.1.5", + "externalReferences": [ + { + "type": "vcs", + "url": "https://github.com/sfackler/rust-stringprep" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#strsim@0.11.1", + "author": "Danny Guo , maxbachmann ", + "name": "strsim", + "version": "0.11.1", + "description": "Implementations of string similarity metrics. Includes Hamming, Levenshtein, OSA, Damerau-Levenshtein, Jaro, Jaro-Winkler, and Sørensen-Dice. ", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f" + } + ], + "licenses": [ + { + "expression": "MIT" + } + ], + "purl": "pkg:cargo/strsim@0.11.1", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/strsim/" + }, + { + "type": "website", + "url": "https://github.com/rapidfuzz/strsim-rs" + }, + { + "type": "vcs", + "url": "https://github.com/rapidfuzz/strsim-rs" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#strum@0.26.3", + "author": "Peter Glotfelty ", + "name": "strum", + "version": "0.26.3", + "description": "Helpful macros for working with enums and strings", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "8fec0f0aef304996cf250b31b5a10dee7980c85da9d759361292b8bca5a18f06" + } + ], + "licenses": [ + { + "expression": "MIT" + } + ], + "purl": "pkg:cargo/strum@0.26.3", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/strum" + }, + { + "type": "website", + "url": "https://github.com/Peternator7/strum" + }, + { + "type": "vcs", + "url": "https://github.com/Peternator7/strum" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#strum@0.27.2", + "author": "Peter Glotfelty ", + "name": "strum", + "version": "0.27.2", + "description": "Helpful macros for working with enums and strings", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "af23d6f6c1a224baef9d3f61e287d2761385a5b88fdab4eb4c6f11aeb54c4bcf" + } + ], + "licenses": [ + { + "expression": "MIT" + } + ], + "purl": "pkg:cargo/strum@0.27.2", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/strum" + }, + { + "type": "website", + "url": "https://github.com/Peternator7/strum" + }, + { + "type": "vcs", + "url": "https://github.com/Peternator7/strum" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#strum_macros@0.26.4", + "author": "Peter Glotfelty ", + "name": "strum_macros", + "version": "0.26.4", + "description": "Helpful macros for working with enums and strings", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "4c6bee85a5a24955dc440386795aa378cd9cf82acd5f764469152d2270e581be" + } + ], + "licenses": [ + { + "expression": "MIT" + } + ], + "purl": "pkg:cargo/strum_macros@0.26.4", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/strum" + }, + { + "type": "website", + "url": "https://github.com/Peternator7/strum" + }, + { + "type": "vcs", + "url": "https://github.com/Peternator7/strum" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#strum_macros@0.27.2", + "author": "Peter Glotfelty ", + "name": "strum_macros", + "version": "0.27.2", + "description": "Helpful macros for working with enums and strings", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "7695ce3845ea4b33927c055a39dc438a45b059f7c1b3d91d38d10355fb8cbca7" + } + ], + "licenses": [ + { + "expression": "MIT" + } + ], + "purl": "pkg:cargo/strum_macros@0.27.2", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/strum" + }, + { + "type": "website", + "url": "https://github.com/Peternator7/strum" + }, + { + "type": "vcs", + "url": "https://github.com/Peternator7/strum" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#subtle@2.6.1", + "author": "Isis Lovecruft , Henry de Valence ", + "name": "subtle", + "version": "2.6.1", + "description": "Pure-Rust traits and utilities for constant-time cryptographic implementations.", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292" + } + ], + "licenses": [ + { + "expression": "BSD-3-Clause" + } + ], + "purl": "pkg:cargo/subtle@2.6.1", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/subtle" + }, + { + "type": "website", + "url": "https://dalek.rs/" + }, + { + "type": "vcs", + "url": "https://github.com/dalek-cryptography/subtle" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#supports-color@3.0.2", + "author": "Kat Marchán ", + "name": "supports-color", + "version": "3.0.2", + "description": "Detects whether a terminal supports color, and gives details about that support.", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "c64fc7232dd8d2e4ac5ce4ef302b1d81e0b80d055b9d77c7c4f51f6aa4c867d6" + } + ], + "licenses": [ + { + "expression": "Apache-2.0" + } + ], + "purl": "pkg:cargo/supports-color@3.0.2", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/supports-color" + }, + { + "type": "vcs", + "url": "https://github.com/zkat/supports-color" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#syn@1.0.109", + "author": "David Tolnay ", + "name": "syn", + "version": "1.0.109", + "description": "Parser for Rust source code", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "72b64191b275b66ffe2469e8af2c1cfe3bafa67b529ead792a6d0160888b4237" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/syn@1.0.109", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/syn" + }, + { + "type": "vcs", + "url": "https://github.com/dtolnay/syn" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#syn@2.0.117", + "author": "David Tolnay ", + "name": "syn", + "version": "2.0.117", + "description": "Parser for Rust source code", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "e665b8803e7b1d2a727f4023456bbbbe74da67099c585258af0ad9c5013b9b99" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/syn@2.0.117", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/syn" + }, + { + "type": "vcs", + "url": "https://github.com/dtolnay/syn" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#sync_wrapper@1.0.2", + "author": "Actyx AG ", + "name": "sync_wrapper", + "version": "1.0.2", + "description": "A tool for enlisting the compiler's help in proving the absence of concurrency", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "0bf256ce5efdfa370213c1dabab5935a12e49f2c58d15e9eac2870d3b4f27263" + } + ], + "licenses": [ + { + "expression": "Apache-2.0" + } + ], + "purl": "pkg:cargo/sync_wrapper@1.0.2", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/sync_wrapper" + }, + { + "type": "website", + "url": "https://docs.rs/sync_wrapper" + }, + { + "type": "vcs", + "url": "https://github.com/Actyx/sync_wrapper" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#synstructure@0.13.2", + "author": "Nika Layzell ", + "name": "synstructure", + "version": "0.13.2", + "description": "Helper methods and macros for custom derives", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "728a70f3dbaf5bab7f0c4b1ac8d7ae5ea60a4b5549c8a5914361c99147a709d2" + } + ], + "licenses": [ + { + "expression": "MIT" + } + ], + "purl": "pkg:cargo/synstructure@0.13.2", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/synstructure" + }, + { + "type": "vcs", + "url": "https://github.com/mystor/synstructure" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#tantivy-bitpacker@0.6.0", + "author": "Paul Masurel ", + "name": "tantivy-bitpacker", + "version": "0.6.0", + "description": "Tantivy-sub crate: bitpacking", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "284899c2325d6832203ac6ff5891b297fc5239c3dc754c5bc1977855b23c10df" + } + ], + "licenses": [ + { + "expression": "MIT" + } + ], + "purl": "pkg:cargo/tantivy-bitpacker@0.6.0", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/tantivy-bitpacker/latest/tantivy_bitpacker" + }, + { + "type": "website", + "url": "https://github.com/quickwit-oss/tantivy" + }, + { + "type": "vcs", + "url": "https://github.com/quickwit-oss/tantivy" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#tantivy-columnar@0.3.0", + "name": "tantivy-columnar", + "version": "0.3.0", + "description": "column oriented storage for tantivy", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "12722224ffbe346c7fec3275c699e508fd0d4710e629e933d5736ec524a1f44e" + } + ], + "licenses": [ + { + "expression": "MIT" + } + ], + "purl": "pkg:cargo/tantivy-columnar@0.3.0", + "externalReferences": [ + { + "type": "website", + "url": "https://github.com/quickwit-oss/tantivy" + }, + { + "type": "vcs", + "url": "https://github.com/quickwit-oss/tantivy" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#tantivy-common@0.7.0", + "author": "Paul Masurel , Pascal Seitz ", + "name": "tantivy-common", + "version": "0.7.0", + "description": "common traits and utility functions used by multiple tantivy subcrates", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "8019e3cabcfd20a1380b491e13ff42f57bb38bf97c3d5fa5c07e50816e0621f4" + } + ], + "licenses": [ + { + "expression": "MIT" + } + ], + "purl": "pkg:cargo/tantivy-common@0.7.0", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/tantivy_common/" + }, + { + "type": "website", + "url": "https://github.com/quickwit-oss/tantivy" + }, + { + "type": "vcs", + "url": "https://github.com/quickwit-oss/tantivy" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#tantivy-fst@0.5.0", + "author": "Andrew Gallant ", + "name": "tantivy-fst", + "version": "0.5.0", + "description": "This is a tantivy-specific fork from the fst crate from Burntsushi. (Please use the fst crate instead.) ", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "d60769b80ad7953d8a7b2c70cdfe722bbcdcac6bccc8ac934c40c034d866fc18" + } + ], + "licenses": [ + { + "expression": "Unlicense OR MIT" + } + ], + "purl": "pkg:cargo/tantivy-fst@0.5.0", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/tantivy-fst" + }, + { + "type": "vcs", + "url": "https://github.com/quickwit-inc/fst" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#tantivy-query-grammar@0.22.0", + "author": "Paul Masurel ", + "name": "tantivy-query-grammar", + "version": "0.22.0", + "description": "Search engine library", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "847434d4af57b32e309f4ab1b4f1707a6c566656264caa427ff4285c4d9d0b82" + } + ], + "licenses": [ + { + "expression": "MIT" + } + ], + "purl": "pkg:cargo/tantivy-query-grammar@0.22.0", + "externalReferences": [ + { + "type": "website", + "url": "https://github.com/quickwit-oss/tantivy" + }, + { + "type": "vcs", + "url": "https://github.com/quickwit-oss/tantivy" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#tantivy-sstable@0.3.0", + "name": "tantivy-sstable", + "version": "0.3.0", + "description": "sstables for tantivy", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "c69578242e8e9fc989119f522ba5b49a38ac20f576fc778035b96cc94f41f98e" + } + ], + "licenses": [ + { + "expression": "MIT" + } + ], + "purl": "pkg:cargo/tantivy-sstable@0.3.0", + "externalReferences": [ + { + "type": "website", + "url": "https://github.com/quickwit-oss/tantivy" + }, + { + "type": "vcs", + "url": "https://github.com/quickwit-oss/tantivy" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#tantivy-stacker@0.3.0", + "name": "tantivy-stacker", + "version": "0.3.0", + "description": "term hashmap used for indexing", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "c56d6ff5591fc332739b3ce7035b57995a3ce29a93ffd6012660e0949c956ea8" + } + ], + "licenses": [ + { + "expression": "MIT" + } + ], + "purl": "pkg:cargo/tantivy-stacker@0.3.0", + "externalReferences": [ + { + "type": "website", + "url": "https://github.com/quickwit-oss/tantivy" + }, + { + "type": "vcs", + "url": "https://github.com/quickwit-oss/tantivy" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#tantivy-tokenizer-api@0.3.0", + "name": "tantivy-tokenizer-api", + "version": "0.3.0", + "description": "Tokenizer API of tantivy", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "2a0dcade25819a89cfe6f17d932c9cedff11989936bf6dd4f336d50392053b04" + } + ], + "licenses": [ + { + "expression": "MIT" + } + ], + "purl": "pkg:cargo/tantivy-tokenizer-api@0.3.0", + "externalReferences": [ + { + "type": "website", + "url": "https://github.com/quickwit-oss/tantivy" + }, + { + "type": "vcs", + "url": "https://github.com/quickwit-oss/tantivy" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#tantivy@0.22.1", + "author": "Paul Masurel ", + "name": "tantivy", + "version": "0.22.1", + "description": "Search engine library", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "96599ea6fccd844fc833fed21d2eecac2e6a7c1afd9e044057391d78b1feb141" + } + ], + "licenses": [ + { + "expression": "MIT" + } + ], + "purl": "pkg:cargo/tantivy@0.22.1", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/tantivy/" + }, + { + "type": "website", + "url": "https://github.com/quickwit-oss/tantivy" + }, + { + "type": "vcs", + "url": "https://github.com/quickwit-oss/tantivy" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#tap@1.0.1", + "author": "Elliott Linder , myrrlyn ", + "name": "tap", + "version": "1.0.1", + "description": "Generic extensions for tapping values in Rust", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "55937e1799185b12863d447f42597ed69d9928686b8d88a1df17376a097d8369" + } + ], + "licenses": [ + { + "expression": "MIT" + } + ], + "purl": "pkg:cargo/tap@1.0.1", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/tap" + }, + { + "type": "website", + "url": "https://github.com/myrrlyn/tap" + }, + { + "type": "vcs", + "url": "https://github.com/myrrlyn/tap" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#target-lexicon@0.13.5", + "author": "Dan Gohman ", + "name": "target-lexicon", + "version": "0.13.5", + "description": "LLVM target triple types", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "adb6935a6f5c20170eeceb1a3835a49e12e19d792f6dd344ccc76a985ca5a6ca" + } + ], + "licenses": [ + { + "expression": "Apache-2.0 WITH LLVM-exception" + } + ], + "purl": "pkg:cargo/target-lexicon@0.13.5", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/target-lexicon/" + }, + { + "type": "vcs", + "url": "https://github.com/bytecodealliance/target-lexicon" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#tempfile@3.27.0", + "author": "Steven Allen , The Rust Project Developers, Ashley Mannix , Jason White ", + "name": "tempfile", + "version": "3.27.0", + "description": "A library for managing temporary files and directories.", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/tempfile@3.27.0", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/tempfile" + }, + { + "type": "website", + "url": "https://stebalien.com/projects/tempfile-rs/" + }, + { + "type": "vcs", + "url": "https://github.com/Stebalien/tempfile" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#termcolor@1.4.1", + "author": "Andrew Gallant ", + "name": "termcolor", + "version": "1.4.1", + "description": "A simple cross platform library for writing colored text to a terminal. ", + "scope": "excluded", + "hashes": [ + { + "alg": "SHA-256", + "content": "06794f8f6c5c898b3275aebefa6b8a1cb24cd2c6c79397ab15774837a0bc5755" + } + ], + "licenses": [ + { + "expression": "Unlicense OR MIT" + } + ], + "purl": "pkg:cargo/termcolor@1.4.1", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/termcolor" + }, + { + "type": "website", + "url": "https://github.com/BurntSushi/termcolor" + }, + { + "type": "vcs", + "url": "https://github.com/BurntSushi/termcolor" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#textwrap@0.16.2", + "author": "Martin Geisler ", + "name": "textwrap", + "version": "0.16.2", + "description": "Library for word wrapping, indenting, and dedenting strings. Has optional support for Unicode and emojis as well as machine hyphenation.", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "c13547615a44dc9c452a8a534638acdf07120d4b6847c8178705da06306a3057" + } + ], + "licenses": [ + { + "expression": "MIT" + } + ], + "purl": "pkg:cargo/textwrap@0.16.2", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/textwrap/" + }, + { + "type": "vcs", + "url": "https://github.com/mgeisler/textwrap" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#thiserror-impl@1.0.69", + "author": "David Tolnay ", + "name": "thiserror-impl", + "version": "1.0.69", + "description": "Implementation detail of the `thiserror` crate", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "4fee6c4efc90059e10f81e6d42c60a18f76588c3d74cb83a0b242a2b6c7504c1" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/thiserror-impl@1.0.69", + "externalReferences": [ + { + "type": "vcs", + "url": "https://github.com/dtolnay/thiserror" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#thiserror-impl@2.0.18", + "author": "David Tolnay ", + "name": "thiserror-impl", + "version": "2.0.18", + "description": "Implementation detail of the `thiserror` crate", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "ebc4ee7f67670e9b64d05fa4253e753e016c6c95ff35b89b7941d6b856dec1d5" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/thiserror-impl@2.0.18", + "externalReferences": [ + { + "type": "vcs", + "url": "https://github.com/dtolnay/thiserror" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#thiserror@1.0.69", + "author": "David Tolnay ", + "name": "thiserror", + "version": "1.0.69", + "description": "derive(Error)", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "b6aaf5339b578ea85b50e080feb250a3e8ae8cfcdff9a461c9ec2904bc923f52" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/thiserror@1.0.69", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/thiserror" + }, + { + "type": "vcs", + "url": "https://github.com/dtolnay/thiserror" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#thiserror@2.0.18", + "author": "David Tolnay ", + "name": "thiserror", + "version": "2.0.18", + "description": "derive(Error)", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "4288b5bcbc7920c07a1149a35cf9590a2aa808e0bc1eafaade0b80947865fbc4" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/thiserror@2.0.18", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/thiserror" + }, + { + "type": "vcs", + "url": "https://github.com/dtolnay/thiserror" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#thread_local@1.1.9", + "author": "Amanieu d'Antras ", + "name": "thread_local", + "version": "1.1.9", + "description": "Per-object thread-local storage", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "f60246a4944f24f6e018aa17cdeffb7818b76356965d03b07d6a9886e8962185" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/thread_local@1.1.9", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/thread_local/" + }, + { + "type": "vcs", + "url": "https://github.com/Amanieu/thread_local-rs" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#thrift@0.17.0", + "author": "Apache Thrift Developers ", + "name": "thrift", + "version": "0.17.0", + "description": "Rust bindings for the Apache Thrift RPC system", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "7e54bc85fc7faa8bc175c4bab5b92ba8d9a3ce893d0e9f42cc455c8ab16a9e09" + } + ], + "licenses": [ + { + "expression": "Apache-2.0" + } + ], + "purl": "pkg:cargo/thrift@0.17.0", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/thrift" + }, + { + "type": "website", + "url": "http://thrift.apache.org" + }, + { + "type": "vcs", + "url": "https://github.com/apache/thrift/tree/master/lib/rs" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#tiff@0.11.3", + "author": "The image-rs Developers", + "name": "tiff", + "version": "0.11.3", + "description": "TIFF decoding and encoding library in pure Rust", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "b63feaf3343d35b6ca4d50483f94843803b0f51634937cc2ec519fc32232bc52" + } + ], + "licenses": [ + { + "expression": "MIT" + } + ], + "purl": "pkg:cargo/tiff@0.11.3", + "externalReferences": [ + { + "type": "vcs", + "url": "https://github.com/image-rs/image-tiff" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#time-core@0.1.8", + "author": "Jacob Pratt , Time contributors", + "name": "time-core", + "version": "0.1.8", + "description": "This crate is an implementation detail and should not be relied upon directly.", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "7694e1cfe791f8d31026952abf09c69ca6f6fa4e1a1229e18988f06a04a12dca" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/time-core@0.1.8", + "externalReferences": [ + { + "type": "vcs", + "url": "https://github.com/time-rs/time" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#time-macros@0.2.27", + "author": "Jacob Pratt , Time contributors", + "name": "time-macros", + "version": "0.2.27", + "description": " Procedural macros for the time crate. This crate is an implementation detail and should not be relied upon directly. ", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "2e70e4c5a0e0a8a4823ad65dfe1a6930e4f4d756dcd9dd7939022b5e8c501215" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/time-macros@0.2.27", + "externalReferences": [ + { + "type": "vcs", + "url": "https://github.com/time-rs/time" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#time@0.3.47", + "author": "Jacob Pratt , Time contributors", + "name": "time", + "version": "0.3.47", + "description": "Date and time library. Fully interoperable with the standard library. Mostly compatible with #![no_std].", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "743bd48c283afc0388f9b8827b976905fb217ad9e647fae3a379a9283c4def2c" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/time@0.3.47", + "externalReferences": [ + { + "type": "website", + "url": "https://time-rs.github.io" + }, + { + "type": "vcs", + "url": "https://github.com/time-rs/time" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#tiny-keccak@2.0.2", + "author": "debris ", + "name": "tiny-keccak", + "version": "2.0.2", + "description": "An implementation of Keccak derived functions.", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "2c9d3793400a45f954c52e73d068316d76b6f4e36977e3fcebb13a2721e80237" + } + ], + "licenses": [ + { + "expression": "CC0-1.0" + } + ], + "purl": "pkg:cargo/tiny-keccak@2.0.2", + "externalReferences": [ + { + "type": "website", + "url": "https://github.com/debris/tiny-keccak" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#tinystr@0.8.2", + "author": "The ICU4X Project Developers", + "name": "tinystr", + "version": "0.8.2", + "description": "A small ASCII-only bounded length string representation.", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "42d3e9c45c09de15d06dd8acf5f4e0e399e85927b7f00711024eb7ae10fa4869" + } + ], + "licenses": [ + { + "expression": "Unicode-3.0" + } + ], + "purl": "pkg:cargo/tinystr@0.8.2", + "externalReferences": [ + { + "type": "vcs", + "url": "https://github.com/unicode-org/icu4x" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#tinytemplate@1.2.1", + "author": "Brook Heisler ", + "name": "tinytemplate", + "version": "1.2.1", + "description": "Simple, lightweight template engine", + "scope": "excluded", + "hashes": [ + { + "alg": "SHA-256", + "content": "be4d6b5f19ff7664e8c98d03e2139cb510db9b0a60b55f8e8709b689d939b6bc" + } + ], + "licenses": [ + { + "expression": "Apache-2.0 OR MIT" + } + ], + "purl": "pkg:cargo/tinytemplate@1.2.1", + "externalReferences": [ + { + "type": "vcs", + "url": "https://github.com/bheisler/TinyTemplate" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#tinyvec@1.11.0", + "author": "Lokathor ", + "name": "tinyvec", + "version": "1.11.0", + "description": "`tinyvec` provides 100% safe vec-like data structures.", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "3e61e67053d25a4e82c844e8424039d9745781b3fc4f32b8d55ed50f5f667ef3" + } + ], + "licenses": [ + { + "expression": "Zlib OR Apache-2.0 OR MIT" + } + ], + "purl": "pkg:cargo/tinyvec@1.11.0", + "externalReferences": [ + { + "type": "vcs", + "url": "https://github.com/Lokathor/tinyvec" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#tinyvec_macros@0.1.1", + "author": "Soveu ", + "name": "tinyvec_macros", + "version": "0.1.1", + "description": "Some macros for tiny containers", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "1f3ccbac311fea05f86f61904b462b55fb3df8837a366dfc601a0161d0532f20" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0 OR Zlib" + } + ], + "purl": "pkg:cargo/tinyvec_macros@0.1.1", + "externalReferences": [ + { + "type": "vcs", + "url": "https://github.com/Soveu/tinyvec_macros" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#tokio-io-timeout@1.2.1", + "author": "Steven Fackler ", + "name": "tokio-io-timeout", + "version": "1.2.1", + "description": "Tokio wrappers which apply timeouts to IO operations", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "0bd86198d9ee903fedd2f9a2e72014287c0d9167e4ae43b5853007205dda1b76" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/tokio-io-timeout@1.2.1", + "externalReferences": [ + { + "type": "vcs", + "url": "https://github.com/sfackler/tokio-io-timeout" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#tokio-macros@2.6.1", + "author": "Tokio Contributors ", + "name": "tokio-macros", + "version": "2.6.1", + "description": "Tokio's proc macros. ", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "5c55a2eff8b69ce66c84f85e1da1c233edc36ceb85a2058d11b0d6a3c7e7569c" + } + ], + "licenses": [ + { + "expression": "MIT" + } + ], + "purl": "pkg:cargo/tokio-macros@2.6.1", + "externalReferences": [ + { + "type": "website", + "url": "https://tokio.rs" + }, + { + "type": "vcs", + "url": "https://github.com/tokio-rs/tokio" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#tokio-native-tls@0.3.1", + "author": "Tokio Contributors ", + "name": "tokio-native-tls", + "version": "0.3.1", + "description": "An implementation of TLS/SSL streams for Tokio using native-tls giving an implementation of TLS for nonblocking I/O streams. ", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "bbae76ab933c85776efabc971569dd6119c580d8f5d448769dec1764bf796ef2" + } + ], + "licenses": [ + { + "expression": "MIT" + } + ], + "purl": "pkg:cargo/tokio-native-tls@0.3.1", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/tokio-native-tls" + }, + { + "type": "website", + "url": "https://tokio.rs" + }, + { + "type": "vcs", + "url": "https://github.com/tokio-rs/tls" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#tokio-rustls@0.24.1", + "name": "tokio-rustls", + "version": "0.24.1", + "description": "Asynchronous TLS/SSL streams for Tokio using Rustls.", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "c28327cf380ac148141087fbfb9de9d7bd4e84ab5d2c28fbc911d753de8a7081" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/tokio-rustls@0.24.1", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/tokio-rustls" + }, + { + "type": "website", + "url": "https://github.com/rustls/tokio-rustls" + }, + { + "type": "vcs", + "url": "https://github.com/rustls/tokio-rustls" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#tokio-rustls@0.26.4", + "name": "tokio-rustls", + "version": "0.26.4", + "description": "Asynchronous TLS/SSL streams for Tokio using Rustls.", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "1729aa945f29d91ba541258c8df89027d5792d85a8841fb65e8bf0f4ede4ef61" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/tokio-rustls@0.26.4", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/tokio-rustls" + }, + { + "type": "website", + "url": "https://github.com/rustls/tokio-rustls" + }, + { + "type": "vcs", + "url": "https://github.com/rustls/tokio-rustls" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#tokio-stream@0.1.18", + "author": "Tokio Contributors ", + "name": "tokio-stream", + "version": "0.1.18", + "description": "Utilities to work with `Stream` and `tokio`. ", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "32da49809aab5c3bc678af03902d4ccddea2a87d028d86392a4b1560c6906c70" + } + ], + "licenses": [ + { + "expression": "MIT" + } + ], + "purl": "pkg:cargo/tokio-stream@0.1.18", + "externalReferences": [ + { + "type": "website", + "url": "https://tokio.rs" + }, + { + "type": "vcs", + "url": "https://github.com/tokio-rs/tokio" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#tokio-util@0.7.18", + "author": "Tokio Contributors ", + "name": "tokio-util", + "version": "0.7.18", + "description": "Additional utilities for working with Tokio. ", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "9ae9cec805b01e8fc3fd2fe289f89149a9b66dd16786abd8b19cfa7b48cb0098" + } + ], + "licenses": [ + { + "expression": "MIT" + } + ], + "purl": "pkg:cargo/tokio-util@0.7.18", + "externalReferences": [ + { + "type": "website", + "url": "https://tokio.rs" + }, + { + "type": "vcs", + "url": "https://github.com/tokio-rs/tokio" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#tokio@1.50.0", + "author": "Tokio Contributors ", + "name": "tokio", + "version": "1.50.0", + "description": "An event-driven, non-blocking I/O platform for writing asynchronous I/O backed applications. ", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "27ad5e34374e03cfffefc301becb44e9dc3c17584f414349ebe29ed26661822d" + } + ], + "licenses": [ + { + "expression": "MIT" + } + ], + "purl": "pkg:cargo/tokio@1.50.0", + "externalReferences": [ + { + "type": "website", + "url": "https://tokio.rs" + }, + { + "type": "vcs", + "url": "https://github.com/tokio-rs/tokio" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#toml@0.8.23", + "name": "toml", + "version": "0.8.23", + "description": "A native Rust encoder and decoder of TOML-formatted files and streams. Provides implementations of the standard Serialize/Deserialize traits for TOML data to facilitate deserializing and serializing Rust structures. ", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "dc1beb996b9d83529a9e75c17a1686767d148d70663143c7854d8b4a09ced362" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/toml@0.8.23", + "externalReferences": [ + { + "type": "vcs", + "url": "https://github.com/toml-rs/toml" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#toml_datetime@0.6.11", + "name": "toml_datetime", + "version": "0.6.11", + "description": "A TOML-compatible datetime type", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "22cddaf88f4fbc13c51aebbf5f8eceb5c7c5a9da2ac40a13519eb5b0a0e8f11c" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/toml_datetime@0.6.11", + "externalReferences": [ + { + "type": "vcs", + "url": "https://github.com/toml-rs/toml" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#toml_edit@0.22.27", + "name": "toml_edit", + "version": "0.22.27", + "description": "Yet another format-preserving TOML parser.", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "41fe8c660ae4257887cf66394862d21dbca4a6ddd26f04a3560410406a2f819a" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/toml_edit@0.22.27", + "externalReferences": [ + { + "type": "vcs", + "url": "https://github.com/toml-rs/toml" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#toml_write@0.1.2", + "name": "toml_write", + "version": "0.1.2", + "description": "A low-level interface for writing out TOML ", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "5d99f8c9a7727884afe522e9bd5edbfc91a3312b36a77b5fb8926e4c31a41801" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/toml_write@0.1.2", + "externalReferences": [ + { + "type": "vcs", + "url": "https://github.com/toml-rs/toml" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#tonic-build@0.14.5", + "author": "Lucio Franco ", + "name": "tonic-build", + "version": "0.14.5", + "description": "Codegen module of `tonic` gRPC implementation. ", + "scope": "excluded", + "hashes": [ + { + "alg": "SHA-256", + "content": "1882ac3bf5ef12877d7ed57aad87e75154c11931c2ba7e6cde5e22d63522c734" + } + ], + "licenses": [ + { + "expression": "MIT" + } + ], + "purl": "pkg:cargo/tonic-build@0.14.5", + "externalReferences": [ + { + "type": "website", + "url": "https://github.com/hyperium/tonic" + }, + { + "type": "vcs", + "url": "https://github.com/hyperium/tonic" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#tonic-prost-build@0.14.5", + "author": "Lucio Franco ", + "name": "tonic-prost-build", + "version": "0.14.5", + "description": "Prost build integration for tonic", + "scope": "excluded", + "hashes": [ + { + "alg": "SHA-256", + "content": "f3144df636917574672e93d0f56d7edec49f90305749c668df5101751bb8f95a" + } + ], + "licenses": [ + { + "expression": "MIT" + } + ], + "purl": "pkg:cargo/tonic-prost-build@0.14.5", + "externalReferences": [ + { + "type": "website", + "url": "https://github.com/hyperium/tonic" + }, + { + "type": "vcs", + "url": "https://github.com/hyperium/tonic" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#tonic-prost@0.14.5", + "author": "Lucio Franco ", + "name": "tonic-prost", + "version": "0.14.5", + "description": "Prost codec implementation for tonic", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "a55376a0bbaa4975a3f10d009ad763d8f4108f067c7c2e74f3001fb49778d309" + } + ], + "licenses": [ + { + "expression": "MIT" + } + ], + "purl": "pkg:cargo/tonic-prost@0.14.5", + "externalReferences": [ + { + "type": "website", + "url": "https://github.com/hyperium/tonic" + }, + { + "type": "vcs", + "url": "https://github.com/hyperium/tonic" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#tonic@0.12.3", + "author": "Lucio Franco ", + "name": "tonic", + "version": "0.12.3", + "description": "A gRPC over HTTP/2 implementation focused on high performance, interoperability, and flexibility. ", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "877c5b330756d856ffcc4553ab34a5684481ade925ecc54bcd1bf02b1d0d4d52" + } + ], + "licenses": [ + { + "expression": "MIT" + } + ], + "purl": "pkg:cargo/tonic@0.12.3", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/tonic/0.12.3" + }, + { + "type": "website", + "url": "https://github.com/hyperium/tonic" + }, + { + "type": "vcs", + "url": "https://github.com/hyperium/tonic" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#tonic@0.14.5", + "author": "Lucio Franco ", + "name": "tonic", + "version": "0.14.5", + "description": "A gRPC over HTTP/2 implementation focused on high performance, interoperability, and flexibility. ", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "fec7c61a0695dc1887c1b53952990f3ad2e3a31453e1f49f10e75424943a93ec" + } + ], + "licenses": [ + { + "expression": "MIT" + } + ], + "purl": "pkg:cargo/tonic@0.14.5", + "externalReferences": [ + { + "type": "website", + "url": "https://github.com/hyperium/tonic" + }, + { + "type": "vcs", + "url": "https://github.com/hyperium/tonic" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#tower-http@0.4.4", + "author": "Tower Maintainers ", + "name": "tower-http", + "version": "0.4.4", + "description": "Tower middleware and utilities for HTTP clients and servers", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "61c5bb1d698276a2443e5ecfabc1008bf15a36c12e6a7176e7bf089ea9131140" + } + ], + "licenses": [ + { + "expression": "MIT" + } + ], + "purl": "pkg:cargo/tower-http@0.4.4", + "externalReferences": [ + { + "type": "website", + "url": "https://github.com/tower-rs/tower-http" + }, + { + "type": "vcs", + "url": "https://github.com/tower-rs/tower-http" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#tower-http@0.6.8", + "author": "Tower Maintainers ", + "name": "tower-http", + "version": "0.6.8", + "description": "Tower middleware and utilities for HTTP clients and servers", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "d4e6559d53cc268e5031cd8429d05415bc4cb4aefc4aa5d6cc35fbf5b924a1f8" + } + ], + "licenses": [ + { + "expression": "MIT" + } + ], + "purl": "pkg:cargo/tower-http@0.6.8", + "externalReferences": [ + { + "type": "website", + "url": "https://github.com/tower-rs/tower-http" + }, + { + "type": "vcs", + "url": "https://github.com/tower-rs/tower-http" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#tower-layer@0.3.3", + "author": "Tower Maintainers ", + "name": "tower-layer", + "version": "0.3.3", + "description": "Decorates a `Service` to allow easy composition between `Service`s. ", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "121c2a6cda46980bb0fcd1647ffaf6cd3fc79a013de288782836f6df9c48780e" + } + ], + "licenses": [ + { + "expression": "MIT" + } + ], + "purl": "pkg:cargo/tower-layer@0.3.3", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/tower-layer/0.3.3" + }, + { + "type": "website", + "url": "https://github.com/tower-rs/tower" + }, + { + "type": "vcs", + "url": "https://github.com/tower-rs/tower" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#tower-service@0.3.3", + "author": "Tower Maintainers ", + "name": "tower-service", + "version": "0.3.3", + "description": "Trait representing an asynchronous, request / response based, client or server. ", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "8df9b6e13f2d32c91b9bd719c00d1958837bc7dec474d94952798cc8e69eeec3" + } + ], + "licenses": [ + { + "expression": "MIT" + } + ], + "purl": "pkg:cargo/tower-service@0.3.3", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/tower-service/0.3.3" + }, + { + "type": "website", + "url": "https://github.com/tower-rs/tower" + }, + { + "type": "vcs", + "url": "https://github.com/tower-rs/tower" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#tower@0.4.13", + "author": "Tower Maintainers ", + "name": "tower", + "version": "0.4.13", + "description": "Tower is a library of modular and reusable components for building robust clients and servers. ", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "b8fa9be0de6cf49e536ce1851f987bd21a43b771b09473c3549a6c853db37c1c" + } + ], + "licenses": [ + { + "expression": "MIT" + } + ], + "purl": "pkg:cargo/tower@0.4.13", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/tower/0.4.13" + }, + { + "type": "website", + "url": "https://github.com/tower-rs/tower" + }, + { + "type": "vcs", + "url": "https://github.com/tower-rs/tower" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#tower@0.5.3", + "author": "Tower Maintainers ", + "name": "tower", + "version": "0.5.3", + "description": "Tower is a library of modular and reusable components for building robust clients and servers. ", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "ebe5ef63511595f1344e2d5cfa636d973292adc0eec1f0ad45fae9f0851ab1d4" + } + ], + "licenses": [ + { + "expression": "MIT" + } + ], + "purl": "pkg:cargo/tower@0.5.3", + "externalReferences": [ + { + "type": "website", + "url": "https://github.com/tower-rs/tower" + }, + { + "type": "vcs", + "url": "https://github.com/tower-rs/tower" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#tracing-attributes@0.1.31", + "author": "Tokio Contributors , Eliza Weisman , David Barsky ", + "name": "tracing-attributes", + "version": "0.1.31", + "description": "Procedural macro attributes for automatically instrumenting functions. ", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "7490cfa5ec963746568740651ac6781f701c9c5ea257c58e057f3ba8cf69e8da" + } + ], + "licenses": [ + { + "expression": "MIT" + } + ], + "purl": "pkg:cargo/tracing-attributes@0.1.31", + "externalReferences": [ + { + "type": "website", + "url": "https://tokio.rs" + }, + { + "type": "vcs", + "url": "https://github.com/tokio-rs/tracing" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#tracing-core@0.1.36", + "author": "Tokio Contributors ", + "name": "tracing-core", + "version": "0.1.36", + "description": "Core primitives for application-level tracing. ", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "db97caf9d906fbde555dd62fa95ddba9eecfd14cb388e4f491a66d74cd5fb79a" + } + ], + "licenses": [ + { + "expression": "MIT" + } + ], + "purl": "pkg:cargo/tracing-core@0.1.36", + "externalReferences": [ + { + "type": "website", + "url": "https://tokio.rs" + }, + { + "type": "vcs", + "url": "https://github.com/tokio-rs/tracing" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#tracing-log@0.2.0", + "author": "Tokio Contributors ", + "name": "tracing-log", + "version": "0.2.0", + "description": "Provides compatibility between `tracing` and the `log` crate. ", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "ee855f1f400bd0e5c02d150ae5de3840039a3f54b025156404e34c23c03f47c3" + } + ], + "licenses": [ + { + "expression": "MIT" + } + ], + "purl": "pkg:cargo/tracing-log@0.2.0", + "externalReferences": [ + { + "type": "website", + "url": "https://tokio.rs" + }, + { + "type": "vcs", + "url": "https://github.com/tokio-rs/tracing" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#tracing-opentelemetry@0.28.0", + "name": "tracing-opentelemetry", + "version": "0.28.0", + "description": "OpenTelemetry integration for tracing", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "97a971f6058498b5c0f1affa23e7ea202057a7301dbff68e968b2d578bcbd053" + } + ], + "licenses": [ + { + "expression": "MIT" + } + ], + "purl": "pkg:cargo/tracing-opentelemetry@0.28.0", + "externalReferences": [ + { + "type": "website", + "url": "https://github.com/tokio-rs/tracing-opentelemetry" + }, + { + "type": "vcs", + "url": "https://github.com/tokio-rs/tracing-opentelemetry" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#tracing-subscriber@0.3.23", + "author": "Eliza Weisman , David Barsky , Tokio Contributors ", + "name": "tracing-subscriber", + "version": "0.3.23", + "description": "Utilities for implementing and composing `tracing` subscribers. ", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "cb7f578e5945fb242538965c2d0b04418d38ec25c79d160cd279bf0731c8d319" + } + ], + "licenses": [ + { + "expression": "MIT" + } + ], + "purl": "pkg:cargo/tracing-subscriber@0.3.23", + "externalReferences": [ + { + "type": "website", + "url": "https://tokio.rs" + }, + { + "type": "vcs", + "url": "https://github.com/tokio-rs/tracing" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#tracing@0.1.44", + "author": "Eliza Weisman , Tokio Contributors ", + "name": "tracing", + "version": "0.1.44", + "description": "Application-level tracing for Rust. ", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "63e71662fa4b2a2c3a26f570f037eb95bb1f85397f3cd8076caed2f026a6d100" + } + ], + "licenses": [ + { + "expression": "MIT" + } + ], + "purl": "pkg:cargo/tracing@0.1.44", + "externalReferences": [ + { + "type": "website", + "url": "https://tokio.rs" + }, + { + "type": "vcs", + "url": "https://github.com/tokio-rs/tracing" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#try-lock@0.2.5", + "author": "Sean McArthur ", + "name": "try-lock", + "version": "0.2.5", + "description": "A lightweight atomic lock.", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "e421abadd41a4225275504ea4d6566923418b7f05506fbc9c0fe86ba7396114b" + } + ], + "licenses": [ + { + "expression": "MIT" + } + ], + "purl": "pkg:cargo/try-lock@0.2.5", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/try-lock" + }, + { + "type": "website", + "url": "https://github.com/seanmonstar/try-lock" + }, + { + "type": "vcs", + "url": "https://github.com/seanmonstar/try-lock" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#tui-input@0.12.1", + "author": "Arijit Basu ", + "name": "tui-input", + "version": "0.12.1", + "description": "TUI input library supporting multiple backends", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "dce25d24adf2c5350c57426f25cf12bc767455a6d9202be155458fc768ea1268" + } + ], + "licenses": [ + { + "expression": "MIT" + } + ], + "purl": "pkg:cargo/tui-input@0.12.1", + "externalReferences": [ + { + "type": "vcs", + "url": "https://github.com/sayanarijit/tui-input" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#twox-hash@2.1.2", + "author": "Jake Goulding ", + "name": "twox-hash", + "version": "2.1.2", + "description": "A Rust implementation of the XXHash and XXH3 algorithms", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "9ea3136b675547379c4bd395ca6b938e5ad3c3d20fad76e7fe85f9e0d011419c" + } + ], + "licenses": [ + { + "expression": "MIT" + } + ], + "purl": "pkg:cargo/twox-hash@2.1.2", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/twox-hash/" + }, + { + "type": "vcs", + "url": "https://github.com/shepmaster/twox-hash" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#typed-path@0.12.3", + "author": "Chip Senkbeil ", + "name": "typed-path", + "version": "0.12.3", + "description": "Provides typed variants of Path and PathBuf for Unix and Windows", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "8e28f89b80c87b8fb0cf04ab448d5dd0dd0ade2f8891bae878de66a75a28600e" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/typed-path@0.12.3", + "externalReferences": [ + { + "type": "website", + "url": "https://github.com/chipsenkbeil/typed-path" + }, + { + "type": "vcs", + "url": "https://github.com/chipsenkbeil/typed-path" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#typenum@1.19.0", + "author": "Paho Lurie-Gregg , Andre Bogus ", + "name": "typenum", + "version": "1.19.0", + "description": "Typenum is a Rust library for type-level numbers evaluated at compile time. It currently supports bits, unsigned integers, and signed integers. It also provides a type-level array of type-level numbers, but its implementation is incomplete.", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "562d481066bde0658276a35467c4af00bdc6ee726305698a55b86e61d7ad82bb" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/typenum@1.19.0", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/typenum" + }, + { + "type": "vcs", + "url": "https://github.com/paholg/typenum" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#ucd-trie@0.1.7", + "author": "Andrew Gallant ", + "name": "ucd-trie", + "version": "0.1.7", + "description": "A trie for storing Unicode codepoint sets and maps. ", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "2896d95c02a80c6d6a5d6e953d479f5ddf2dfdb6a244441010e373ac0fb88971" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/ucd-trie@0.1.7", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/ucd-trie" + }, + { + "type": "website", + "url": "https://github.com/BurntSushi/ucd-generate" + }, + { + "type": "vcs", + "url": "https://github.com/BurntSushi/ucd-generate" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#unarray@0.1.4", + "name": "unarray", + "version": "0.1.4", + "description": "Utilities for working with uninitialized arrays", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "eaea85b334db583fe3274d12b4cd1880032beab409c0d774be044d4480ab9a94" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/unarray@0.1.4", + "externalReferences": [ + { + "type": "vcs", + "url": "https://github.com/cameron1024/unarray" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#uncased@0.9.10", + "author": "Sergio Benitez ", + "name": "uncased", + "version": "0.9.10", + "description": "Case-preserving, ASCII case-insensitive, no_std string types.", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "e1b88fcfe09e89d3866a5c11019378088af2d24c3fbd4f0543f96b479ec90697" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/uncased@0.9.10", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/uncased/0.9" + }, + { + "type": "vcs", + "url": "https://github.com/SergioBenitez/uncased" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#unicase@2.9.0", + "author": "Sean McArthur ", + "name": "unicase", + "version": "2.9.0", + "description": "A case-insensitive wrapper around strings.", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "dbc4bc3a9f746d862c45cb89d705aa10f187bb96c76001afab07a0d35ce60142" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/unicase@2.9.0", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/unicase" + }, + { + "type": "vcs", + "url": "https://github.com/seanmonstar/unicase" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#unicode-bidi@0.3.18", + "author": "The Servo Project Developers", + "name": "unicode-bidi", + "version": "0.3.18", + "description": "Implementation of the Unicode Bidirectional Algorithm", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "5c1cb5db39152898a79168971543b1cb5020dff7fe43c8dc468b0885f5e29df5" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/unicode-bidi@0.3.18", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/unicode-bidi/" + }, + { + "type": "vcs", + "url": "https://github.com/servo/unicode-bidi" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#unicode-ident@1.0.24", + "author": "David Tolnay ", + "name": "unicode-ident", + "version": "1.0.24", + "description": "Determine whether characters have the XID_Start or XID_Continue properties according to Unicode Standard Annex #31", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75" + } + ], + "licenses": [ + { + "expression": "(MIT OR Apache-2.0) AND Unicode-3.0" + } + ], + "purl": "pkg:cargo/unicode-ident@1.0.24", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/unicode-ident" + }, + { + "type": "vcs", + "url": "https://github.com/dtolnay/unicode-ident" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#unicode-linebreak@0.1.5", + "author": "Axel Forsman ", + "name": "unicode-linebreak", + "version": "0.1.5", + "description": "Implementation of the Unicode Line Breaking Algorithm", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "3b09c83c3c29d37506a3e260c08c03743a6bb66a9cd432c6934ab501a190571f" + } + ], + "licenses": [ + { + "expression": "Apache-2.0" + } + ], + "purl": "pkg:cargo/unicode-linebreak@0.1.5", + "externalReferences": [ + { + "type": "website", + "url": "https://github.com/axelf4/unicode-linebreak" + }, + { + "type": "vcs", + "url": "https://github.com/axelf4/unicode-linebreak" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#unicode-normalization@0.1.25", + "author": "kwantam , Manish Goregaokar ", + "name": "unicode-normalization", + "version": "0.1.25", + "description": "This crate provides functions for normalization of Unicode strings, including Canonical and Compatible Decomposition and Recomposition, as described in Unicode Standard Annex #15. ", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "5fd4f6878c9cb28d874b009da9e8d183b5abc80117c40bbd187a1fde336be6e8" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/unicode-normalization@0.1.25", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/unicode-normalization/" + }, + { + "type": "website", + "url": "https://github.com/unicode-rs/unicode-normalization" + }, + { + "type": "vcs", + "url": "https://github.com/unicode-rs/unicode-normalization" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#unicode-properties@0.1.4", + "author": "Charles Lew , Manish Goregaokar ", + "name": "unicode-properties", + "version": "0.1.4", + "description": "Query character Unicode properties according to UAX #44 and UTR #51. ", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "7df058c713841ad818f1dc5d3fd88063241cc61f49f5fbea4b951e8cf5a8d71d" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/unicode-properties@0.1.4", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/unicode-properties" + }, + { + "type": "website", + "url": "https://github.com/unicode-rs/unicode-properties" + }, + { + "type": "vcs", + "url": "https://github.com/unicode-rs/unicode-properties" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#unicode-segmentation@1.12.0", + "author": "kwantam , Manish Goregaokar ", + "name": "unicode-segmentation", + "version": "1.12.0", + "description": "This crate provides Grapheme Cluster, Word and Sentence boundaries according to Unicode Standard Annex #29 rules. ", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "f6ccf251212114b54433ec949fd6a7841275f9ada20dddd2f29e9ceea4501493" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/unicode-segmentation@1.12.0", + "externalReferences": [ + { + "type": "website", + "url": "https://github.com/unicode-rs/unicode-segmentation" + }, + { + "type": "vcs", + "url": "https://github.com/unicode-rs/unicode-segmentation" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#unicode-truncate@1.1.0", + "author": "Aetf ", + "name": "unicode-truncate", + "version": "1.1.0", + "description": "Unicode-aware algorithm to pad or truncate `str` in terms of displayed width. ", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "b3644627a5af5fa321c95b9b235a72fd24cd29c648c2c379431e6628655627bf" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/unicode-truncate@1.1.0", + "externalReferences": [ + { + "type": "website", + "url": "https://github.com/Aetf/unicode-truncate" + }, + { + "type": "vcs", + "url": "https://github.com/Aetf/unicode-truncate" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#unicode-width@0.1.14", + "author": "kwantam , Manish Goregaokar ", + "name": "unicode-width", + "version": "0.1.14", + "description": "Determine displayed width of `char` and `str` types according to Unicode Standard Annex #11 rules. ", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "7dd6e30e90baa6f72411720665d41d89b9a3d039dc45b8faea1ddd07f617f6af" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/unicode-width@0.1.14", + "externalReferences": [ + { + "type": "website", + "url": "https://github.com/unicode-rs/unicode-width" + }, + { + "type": "vcs", + "url": "https://github.com/unicode-rs/unicode-width" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#unicode-width@0.2.0", + "author": "kwantam , Manish Goregaokar ", + "name": "unicode-width", + "version": "0.2.0", + "description": "Determine displayed width of `char` and `str` types according to Unicode Standard Annex #11 rules. ", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "1fc81956842c57dac11422a97c3b8195a1ff727f06e85c84ed2e8aa277c9a0fd" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/unicode-width@0.2.0", + "externalReferences": [ + { + "type": "website", + "url": "https://github.com/unicode-rs/unicode-width" + }, + { + "type": "vcs", + "url": "https://github.com/unicode-rs/unicode-width" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#unindent@0.2.4", + "author": "David Tolnay ", + "name": "unindent", + "version": "0.2.4", + "description": "Remove a column of leading whitespace from a string", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "7264e107f553ccae879d21fbea1d6724ac785e8c3bfc762137959b5802826ef3" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/unindent@0.2.4", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/unindent" + }, + { + "type": "vcs", + "url": "https://github.com/dtolnay/indoc" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#unsafe-libyaml@0.2.11", + "author": "David Tolnay ", + "name": "unsafe-libyaml", + "version": "0.2.11", + "description": "libyaml transpiled to rust by c2rust", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "673aac59facbab8a9007c7f6108d11f63b603f7cabff99fabf650fea5c32b861" + } + ], + "licenses": [ + { + "expression": "MIT" + } + ], + "purl": "pkg:cargo/unsafe-libyaml@0.2.11", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/unsafe-libyaml" + }, + { + "type": "vcs", + "url": "https://github.com/dtolnay/unsafe-libyaml" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#untrusted@0.7.1", + "author": "Brian Smith ", + "name": "untrusted", + "version": "0.7.1", + "description": "Safe, fast, zero-panic, zero-crashing, zero-allocation parsing of untrusted inputs in Rust.", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "a156c684c91ea7d62626509bce3cb4e1d9ed5c4d978f7b4352658f96a4c26b4a" + } + ], + "licenses": [ + { + "expression": "ISC" + } + ], + "purl": "pkg:cargo/untrusted@0.7.1", + "externalReferences": [ + { + "type": "documentation", + "url": "https://briansmith.org/rustdoc/untrusted/" + }, + { + "type": "vcs", + "url": "https://github.com/briansmith/untrusted" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#untrusted@0.9.0", + "author": "Brian Smith ", + "name": "untrusted", + "version": "0.9.0", + "description": "Safe, fast, zero-panic, zero-crashing, zero-allocation parsing of untrusted inputs in Rust.", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "8ecb6da28b8a351d773b68d5825ac39017e680750f980f3a1a85cd8dd28a47c1" + } + ], + "licenses": [ + { + "expression": "ISC" + } + ], + "purl": "pkg:cargo/untrusted@0.9.0", + "externalReferences": [ + { + "type": "documentation", + "url": "https://briansmith.org/rustdoc/untrusted/" + }, + { + "type": "vcs", + "url": "https://github.com/briansmith/untrusted" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#url@2.5.8", + "author": "The rust-url developers", + "name": "url", + "version": "2.5.8", + "description": "URL library for Rust, based on the WHATWG URL Standard", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "ff67a8a4397373c3ef660812acab3268222035010ab8680ec4215f38ba3d0eed" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/url@2.5.8", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/url" + }, + { + "type": "vcs", + "url": "https://github.com/servo/rust-url" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#urlencoding@2.1.3", + "author": "Kornel , Bertram Truong ", + "name": "urlencoding", + "version": "2.1.3", + "description": "A Rust library for doing URL percentage encoding.", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "daf8dba3b7eb870caf1ddeed7bc9d2a049f3cfdfae7cb521b087cc33ae4c49da" + } + ], + "licenses": [ + { + "expression": "MIT" + } + ], + "purl": "pkg:cargo/urlencoding@2.1.3", + "externalReferences": [ + { + "type": "website", + "url": "https://lib.rs/urlencoding" + }, + { + "type": "vcs", + "url": "https://github.com/kornelski/rust_urlencoding" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#usearch@2.23.0", + "author": "Ash Vardanian <1983160+ashvardanian@users.noreply.github.com>", + "name": "usearch", + "version": "2.23.0", + "description": "Smaller & Faster Single-File Vector Search Engine from Unum", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "0a03c05af8d678ec19f014c734ab667c20ea54128b4f9a1472cb470246a9b341" + } + ], + "licenses": [ + { + "expression": "Apache-2.0" + } + ], + "purl": "pkg:cargo/usearch@2.23.0", + "externalReferences": [ + { + "type": "documentation", + "url": "https://unum-cloud.github.io/usearch" + }, + { + "type": "vcs", + "url": "https://github.com/unum-cloud/usearch" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#utf8-ranges@1.0.5", + "author": "Andrew Gallant ", + "name": "utf8-ranges", + "version": "1.0.5", + "description": "DEPRECATED. Use regex-syntax::utf8 submodule instead.", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "7fcfc827f90e53a02eaef5e535ee14266c1d569214c6aa70133a624d8a3164ba" + } + ], + "licenses": [ + { + "expression": "Unlicense OR MIT" + } + ], + "purl": "pkg:cargo/utf8-ranges@1.0.5", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/utf8-ranges" + }, + { + "type": "website", + "url": "https://github.com/BurntSushi/utf8-ranges" + }, + { + "type": "vcs", + "url": "https://github.com/BurntSushi/utf8-ranges" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#utf8_iter@1.0.4", + "author": "Henri Sivonen ", + "name": "utf8_iter", + "version": "1.0.4", + "description": "Iterator by char over potentially-invalid UTF-8 in &[u8]", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "b6c140620e7ffbb22c2dee59cafe6084a59b5ffc27a8859a5f0d494b5d52b6be" + } + ], + "licenses": [ + { + "expression": "Apache-2.0 OR MIT" + } + ], + "purl": "pkg:cargo/utf8_iter@1.0.4", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/utf8_iter/" + }, + { + "type": "website", + "url": "https://docs.rs/utf8_iter/" + }, + { + "type": "vcs", + "url": "https://github.com/hsivonen/utf8_iter" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#utf8parse@0.2.2", + "author": "Joe Wilm , Christian Duerr ", + "name": "utf8parse", + "version": "0.2.2", + "description": "Table-driven UTF-8 parser", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "06abde3611657adf66d383f00b093d7faecc7fa57071cce2578660c9f1010821" + } + ], + "licenses": [ + { + "expression": "Apache-2.0 OR MIT" + } + ], + "purl": "pkg:cargo/utf8parse@0.2.2", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/utf8parse/" + }, + { + "type": "vcs", + "url": "https://github.com/alacritty/vte" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#utoipa-axum@0.2.0", + "author": "Juha Kukkonen ", + "name": "utoipa-axum", + "version": "0.2.0", + "description": "Utoipa's axum bindings for seamless integration for the two", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "7c25bae5bccc842449ec0c5ddc5cbb6a3a1eaeac4503895dc105a1138f8234a0" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/utoipa-axum@0.2.0", + "externalReferences": [ + { + "type": "vcs", + "url": "https://github.com/juhaku/utoipa" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#utoipa-gen@5.4.0", + "author": "Juha Kukkonen ", + "name": "utoipa-gen", + "version": "5.4.0", + "description": "Code generation implementation for utoipa", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "6d79d08d92ab8af4c5e8a6da20c47ae3f61a0f1dabc1997cdf2d082b757ca08b" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/utoipa-gen@5.4.0", + "externalReferences": [ + { + "type": "vcs", + "url": "https://github.com/juhaku/utoipa" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#utoipa-swagger-ui@9.0.2", + "author": "Juha Kukkonen ", + "name": "utoipa-swagger-ui", + "version": "9.0.2", + "description": "Swagger UI for utoipa", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "d047458f1b5b65237c2f6dc6db136945667f40a7668627b3490b9513a3d43a55" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/utoipa-swagger-ui@9.0.2", + "externalReferences": [ + { + "type": "vcs", + "url": "https://github.com/juhaku/utoipa" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#utoipa@5.4.0", + "author": "Juha Kukkonen ", + "name": "utoipa", + "version": "5.4.0", + "description": "Compile time generated OpenAPI documentation for Rust", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "2fcc29c80c21c31608227e0912b2d7fddba57ad76b606890627ba8ee7964e993" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/utoipa@5.4.0", + "externalReferences": [ + { + "type": "vcs", + "url": "https://github.com/juhaku/utoipa" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#uuid@1.22.0", + "author": "Ashley Mannix, Dylan DPC, Hunar Roop Kahlon", + "name": "uuid", + "version": "1.22.0", + "description": "A library to generate and parse UUIDs.", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "a68d3c8f01c0cfa54a75291d83601161799e4a89a39e0929f4b0354d88757a37" + } + ], + "licenses": [ + { + "expression": "Apache-2.0 OR MIT" + } + ], + "purl": "pkg:cargo/uuid@1.22.0", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/uuid" + }, + { + "type": "website", + "url": "https://github.com/uuid-rs/uuid" + }, + { + "type": "vcs", + "url": "https://github.com/uuid-rs/uuid" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#validator@0.19.0", + "author": "Vincent Prouillet ", + "name": "vcpkg", + "version": "0.2.15", + "description": "A library to find native dependencies in a vcpkg tree at build time in order to be used in Cargo build scripts. ", + "scope": "excluded", + "hashes": [ + { + "alg": "SHA-256", + "content": "accd4ea62f7bb7a82fe23066fb0957d48ef677f6eeb8215f372f52e48bb32426" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/vcpkg@0.2.15", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/vcpkg" + }, + { + "type": "vcs", + "url": "https://github.com/mcgoo/vcpkg-rs" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#version_check@0.9.5", + "author": "Sergio Benitez ", + "name": "version_check", + "version": "0.9.5", + "description": "Tiny crate to check the version of the installed/running rustc.", + "scope": "excluded", + "hashes": [ + { + "alg": "SHA-256", + "content": "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/version_check@0.9.5", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/version_check/" + }, + { + "type": "vcs", + "url": "https://github.com/SergioBenitez/version_check" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#vsimd@0.8.0", + "name": "vsimd", + "version": "0.8.0", + "description": "SIMD utilities", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "5c3082ca00d5a5ef149bb8b555a72ae84c9c59f7250f013ac822ac2e49b19c64" + } + ], + "licenses": [ + { + "expression": "MIT" + } + ], + "purl": "pkg:cargo/vsimd@0.8.0", + "externalReferences": [ + { + "type": "vcs", + "url": "https://github.com/Nugine/simd" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#wait-timeout@0.2.1", + "author": "Alex Crichton ", + "name": "wait-timeout", + "version": "0.2.1", + "description": "A crate to wait on a child process with a timeout specified across Unix and Windows platforms. ", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "09ac3b126d3914f9849036f826e054cbabdc8519970b8998ddaf3b5bd3c65f11" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/wait-timeout@0.2.1", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/wait-timeout" + }, + { + "type": "website", + "url": "https://github.com/alexcrichton/wait-timeout" + }, + { + "type": "vcs", + "url": "https://github.com/alexcrichton/wait-timeout" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#walkdir@2.5.0", + "author": "Andrew Gallant ", + "name": "walkdir", + "version": "2.5.0", + "description": "Recursively walk a directory.", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "29790946404f91d9c5d06f9874efddea1dc06c5efe94541a7d6863108e3a5e4b" + } + ], + "licenses": [ + { + "expression": "Unlicense OR MIT" + } + ], + "purl": "pkg:cargo/walkdir@2.5.0", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/walkdir/" + }, + { + "type": "website", + "url": "https://github.com/BurntSushi/walkdir" + }, + { + "type": "vcs", + "url": "https://github.com/BurntSushi/walkdir" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#want@0.3.1", + "author": "Sean McArthur ", + "name": "want", + "version": "0.3.1", + "description": "Detect when another Future wants a result.", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "bfa7760aed19e106de2c7c0b581b509f2f25d3dacaf737cb82ac61bc6d760b0e" + } + ], + "licenses": [ + { + "expression": "MIT" + } + ], + "purl": "pkg:cargo/want@0.3.1", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/want" + }, + { + "type": "vcs", + "url": "https://github.com/seanmonstar/want" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#web-time@1.1.0", + "name": "web-time", + "version": "1.1.0", + "description": "Drop-in replacement for std::time for Wasm in browsers", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "5a6580f308b1fad9207618087a65c04e7a10bc77e02c8e84e9b00dd4b12fa0bb" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/web-time@1.1.0", + "externalReferences": [ + { + "type": "vcs", + "url": "https://github.com/daxpedda/web-time" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#webbrowser@1.2.0", + "author": "Amod Malviya @amodm", + "name": "webbrowser", + "version": "1.2.0", + "description": "Open URLs in web browsers available on a platform", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "fe985f41e291eecef5e5c0770a18d28390addb03331c043964d9e916453d6f16" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/webbrowser@1.2.0", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/webbrowser" + }, + { + "type": "website", + "url": "https://github.com/amodm/webbrowser-rs" + }, + { + "type": "vcs", + "url": "https://github.com/amodm/webbrowser-rs" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#webpki-roots@1.0.6", + "name": "webpki-roots", + "version": "1.0.6", + "description": "Mozilla's CA root certificates for use with webpki", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "22cfaf3c063993ff62e73cb4311efde4db1efb31ab78a3e5c457939ad5cc0bed" + } + ], + "licenses": [ + { + "expression": "CDLA-Permissive-2.0" + } + ], + "purl": "pkg:cargo/webpki-roots@1.0.6", + "externalReferences": [ + { + "type": "website", + "url": "https://github.com/rustls/webpki-roots" + }, + { + "type": "vcs", + "url": "https://github.com/rustls/webpki-roots" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#weezl@0.1.12", + "author": "The image-rs Developers", + "name": "weezl", + "version": "0.1.12", + "description": "Fast LZW compression and decompression.", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "a28ac98ddc8b9274cb41bb4d9d4d5c425b6020c50c46f25559911905610b4a88" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/weezl@0.1.12", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/weezl" + }, + { + "type": "vcs", + "url": "https://github.com/image-rs/weezl" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#whoami@1.6.1", + "name": "whoami", + "version": "1.6.1", + "description": "Retrieve the current user and environment.", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "5d4a4db5077702ca3015d3d02d74974948aba2ad9e12ab7df718ee64ccd7e97d" + } + ], + "licenses": [ + { + "expression": "Apache-2.0 OR BSL-1.0 OR MIT" + } + ], + "purl": "pkg:cargo/whoami@1.6.1", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/whoami" + }, + { + "type": "website", + "url": "https://github.com/ardaku/whoami/blob/v1/CHANGELOG.md" + }, + { + "type": "vcs", + "url": "https://github.com/ardaku/whoami" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#winapi-util@0.1.11", + "author": "Andrew Gallant ", + "name": "winapi-util", + "version": "0.1.11", + "description": "A dumping ground for high level safe wrappers over windows-sys.", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22" + } + ], + "licenses": [ + { + "expression": "Unlicense OR MIT" + } + ], + "purl": "pkg:cargo/winapi-util@0.1.11", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/winapi-util" + }, + { + "type": "website", + "url": "https://github.com/BurntSushi/winapi-util" + }, + { + "type": "vcs", + "url": "https://github.com/BurntSushi/winapi-util" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#winapi@0.3.9", + "author": "Peter Atashian ", + "name": "winapi", + "version": "0.3.9", + "description": "Raw FFI bindings for all of Windows API.", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "5c839a674fcd7a98952e593242ea400abe93992746761e38641405d28b00f419" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/winapi@0.3.9", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/winapi/" + }, + { + "type": "vcs", + "url": "https://github.com/retep998/winapi-rs" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#windows-link@0.2.1", + "name": "windows-link", + "version": "0.2.1", + "description": "Linking for Windows", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/windows-link@0.2.1", + "externalReferences": [ + { + "type": "vcs", + "url": "https://github.com/microsoft/windows-rs" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#windows-registry@0.6.1", + "name": "windows-registry", + "version": "0.6.1", + "description": "Windows registry", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "02752bf7fbdcce7f2a27a742f798510f3e5ad88dbe84871e5168e2120c3d5720" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/windows-registry@0.6.1", + "externalReferences": [ + { + "type": "vcs", + "url": "https://github.com/microsoft/windows-rs" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#windows-result@0.4.1", + "name": "windows-result", + "version": "0.4.1", + "description": "Windows error handling", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "7781fa89eaf60850ac3d2da7af8e5242a5ea78d1a11c49bf2910bb5a73853eb5" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/windows-result@0.4.1", + "externalReferences": [ + { + "type": "vcs", + "url": "https://github.com/microsoft/windows-rs" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#windows-strings@0.5.1", + "name": "windows-strings", + "version": "0.5.1", + "description": "Windows string types", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "7837d08f69c77cf6b07689544538e017c1bfcf57e34b4c0ff58e6c2cd3b37091" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/windows-strings@0.5.1", + "externalReferences": [ + { + "type": "vcs", + "url": "https://github.com/microsoft/windows-rs" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#windows-sys@0.48.0", + "author": "Microsoft", + "name": "windows-sys", + "version": "0.48.0", + "description": "Rust for Windows", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "677d2418bec65e3338edb076e806bc1ec15693c5d0104683f2efe857f61056a9" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/windows-sys@0.48.0", + "externalReferences": [ + { + "type": "vcs", + "url": "https://github.com/microsoft/windows-rs" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#windows-sys@0.52.0", + "author": "Microsoft", + "name": "windows-sys", + "version": "0.52.0", + "description": "Rust for Windows", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "282be5f36a8ce781fad8c8ae18fa3f9beff57ec1b52cb3de0789201425d9a33d" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/windows-sys@0.52.0", + "externalReferences": [ + { + "type": "vcs", + "url": "https://github.com/microsoft/windows-rs" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#windows-sys@0.59.0", + "author": "Microsoft", + "name": "windows-sys", + "version": "0.59.0", + "description": "Rust for Windows", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "1e38bc4d79ed67fd075bcc251a1c39b32a1776bbe92e5bef1f0bf1f8c531853b" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/windows-sys@0.59.0", + "externalReferences": [ + { + "type": "vcs", + "url": "https://github.com/microsoft/windows-rs" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#windows-sys@0.60.2", + "author": "Microsoft", + "name": "windows-sys", + "version": "0.60.2", + "description": "Rust for Windows", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "f2f500e4d28234f72040990ec9d39e3a6b950f9f22d3dba18416c35882612bcb" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/windows-sys@0.60.2", + "externalReferences": [ + { + "type": "vcs", + "url": "https://github.com/microsoft/windows-rs" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#windows-sys@0.61.2", + "name": "windows-sys", + "version": "0.61.2", + "description": "Rust for Windows", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/windows-sys@0.61.2", + "externalReferences": [ + { + "type": "vcs", + "url": "https://github.com/microsoft/windows-rs" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#windows-targets@0.48.5", + "author": "Microsoft", + "name": "windows-targets", + "version": "0.48.5", + "description": "Import libs for Windows", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "9a2fa6e2155d7247be68c096456083145c183cbbbc2764150dda45a87197940c" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/windows-targets@0.48.5", + "externalReferences": [ + { + "type": "vcs", + "url": "https://github.com/microsoft/windows-rs" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#windows-targets@0.52.6", + "author": "Microsoft", + "name": "windows-targets", + "version": "0.52.6", + "description": "Import libs for Windows", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/windows-targets@0.52.6", + "externalReferences": [ + { + "type": "vcs", + "url": "https://github.com/microsoft/windows-rs" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#windows-targets@0.53.5", + "name": "windows-targets", + "version": "0.53.5", + "description": "Import libs for Windows", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "4945f9f551b88e0d65f3db0bc25c33b8acea4d9e41163edf90dcd0b19f9069f3" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/windows-targets@0.53.5", + "externalReferences": [ + { + "type": "vcs", + "url": "https://github.com/microsoft/windows-rs" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#windows_x86_64_msvc@0.48.5", + "author": "Microsoft", + "name": "windows_x86_64_msvc", + "version": "0.48.5", + "description": "Import lib for Windows", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "ed94fce61571a4006852b7389a063ab983c02eb1bb37b47f8272ce92d06d9538" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/windows_x86_64_msvc@0.48.5", + "externalReferences": [ + { + "type": "vcs", + "url": "https://github.com/microsoft/windows-rs" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#windows_x86_64_msvc@0.52.6", + "author": "Microsoft", + "name": "windows_x86_64_msvc", + "version": "0.52.6", + "description": "Import lib for Windows", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/windows_x86_64_msvc@0.52.6", + "externalReferences": [ + { + "type": "vcs", + "url": "https://github.com/microsoft/windows-rs" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#windows_x86_64_msvc@0.53.1", + "name": "windows_x86_64_msvc", + "version": "0.53.1", + "description": "Import lib for Windows", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "d6bbff5f0aada427a1e5a6da5f1f98158182f26556f345ac9e04d36d0ebed650" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/windows_x86_64_msvc@0.53.1", + "externalReferences": [ + { + "type": "vcs", + "url": "https://github.com/microsoft/windows-rs" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#winnow@0.7.15", + "name": "winnow", + "version": "0.7.15", + "description": "A byte-oriented, zero-copy, parser combinators library", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "df79d97927682d2fd8adb29682d1140b343be4ac0f08fd68b7765d9c059d3945" + } + ], + "licenses": [ + { + "expression": "MIT" + } + ], + "purl": "pkg:cargo/winnow@0.7.15", + "externalReferences": [ + { + "type": "vcs", + "url": "https://github.com/winnow-rs/winnow" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#writeable@0.6.2", + "author": "The ICU4X Project Developers", + "name": "writeable", + "version": "0.6.2", + "description": "A more efficient alternative to fmt::Display", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "9edde0db4769d2dc68579893f2306b26c6ecfbe0ef499b013d731b7b9247e0b9" + } + ], + "licenses": [ + { + "expression": "Unicode-3.0" + } + ], + "purl": "pkg:cargo/writeable@0.6.2", + "externalReferences": [ + { + "type": "vcs", + "url": "https://github.com/unicode-org/icu4x" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#wyz@0.5.1", + "author": "myrrlyn ", + "name": "wyz", + "version": "0.5.1", + "description": "myrrlyn’s utility collection", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "05f360fc0b24296329c78fda852a1e9ae82de9cf7b27dae4b7f62f118f77b9ed" + } + ], + "licenses": [ + { + "expression": "MIT" + } + ], + "purl": "pkg:cargo/wyz@0.5.1", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/wyz" + }, + { + "type": "website", + "url": "https://myrrlyn.net/crates/wyz" + }, + { + "type": "vcs", + "url": "https://github.com/myrrlyn/wyz" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#xmlparser@0.13.6", + "author": "Yevhenii Reizner ", + "name": "xmlparser", + "version": "0.13.6", + "description": "Pull-based, zero-allocation XML parser.", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "66fee0b777b0f5ac1c69bb06d361268faafa61cd4682ae064a171c16c433e9e4" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/xmlparser@0.13.6", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/xmlparser/" + }, + { + "type": "vcs", + "url": "https://github.com/RazrFalcon/xmlparser" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#yansi@1.0.1", + "author": "Sergio Benitez ", + "name": "yansi", + "version": "1.0.1", + "description": "A dead simple ANSI terminal color painting library.", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "cfe53a6657fd280eaa890a3bc59152892ffa3e30101319d168b781ed6529b049" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/yansi@1.0.1", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/yansi" + }, + { + "type": "vcs", + "url": "https://github.com/SergioBenitez/yansi" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#yoke-derive@0.8.1", + "author": "Manish Goregaokar ", + "name": "yoke-derive", + "version": "0.8.1", + "description": "Custom derive for the yoke crate", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "b659052874eb698efe5b9e8cf382204678a0086ebf46982b79d6ca3182927e5d" + } + ], + "licenses": [ + { + "expression": "Unicode-3.0" + } + ], + "purl": "pkg:cargo/yoke-derive@0.8.1", + "externalReferences": [ + { + "type": "vcs", + "url": "https://github.com/unicode-org/icu4x" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#yoke@0.8.1", + "author": "Manish Goregaokar ", + "name": "yoke", + "version": "0.8.1", + "description": "Abstraction allowing borrowed data to be carried along with the backing data it borrows from", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "72d6e5c6afb84d73944e5cedb052c4680d5657337201555f9f2a16b7406d4954" + } + ], + "licenses": [ + { + "expression": "Unicode-3.0" + } + ], + "purl": "pkg:cargo/yoke@0.8.1", + "externalReferences": [ + { + "type": "vcs", + "url": "https://github.com/unicode-org/icu4x" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#zerocopy-derive@0.8.47", + "author": "Joshua Liebow-Feeser , Jack Wrenn ", + "name": "zerocopy-derive", + "version": "0.8.47", + "description": "Custom derive for traits from the zerocopy crate", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "0e8bc7269b54418e7aeeef514aa68f8690b8c0489a06b0136e5f57c4c5ccab89" + } + ], + "licenses": [ + { + "expression": "BSD-2-Clause OR Apache-2.0 OR MIT" + } + ], + "purl": "pkg:cargo/zerocopy-derive@0.8.47", + "externalReferences": [ + { + "type": "vcs", + "url": "https://github.com/google/zerocopy" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#zerocopy@0.8.47", + "author": "Joshua Liebow-Feeser , Jack Wrenn ", + "name": "zerocopy", + "version": "0.8.47", + "description": "Zerocopy makes zero-cost memory manipulation effortless. We write \"unsafe\" so you don't have to.", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "efbb2a062be311f2ba113ce66f697a4dc589f85e78a4aea276200804cea0ed87" + } + ], + "licenses": [ + { + "expression": "BSD-2-Clause OR Apache-2.0 OR MIT" + } + ], + "purl": "pkg:cargo/zerocopy@0.8.47", + "externalReferences": [ + { + "type": "vcs", + "url": "https://github.com/google/zerocopy" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#zerofrom-derive@0.1.6", + "author": "Manish Goregaokar ", + "name": "zerofrom-derive", + "version": "0.1.6", + "description": "Custom derive for the zerofrom crate", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "d71e5d6e06ab090c67b5e44993ec16b72dcbaabc526db883a360057678b48502" + } + ], + "licenses": [ + { + "expression": "Unicode-3.0" + } + ], + "purl": "pkg:cargo/zerofrom-derive@0.1.6", + "externalReferences": [ + { + "type": "vcs", + "url": "https://github.com/unicode-org/icu4x" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#zerofrom@0.1.6", + "author": "Manish Goregaokar ", + "name": "zerofrom", + "version": "0.1.6", + "description": "ZeroFrom trait for constructing", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "50cc42e0333e05660c3587f3bf9d0478688e15d870fab3346451ce7f8c9fbea5" + } + ], + "licenses": [ + { + "expression": "Unicode-3.0" + } + ], + "purl": "pkg:cargo/zerofrom@0.1.6", + "externalReferences": [ + { + "type": "vcs", + "url": "https://github.com/unicode-org/icu4x" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#zeroize@1.8.2", + "author": "The RustCrypto Project Developers", + "name": "zeroize", + "version": "1.8.2", + "description": "Securely clear secrets from memory with a simple trait built on stable Rust primitives which guarantee memory is zeroed using an operation will not be 'optimized away' by the compiler. Uses a portable pure Rust implementation that works everywhere, even WASM! ", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "b97154e67e32c85465826e8bcc1c59429aaaf107c1e4a9e53c8d8ccd5eff88d0" + } + ], + "licenses": [ + { + "expression": "Apache-2.0 OR MIT" + } + ], + "purl": "pkg:cargo/zeroize@1.8.2", + "externalReferences": [ + { + "type": "website", + "url": "https://github.com/RustCrypto/utils/tree/master/zeroize" + }, + { + "type": "vcs", + "url": "https://github.com/RustCrypto/utils" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#zerotrie@0.2.3", + "author": "The ICU4X Project Developers", + "name": "zerotrie", + "version": "0.2.3", + "description": "A data structure that efficiently maps strings to integers", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "2a59c17a5562d507e4b54960e8569ebee33bee890c70aa3fe7b97e85a9fd7851" + } + ], + "licenses": [ + { + "expression": "Unicode-3.0" + } + ], + "purl": "pkg:cargo/zerotrie@0.2.3", + "externalReferences": [ + { + "type": "website", + "url": "https://icu4x.unicode.org" + }, + { + "type": "vcs", + "url": "https://github.com/unicode-org/icu4x" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#zerovec-derive@0.11.2", + "author": "Manish Goregaokar ", + "name": "zerovec-derive", + "version": "0.11.2", + "description": "Custom derive for the zerovec crate", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "eadce39539ca5cb3985590102671f2567e659fca9666581ad3411d59207951f3" + } + ], + "licenses": [ + { + "expression": "Unicode-3.0" + } + ], + "purl": "pkg:cargo/zerovec-derive@0.11.2", + "externalReferences": [ + { + "type": "vcs", + "url": "https://github.com/unicode-org/icu4x" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#zerovec@0.11.5", + "author": "The ICU4X Project Developers", + "name": "zerovec", + "version": "0.11.5", + "description": "Zero-copy vector backed by a byte array", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "6c28719294829477f525be0186d13efa9a3c602f7ec202ca9e353d310fb9a002" + } + ], + "licenses": [ + { + "expression": "Unicode-3.0" + } + ], + "purl": "pkg:cargo/zerovec@0.11.5", + "externalReferences": [ + { + "type": "vcs", + "url": "https://github.com/unicode-org/icu4x" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#zip-extract@0.2.3", + "author": "M*C*O ", + "name": "zip-extract", + "version": "0.2.3", + "description": "Archive extraction via zip-rs, automated.", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "db6d94e397dd6d0273e6747e46e7aa0289bfd9736ba8772f2fe948bc4adc3f73" + } + ], + "licenses": [ + { + "expression": "MIT" + } + ], + "purl": "pkg:cargo/zip-extract@0.2.3", + "externalReferences": [ + { + "type": "vcs", + "url": "https://github.com/MCOfficer/zip-extract" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#zip@3.0.0", + "author": "Mathijs van de Nes , Marli Frost , Ryan Levick , Chris Hennick ", + "name": "zip", + "version": "3.0.0", + "description": "Library to support the reading and writing of zip files. ", + "scope": "excluded", + "hashes": [ + { + "alg": "SHA-256", + "content": "12598812502ed0105f607f941c386f43d441e00148fce9dec3ca5ffb0bde9308" + } + ], + "licenses": [ + { + "expression": "MIT" + } + ], + "purl": "pkg:cargo/zip@3.0.0", + "externalReferences": [ + { + "type": "vcs", + "url": "https://github.com/zip-rs/zip2.git" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#zip@8.3.0", + "author": "Mathijs van de Nes , Marli Frost , Ryan Levick , Chris Hennick ", + "name": "zip", + "version": "8.3.0", + "description": "Library to support the reading and writing of zip files. ", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "4a243cfad17427fc077f529da5a95abe4e94fd2bfdb601611870a6557cc67657" + } + ], + "licenses": [ + { + "expression": "MIT" + } + ], + "purl": "pkg:cargo/zip@8.3.0", + "externalReferences": [ + { + "type": "vcs", + "url": "https://github.com/zip-rs/zip2.git" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#zlib-rs@0.6.3", + "name": "zlib-rs", + "version": "0.6.3", + "description": "A memory-safe zlib implementation written in rust", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "3be3d40e40a133f9c916ee3f9f4fa2d9d63435b5fbe1bfc6d9dae0aa0ada1513" + } + ], + "licenses": [ + { + "expression": "Zlib" + } + ], + "purl": "pkg:cargo/zlib-rs@0.6.3", + "externalReferences": [ + { + "type": "website", + "url": "https://github.com/trifectatechfoundation/zlib-rs" + }, + { + "type": "vcs", + "url": "https://github.com/trifectatechfoundation/zlib-rs" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#zmij@1.0.21", + "author": "David Tolnay ", + "name": "zmij", + "version": "1.0.21", + "description": "A double-to-string conversion algorithm based on Schubfach and yy", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "b8848ee67ecc8aedbaf3e4122217aff892639231befc6a1b58d29fff4c2cabaa" + } + ], + "licenses": [ + { + "expression": "MIT" + } + ], + "purl": "pkg:cargo/zmij@1.0.21", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/zmij" + }, + { + "type": "vcs", + "url": "https://github.com/dtolnay/zmij" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#zopfli@0.8.3", + "name": "zopfli", + "version": "0.8.3", + "description": "A Rust implementation of the Zopfli compression algorithm.", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "f05cd8797d63865425ff89b5c4a48804f35ba0ce8d125800027ad6017d2b5249" + } + ], + "licenses": [ + { + "expression": "Apache-2.0" + } + ], + "purl": "pkg:cargo/zopfli@0.8.3", + "externalReferences": [ + { + "type": "website", + "url": "https://github.com/zopfli-rs/zopfli" + }, + { + "type": "vcs", + "url": "https://github.com/zopfli-rs/zopfli" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#zstd-safe@7.2.4", + "author": "Alexandre Bury ", + "name": "zstd-safe", + "version": "7.2.4", + "description": "Safe low-level bindings for the zstd compression library.", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "8f49c4d5f0abb602a93fb8736af2a4f4dd9512e36f7f570d66e65ff867ed3b9d" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/zstd-safe@7.2.4", + "externalReferences": [ + { + "type": "vcs", + "url": "https://github.com/gyscos/zstd-rs" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#zstd-sys@2.0.16+zstd.1.5.7", + "author": "Alexandre Bury ", + "name": "zstd-sys", + "version": "2.0.16+zstd.1.5.7", + "description": "Low-level bindings for the zstd compression library.", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "91e19ebc2adc8f83e43039e79776e3fda8ca919132d68a1fed6a5faca2683748" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/zstd-sys@2.0.16+zstd.1.5.7", + "externalReferences": [ + { + "type": "other", + "url": "zstd" + }, + { + "type": "vcs", + "url": "https://github.com/gyscos/zstd-rs" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#zstd@0.13.3", + "author": "Alexandre Bury ", + "name": "zstd", + "version": "0.13.3", + "description": "Binding for the zstd compression library.", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "e91ee311a569c327171651566e07972200e76fcfe2242a4fa446149a3881c08a" + } + ], + "licenses": [ + { + "expression": "MIT" + } + ], + "purl": "pkg:cargo/zstd@0.13.3", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/zstd" + }, + { + "type": "vcs", + "url": "https://github.com/gyscos/zstd-rs" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#zune-core@0.5.1", + "name": "zune-core", + "version": "0.5.1", + "description": "Core utilities for image processing in the zune family of crates", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "cb8a0807f7c01457d0379ba880ba6322660448ddebc890ce29bb64da71fb40f9" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0 OR Zlib" + } + ], + "purl": "pkg:cargo/zune-core@0.5.1", + "externalReferences": [ + { + "type": "vcs", + "url": "https://github.com/etemesi254/zune-image" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#zune-jpeg@0.5.13", + "author": "caleb ", + "name": "zune-jpeg", + "version": "0.5.13", + "description": "A fast, correct and safe jpeg decoder", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "ec5f41c76397b7da451efd19915684f727d7e1d516384ca6bd0ec43ec94de23c" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0 OR Zlib" + } + ], + "purl": "pkg:cargo/zune-jpeg@0.5.13", + "externalReferences": [ + { + "type": "vcs", + "url": "https://github.com/etemesi254/zune-image/tree/dev/crates/zune-jpeg" + } + ] + } + ], + "dependencies": [ + { + "ref": "git+https://github.com/chroma-core/hnswlib.git?branch=master#hnswlib@0.8.2", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#cc@1.2.57", + "registry+https://github.com/rust-lang/crates.io-index#thiserror@1.0.69" + ] + }, + { + "ref": "path+file:///C:/a/chroma/chroma/rust/api-types#chroma-api-types@0.14.0", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#serde@1.0.228", + "registry+https://github.com/rust-lang/crates.io-index#utoipa@5.4.0" + ] + }, + { + "ref": "path+file:///C:/a/chroma/chroma/rust/blockstore#chroma-blockstore@0.1.0", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#arrow@55.2.0", + "registry+https://github.com/rust-lang/crates.io-index#async-trait@0.1.89", + "registry+https://github.com/rust-lang/crates.io-index#bincode@1.3.3", + "registry+https://github.com/rust-lang/crates.io-index#bytes@1.11.1", + "path+file:///C:/a/chroma/chroma/rust/cache#chroma-cache@0.1.0", + "path+file:///C:/a/chroma/chroma/rust/config#chroma-config@0.1.0", + "path+file:///C:/a/chroma/chroma/rust/error#chroma-error@0.14.0", + "path+file:///C:/a/chroma/chroma/rust/storage#chroma-storage@0.1.0", + "path+file:///C:/a/chroma/chroma/rust/tracing#chroma-tracing@0.1.0", + "path+file:///C:/a/chroma/chroma/rust/types#chroma-types@0.14.0", + "registry+https://github.com/rust-lang/crates.io-index#flatbuffers@25.12.19", + "registry+https://github.com/rust-lang/crates.io-index#futures@0.3.32", + "registry+https://github.com/rust-lang/crates.io-index#itertools@0.13.0", + "registry+https://github.com/rust-lang/crates.io-index#num_cpus@1.17.0", + "registry+https://github.com/rust-lang/crates.io-index#opentelemetry@0.27.1", + "registry+https://github.com/rust-lang/crates.io-index#parking_lot@0.12.5", + "registry+https://github.com/rust-lang/crates.io-index#prost@0.14.3", + "registry+https://github.com/rust-lang/crates.io-index#roaring@0.10.12", + "registry+https://github.com/rust-lang/crates.io-index#serde@1.0.228", + "registry+https://github.com/rust-lang/crates.io-index#serde_bytes@0.11.19", + "registry+https://github.com/rust-lang/crates.io-index#shuttle@0.7.1", + "registry+https://github.com/rust-lang/crates.io-index#tempfile@3.27.0", + "registry+https://github.com/rust-lang/crates.io-index#thiserror@1.0.69", + "registry+https://github.com/rust-lang/crates.io-index#tokio@1.50.0", + "registry+https://github.com/rust-lang/crates.io-index#tracing@0.1.44", + "registry+https://github.com/rust-lang/crates.io-index#uuid@1.22.0" + ] + }, + { + "ref": "path+file:///C:/a/chroma/chroma/rust/cache#chroma-cache@0.1.0", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#ahash@0.8.12", + "registry+https://github.com/rust-lang/crates.io-index#anyhow@1.0.102", + "registry+https://github.com/rust-lang/crates.io-index#async-trait@0.1.89", + "path+file:///C:/a/chroma/chroma/rust/error#chroma-error@0.14.0", + "path+file:///C:/a/chroma/chroma/rust/tracing#chroma-tracing@0.1.0", + "registry+https://github.com/rust-lang/crates.io-index#clap@4.6.0", + "registry+https://github.com/rust-lang/crates.io-index#foyer@0.17.4", + "registry+https://github.com/rust-lang/crates.io-index#mixtrics@0.1.0", + "registry+https://github.com/rust-lang/crates.io-index#opentelemetry@0.27.1", + "registry+https://github.com/rust-lang/crates.io-index#parking_lot@0.12.5", + "registry+https://github.com/rust-lang/crates.io-index#serde@1.0.228", + "registry+https://github.com/rust-lang/crates.io-index#serde_yaml@0.9.34+deprecated", + "registry+https://github.com/rust-lang/crates.io-index#thiserror@1.0.69", + "registry+https://github.com/rust-lang/crates.io-index#tokio@1.50.0" + ] + }, + { + "ref": "path+file:///C:/a/chroma/chroma/rust/chroma#0.14.0", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#async-trait@0.1.89", + "registry+https://github.com/rust-lang/crates.io-index#backon@1.6.0", + "registry+https://github.com/rust-lang/crates.io-index#bon@3.9.1", + "path+file:///C:/a/chroma/chroma/rust/api-types#chroma-api-types@0.14.0", + "path+file:///C:/a/chroma/chroma/rust/error#chroma-error@0.14.0", + "path+file:///C:/a/chroma/chroma/rust/types#chroma-types@0.14.0", + "registry+https://github.com/rust-lang/crates.io-index#failsafe@1.3.0", + "registry+https://github.com/rust-lang/crates.io-index#murmur3@0.5.2", + "registry+https://github.com/rust-lang/crates.io-index#parking_lot@0.12.5", + "registry+https://github.com/rust-lang/crates.io-index#reqwest@0.13.2", + "registry+https://github.com/rust-lang/crates.io-index#rust-stemmers@1.2.0", + "registry+https://github.com/rust-lang/crates.io-index#serde@1.0.228", + "registry+https://github.com/rust-lang/crates.io-index#serde_json@1.0.149", + "registry+https://github.com/rust-lang/crates.io-index#thiserror@1.0.69", + "registry+https://github.com/rust-lang/crates.io-index#tokio@1.50.0", + "registry+https://github.com/rust-lang/crates.io-index#tracing@0.1.44" + ] + }, + { + "ref": "path+file:///C:/a/chroma/chroma/rust/cli#chroma-cli@1.4.4", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#arboard@3.6.1", + "registry+https://github.com/rust-lang/crates.io-index#bytes@1.11.1", + "path+file:///C:/a/chroma/chroma/rust/chroma#0.14.0", + "path+file:///C:/a/chroma/chroma/rust/config#chroma-config@0.1.0", + "path+file:///C:/a/chroma/chroma/rust/frontend#chroma-frontend@1.0.0", + "path+file:///C:/a/chroma/chroma/rust/log#chroma-log@0.1.0", + "path+file:///C:/a/chroma/chroma/rust/segment#chroma-segment@0.1.0", + "path+file:///C:/a/chroma/chroma/rust/sqlite#chroma-sqlite@0.1.0", + "path+file:///C:/a/chroma/chroma/rust/sysdb#chroma-sysdb@0.1.0", + "path+file:///C:/a/chroma/chroma/rust/system#chroma-system@0.1.0", + "path+file:///C:/a/chroma/chroma/rust/types#chroma-types@0.14.0", + "registry+https://github.com/rust-lang/crates.io-index#chrono@0.4.44", + "registry+https://github.com/rust-lang/crates.io-index#clap@4.6.0", + "registry+https://github.com/rust-lang/crates.io-index#colored@3.1.1", + "registry+https://github.com/rust-lang/crates.io-index#crossterm@0.29.0", + "registry+https://github.com/rust-lang/crates.io-index#dialoguer@0.11.0", + "registry+https://github.com/rust-lang/crates.io-index#dirs@6.0.0", + "registry+https://github.com/rust-lang/crates.io-index#futures@0.3.32", + "registry+https://github.com/rust-lang/crates.io-index#futures-util@0.3.32", + "registry+https://github.com/rust-lang/crates.io-index#indicatif@0.17.11", + "registry+https://github.com/rust-lang/crates.io-index#rand@0.8.5", + "registry+https://github.com/rust-lang/crates.io-index#ratatui@0.29.0", + "registry+https://github.com/rust-lang/crates.io-index#regex@1.12.3", + "registry+https://github.com/rust-lang/crates.io-index#reqwest@0.13.2", + "registry+https://github.com/rust-lang/crates.io-index#semver@1.0.27", + "registry+https://github.com/rust-lang/crates.io-index#serde@1.0.228", + "registry+https://github.com/rust-lang/crates.io-index#serde_json@1.0.149", + "registry+https://github.com/rust-lang/crates.io-index#sqlx@0.8.6", + "registry+https://github.com/rust-lang/crates.io-index#strum@0.27.2", + "registry+https://github.com/rust-lang/crates.io-index#strum_macros@0.27.2", + "registry+https://github.com/rust-lang/crates.io-index#supports-color@3.0.2", + "registry+https://github.com/rust-lang/crates.io-index#textwrap@0.16.2", + "registry+https://github.com/rust-lang/crates.io-index#thiserror@1.0.69", + "registry+https://github.com/rust-lang/crates.io-index#tokio@1.50.0", + "registry+https://github.com/rust-lang/crates.io-index#toml@0.8.23", + "registry+https://github.com/rust-lang/crates.io-index#tui-input@0.12.1", + "registry+https://github.com/rust-lang/crates.io-index#webbrowser@1.2.0", + "registry+https://github.com/rust-lang/crates.io-index#zip-extract@0.2.3" + ] + }, + { + "ref": "path+file:///C:/a/chroma/chroma/rust/config#chroma-config@0.1.0", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#async-trait@0.1.89", + "path+file:///C:/a/chroma/chroma/rust/error#chroma-error@0.14.0", + "registry+https://github.com/rust-lang/crates.io-index#figment@0.10.19", + "registry+https://github.com/rust-lang/crates.io-index#murmur3@0.5.2", + "registry+https://github.com/rust-lang/crates.io-index#parking_lot@0.12.5", + "registry+https://github.com/rust-lang/crates.io-index#serde@1.0.228", + "registry+https://github.com/rust-lang/crates.io-index#thiserror@1.0.69" + ] + }, + { + "ref": "path+file:///C:/a/chroma/chroma/rust/distance#chroma-distance@0.1.0", + "dependsOn": [ + "path+file:///C:/a/chroma/chroma/rust/error#chroma-error@0.14.0", + "path+file:///C:/a/chroma/chroma/rust/types#chroma-types@0.14.0", + "registry+https://github.com/rust-lang/crates.io-index#thiserror@1.0.69" + ] + }, + { + "ref": "path+file:///C:/a/chroma/chroma/rust/error#chroma-error@0.14.0", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#http@1.4.0", + "registry+https://github.com/rust-lang/crates.io-index#sqlx@0.8.6", + "registry+https://github.com/rust-lang/crates.io-index#thiserror@1.0.69", + "registry+https://github.com/rust-lang/crates.io-index#tonic@0.14.5", + "registry+https://github.com/rust-lang/crates.io-index#validator@0.19.0" + ] + }, + { + "ref": "path+file:///C:/a/chroma/chroma/rust/frontend#chroma-frontend@1.0.0", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#async-trait@0.1.89", + "registry+https://github.com/rust-lang/crates.io-index#axum@0.8.8", + "registry+https://github.com/rust-lang/crates.io-index#backon@1.6.0", + "path+file:///C:/a/chroma/chroma/rust/chroma#0.14.0", + "path+file:///C:/a/chroma/chroma/rust/api-types#chroma-api-types@0.14.0", + "path+file:///C:/a/chroma/chroma/rust/cache#chroma-cache@0.1.0", + "path+file:///C:/a/chroma/chroma/rust/config#chroma-config@0.1.0", + "path+file:///C:/a/chroma/chroma/rust/distance#chroma-distance@0.1.0", + "path+file:///C:/a/chroma/chroma/rust/error#chroma-error@0.14.0", + "path+file:///C:/a/chroma/chroma/rust/log#chroma-log@0.1.0", + "path+file:///C:/a/chroma/chroma/rust/memberlist#chroma-memberlist@0.1.0", + "path+file:///C:/a/chroma/chroma/rust/metering#chroma-metering@0.1.0", + "path+file:///C:/a/chroma/chroma/rust/segment#chroma-segment@0.1.0", + "path+file:///C:/a/chroma/chroma/rust/sqlite#chroma-sqlite@0.1.0", + "path+file:///C:/a/chroma/chroma/rust/sysdb#chroma-sysdb@0.1.0", + "path+file:///C:/a/chroma/chroma/rust/system#chroma-system@0.1.0", + "path+file:///C:/a/chroma/chroma/rust/tracing#chroma-tracing@0.1.0", + "path+file:///C:/a/chroma/chroma/rust/types#chroma-types@0.14.0", + "registry+https://github.com/rust-lang/crates.io-index#figment@0.10.19", + "registry+https://github.com/rust-lang/crates.io-index#futures@0.3.32", + "registry+https://github.com/rust-lang/crates.io-index#http-body-util@0.1.3", + "registry+https://github.com/rust-lang/crates.io-index#lazy_static@1.5.0", + "path+file:///C:/a/chroma/chroma/rust/mdac#0.1.0", + "registry+https://github.com/rust-lang/crates.io-index#opentelemetry@0.27.1", + "registry+https://github.com/rust-lang/crates.io-index#parking_lot@0.12.5", + "registry+https://github.com/rust-lang/crates.io-index#rand@0.8.5", + "registry+https://github.com/rust-lang/crates.io-index#rust-embed@8.11.0", + "registry+https://github.com/rust-lang/crates.io-index#serde@1.0.228", + "registry+https://github.com/rust-lang/crates.io-index#serde_json@1.0.149", + "registry+https://github.com/rust-lang/crates.io-index#strum@0.27.2", + "registry+https://github.com/rust-lang/crates.io-index#strum_macros@0.27.2", + "registry+https://github.com/rust-lang/crates.io-index#thiserror@1.0.69", + "registry+https://github.com/rust-lang/crates.io-index#tokio@1.50.0", + "registry+https://github.com/rust-lang/crates.io-index#tonic@0.14.5", + "registry+https://github.com/rust-lang/crates.io-index#tower@0.5.3", + "registry+https://github.com/rust-lang/crates.io-index#tower-http@0.6.8", + "registry+https://github.com/rust-lang/crates.io-index#tracing@0.1.44", + "registry+https://github.com/rust-lang/crates.io-index#tracing-opentelemetry@0.28.0", + "registry+https://github.com/rust-lang/crates.io-index#utoipa@5.4.0", + "registry+https://github.com/rust-lang/crates.io-index#utoipa-axum@0.2.0", + "registry+https://github.com/rust-lang/crates.io-index#utoipa-swagger-ui@9.0.2", + "registry+https://github.com/rust-lang/crates.io-index#uuid@1.22.0", + "registry+https://github.com/rust-lang/crates.io-index#validator@0.19.0" + ] + }, + { + "ref": "path+file:///C:/a/chroma/chroma/rust/index#chroma-index@0.1.0", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#arrow@55.2.0", + "registry+https://github.com/rust-lang/crates.io-index#async-trait@0.1.89", + "registry+https://github.com/rust-lang/crates.io-index#base64@0.22.1", + "registry+https://github.com/rust-lang/crates.io-index#bitpacking@0.9.3", + "registry+https://github.com/rust-lang/crates.io-index#bytemuck@1.25.0", + "path+file:///C:/a/chroma/chroma/rust/blockstore#chroma-blockstore@0.1.0", + "path+file:///C:/a/chroma/chroma/rust/cache#chroma-cache@0.1.0", + "path+file:///C:/a/chroma/chroma/rust/config#chroma-config@0.1.0", + "path+file:///C:/a/chroma/chroma/rust/distance#chroma-distance@0.1.0", + "path+file:///C:/a/chroma/chroma/rust/error#chroma-error@0.14.0", + "path+file:///C:/a/chroma/chroma/rust/storage#chroma-storage@0.1.0", + "path+file:///C:/a/chroma/chroma/rust/tracing#chroma-tracing@0.1.0", + "path+file:///C:/a/chroma/chroma/rust/types#chroma-types@0.14.0", + "registry+https://github.com/rust-lang/crates.io-index#dashmap@6.1.0", + "registry+https://github.com/rust-lang/crates.io-index#faer@0.24.0", + "registry+https://github.com/rust-lang/crates.io-index#futures@0.3.32", + "registry+https://github.com/rust-lang/crates.io-index#half@2.7.1", + "git+https://github.com/chroma-core/hnswlib.git?branch=master#hnswlib@0.8.2", + "registry+https://github.com/rust-lang/crates.io-index#itertools@0.13.0", + "registry+https://github.com/rust-lang/crates.io-index#opentelemetry@0.27.1", + "registry+https://github.com/rust-lang/crates.io-index#parking_lot@0.12.5", + "registry+https://github.com/rust-lang/crates.io-index#parquet@55.2.0", + "registry+https://github.com/rust-lang/crates.io-index#rand@0.8.5", + "registry+https://github.com/rust-lang/crates.io-index#roaring@0.10.12", + "registry+https://github.com/rust-lang/crates.io-index#serde@1.0.228", + "registry+https://github.com/rust-lang/crates.io-index#simsimd@6.5.16", + "registry+https://github.com/rust-lang/crates.io-index#tantivy@0.22.1", + "registry+https://github.com/rust-lang/crates.io-index#tempfile@3.27.0", + "registry+https://github.com/rust-lang/crates.io-index#thiserror@1.0.69", + "registry+https://github.com/rust-lang/crates.io-index#tokio@1.50.0", + "registry+https://github.com/rust-lang/crates.io-index#tracing@0.1.44", + "registry+https://github.com/rust-lang/crates.io-index#usearch@2.23.0", + "registry+https://github.com/rust-lang/crates.io-index#uuid@1.22.0" + ] + }, + { + "ref": "path+file:///C:/a/chroma/chroma/rust/log#chroma-log@0.1.0", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#async-trait@0.1.89", + "registry+https://github.com/rust-lang/crates.io-index#bytemuck@1.25.0", + "path+file:///C:/a/chroma/chroma/rust/config#chroma-config@0.1.0", + "path+file:///C:/a/chroma/chroma/rust/error#chroma-error@0.14.0", + "path+file:///C:/a/chroma/chroma/rust/memberlist#chroma-memberlist@0.1.0", + "path+file:///C:/a/chroma/chroma/rust/segment#chroma-segment@0.1.0", + "path+file:///C:/a/chroma/chroma/rust/sqlite#chroma-sqlite@0.1.0", + "path+file:///C:/a/chroma/chroma/rust/sysdb#chroma-sysdb@0.1.0", + "path+file:///C:/a/chroma/chroma/rust/system#chroma-system@0.1.0", + "path+file:///C:/a/chroma/chroma/rust/tracing#chroma-tracing@0.1.0", + "path+file:///C:/a/chroma/chroma/rust/types#chroma-types@0.14.0", + "registry+https://github.com/rust-lang/crates.io-index#futures@0.3.32", + "registry+https://github.com/rust-lang/crates.io-index#hyper@1.8.1", + "registry+https://github.com/rust-lang/crates.io-index#opentelemetry@0.27.1", + "registry+https://github.com/rust-lang/crates.io-index#rand@0.8.5", + "registry+https://github.com/rust-lang/crates.io-index#serde@1.0.228", + "registry+https://github.com/rust-lang/crates.io-index#serde_json@1.0.149", + "registry+https://github.com/rust-lang/crates.io-index#sqlx@0.8.6", + "registry+https://github.com/rust-lang/crates.io-index#thiserror@1.0.69", + "registry+https://github.com/rust-lang/crates.io-index#tokio@1.50.0", + "registry+https://github.com/rust-lang/crates.io-index#tonic@0.14.5", + "registry+https://github.com/rust-lang/crates.io-index#tower@0.5.3", + "registry+https://github.com/rust-lang/crates.io-index#tracing@0.1.44", + "registry+https://github.com/rust-lang/crates.io-index#uuid@1.22.0" + ] + }, + { + "ref": "path+file:///C:/a/chroma/chroma/rust/mdac#0.1.0", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#serde@1.0.228", + "registry+https://github.com/rust-lang/crates.io-index#siphasher@1.0.2" + ] + }, + { + "ref": "path+file:///C:/a/chroma/chroma/rust/memberlist#chroma-memberlist@0.1.0", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#async-trait@0.1.89", + "path+file:///C:/a/chroma/chroma/rust/config#chroma-config@0.1.0", + "path+file:///C:/a/chroma/chroma/rust/error#chroma-error@0.14.0", + "path+file:///C:/a/chroma/chroma/rust/system#chroma-system@0.1.0", + "path+file:///C:/a/chroma/chroma/rust/tracing#chroma-tracing@0.1.0", + "path+file:///C:/a/chroma/chroma/rust/types#chroma-types@0.14.0", + "registry+https://github.com/rust-lang/crates.io-index#futures@0.3.32", + "registry+https://github.com/rust-lang/crates.io-index#k8s-openapi@0.20.0", + "registry+https://github.com/rust-lang/crates.io-index#kube@0.87.2", + "registry+https://github.com/rust-lang/crates.io-index#opentelemetry@0.27.1", + "registry+https://github.com/rust-lang/crates.io-index#parking_lot@0.12.5", + "registry+https://github.com/rust-lang/crates.io-index#schemars@0.8.22", + "registry+https://github.com/rust-lang/crates.io-index#serde@1.0.228", + "registry+https://github.com/rust-lang/crates.io-index#serde_json@1.0.149", + "registry+https://github.com/rust-lang/crates.io-index#thiserror@1.0.69", + "registry+https://github.com/rust-lang/crates.io-index#tokio@1.50.0", + "registry+https://github.com/rust-lang/crates.io-index#tonic@0.14.5", + "registry+https://github.com/rust-lang/crates.io-index#tower@0.5.3", + "registry+https://github.com/rust-lang/crates.io-index#tracing@0.1.44" + ] + }, + { + "ref": "path+file:///C:/a/chroma/chroma/rust/metering#chroma-metering@0.1.0", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#async-trait@0.1.89", + "path+file:///C:/a/chroma/chroma/rust/metering-macros#chroma-metering-macros@0.1.0", + "path+file:///C:/a/chroma/chroma/rust/system#chroma-system@0.1.0", + "registry+https://github.com/rust-lang/crates.io-index#pin-project@1.1.11", + "registry+https://github.com/rust-lang/crates.io-index#serde@1.0.228", + "registry+https://github.com/rust-lang/crates.io-index#thiserror@1.0.69", + "registry+https://github.com/rust-lang/crates.io-index#tracing@0.1.44" + ] + }, + { + "ref": "path+file:///C:/a/chroma/chroma/rust/metering-macros#chroma-metering-macros@0.1.0", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#async-trait@0.1.89", + "path+file:///C:/a/chroma/chroma/rust/system#chroma-system@0.1.0", + "registry+https://github.com/rust-lang/crates.io-index#pin-project@1.1.11", + "registry+https://github.com/rust-lang/crates.io-index#proc-macro2@1.0.106", + "registry+https://github.com/rust-lang/crates.io-index#quote@1.0.45", + "registry+https://github.com/rust-lang/crates.io-index#syn@2.0.117", + "registry+https://github.com/rust-lang/crates.io-index#thiserror@1.0.69", + "registry+https://github.com/rust-lang/crates.io-index#tracing@0.1.44" + ] + }, + { + "ref": "path+file:///C:/a/chroma/chroma/rust/python_bindings#chromadb_rust_bindings@0.1.0", + "dependsOn": [ + "path+file:///C:/a/chroma/chroma/rust/cache#chroma-cache@0.1.0", + "path+file:///C:/a/chroma/chroma/rust/cli#chroma-cli@1.4.4", + "path+file:///C:/a/chroma/chroma/rust/config#chroma-config@0.1.0", + "path+file:///C:/a/chroma/chroma/rust/error#chroma-error@0.14.0", + "path+file:///C:/a/chroma/chroma/rust/frontend#chroma-frontend@1.0.0", + "path+file:///C:/a/chroma/chroma/rust/log#chroma-log@0.1.0", + "path+file:///C:/a/chroma/chroma/rust/segment#chroma-segment@0.1.0", + "path+file:///C:/a/chroma/chroma/rust/sqlite#chroma-sqlite@0.1.0", + "path+file:///C:/a/chroma/chroma/rust/sysdb#chroma-sysdb@0.1.0", + "path+file:///C:/a/chroma/chroma/rust/system#chroma-system@0.1.0", + "path+file:///C:/a/chroma/chroma/rust/types#chroma-types@0.14.0", + "registry+https://github.com/rust-lang/crates.io-index#pyo3@0.24.2", + "registry+https://github.com/rust-lang/crates.io-index#serde_json@1.0.149", + "registry+https://github.com/rust-lang/crates.io-index#thiserror@1.0.69", + "registry+https://github.com/rust-lang/crates.io-index#tokio@1.50.0", + "registry+https://github.com/rust-lang/crates.io-index#uuid@1.22.0" + ] + }, + { + "ref": "path+file:///C:/a/chroma/chroma/rust/segment#chroma-segment@0.1.0", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#async-trait@0.1.89", + "registry+https://github.com/rust-lang/crates.io-index#bincode@1.3.3", + "registry+https://github.com/rust-lang/crates.io-index#bytes@1.11.1", + "path+file:///C:/a/chroma/chroma/rust/blockstore#chroma-blockstore@0.1.0", + "path+file:///C:/a/chroma/chroma/rust/cache#chroma-cache@0.1.0", + "path+file:///C:/a/chroma/chroma/rust/config#chroma-config@0.1.0", + "path+file:///C:/a/chroma/chroma/rust/distance#chroma-distance@0.1.0", + "path+file:///C:/a/chroma/chroma/rust/error#chroma-error@0.14.0", + "path+file:///C:/a/chroma/chroma/rust/index#chroma-index@0.1.0", + "path+file:///C:/a/chroma/chroma/rust/sqlite#chroma-sqlite@0.1.0", + "path+file:///C:/a/chroma/chroma/rust/storage#chroma-storage@0.1.0", + "path+file:///C:/a/chroma/chroma/rust/types#chroma-types@0.14.0", + "registry+https://github.com/rust-lang/crates.io-index#chrono@0.4.44", + "registry+https://github.com/rust-lang/crates.io-index#faer@0.24.0", + "registry+https://github.com/rust-lang/crates.io-index#fastbloom@0.17.0", + "registry+https://github.com/rust-lang/crates.io-index#futures@0.3.32", + "registry+https://github.com/rust-lang/crates.io-index#opentelemetry@0.27.1", + "registry+https://github.com/rust-lang/crates.io-index#prost@0.14.3", + "registry+https://github.com/rust-lang/crates.io-index#rayon@1.11.0", + "registry+https://github.com/rust-lang/crates.io-index#regex@1.12.3", + "registry+https://github.com/rust-lang/crates.io-index#roaring@0.10.12", + "registry+https://github.com/rust-lang/crates.io-index#sea-query@0.32.7", + "registry+https://github.com/rust-lang/crates.io-index#sea-query-binder@0.7.0", + "registry+https://github.com/rust-lang/crates.io-index#serde@1.0.228", + "registry+https://github.com/rust-lang/crates.io-index#serde-pickle@1.2.0", + "registry+https://github.com/rust-lang/crates.io-index#serde_json@1.0.149", + "registry+https://github.com/rust-lang/crates.io-index#sqlx@0.8.6", + "registry+https://github.com/rust-lang/crates.io-index#tantivy@0.22.1", + "registry+https://github.com/rust-lang/crates.io-index#tempfile@3.27.0", + "registry+https://github.com/rust-lang/crates.io-index#thiserror@1.0.69", + "registry+https://github.com/rust-lang/crates.io-index#tokio@1.50.0", + "registry+https://github.com/rust-lang/crates.io-index#tracing@0.1.44", + "registry+https://github.com/rust-lang/crates.io-index#uuid@1.22.0" + ] + }, + { + "ref": "path+file:///C:/a/chroma/chroma/rust/sqlite#chroma-sqlite@0.1.0", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#async-trait@0.1.89", + "path+file:///C:/a/chroma/chroma/rust/config#chroma-config@0.1.0", + "path+file:///C:/a/chroma/chroma/rust/error#chroma-error@0.14.0", + "path+file:///C:/a/chroma/chroma/rust/types#chroma-types@0.14.0", + "registry+https://github.com/rust-lang/crates.io-index#md5@0.7.0", + "registry+https://github.com/rust-lang/crates.io-index#pyo3@0.24.2", + "registry+https://github.com/rust-lang/crates.io-index#regex@1.12.3", + "registry+https://github.com/rust-lang/crates.io-index#rust-embed@8.11.0", + "registry+https://github.com/rust-lang/crates.io-index#sea-query@0.32.7", + "registry+https://github.com/rust-lang/crates.io-index#sea-query-binder@0.7.0", + "registry+https://github.com/rust-lang/crates.io-index#serde@1.0.228", + "registry+https://github.com/rust-lang/crates.io-index#sha2@0.10.9", + "registry+https://github.com/rust-lang/crates.io-index#sqlx@0.8.6", + "registry+https://github.com/rust-lang/crates.io-index#tempfile@3.27.0", + "registry+https://github.com/rust-lang/crates.io-index#thiserror@1.0.69", + "registry+https://github.com/rust-lang/crates.io-index#tokio@1.50.0" + ] + }, + { + "ref": "path+file:///C:/a/chroma/chroma/rust/storage#chroma-storage@0.1.0", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#async-trait@0.1.89", + "registry+https://github.com/rust-lang/crates.io-index#aws-config@1.8.15", + "registry+https://github.com/rust-lang/crates.io-index#aws-sdk-s3@1.119.0", + "registry+https://github.com/rust-lang/crates.io-index#aws-smithy-types@1.4.7", + "registry+https://github.com/rust-lang/crates.io-index#bytes@1.11.1", + "path+file:///C:/a/chroma/chroma/rust/config#chroma-config@0.1.0", + "path+file:///C:/a/chroma/chroma/rust/error#chroma-error@0.14.0", + "path+file:///C:/a/chroma/chroma/rust/tracing#chroma-tracing@0.1.0", + "path+file:///C:/a/chroma/chroma/rust/types#chroma-types@0.14.0", + "registry+https://github.com/rust-lang/crates.io-index#futures@0.3.32", + "registry+https://github.com/rust-lang/crates.io-index#object_store@0.12.5", + "registry+https://github.com/rust-lang/crates.io-index#opentelemetry@0.27.1", + "registry+https://github.com/rust-lang/crates.io-index#rand@0.8.5", + "registry+https://github.com/rust-lang/crates.io-index#serde@1.0.228", + "registry+https://github.com/rust-lang/crates.io-index#serde_json@1.0.149", + "registry+https://github.com/rust-lang/crates.io-index#tempfile@3.27.0", + "registry+https://github.com/rust-lang/crates.io-index#thiserror@1.0.69", + "registry+https://github.com/rust-lang/crates.io-index#tokio@1.50.0", + "registry+https://github.com/rust-lang/crates.io-index#tracing@0.1.44" + ] + }, + { + "ref": "path+file:///C:/a/chroma/chroma/rust/sysdb#chroma-sysdb@0.1.0", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#async-trait@0.1.89", + "path+file:///C:/a/chroma/chroma/rust/config#chroma-config@0.1.0", + "path+file:///C:/a/chroma/chroma/rust/error#chroma-error@0.14.0", + "path+file:///C:/a/chroma/chroma/rust/sqlite#chroma-sqlite@0.1.0", + "path+file:///C:/a/chroma/chroma/rust/storage#chroma-storage@0.1.0", + "path+file:///C:/a/chroma/chroma/rust/tracing#chroma-tracing@0.1.0", + "path+file:///C:/a/chroma/chroma/rust/types#chroma-types@0.14.0", + "registry+https://github.com/rust-lang/crates.io-index#chrono@0.4.44", + "registry+https://github.com/rust-lang/crates.io-index#clap@4.6.0", + "registry+https://github.com/rust-lang/crates.io-index#derivative@2.2.0", + "registry+https://github.com/rust-lang/crates.io-index#futures@0.3.32", + "registry+https://github.com/rust-lang/crates.io-index#parking_lot@0.12.5", + "registry+https://github.com/rust-lang/crates.io-index#prost@0.14.3", + "registry+https://github.com/rust-lang/crates.io-index#prost-types@0.14.3", + "registry+https://github.com/rust-lang/crates.io-index#sea-query@0.32.7", + "registry+https://github.com/rust-lang/crates.io-index#sea-query-binder@0.7.0", + "registry+https://github.com/rust-lang/crates.io-index#serde@1.0.228", + "registry+https://github.com/rust-lang/crates.io-index#serde_json@1.0.149", + "registry+https://github.com/rust-lang/crates.io-index#sqlx@0.8.6", + "registry+https://github.com/rust-lang/crates.io-index#thiserror@1.0.69", + "registry+https://github.com/rust-lang/crates.io-index#tokio@1.50.0", + "registry+https://github.com/rust-lang/crates.io-index#tonic@0.14.5", + "registry+https://github.com/rust-lang/crates.io-index#tower@0.5.3", + "registry+https://github.com/rust-lang/crates.io-index#tracing@0.1.44", + "registry+https://github.com/rust-lang/crates.io-index#uuid@1.22.0" + ] + }, + { + "ref": "path+file:///C:/a/chroma/chroma/rust/system#chroma-system@0.1.0", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#async-trait@0.1.89", + "path+file:///C:/a/chroma/chroma/rust/config#chroma-config@0.1.0", + "path+file:///C:/a/chroma/chroma/rust/error#chroma-error@0.14.0", + "registry+https://github.com/rust-lang/crates.io-index#futures@0.3.32", + "registry+https://github.com/rust-lang/crates.io-index#libc@0.2.183", + "registry+https://github.com/rust-lang/crates.io-index#opentelemetry@0.27.1", + "registry+https://github.com/rust-lang/crates.io-index#parking_lot@0.12.5", + "registry+https://github.com/rust-lang/crates.io-index#rand@0.8.5", + "registry+https://github.com/rust-lang/crates.io-index#serde@1.0.228", + "registry+https://github.com/rust-lang/crates.io-index#tempfile@3.27.0", + "registry+https://github.com/rust-lang/crates.io-index#thiserror@1.0.69", + "registry+https://github.com/rust-lang/crates.io-index#tokio@1.50.0", + "registry+https://github.com/rust-lang/crates.io-index#tokio-util@0.7.18", + "registry+https://github.com/rust-lang/crates.io-index#tracing@0.1.44", + "registry+https://github.com/rust-lang/crates.io-index#uuid@1.22.0" + ] + }, + { + "ref": "path+file:///C:/a/chroma/chroma/rust/tracing#chroma-tracing@0.1.0", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#axum@0.8.8", + "path+file:///C:/a/chroma/chroma/rust/system#chroma-system@0.1.0", + "registry+https://github.com/rust-lang/crates.io-index#fastrace@0.7.8", + "registry+https://github.com/rust-lang/crates.io-index#fastrace-opentelemetry@0.8.1", + "registry+https://github.com/rust-lang/crates.io-index#futures@0.3.32", + "registry+https://github.com/rust-lang/crates.io-index#http@1.4.0", + "registry+https://github.com/rust-lang/crates.io-index#opentelemetry@0.27.1", + "registry+https://github.com/rust-lang/crates.io-index#opentelemetry-otlp@0.27.0", + "registry+https://github.com/rust-lang/crates.io-index#opentelemetry_sdk@0.27.1", + "registry+https://github.com/rust-lang/crates.io-index#rustls@0.23.37", + "registry+https://github.com/rust-lang/crates.io-index#serde@1.0.228", + "registry+https://github.com/rust-lang/crates.io-index#serde_json@1.0.149", + "registry+https://github.com/rust-lang/crates.io-index#tokio@1.50.0", + "registry+https://github.com/rust-lang/crates.io-index#tonic@0.14.5", + "registry+https://github.com/rust-lang/crates.io-index#tower@0.5.3", + "registry+https://github.com/rust-lang/crates.io-index#tower-http@0.6.8", + "registry+https://github.com/rust-lang/crates.io-index#tracing@0.1.44", + "registry+https://github.com/rust-lang/crates.io-index#tracing-opentelemetry@0.28.0", + "registry+https://github.com/rust-lang/crates.io-index#tracing-subscriber@0.3.23", + "registry+https://github.com/rust-lang/crates.io-index#uuid@1.22.0" + ] + }, + { + "ref": "path+file:///C:/a/chroma/chroma/rust/types#chroma-types@0.14.0", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#async-trait@0.1.89", + "registry+https://github.com/rust-lang/crates.io-index#base64@0.22.1", + "registry+https://github.com/rust-lang/crates.io-index#bitpacking@0.9.3", + "path+file:///C:/a/chroma/chroma/rust/error#chroma-error@0.14.0", + "registry+https://github.com/rust-lang/crates.io-index#chrono@0.4.44", + "registry+https://github.com/rust-lang/crates.io-index#criterion@0.7.0", + "registry+https://github.com/rust-lang/crates.io-index#half@2.7.1", + "registry+https://github.com/rust-lang/crates.io-index#itertools@0.13.0", + "registry+https://github.com/rust-lang/crates.io-index#proptest@1.10.0", + "registry+https://github.com/rust-lang/crates.io-index#proptest-derive@0.5.1", + "registry+https://github.com/rust-lang/crates.io-index#prost@0.14.3", + "registry+https://github.com/rust-lang/crates.io-index#prost-types@0.14.3", + "registry+https://github.com/rust-lang/crates.io-index#pyo3@0.24.2", + "registry+https://github.com/rust-lang/crates.io-index#regex@1.12.3", + "registry+https://github.com/rust-lang/crates.io-index#regex-syntax@0.8.10", + "registry+https://github.com/rust-lang/crates.io-index#roaring@0.10.12", + "registry+https://github.com/rust-lang/crates.io-index#serde@1.0.228", + "registry+https://github.com/rust-lang/crates.io-index#serde_json@1.0.149", + "registry+https://github.com/rust-lang/crates.io-index#sprs@0.11.4", + "registry+https://github.com/rust-lang/crates.io-index#thiserror@1.0.69", + "registry+https://github.com/rust-lang/crates.io-index#tokio@1.50.0", + "registry+https://github.com/rust-lang/crates.io-index#tonic@0.14.5", + "registry+https://github.com/rust-lang/crates.io-index#tonic-prost@0.14.5", + "registry+https://github.com/rust-lang/crates.io-index#tonic-prost-build@0.14.5", + "registry+https://github.com/rust-lang/crates.io-index#utoipa@5.4.0", + "registry+https://github.com/rust-lang/crates.io-index#uuid@1.22.0", + "registry+https://github.com/rust-lang/crates.io-index#validator@0.19.0" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#adler2@2.0.1" + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#aes@0.8.4", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#cfg-if@1.0.4", + "registry+https://github.com/rust-lang/crates.io-index#cipher@0.4.4", + "registry+https://github.com/rust-lang/crates.io-index#cpufeatures@0.2.17" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#ahash@0.8.12", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#cfg-if@1.0.4", + "registry+https://github.com/rust-lang/crates.io-index#const-random@0.1.18", + "registry+https://github.com/rust-lang/crates.io-index#getrandom@0.3.4", + "registry+https://github.com/rust-lang/crates.io-index#once_cell@1.21.4", + "registry+https://github.com/rust-lang/crates.io-index#version_check@0.9.5", + "registry+https://github.com/rust-lang/crates.io-index#zerocopy@0.8.47" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#aho-corasick@1.1.4", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#memchr@2.8.0" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#alga@0.9.3", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#approx@0.3.2", + "registry+https://github.com/rust-lang/crates.io-index#num-complex@0.2.4", + "registry+https://github.com/rust-lang/crates.io-index#num-traits@0.2.19" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#alloc-no-stdlib@2.0.4" + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#alloc-stdlib@0.2.2", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#alloc-no-stdlib@2.0.4" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#allocator-api2@0.2.21" + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#anes@0.1.6" + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#anstream@1.0.0", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#anstyle@1.0.14", + "registry+https://github.com/rust-lang/crates.io-index#anstyle-parse@1.0.0", + "registry+https://github.com/rust-lang/crates.io-index#anstyle-query@1.1.5", + "registry+https://github.com/rust-lang/crates.io-index#anstyle-wincon@3.0.11", + "registry+https://github.com/rust-lang/crates.io-index#colorchoice@1.0.5", + "registry+https://github.com/rust-lang/crates.io-index#is_terminal_polyfill@1.70.2", + "registry+https://github.com/rust-lang/crates.io-index#utf8parse@0.2.2" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#anstyle-parse@1.0.0", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#utf8parse@0.2.2" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#anstyle-query@1.1.5", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#windows-sys@0.61.2" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#anstyle-wincon@3.0.11", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#anstyle@1.0.14", + "registry+https://github.com/rust-lang/crates.io-index#once_cell_polyfill@1.70.2", + "registry+https://github.com/rust-lang/crates.io-index#windows-sys@0.61.2" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#anstyle@1.0.14" + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#anyhow@1.0.102" + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#approx@0.3.2", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#num-traits@0.2.19" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#arboard@3.6.1", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#clipboard-win@5.4.1", + "registry+https://github.com/rust-lang/crates.io-index#image@0.25.10", + "registry+https://github.com/rust-lang/crates.io-index#log@0.4.29", + "registry+https://github.com/rust-lang/crates.io-index#windows-sys@0.60.2" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#arc-swap@1.8.2", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#rustversion@1.0.22" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#array-util@1.0.2", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#arrayvec@0.7.6" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#arrayvec@0.7.6" + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#arrow-arith@55.2.0", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#arrow-array@55.2.0", + "registry+https://github.com/rust-lang/crates.io-index#arrow-buffer@55.2.0", + "registry+https://github.com/rust-lang/crates.io-index#arrow-data@55.2.0", + "registry+https://github.com/rust-lang/crates.io-index#arrow-schema@55.2.0", + "registry+https://github.com/rust-lang/crates.io-index#chrono@0.4.44", + "registry+https://github.com/rust-lang/crates.io-index#num@0.4.3" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#arrow-array@55.2.0", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#ahash@0.8.12", + "registry+https://github.com/rust-lang/crates.io-index#arrow-buffer@55.2.0", + "registry+https://github.com/rust-lang/crates.io-index#arrow-data@55.2.0", + "registry+https://github.com/rust-lang/crates.io-index#arrow-schema@55.2.0", + "registry+https://github.com/rust-lang/crates.io-index#chrono@0.4.44", + "registry+https://github.com/rust-lang/crates.io-index#half@2.7.1", + "registry+https://github.com/rust-lang/crates.io-index#hashbrown@0.15.5", + "registry+https://github.com/rust-lang/crates.io-index#num@0.4.3" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#arrow-buffer@55.2.0", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#bytes@1.11.1", + "registry+https://github.com/rust-lang/crates.io-index#half@2.7.1", + "registry+https://github.com/rust-lang/crates.io-index#num@0.4.3" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#arrow-cast@55.2.0", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#arrow-array@55.2.0", + "registry+https://github.com/rust-lang/crates.io-index#arrow-buffer@55.2.0", + "registry+https://github.com/rust-lang/crates.io-index#arrow-data@55.2.0", + "registry+https://github.com/rust-lang/crates.io-index#arrow-schema@55.2.0", + "registry+https://github.com/rust-lang/crates.io-index#arrow-select@55.2.0", + "registry+https://github.com/rust-lang/crates.io-index#atoi@2.0.0", + "registry+https://github.com/rust-lang/crates.io-index#base64@0.22.1", + "registry+https://github.com/rust-lang/crates.io-index#chrono@0.4.44", + "registry+https://github.com/rust-lang/crates.io-index#half@2.7.1", + "registry+https://github.com/rust-lang/crates.io-index#lexical-core@1.0.6", + "registry+https://github.com/rust-lang/crates.io-index#num@0.4.3", + "registry+https://github.com/rust-lang/crates.io-index#ryu@1.0.23" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#arrow-csv@55.2.0", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#arrow-array@55.2.0", + "registry+https://github.com/rust-lang/crates.io-index#arrow-cast@55.2.0", + "registry+https://github.com/rust-lang/crates.io-index#arrow-schema@55.2.0", + "registry+https://github.com/rust-lang/crates.io-index#chrono@0.4.44", + "registry+https://github.com/rust-lang/crates.io-index#csv@1.4.0", + "registry+https://github.com/rust-lang/crates.io-index#csv-core@0.1.13", + "registry+https://github.com/rust-lang/crates.io-index#regex@1.12.3" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#arrow-data@55.2.0", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#arrow-buffer@55.2.0", + "registry+https://github.com/rust-lang/crates.io-index#arrow-schema@55.2.0", + "registry+https://github.com/rust-lang/crates.io-index#half@2.7.1", + "registry+https://github.com/rust-lang/crates.io-index#num@0.4.3" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#arrow-ipc@55.2.0", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#arrow-array@55.2.0", + "registry+https://github.com/rust-lang/crates.io-index#arrow-buffer@55.2.0", + "registry+https://github.com/rust-lang/crates.io-index#arrow-data@55.2.0", + "registry+https://github.com/rust-lang/crates.io-index#arrow-schema@55.2.0", + "registry+https://github.com/rust-lang/crates.io-index#flatbuffers@25.12.19" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#arrow-json@55.2.0", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#arrow-array@55.2.0", + "registry+https://github.com/rust-lang/crates.io-index#arrow-buffer@55.2.0", + "registry+https://github.com/rust-lang/crates.io-index#arrow-cast@55.2.0", + "registry+https://github.com/rust-lang/crates.io-index#arrow-data@55.2.0", + "registry+https://github.com/rust-lang/crates.io-index#arrow-schema@55.2.0", + "registry+https://github.com/rust-lang/crates.io-index#chrono@0.4.44", + "registry+https://github.com/rust-lang/crates.io-index#half@2.7.1", + "registry+https://github.com/rust-lang/crates.io-index#indexmap@2.13.0", + "registry+https://github.com/rust-lang/crates.io-index#lexical-core@1.0.6", + "registry+https://github.com/rust-lang/crates.io-index#memchr@2.8.0", + "registry+https://github.com/rust-lang/crates.io-index#num@0.4.3", + "registry+https://github.com/rust-lang/crates.io-index#serde@1.0.228", + "registry+https://github.com/rust-lang/crates.io-index#serde_json@1.0.149", + "registry+https://github.com/rust-lang/crates.io-index#simdutf8@0.1.5" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#arrow-ord@55.2.0", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#arrow-array@55.2.0", + "registry+https://github.com/rust-lang/crates.io-index#arrow-buffer@55.2.0", + "registry+https://github.com/rust-lang/crates.io-index#arrow-data@55.2.0", + "registry+https://github.com/rust-lang/crates.io-index#arrow-schema@55.2.0", + "registry+https://github.com/rust-lang/crates.io-index#arrow-select@55.2.0" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#arrow-row@55.2.0", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#arrow-array@55.2.0", + "registry+https://github.com/rust-lang/crates.io-index#arrow-buffer@55.2.0", + "registry+https://github.com/rust-lang/crates.io-index#arrow-data@55.2.0", + "registry+https://github.com/rust-lang/crates.io-index#arrow-schema@55.2.0", + "registry+https://github.com/rust-lang/crates.io-index#half@2.7.1" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#arrow-schema@55.2.0" + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#arrow-select@55.2.0", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#ahash@0.8.12", + "registry+https://github.com/rust-lang/crates.io-index#arrow-array@55.2.0", + "registry+https://github.com/rust-lang/crates.io-index#arrow-buffer@55.2.0", + "registry+https://github.com/rust-lang/crates.io-index#arrow-data@55.2.0", + "registry+https://github.com/rust-lang/crates.io-index#arrow-schema@55.2.0", + "registry+https://github.com/rust-lang/crates.io-index#num@0.4.3" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#arrow-string@55.2.0", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#arrow-array@55.2.0", + "registry+https://github.com/rust-lang/crates.io-index#arrow-buffer@55.2.0", + "registry+https://github.com/rust-lang/crates.io-index#arrow-data@55.2.0", + "registry+https://github.com/rust-lang/crates.io-index#arrow-schema@55.2.0", + "registry+https://github.com/rust-lang/crates.io-index#arrow-select@55.2.0", + "registry+https://github.com/rust-lang/crates.io-index#memchr@2.8.0", + "registry+https://github.com/rust-lang/crates.io-index#num@0.4.3", + "registry+https://github.com/rust-lang/crates.io-index#regex@1.12.3", + "registry+https://github.com/rust-lang/crates.io-index#regex-syntax@0.8.10" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#arrow@55.2.0", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#arrow-arith@55.2.0", + "registry+https://github.com/rust-lang/crates.io-index#arrow-array@55.2.0", + "registry+https://github.com/rust-lang/crates.io-index#arrow-buffer@55.2.0", + "registry+https://github.com/rust-lang/crates.io-index#arrow-cast@55.2.0", + "registry+https://github.com/rust-lang/crates.io-index#arrow-csv@55.2.0", + "registry+https://github.com/rust-lang/crates.io-index#arrow-data@55.2.0", + "registry+https://github.com/rust-lang/crates.io-index#arrow-ipc@55.2.0", + "registry+https://github.com/rust-lang/crates.io-index#arrow-json@55.2.0", + "registry+https://github.com/rust-lang/crates.io-index#arrow-ord@55.2.0", + "registry+https://github.com/rust-lang/crates.io-index#arrow-row@55.2.0", + "registry+https://github.com/rust-lang/crates.io-index#arrow-schema@55.2.0", + "registry+https://github.com/rust-lang/crates.io-index#arrow-select@55.2.0", + "registry+https://github.com/rust-lang/crates.io-index#arrow-string@55.2.0" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#assoc@0.1.3" + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#async-stream-impl@0.3.6", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#proc-macro2@1.0.106", + "registry+https://github.com/rust-lang/crates.io-index#quote@1.0.45", + "registry+https://github.com/rust-lang/crates.io-index#syn@2.0.117" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#async-stream@0.3.6", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#async-stream-impl@0.3.6", + "registry+https://github.com/rust-lang/crates.io-index#futures-core@0.3.32", + "registry+https://github.com/rust-lang/crates.io-index#pin-project-lite@0.2.17" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#async-trait@0.1.89", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#proc-macro2@1.0.106", + "registry+https://github.com/rust-lang/crates.io-index#quote@1.0.45", + "registry+https://github.com/rust-lang/crates.io-index#syn@2.0.117" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#atoi@2.0.0", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#num-traits@0.2.19" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#atomic-waker@1.1.2" + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#auto_enums@0.8.8", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#derive_utils@0.15.1", + "registry+https://github.com/rust-lang/crates.io-index#proc-macro2@1.0.106", + "registry+https://github.com/rust-lang/crates.io-index#quote@1.0.45", + "registry+https://github.com/rust-lang/crates.io-index#syn@2.0.117" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#autocfg@1.5.0" + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#aws-config@1.8.15", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#aws-credential-types@1.2.14", + "registry+https://github.com/rust-lang/crates.io-index#aws-runtime@1.7.2", + "registry+https://github.com/rust-lang/crates.io-index#aws-sdk-sso@1.97.0", + "registry+https://github.com/rust-lang/crates.io-index#aws-sdk-ssooidc@1.99.0", + "registry+https://github.com/rust-lang/crates.io-index#aws-sdk-sts@1.101.0", + "registry+https://github.com/rust-lang/crates.io-index#aws-smithy-async@1.2.14", + "registry+https://github.com/rust-lang/crates.io-index#aws-smithy-http@0.63.6", + "registry+https://github.com/rust-lang/crates.io-index#aws-smithy-json@0.62.5", + "registry+https://github.com/rust-lang/crates.io-index#aws-smithy-runtime@1.10.3", + "registry+https://github.com/rust-lang/crates.io-index#aws-smithy-runtime-api@1.11.6", + "registry+https://github.com/rust-lang/crates.io-index#aws-smithy-types@1.4.7", + "registry+https://github.com/rust-lang/crates.io-index#aws-types@1.3.14", + "registry+https://github.com/rust-lang/crates.io-index#bytes@1.11.1", + "registry+https://github.com/rust-lang/crates.io-index#fastrand@2.3.0", + "registry+https://github.com/rust-lang/crates.io-index#hex@0.4.3", + "registry+https://github.com/rust-lang/crates.io-index#http@1.4.0", + "registry+https://github.com/rust-lang/crates.io-index#sha1@0.10.6", + "registry+https://github.com/rust-lang/crates.io-index#time@0.3.47", + "registry+https://github.com/rust-lang/crates.io-index#tokio@1.50.0", + "registry+https://github.com/rust-lang/crates.io-index#tracing@0.1.44", + "registry+https://github.com/rust-lang/crates.io-index#url@2.5.8", + "registry+https://github.com/rust-lang/crates.io-index#zeroize@1.8.2" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#aws-credential-types@1.2.14", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#aws-smithy-async@1.2.14", + "registry+https://github.com/rust-lang/crates.io-index#aws-smithy-runtime-api@1.11.6", + "registry+https://github.com/rust-lang/crates.io-index#aws-smithy-types@1.4.7", + "registry+https://github.com/rust-lang/crates.io-index#zeroize@1.8.2" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#aws-lc-rs@1.16.2", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#aws-lc-sys@0.39.0", + "registry+https://github.com/rust-lang/crates.io-index#untrusted@0.7.1", + "registry+https://github.com/rust-lang/crates.io-index#zeroize@1.8.2" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#aws-lc-sys@0.39.0", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#cc@1.2.57", + "registry+https://github.com/rust-lang/crates.io-index#cmake@0.1.57", + "registry+https://github.com/rust-lang/crates.io-index#dunce@1.0.5", + "registry+https://github.com/rust-lang/crates.io-index#fs_extra@1.3.0" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#aws-runtime@1.7.2", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#aws-credential-types@1.2.14", + "registry+https://github.com/rust-lang/crates.io-index#aws-sigv4@1.4.2", + "registry+https://github.com/rust-lang/crates.io-index#aws-smithy-async@1.2.14", + "registry+https://github.com/rust-lang/crates.io-index#aws-smithy-eventstream@0.60.20", + "registry+https://github.com/rust-lang/crates.io-index#aws-smithy-http@0.63.6", + "registry+https://github.com/rust-lang/crates.io-index#aws-smithy-runtime@1.10.3", + "registry+https://github.com/rust-lang/crates.io-index#aws-smithy-runtime-api@1.11.6", + "registry+https://github.com/rust-lang/crates.io-index#aws-smithy-types@1.4.7", + "registry+https://github.com/rust-lang/crates.io-index#aws-types@1.3.14", + "registry+https://github.com/rust-lang/crates.io-index#bytes@1.11.1", + "registry+https://github.com/rust-lang/crates.io-index#bytes-utils@0.1.4", + "registry+https://github.com/rust-lang/crates.io-index#fastrand@2.3.0", + "registry+https://github.com/rust-lang/crates.io-index#http@0.2.12", + "registry+https://github.com/rust-lang/crates.io-index#http@1.4.0", + "registry+https://github.com/rust-lang/crates.io-index#http-body@0.4.6", + "registry+https://github.com/rust-lang/crates.io-index#http-body@1.0.1", + "registry+https://github.com/rust-lang/crates.io-index#percent-encoding@2.3.2", + "registry+https://github.com/rust-lang/crates.io-index#pin-project-lite@0.2.17", + "registry+https://github.com/rust-lang/crates.io-index#tracing@0.1.44", + "registry+https://github.com/rust-lang/crates.io-index#uuid@1.22.0" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#aws-sdk-s3@1.119.0", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#aws-credential-types@1.2.14", + "registry+https://github.com/rust-lang/crates.io-index#aws-runtime@1.7.2", + "registry+https://github.com/rust-lang/crates.io-index#aws-sigv4@1.4.2", + "registry+https://github.com/rust-lang/crates.io-index#aws-smithy-async@1.2.14", + "registry+https://github.com/rust-lang/crates.io-index#aws-smithy-checksums@0.63.12", + "registry+https://github.com/rust-lang/crates.io-index#aws-smithy-eventstream@0.60.20", + "registry+https://github.com/rust-lang/crates.io-index#aws-smithy-http@0.62.6", + "registry+https://github.com/rust-lang/crates.io-index#aws-smithy-json@0.61.9", + "registry+https://github.com/rust-lang/crates.io-index#aws-smithy-runtime@1.10.3", + "registry+https://github.com/rust-lang/crates.io-index#aws-smithy-runtime-api@1.11.6", + "registry+https://github.com/rust-lang/crates.io-index#aws-smithy-types@1.4.7", + "registry+https://github.com/rust-lang/crates.io-index#aws-smithy-xml@0.60.15", + "registry+https://github.com/rust-lang/crates.io-index#aws-types@1.3.14", + "registry+https://github.com/rust-lang/crates.io-index#bytes@1.11.1", + "registry+https://github.com/rust-lang/crates.io-index#fastrand@2.3.0", + "registry+https://github.com/rust-lang/crates.io-index#hex@0.4.3", + "registry+https://github.com/rust-lang/crates.io-index#hmac@0.12.1", + "registry+https://github.com/rust-lang/crates.io-index#http@0.2.12", + "registry+https://github.com/rust-lang/crates.io-index#http@1.4.0", + "registry+https://github.com/rust-lang/crates.io-index#http-body@0.4.6", + "registry+https://github.com/rust-lang/crates.io-index#lru@0.12.5", + "registry+https://github.com/rust-lang/crates.io-index#percent-encoding@2.3.2", + "registry+https://github.com/rust-lang/crates.io-index#regex-lite@0.1.9", + "registry+https://github.com/rust-lang/crates.io-index#sha2@0.10.9", + "registry+https://github.com/rust-lang/crates.io-index#tracing@0.1.44", + "registry+https://github.com/rust-lang/crates.io-index#url@2.5.8" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#aws-sdk-sso@1.97.0", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#aws-credential-types@1.2.14", + "registry+https://github.com/rust-lang/crates.io-index#aws-runtime@1.7.2", + "registry+https://github.com/rust-lang/crates.io-index#aws-smithy-async@1.2.14", + "registry+https://github.com/rust-lang/crates.io-index#aws-smithy-http@0.63.6", + "registry+https://github.com/rust-lang/crates.io-index#aws-smithy-json@0.62.5", + "registry+https://github.com/rust-lang/crates.io-index#aws-smithy-observability@0.2.6", + "registry+https://github.com/rust-lang/crates.io-index#aws-smithy-runtime@1.10.3", + "registry+https://github.com/rust-lang/crates.io-index#aws-smithy-runtime-api@1.11.6", + "registry+https://github.com/rust-lang/crates.io-index#aws-smithy-types@1.4.7", + "registry+https://github.com/rust-lang/crates.io-index#aws-types@1.3.14", + "registry+https://github.com/rust-lang/crates.io-index#bytes@1.11.1", + "registry+https://github.com/rust-lang/crates.io-index#fastrand@2.3.0", + "registry+https://github.com/rust-lang/crates.io-index#http@0.2.12", + "registry+https://github.com/rust-lang/crates.io-index#http@1.4.0", + "registry+https://github.com/rust-lang/crates.io-index#regex-lite@0.1.9", + "registry+https://github.com/rust-lang/crates.io-index#tracing@0.1.44" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#aws-sdk-ssooidc@1.99.0", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#aws-credential-types@1.2.14", + "registry+https://github.com/rust-lang/crates.io-index#aws-runtime@1.7.2", + "registry+https://github.com/rust-lang/crates.io-index#aws-smithy-async@1.2.14", + "registry+https://github.com/rust-lang/crates.io-index#aws-smithy-http@0.63.6", + "registry+https://github.com/rust-lang/crates.io-index#aws-smithy-json@0.62.5", + "registry+https://github.com/rust-lang/crates.io-index#aws-smithy-observability@0.2.6", + "registry+https://github.com/rust-lang/crates.io-index#aws-smithy-runtime@1.10.3", + "registry+https://github.com/rust-lang/crates.io-index#aws-smithy-runtime-api@1.11.6", + "registry+https://github.com/rust-lang/crates.io-index#aws-smithy-types@1.4.7", + "registry+https://github.com/rust-lang/crates.io-index#aws-types@1.3.14", + "registry+https://github.com/rust-lang/crates.io-index#bytes@1.11.1", + "registry+https://github.com/rust-lang/crates.io-index#fastrand@2.3.0", + "registry+https://github.com/rust-lang/crates.io-index#http@0.2.12", + "registry+https://github.com/rust-lang/crates.io-index#http@1.4.0", + "registry+https://github.com/rust-lang/crates.io-index#regex-lite@0.1.9", + "registry+https://github.com/rust-lang/crates.io-index#tracing@0.1.44" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#aws-sdk-sts@1.101.0", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#aws-credential-types@1.2.14", + "registry+https://github.com/rust-lang/crates.io-index#aws-runtime@1.7.2", + "registry+https://github.com/rust-lang/crates.io-index#aws-smithy-async@1.2.14", + "registry+https://github.com/rust-lang/crates.io-index#aws-smithy-http@0.63.6", + "registry+https://github.com/rust-lang/crates.io-index#aws-smithy-json@0.62.5", + "registry+https://github.com/rust-lang/crates.io-index#aws-smithy-observability@0.2.6", + "registry+https://github.com/rust-lang/crates.io-index#aws-smithy-query@0.60.15", + "registry+https://github.com/rust-lang/crates.io-index#aws-smithy-runtime@1.10.3", + "registry+https://github.com/rust-lang/crates.io-index#aws-smithy-runtime-api@1.11.6", + "registry+https://github.com/rust-lang/crates.io-index#aws-smithy-types@1.4.7", + "registry+https://github.com/rust-lang/crates.io-index#aws-smithy-xml@0.60.15", + "registry+https://github.com/rust-lang/crates.io-index#aws-types@1.3.14", + "registry+https://github.com/rust-lang/crates.io-index#fastrand@2.3.0", + "registry+https://github.com/rust-lang/crates.io-index#http@0.2.12", + "registry+https://github.com/rust-lang/crates.io-index#http@1.4.0", + "registry+https://github.com/rust-lang/crates.io-index#regex-lite@0.1.9", + "registry+https://github.com/rust-lang/crates.io-index#tracing@0.1.44" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#aws-sigv4@1.4.2", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#aws-credential-types@1.2.14", + "registry+https://github.com/rust-lang/crates.io-index#aws-smithy-eventstream@0.60.20", + "registry+https://github.com/rust-lang/crates.io-index#aws-smithy-http@0.63.6", + "registry+https://github.com/rust-lang/crates.io-index#aws-smithy-runtime-api@1.11.6", + "registry+https://github.com/rust-lang/crates.io-index#aws-smithy-types@1.4.7", + "registry+https://github.com/rust-lang/crates.io-index#bytes@1.11.1", + "registry+https://github.com/rust-lang/crates.io-index#crypto-bigint@0.5.5", + "registry+https://github.com/rust-lang/crates.io-index#form_urlencoded@1.2.2", + "registry+https://github.com/rust-lang/crates.io-index#hex@0.4.3", + "registry+https://github.com/rust-lang/crates.io-index#hmac@0.12.1", + "registry+https://github.com/rust-lang/crates.io-index#http@0.2.12", + "registry+https://github.com/rust-lang/crates.io-index#http@1.4.0", + "registry+https://github.com/rust-lang/crates.io-index#p256@0.11.1", + "registry+https://github.com/rust-lang/crates.io-index#percent-encoding@2.3.2", + "registry+https://github.com/rust-lang/crates.io-index#ring@0.17.14", + "registry+https://github.com/rust-lang/crates.io-index#sha2@0.10.9", + "registry+https://github.com/rust-lang/crates.io-index#subtle@2.6.1", + "registry+https://github.com/rust-lang/crates.io-index#time@0.3.47", + "registry+https://github.com/rust-lang/crates.io-index#tracing@0.1.44", + "registry+https://github.com/rust-lang/crates.io-index#zeroize@1.8.2" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#aws-smithy-async@1.2.14", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#futures-util@0.3.32", + "registry+https://github.com/rust-lang/crates.io-index#pin-project-lite@0.2.17", + "registry+https://github.com/rust-lang/crates.io-index#tokio@1.50.0" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#aws-smithy-checksums@0.63.12", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#aws-smithy-http@0.62.6", + "registry+https://github.com/rust-lang/crates.io-index#aws-smithy-types@1.4.7", + "registry+https://github.com/rust-lang/crates.io-index#bytes@1.11.1", + "registry+https://github.com/rust-lang/crates.io-index#crc-fast@1.6.0", + "registry+https://github.com/rust-lang/crates.io-index#hex@0.4.3", + "registry+https://github.com/rust-lang/crates.io-index#http@0.2.12", + "registry+https://github.com/rust-lang/crates.io-index#http-body@0.4.6", + "registry+https://github.com/rust-lang/crates.io-index#md-5@0.10.6", + "registry+https://github.com/rust-lang/crates.io-index#pin-project-lite@0.2.17", + "registry+https://github.com/rust-lang/crates.io-index#sha1@0.10.6", + "registry+https://github.com/rust-lang/crates.io-index#sha2@0.10.9", + "registry+https://github.com/rust-lang/crates.io-index#tracing@0.1.44" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#aws-smithy-eventstream@0.60.20", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#aws-smithy-types@1.4.7", + "registry+https://github.com/rust-lang/crates.io-index#bytes@1.11.1", + "registry+https://github.com/rust-lang/crates.io-index#crc32fast@1.5.0" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#aws-smithy-http-client@1.1.12", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#aws-smithy-async@1.2.14", + "registry+https://github.com/rust-lang/crates.io-index#aws-smithy-runtime-api@1.11.6", + "registry+https://github.com/rust-lang/crates.io-index#aws-smithy-types@1.4.7", + "registry+https://github.com/rust-lang/crates.io-index#h2@0.3.27", + "registry+https://github.com/rust-lang/crates.io-index#h2@0.4.13", + "registry+https://github.com/rust-lang/crates.io-index#http@0.2.12", + "registry+https://github.com/rust-lang/crates.io-index#http@1.4.0", + "registry+https://github.com/rust-lang/crates.io-index#http-body@0.4.6", + "registry+https://github.com/rust-lang/crates.io-index#hyper@0.14.32", + "registry+https://github.com/rust-lang/crates.io-index#hyper@1.8.1", + "registry+https://github.com/rust-lang/crates.io-index#hyper-rustls@0.24.2", + "registry+https://github.com/rust-lang/crates.io-index#hyper-rustls@0.27.7", + "registry+https://github.com/rust-lang/crates.io-index#hyper-util@0.1.20", + "registry+https://github.com/rust-lang/crates.io-index#pin-project-lite@0.2.17", + "registry+https://github.com/rust-lang/crates.io-index#rustls@0.21.12", + "registry+https://github.com/rust-lang/crates.io-index#rustls@0.23.37", + "registry+https://github.com/rust-lang/crates.io-index#rustls-native-certs@0.8.3", + "registry+https://github.com/rust-lang/crates.io-index#rustls-pki-types@1.14.0", + "registry+https://github.com/rust-lang/crates.io-index#tokio@1.50.0", + "registry+https://github.com/rust-lang/crates.io-index#tokio-rustls@0.26.4", + "registry+https://github.com/rust-lang/crates.io-index#tower@0.5.3", + "registry+https://github.com/rust-lang/crates.io-index#tracing@0.1.44" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#aws-smithy-http@0.62.6", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#aws-smithy-eventstream@0.60.20", + "registry+https://github.com/rust-lang/crates.io-index#aws-smithy-runtime-api@1.11.6", + "registry+https://github.com/rust-lang/crates.io-index#aws-smithy-types@1.4.7", + "registry+https://github.com/rust-lang/crates.io-index#bytes@1.11.1", + "registry+https://github.com/rust-lang/crates.io-index#bytes-utils@0.1.4", + "registry+https://github.com/rust-lang/crates.io-index#futures-core@0.3.32", + "registry+https://github.com/rust-lang/crates.io-index#futures-util@0.3.32", + "registry+https://github.com/rust-lang/crates.io-index#http@0.2.12", + "registry+https://github.com/rust-lang/crates.io-index#http@1.4.0", + "registry+https://github.com/rust-lang/crates.io-index#http-body@0.4.6", + "registry+https://github.com/rust-lang/crates.io-index#percent-encoding@2.3.2", + "registry+https://github.com/rust-lang/crates.io-index#pin-project-lite@0.2.17", + "registry+https://github.com/rust-lang/crates.io-index#pin-utils@0.1.0", + "registry+https://github.com/rust-lang/crates.io-index#tracing@0.1.44" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#aws-smithy-http@0.63.6", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#aws-smithy-runtime-api@1.11.6", + "registry+https://github.com/rust-lang/crates.io-index#aws-smithy-types@1.4.7", + "registry+https://github.com/rust-lang/crates.io-index#bytes@1.11.1", + "registry+https://github.com/rust-lang/crates.io-index#bytes-utils@0.1.4", + "registry+https://github.com/rust-lang/crates.io-index#futures-core@0.3.32", + "registry+https://github.com/rust-lang/crates.io-index#futures-util@0.3.32", + "registry+https://github.com/rust-lang/crates.io-index#http@1.4.0", + "registry+https://github.com/rust-lang/crates.io-index#http-body@1.0.1", + "registry+https://github.com/rust-lang/crates.io-index#http-body-util@0.1.3", + "registry+https://github.com/rust-lang/crates.io-index#percent-encoding@2.3.2", + "registry+https://github.com/rust-lang/crates.io-index#pin-project-lite@0.2.17", + "registry+https://github.com/rust-lang/crates.io-index#pin-utils@0.1.0", + "registry+https://github.com/rust-lang/crates.io-index#tracing@0.1.44" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#aws-smithy-json@0.61.9", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#aws-smithy-types@1.4.7" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#aws-smithy-json@0.62.5", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#aws-smithy-types@1.4.7" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#aws-smithy-observability@0.2.6", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#aws-smithy-runtime-api@1.11.6" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#aws-smithy-query@0.60.15", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#aws-smithy-types@1.4.7", + "registry+https://github.com/rust-lang/crates.io-index#urlencoding@2.1.3" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#aws-smithy-runtime-api@1.11.6", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#aws-smithy-async@1.2.14", + "registry+https://github.com/rust-lang/crates.io-index#aws-smithy-types@1.4.7", + "registry+https://github.com/rust-lang/crates.io-index#bytes@1.11.1", + "registry+https://github.com/rust-lang/crates.io-index#http@0.2.12", + "registry+https://github.com/rust-lang/crates.io-index#http@1.4.0", + "registry+https://github.com/rust-lang/crates.io-index#pin-project-lite@0.2.17", + "registry+https://github.com/rust-lang/crates.io-index#tokio@1.50.0", + "registry+https://github.com/rust-lang/crates.io-index#tracing@0.1.44", + "registry+https://github.com/rust-lang/crates.io-index#zeroize@1.8.2" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#aws-smithy-runtime@1.10.3", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#aws-smithy-async@1.2.14", + "registry+https://github.com/rust-lang/crates.io-index#aws-smithy-http@0.63.6", + "registry+https://github.com/rust-lang/crates.io-index#aws-smithy-http-client@1.1.12", + "registry+https://github.com/rust-lang/crates.io-index#aws-smithy-observability@0.2.6", + "registry+https://github.com/rust-lang/crates.io-index#aws-smithy-runtime-api@1.11.6", + "registry+https://github.com/rust-lang/crates.io-index#aws-smithy-types@1.4.7", + "registry+https://github.com/rust-lang/crates.io-index#bytes@1.11.1", + "registry+https://github.com/rust-lang/crates.io-index#fastrand@2.3.0", + "registry+https://github.com/rust-lang/crates.io-index#http@0.2.12", + "registry+https://github.com/rust-lang/crates.io-index#http@1.4.0", + "registry+https://github.com/rust-lang/crates.io-index#http-body@0.4.6", + "registry+https://github.com/rust-lang/crates.io-index#http-body@1.0.1", + "registry+https://github.com/rust-lang/crates.io-index#http-body-util@0.1.3", + "registry+https://github.com/rust-lang/crates.io-index#pin-project-lite@0.2.17", + "registry+https://github.com/rust-lang/crates.io-index#pin-utils@0.1.0", + "registry+https://github.com/rust-lang/crates.io-index#tokio@1.50.0", + "registry+https://github.com/rust-lang/crates.io-index#tracing@0.1.44" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#aws-smithy-types@1.4.7", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#base64-simd@0.8.0", + "registry+https://github.com/rust-lang/crates.io-index#bytes@1.11.1", + "registry+https://github.com/rust-lang/crates.io-index#bytes-utils@0.1.4", + "registry+https://github.com/rust-lang/crates.io-index#futures-core@0.3.32", + "registry+https://github.com/rust-lang/crates.io-index#http@0.2.12", + "registry+https://github.com/rust-lang/crates.io-index#http@1.4.0", + "registry+https://github.com/rust-lang/crates.io-index#http-body@0.4.6", + "registry+https://github.com/rust-lang/crates.io-index#http-body@1.0.1", + "registry+https://github.com/rust-lang/crates.io-index#http-body-util@0.1.3", + "registry+https://github.com/rust-lang/crates.io-index#itoa@1.0.18", + "registry+https://github.com/rust-lang/crates.io-index#num-integer@0.1.46", + "registry+https://github.com/rust-lang/crates.io-index#pin-project-lite@0.2.17", + "registry+https://github.com/rust-lang/crates.io-index#pin-utils@0.1.0", + "registry+https://github.com/rust-lang/crates.io-index#ryu@1.0.23", + "registry+https://github.com/rust-lang/crates.io-index#time@0.3.47", + "registry+https://github.com/rust-lang/crates.io-index#tokio@1.50.0", + "registry+https://github.com/rust-lang/crates.io-index#tokio-util@0.7.18" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#aws-smithy-xml@0.60.15", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#xmlparser@0.13.6" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#aws-types@1.3.14", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#aws-credential-types@1.2.14", + "registry+https://github.com/rust-lang/crates.io-index#aws-smithy-async@1.2.14", + "registry+https://github.com/rust-lang/crates.io-index#aws-smithy-runtime-api@1.11.6", + "registry+https://github.com/rust-lang/crates.io-index#aws-smithy-types@1.4.7", + "registry+https://github.com/rust-lang/crates.io-index#rustc_version@0.4.1", + "registry+https://github.com/rust-lang/crates.io-index#tracing@0.1.44" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#axum-core@0.4.5", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#async-trait@0.1.89", + "registry+https://github.com/rust-lang/crates.io-index#bytes@1.11.1", + "registry+https://github.com/rust-lang/crates.io-index#futures-util@0.3.32", + "registry+https://github.com/rust-lang/crates.io-index#http@1.4.0", + "registry+https://github.com/rust-lang/crates.io-index#http-body@1.0.1", + "registry+https://github.com/rust-lang/crates.io-index#http-body-util@0.1.3", + "registry+https://github.com/rust-lang/crates.io-index#mime@0.3.17", + "registry+https://github.com/rust-lang/crates.io-index#pin-project-lite@0.2.17", + "registry+https://github.com/rust-lang/crates.io-index#rustversion@1.0.22", + "registry+https://github.com/rust-lang/crates.io-index#sync_wrapper@1.0.2", + "registry+https://github.com/rust-lang/crates.io-index#tower-layer@0.3.3", + "registry+https://github.com/rust-lang/crates.io-index#tower-service@0.3.3" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#axum-core@0.5.6", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#bytes@1.11.1", + "registry+https://github.com/rust-lang/crates.io-index#futures-core@0.3.32", + "registry+https://github.com/rust-lang/crates.io-index#http@1.4.0", + "registry+https://github.com/rust-lang/crates.io-index#http-body@1.0.1", + "registry+https://github.com/rust-lang/crates.io-index#http-body-util@0.1.3", + "registry+https://github.com/rust-lang/crates.io-index#mime@0.3.17", + "registry+https://github.com/rust-lang/crates.io-index#pin-project-lite@0.2.17", + "registry+https://github.com/rust-lang/crates.io-index#sync_wrapper@1.0.2", + "registry+https://github.com/rust-lang/crates.io-index#tower-layer@0.3.3", + "registry+https://github.com/rust-lang/crates.io-index#tower-service@0.3.3", + "registry+https://github.com/rust-lang/crates.io-index#tracing@0.1.44" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#axum-macros@0.5.0", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#proc-macro2@1.0.106", + "registry+https://github.com/rust-lang/crates.io-index#quote@1.0.45", + "registry+https://github.com/rust-lang/crates.io-index#syn@2.0.117" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#axum@0.7.9", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#async-trait@0.1.89", + "registry+https://github.com/rust-lang/crates.io-index#axum-core@0.4.5", + "registry+https://github.com/rust-lang/crates.io-index#bytes@1.11.1", + "registry+https://github.com/rust-lang/crates.io-index#futures-util@0.3.32", + "registry+https://github.com/rust-lang/crates.io-index#http@1.4.0", + "registry+https://github.com/rust-lang/crates.io-index#http-body@1.0.1", + "registry+https://github.com/rust-lang/crates.io-index#http-body-util@0.1.3", + "registry+https://github.com/rust-lang/crates.io-index#itoa@1.0.18", + "registry+https://github.com/rust-lang/crates.io-index#matchit@0.7.3", + "registry+https://github.com/rust-lang/crates.io-index#memchr@2.8.0", + "registry+https://github.com/rust-lang/crates.io-index#mime@0.3.17", + "registry+https://github.com/rust-lang/crates.io-index#percent-encoding@2.3.2", + "registry+https://github.com/rust-lang/crates.io-index#pin-project-lite@0.2.17", + "registry+https://github.com/rust-lang/crates.io-index#rustversion@1.0.22", + "registry+https://github.com/rust-lang/crates.io-index#serde@1.0.228", + "registry+https://github.com/rust-lang/crates.io-index#sync_wrapper@1.0.2", + "registry+https://github.com/rust-lang/crates.io-index#tower@0.5.3", + "registry+https://github.com/rust-lang/crates.io-index#tower-layer@0.3.3", + "registry+https://github.com/rust-lang/crates.io-index#tower-service@0.3.3" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#axum@0.8.8", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#axum-core@0.5.6", + "registry+https://github.com/rust-lang/crates.io-index#axum-macros@0.5.0", + "registry+https://github.com/rust-lang/crates.io-index#bytes@1.11.1", + "registry+https://github.com/rust-lang/crates.io-index#form_urlencoded@1.2.2", + "registry+https://github.com/rust-lang/crates.io-index#futures-util@0.3.32", + "registry+https://github.com/rust-lang/crates.io-index#http@1.4.0", + "registry+https://github.com/rust-lang/crates.io-index#http-body@1.0.1", + "registry+https://github.com/rust-lang/crates.io-index#http-body-util@0.1.3", + "registry+https://github.com/rust-lang/crates.io-index#hyper@1.8.1", + "registry+https://github.com/rust-lang/crates.io-index#hyper-util@0.1.20", + "registry+https://github.com/rust-lang/crates.io-index#itoa@1.0.18", + "registry+https://github.com/rust-lang/crates.io-index#matchit@0.8.4", + "registry+https://github.com/rust-lang/crates.io-index#memchr@2.8.0", + "registry+https://github.com/rust-lang/crates.io-index#mime@0.3.17", + "registry+https://github.com/rust-lang/crates.io-index#percent-encoding@2.3.2", + "registry+https://github.com/rust-lang/crates.io-index#pin-project-lite@0.2.17", + "registry+https://github.com/rust-lang/crates.io-index#serde_core@1.0.228", + "registry+https://github.com/rust-lang/crates.io-index#serde_json@1.0.149", + "registry+https://github.com/rust-lang/crates.io-index#serde_path_to_error@0.1.20", + "registry+https://github.com/rust-lang/crates.io-index#serde_urlencoded@0.7.1", + "registry+https://github.com/rust-lang/crates.io-index#sync_wrapper@1.0.2", + "registry+https://github.com/rust-lang/crates.io-index#tokio@1.50.0", + "registry+https://github.com/rust-lang/crates.io-index#tower@0.5.3", + "registry+https://github.com/rust-lang/crates.io-index#tower-layer@0.3.3", + "registry+https://github.com/rust-lang/crates.io-index#tower-service@0.3.3", + "registry+https://github.com/rust-lang/crates.io-index#tracing@0.1.44" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#backoff@0.4.0", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#getrandom@0.2.17", + "registry+https://github.com/rust-lang/crates.io-index#instant@0.1.13", + "registry+https://github.com/rust-lang/crates.io-index#rand@0.8.5" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#backon@1.6.0", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#fastrand@2.3.0", + "registry+https://github.com/rust-lang/crates.io-index#tokio@1.50.0" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#base16ct@0.1.1" + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#base64-simd@0.8.0", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#outref@0.5.2", + "registry+https://github.com/rust-lang/crates.io-index#vsimd@0.8.0" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#base64@0.21.7" + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#base64@0.22.1" + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#base64ct@1.8.3" + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#bincode@1.3.3", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#serde@1.0.228" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#bit-set@0.8.0", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#bit-vec@0.8.0" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#bit-vec@0.8.0" + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#bitflags@2.11.0", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#serde_core@1.0.228" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#bitpacking@0.9.3", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#crunchy@0.2.4" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#bitvec@1.0.1", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#funty@2.0.0", + "registry+https://github.com/rust-lang/crates.io-index#radium@0.7.0", + "registry+https://github.com/rust-lang/crates.io-index#tap@1.0.1", + "registry+https://github.com/rust-lang/crates.io-index#wyz@0.5.1" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#block-buffer@0.10.4", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#generic-array@0.14.7" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#bon-macros@3.9.1", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#darling@0.23.0", + "registry+https://github.com/rust-lang/crates.io-index#ident_case@1.0.1", + "registry+https://github.com/rust-lang/crates.io-index#prettyplease@0.2.37", + "registry+https://github.com/rust-lang/crates.io-index#proc-macro2@1.0.106", + "registry+https://github.com/rust-lang/crates.io-index#quote@1.0.45", + "registry+https://github.com/rust-lang/crates.io-index#rustversion@1.0.22", + "registry+https://github.com/rust-lang/crates.io-index#syn@2.0.117" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#bon@3.9.1", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#bon-macros@3.9.1", + "registry+https://github.com/rust-lang/crates.io-index#rustversion@1.0.22" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#brotli-decompressor@5.0.0", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#alloc-no-stdlib@2.0.4", + "registry+https://github.com/rust-lang/crates.io-index#alloc-stdlib@0.2.2" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#brotli@8.0.2", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#alloc-no-stdlib@2.0.4", + "registry+https://github.com/rust-lang/crates.io-index#alloc-stdlib@0.2.2", + "registry+https://github.com/rust-lang/crates.io-index#brotli-decompressor@5.0.0" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#bstr@1.12.1", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#memchr@2.8.0", + "registry+https://github.com/rust-lang/crates.io-index#serde@1.0.228" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#bumpalo@3.20.2" + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#bytemuck@1.25.0", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#bytemuck_derive@1.10.2" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#bytemuck_derive@1.10.2", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#proc-macro2@1.0.106", + "registry+https://github.com/rust-lang/crates.io-index#quote@1.0.45", + "registry+https://github.com/rust-lang/crates.io-index#syn@2.0.117" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#byteorder-lite@0.1.0" + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#byteorder@1.5.0" + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#bytes-utils@0.1.4", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#bytes@1.11.1", + "registry+https://github.com/rust-lang/crates.io-index#either@1.15.0" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#bytes@1.11.1", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#serde@1.0.228" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#bzip2@0.6.1", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#libbz2-rs-sys@0.2.2" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#cassowary@0.3.0" + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#cast@0.3.0" + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#castaway@0.2.4", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#rustversion@1.0.22" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#cc@1.2.57", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#find-msvc-tools@0.1.9", + "registry+https://github.com/rust-lang/crates.io-index#jobserver@0.1.34", + "registry+https://github.com/rust-lang/crates.io-index#shlex@1.3.0" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#census@0.4.2" + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#cfg-if@1.0.4" + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#cfg_aliases@0.2.1" + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#chacha20@0.10.0", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#cfg-if@1.0.4", + "registry+https://github.com/rust-lang/crates.io-index#cpufeatures@0.3.0", + "registry+https://github.com/rust-lang/crates.io-index#rand_core@0.10.0" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#chrono@0.4.44", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#num-traits@0.2.19", + "registry+https://github.com/rust-lang/crates.io-index#serde@1.0.228", + "registry+https://github.com/rust-lang/crates.io-index#windows-link@0.2.1" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#ciborium-io@0.2.2" + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#ciborium-ll@0.2.2", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#ciborium-io@0.2.2", + "registry+https://github.com/rust-lang/crates.io-index#half@2.7.1" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#ciborium@0.2.2", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#ciborium-io@0.2.2", + "registry+https://github.com/rust-lang/crates.io-index#ciborium-ll@0.2.2", + "registry+https://github.com/rust-lang/crates.io-index#serde@1.0.228" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#cipher@0.4.4", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#crypto-common@0.1.7", + "registry+https://github.com/rust-lang/crates.io-index#inout@0.1.4" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#clap@4.6.0", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#clap_builder@4.6.0", + "registry+https://github.com/rust-lang/crates.io-index#clap_derive@4.6.0" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#clap_builder@4.6.0", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#anstream@1.0.0", + "registry+https://github.com/rust-lang/crates.io-index#anstyle@1.0.14", + "registry+https://github.com/rust-lang/crates.io-index#clap_lex@1.1.0", + "registry+https://github.com/rust-lang/crates.io-index#strsim@0.11.1" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#clap_derive@4.6.0", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#heck@0.5.0", + "registry+https://github.com/rust-lang/crates.io-index#proc-macro2@1.0.106", + "registry+https://github.com/rust-lang/crates.io-index#quote@1.0.45", + "registry+https://github.com/rust-lang/crates.io-index#syn@2.0.117" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#clap_lex@1.1.0" + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#clipboard-win@5.4.1", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#error-code@3.3.2" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#cmake@0.1.57", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#cc@1.2.57" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#cmsketch@0.2.4" + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#codespan-reporting@0.13.1", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#serde@1.0.228", + "registry+https://github.com/rust-lang/crates.io-index#termcolor@1.4.1", + "registry+https://github.com/rust-lang/crates.io-index#unicode-width@0.2.0" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#colorchoice@1.0.5" + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#colored@3.1.1", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#windows-sys@0.61.2" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#compact_str@0.8.1", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#castaway@0.2.4", + "registry+https://github.com/rust-lang/crates.io-index#cfg-if@1.0.4", + "registry+https://github.com/rust-lang/crates.io-index#itoa@1.0.18", + "registry+https://github.com/rust-lang/crates.io-index#rustversion@1.0.22", + "registry+https://github.com/rust-lang/crates.io-index#ryu@1.0.23", + "registry+https://github.com/rust-lang/crates.io-index#static_assertions@1.1.0" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#concurrent-queue@2.5.0", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#crossbeam-utils@0.8.21" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#console@0.15.11", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#encode_unicode@1.0.0", + "registry+https://github.com/rust-lang/crates.io-index#libc@0.2.183", + "registry+https://github.com/rust-lang/crates.io-index#once_cell@1.21.4", + "registry+https://github.com/rust-lang/crates.io-index#unicode-width@0.2.0", + "registry+https://github.com/rust-lang/crates.io-index#windows-sys@0.59.0" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#const-oid@0.9.6" + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#const-random-macro@0.1.16", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#getrandom@0.2.17", + "registry+https://github.com/rust-lang/crates.io-index#once_cell@1.21.4", + "registry+https://github.com/rust-lang/crates.io-index#tiny-keccak@2.0.2" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#const-random@0.1.18", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#const-random-macro@0.1.16" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#constant_time_eq@0.4.2" + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#convert_case@0.10.0", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#unicode-segmentation@1.12.0" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#cpufeatures@0.2.17" + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#cpufeatures@0.3.0" + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#crc-catalog@2.4.0" + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#crc-fast@1.6.0", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#crc@3.4.0", + "registry+https://github.com/rust-lang/crates.io-index#digest@0.10.7", + "registry+https://github.com/rust-lang/crates.io-index#rand@0.9.2", + "registry+https://github.com/rust-lang/crates.io-index#regex@1.12.3", + "registry+https://github.com/rust-lang/crates.io-index#rustversion@1.0.22" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#crc32fast@1.5.0", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#cfg-if@1.0.4" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#crc@3.4.0", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#crc-catalog@2.4.0" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#criterion-plot@0.6.0", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#cast@0.3.0", + "registry+https://github.com/rust-lang/crates.io-index#itertools@0.13.0" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#criterion@0.7.0", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#anes@0.1.6", + "registry+https://github.com/rust-lang/crates.io-index#cast@0.3.0", + "registry+https://github.com/rust-lang/crates.io-index#ciborium@0.2.2", + "registry+https://github.com/rust-lang/crates.io-index#clap@4.6.0", + "registry+https://github.com/rust-lang/crates.io-index#criterion-plot@0.6.0", + "registry+https://github.com/rust-lang/crates.io-index#itertools@0.13.0", + "registry+https://github.com/rust-lang/crates.io-index#num-traits@0.2.19", + "registry+https://github.com/rust-lang/crates.io-index#oorandom@11.1.5", + "registry+https://github.com/rust-lang/crates.io-index#plotters@0.3.7", + "registry+https://github.com/rust-lang/crates.io-index#rayon@1.11.0", + "registry+https://github.com/rust-lang/crates.io-index#regex@1.12.3", + "registry+https://github.com/rust-lang/crates.io-index#serde@1.0.228", + "registry+https://github.com/rust-lang/crates.io-index#serde_json@1.0.149", + "registry+https://github.com/rust-lang/crates.io-index#tinytemplate@1.2.1", + "registry+https://github.com/rust-lang/crates.io-index#tokio@1.50.0", + "registry+https://github.com/rust-lang/crates.io-index#walkdir@2.5.0" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#crossbeam-channel@0.5.15", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#crossbeam-utils@0.8.21" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#crossbeam-deque@0.8.6", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#crossbeam-epoch@0.9.18", + "registry+https://github.com/rust-lang/crates.io-index#crossbeam-utils@0.8.21" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#crossbeam-epoch@0.9.18", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#crossbeam-utils@0.8.21" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#crossbeam-queue@0.3.12", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#crossbeam-utils@0.8.21" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#crossbeam-utils@0.8.21" + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#crossterm@0.28.1", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#bitflags@2.11.0", + "registry+https://github.com/rust-lang/crates.io-index#crossterm_winapi@0.9.1", + "registry+https://github.com/rust-lang/crates.io-index#parking_lot@0.12.5", + "registry+https://github.com/rust-lang/crates.io-index#winapi@0.3.9" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#crossterm@0.29.0", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#bitflags@2.11.0", + "registry+https://github.com/rust-lang/crates.io-index#crossterm_winapi@0.9.1", + "registry+https://github.com/rust-lang/crates.io-index#derive_more@2.1.1", + "registry+https://github.com/rust-lang/crates.io-index#document-features@0.2.12", + "registry+https://github.com/rust-lang/crates.io-index#futures-core@0.3.32", + "registry+https://github.com/rust-lang/crates.io-index#parking_lot@0.12.5", + "registry+https://github.com/rust-lang/crates.io-index#winapi@0.3.9" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#crossterm_winapi@0.9.1", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#winapi@0.3.9" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#crunchy@0.2.4" + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#crypto-bigint@0.4.9", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#generic-array@0.14.7", + "registry+https://github.com/rust-lang/crates.io-index#rand_core@0.6.4", + "registry+https://github.com/rust-lang/crates.io-index#subtle@2.6.1", + "registry+https://github.com/rust-lang/crates.io-index#zeroize@1.8.2" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#crypto-bigint@0.5.5", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#rand_core@0.6.4", + "registry+https://github.com/rust-lang/crates.io-index#subtle@2.6.1" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#crypto-common@0.1.7", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#generic-array@0.14.7", + "registry+https://github.com/rust-lang/crates.io-index#typenum@1.19.0" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#csv-core@0.1.13", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#memchr@2.8.0" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#csv@1.4.0", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#csv-core@0.1.13", + "registry+https://github.com/rust-lang/crates.io-index#itoa@1.0.18", + "registry+https://github.com/rust-lang/crates.io-index#ryu@1.0.23", + "registry+https://github.com/rust-lang/crates.io-index#serde_core@1.0.228" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#cxx-build@1.0.194", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#cc@1.2.57", + "registry+https://github.com/rust-lang/crates.io-index#codespan-reporting@0.13.1", + "registry+https://github.com/rust-lang/crates.io-index#indexmap@2.13.0", + "registry+https://github.com/rust-lang/crates.io-index#proc-macro2@1.0.106", + "registry+https://github.com/rust-lang/crates.io-index#quote@1.0.45", + "registry+https://github.com/rust-lang/crates.io-index#scratch@1.0.9", + "registry+https://github.com/rust-lang/crates.io-index#syn@2.0.117" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#cxx@1.0.194", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#cc@1.2.57", + "registry+https://github.com/rust-lang/crates.io-index#cxxbridge-flags@1.0.194", + "registry+https://github.com/rust-lang/crates.io-index#cxxbridge-macro@1.0.194", + "registry+https://github.com/rust-lang/crates.io-index#foldhash@0.2.0", + "registry+https://github.com/rust-lang/crates.io-index#link-cplusplus@1.0.12" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#cxxbridge-flags@1.0.194" + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#cxxbridge-macro@1.0.194", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#indexmap@2.13.0", + "registry+https://github.com/rust-lang/crates.io-index#proc-macro2@1.0.106", + "registry+https://github.com/rust-lang/crates.io-index#quote@1.0.45", + "registry+https://github.com/rust-lang/crates.io-index#syn@2.0.117" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#darling@0.20.11", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#darling_core@0.20.11", + "registry+https://github.com/rust-lang/crates.io-index#darling_macro@0.20.11" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#darling@0.23.0", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#darling_core@0.23.0", + "registry+https://github.com/rust-lang/crates.io-index#darling_macro@0.23.0" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#darling_core@0.20.11", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#fnv@1.0.7", + "registry+https://github.com/rust-lang/crates.io-index#ident_case@1.0.1", + "registry+https://github.com/rust-lang/crates.io-index#proc-macro2@1.0.106", + "registry+https://github.com/rust-lang/crates.io-index#quote@1.0.45", + "registry+https://github.com/rust-lang/crates.io-index#strsim@0.11.1", + "registry+https://github.com/rust-lang/crates.io-index#syn@2.0.117" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#darling_core@0.23.0", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#ident_case@1.0.1", + "registry+https://github.com/rust-lang/crates.io-index#proc-macro2@1.0.106", + "registry+https://github.com/rust-lang/crates.io-index#quote@1.0.45", + "registry+https://github.com/rust-lang/crates.io-index#strsim@0.11.1", + "registry+https://github.com/rust-lang/crates.io-index#syn@2.0.117" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#darling_macro@0.20.11", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#darling_core@0.20.11", + "registry+https://github.com/rust-lang/crates.io-index#quote@1.0.45", + "registry+https://github.com/rust-lang/crates.io-index#syn@2.0.117" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#darling_macro@0.23.0", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#darling_core@0.23.0", + "registry+https://github.com/rust-lang/crates.io-index#quote@1.0.45", + "registry+https://github.com/rust-lang/crates.io-index#syn@2.0.117" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#dashmap@6.1.0", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#cfg-if@1.0.4", + "registry+https://github.com/rust-lang/crates.io-index#crossbeam-utils@0.8.21", + "registry+https://github.com/rust-lang/crates.io-index#hashbrown@0.14.5", + "registry+https://github.com/rust-lang/crates.io-index#lock_api@0.4.14", + "registry+https://github.com/rust-lang/crates.io-index#once_cell@1.21.4", + "registry+https://github.com/rust-lang/crates.io-index#parking_lot_core@0.9.12" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#defer@0.2.1" + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#deflate64@0.1.11" + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#der@0.6.1", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#const-oid@0.9.6", + "registry+https://github.com/rust-lang/crates.io-index#zeroize@1.8.2" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#der@0.7.10", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#const-oid@0.9.6", + "registry+https://github.com/rust-lang/crates.io-index#pem-rfc7468@0.7.0", + "registry+https://github.com/rust-lang/crates.io-index#zeroize@1.8.2" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#deranged@0.5.8", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#powerfmt@0.2.0", + "registry+https://github.com/rust-lang/crates.io-index#serde_core@1.0.228" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#derivative@2.2.0", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#proc-macro2@1.0.106", + "registry+https://github.com/rust-lang/crates.io-index#quote@1.0.45", + "registry+https://github.com/rust-lang/crates.io-index#syn@1.0.109" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#derive_more-impl@2.1.1", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#convert_case@0.10.0", + "registry+https://github.com/rust-lang/crates.io-index#proc-macro2@1.0.106", + "registry+https://github.com/rust-lang/crates.io-index#quote@1.0.45", + "registry+https://github.com/rust-lang/crates.io-index#rustc_version@0.4.1", + "registry+https://github.com/rust-lang/crates.io-index#syn@2.0.117" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#derive_more@2.1.1", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#derive_more-impl@2.1.1" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#derive_utils@0.15.1", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#proc-macro2@1.0.106", + "registry+https://github.com/rust-lang/crates.io-index#quote@1.0.45", + "registry+https://github.com/rust-lang/crates.io-index#syn@2.0.117" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#dialoguer@0.11.0", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#console@0.15.11", + "registry+https://github.com/rust-lang/crates.io-index#shell-words@1.1.1", + "registry+https://github.com/rust-lang/crates.io-index#tempfile@3.27.0", + "registry+https://github.com/rust-lang/crates.io-index#thiserror@1.0.69", + "registry+https://github.com/rust-lang/crates.io-index#zeroize@1.8.2" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#digest@0.10.7", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#block-buffer@0.10.4", + "registry+https://github.com/rust-lang/crates.io-index#const-oid@0.9.6", + "registry+https://github.com/rust-lang/crates.io-index#crypto-common@0.1.7", + "registry+https://github.com/rust-lang/crates.io-index#subtle@2.6.1" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#dirs-sys@0.5.0", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#option-ext@0.2.0", + "registry+https://github.com/rust-lang/crates.io-index#windows-sys@0.61.2" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#dirs@6.0.0", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#dirs-sys@0.5.0" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#displaydoc@0.2.5", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#proc-macro2@1.0.106", + "registry+https://github.com/rust-lang/crates.io-index#quote@1.0.45", + "registry+https://github.com/rust-lang/crates.io-index#syn@2.0.117" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#document-features@0.2.12", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#litrs@1.0.0" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#dotenvy@0.15.7" + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#downcast-rs@1.2.1" + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#dunce@1.0.5" + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#dyn-clone@1.0.20" + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#dyn-stack-macros@0.1.3" + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#dyn-stack@0.13.2", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#bytemuck@1.25.0", + "registry+https://github.com/rust-lang/crates.io-index#dyn-stack-macros@0.1.3" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#ecdsa@0.14.8", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#der@0.6.1", + "registry+https://github.com/rust-lang/crates.io-index#elliptic-curve@0.12.3", + "registry+https://github.com/rust-lang/crates.io-index#rfc6979@0.3.1", + "registry+https://github.com/rust-lang/crates.io-index#signature@1.6.4" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#either@1.15.0", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#serde@1.0.228" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#elliptic-curve@0.12.3", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#base16ct@0.1.1", + "registry+https://github.com/rust-lang/crates.io-index#crypto-bigint@0.4.9", + "registry+https://github.com/rust-lang/crates.io-index#der@0.6.1", + "registry+https://github.com/rust-lang/crates.io-index#digest@0.10.7", + "registry+https://github.com/rust-lang/crates.io-index#ff@0.12.1", + "registry+https://github.com/rust-lang/crates.io-index#generic-array@0.14.7", + "registry+https://github.com/rust-lang/crates.io-index#group@0.12.1", + "registry+https://github.com/rust-lang/crates.io-index#pkcs8@0.9.0", + "registry+https://github.com/rust-lang/crates.io-index#rand_core@0.6.4", + "registry+https://github.com/rust-lang/crates.io-index#sec1@0.3.0", + "registry+https://github.com/rust-lang/crates.io-index#subtle@2.6.1", + "registry+https://github.com/rust-lang/crates.io-index#zeroize@1.8.2" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#encode_unicode@1.0.0" + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#encoding_rs@0.8.35", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#cfg-if@1.0.4" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#equator-macro@0.2.1", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#proc-macro2@1.0.106", + "registry+https://github.com/rust-lang/crates.io-index#quote@1.0.45", + "registry+https://github.com/rust-lang/crates.io-index#syn@2.0.117" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#equator-macro@0.6.0" + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#equator@0.2.2", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#equator-macro@0.2.1" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#equator@0.6.0", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#equator-macro@0.6.0" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#equivalent@1.0.2" + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#error-code@3.3.2" + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#etcetera@0.8.0", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#cfg-if@1.0.4", + "registry+https://github.com/rust-lang/crates.io-index#home@0.5.12", + "registry+https://github.com/rust-lang/crates.io-index#windows-sys@0.48.0" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#event-listener@5.4.1", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#concurrent-queue@2.5.0", + "registry+https://github.com/rust-lang/crates.io-index#parking@2.2.1", + "registry+https://github.com/rust-lang/crates.io-index#pin-project-lite@0.2.17" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#faer-traits@0.24.0", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#bytemuck@1.25.0", + "registry+https://github.com/rust-lang/crates.io-index#dyn-stack@0.13.2", + "registry+https://github.com/rust-lang/crates.io-index#generativity@1.1.0", + "registry+https://github.com/rust-lang/crates.io-index#libm@0.2.16", + "registry+https://github.com/rust-lang/crates.io-index#num-complex@0.4.6", + "registry+https://github.com/rust-lang/crates.io-index#num-traits@0.2.19", + "registry+https://github.com/rust-lang/crates.io-index#pulp@0.22.2", + "registry+https://github.com/rust-lang/crates.io-index#qd@0.8.0", + "registry+https://github.com/rust-lang/crates.io-index#reborrow@0.5.5" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#faer@0.24.0", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#bytemuck@1.25.0", + "registry+https://github.com/rust-lang/crates.io-index#dyn-stack@0.13.2", + "registry+https://github.com/rust-lang/crates.io-index#equator@0.6.0", + "registry+https://github.com/rust-lang/crates.io-index#faer-traits@0.24.0", + "registry+https://github.com/rust-lang/crates.io-index#gemm@0.19.0", + "registry+https://github.com/rust-lang/crates.io-index#generativity@1.1.0", + "registry+https://github.com/rust-lang/crates.io-index#libm@0.2.16", + "registry+https://github.com/rust-lang/crates.io-index#nano-gemm@0.2.2", + "registry+https://github.com/rust-lang/crates.io-index#num-complex@0.4.6", + "registry+https://github.com/rust-lang/crates.io-index#num-traits@0.2.19", + "registry+https://github.com/rust-lang/crates.io-index#private-gemm-x86@0.1.20", + "registry+https://github.com/rust-lang/crates.io-index#pulp@0.22.2", + "registry+https://github.com/rust-lang/crates.io-index#rand@0.9.2", + "registry+https://github.com/rust-lang/crates.io-index#rand_distr@0.5.1", + "registry+https://github.com/rust-lang/crates.io-index#reborrow@0.5.5" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#failsafe@1.3.0", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#futures-core@0.3.32", + "registry+https://github.com/rust-lang/crates.io-index#parking_lot@0.12.5", + "registry+https://github.com/rust-lang/crates.io-index#pin-project@1.1.11", + "registry+https://github.com/rust-lang/crates.io-index#rand@0.8.5" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#fastant@0.1.11", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#small_ctor@0.1.2", + "registry+https://github.com/rust-lang/crates.io-index#web-time@1.1.0" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#fastbloom@0.17.0", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#foldhash@0.2.0", + "registry+https://github.com/rust-lang/crates.io-index#libm@0.2.16", + "registry+https://github.com/rust-lang/crates.io-index#portable-atomic@1.13.1", + "registry+https://github.com/rust-lang/crates.io-index#rand@0.9.2", + "registry+https://github.com/rust-lang/crates.io-index#serde@1.0.228", + "registry+https://github.com/rust-lang/crates.io-index#siphasher@1.0.2" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#fastdivide@0.4.2" + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#fastrace-macro@0.7.17", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#proc-macro-error2@2.0.1", + "registry+https://github.com/rust-lang/crates.io-index#proc-macro2@1.0.106", + "registry+https://github.com/rust-lang/crates.io-index#quote@1.0.45", + "registry+https://github.com/rust-lang/crates.io-index#syn@2.0.117" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#fastrace-opentelemetry@0.8.1", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#fastrace@0.7.8", + "registry+https://github.com/rust-lang/crates.io-index#log@0.4.29", + "registry+https://github.com/rust-lang/crates.io-index#opentelemetry@0.27.1", + "registry+https://github.com/rust-lang/crates.io-index#opentelemetry_sdk@0.27.1", + "registry+https://github.com/rust-lang/crates.io-index#pollster@0.4.0" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#fastrace@0.7.8", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#fastant@0.1.11", + "registry+https://github.com/rust-lang/crates.io-index#fastrace-macro@0.7.17", + "registry+https://github.com/rust-lang/crates.io-index#once_cell@1.21.4", + "registry+https://github.com/rust-lang/crates.io-index#parking_lot@0.12.5", + "registry+https://github.com/rust-lang/crates.io-index#pin-project@1.1.11", + "registry+https://github.com/rust-lang/crates.io-index#rand@0.9.2", + "registry+https://github.com/rust-lang/crates.io-index#rtrb@0.3.3", + "registry+https://github.com/rust-lang/crates.io-index#serde@1.0.228" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#fastrand@2.3.0" + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#fax@0.2.6", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#fax_derive@0.2.0" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#fax_derive@0.2.0", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#proc-macro2@1.0.106", + "registry+https://github.com/rust-lang/crates.io-index#quote@1.0.45", + "registry+https://github.com/rust-lang/crates.io-index#syn@2.0.117" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#fdeflate@0.3.7", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#simd-adler32@0.3.8" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#ff@0.12.1", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#rand_core@0.6.4", + "registry+https://github.com/rust-lang/crates.io-index#subtle@2.6.1" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#figment@0.10.19", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#parking_lot@0.12.5", + "registry+https://github.com/rust-lang/crates.io-index#pear@0.2.9", + "registry+https://github.com/rust-lang/crates.io-index#serde@1.0.228", + "registry+https://github.com/rust-lang/crates.io-index#serde_yaml@0.9.34+deprecated", + "registry+https://github.com/rust-lang/crates.io-index#tempfile@3.27.0", + "registry+https://github.com/rust-lang/crates.io-index#uncased@0.9.10", + "registry+https://github.com/rust-lang/crates.io-index#version_check@0.9.5" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#find-msvc-tools@0.1.9" + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#fixedbitset@0.5.7" + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#flatbuffers@25.12.19", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#bitflags@2.11.0", + "registry+https://github.com/rust-lang/crates.io-index#rustc_version@0.4.1" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#flate2@1.1.9", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#crc32fast@1.5.0", + "registry+https://github.com/rust-lang/crates.io-index#miniz_oxide@0.8.9", + "registry+https://github.com/rust-lang/crates.io-index#zlib-rs@0.6.3" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#flume@0.11.1", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#futures-core@0.3.32", + "registry+https://github.com/rust-lang/crates.io-index#futures-sink@0.3.32", + "registry+https://github.com/rust-lang/crates.io-index#nanorand@0.7.0", + "registry+https://github.com/rust-lang/crates.io-index#spin@0.9.8" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#fnv@1.0.7" + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#foldhash@0.1.5" + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#foldhash@0.2.0" + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#form_urlencoded@1.2.2", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#percent-encoding@2.3.2" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#foyer-common@0.17.4", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#bincode@1.3.3", + "registry+https://github.com/rust-lang/crates.io-index#bytes@1.11.1", + "registry+https://github.com/rust-lang/crates.io-index#cfg-if@1.0.4", + "registry+https://github.com/rust-lang/crates.io-index#fastrace@0.7.8", + "registry+https://github.com/rust-lang/crates.io-index#itertools@0.14.0", + "registry+https://github.com/rust-lang/crates.io-index#mixtrics@0.1.0", + "registry+https://github.com/rust-lang/crates.io-index#parking_lot@0.12.5", + "registry+https://github.com/rust-lang/crates.io-index#pin-project@1.1.11", + "registry+https://github.com/rust-lang/crates.io-index#serde@1.0.228", + "registry+https://github.com/rust-lang/crates.io-index#thiserror@2.0.18", + "registry+https://github.com/rust-lang/crates.io-index#tokio@1.50.0", + "registry+https://github.com/rust-lang/crates.io-index#twox-hash@2.1.2" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#foyer-intrusive-collections@0.10.0-dev", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#memoffset@0.9.1" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#foyer-memory@0.17.4", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#arc-swap@1.8.2", + "registry+https://github.com/rust-lang/crates.io-index#bitflags@2.11.0", + "registry+https://github.com/rust-lang/crates.io-index#cmsketch@0.2.4", + "registry+https://github.com/rust-lang/crates.io-index#equivalent@1.0.2", + "registry+https://github.com/rust-lang/crates.io-index#fastrace@0.7.8", + "registry+https://github.com/rust-lang/crates.io-index#foyer-common@0.17.4", + "registry+https://github.com/rust-lang/crates.io-index#foyer-intrusive-collections@0.10.0-dev", + "registry+https://github.com/rust-lang/crates.io-index#hashbrown@0.15.5", + "registry+https://github.com/rust-lang/crates.io-index#itertools@0.14.0", + "registry+https://github.com/rust-lang/crates.io-index#mixtrics@0.1.0", + "registry+https://github.com/rust-lang/crates.io-index#parking_lot@0.12.5", + "registry+https://github.com/rust-lang/crates.io-index#pin-project@1.1.11", + "registry+https://github.com/rust-lang/crates.io-index#serde@1.0.228", + "registry+https://github.com/rust-lang/crates.io-index#thiserror@2.0.18", + "registry+https://github.com/rust-lang/crates.io-index#tokio@1.50.0", + "registry+https://github.com/rust-lang/crates.io-index#tracing@0.1.44" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#foyer-storage@0.17.4", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#allocator-api2@0.2.21", + "registry+https://github.com/rust-lang/crates.io-index#anyhow@1.0.102", + "registry+https://github.com/rust-lang/crates.io-index#array-util@1.0.2", + "registry+https://github.com/rust-lang/crates.io-index#auto_enums@0.8.8", + "registry+https://github.com/rust-lang/crates.io-index#bytes@1.11.1", + "registry+https://github.com/rust-lang/crates.io-index#clap@4.6.0", + "registry+https://github.com/rust-lang/crates.io-index#equivalent@1.0.2", + "registry+https://github.com/rust-lang/crates.io-index#fastrace@0.7.8", + "registry+https://github.com/rust-lang/crates.io-index#flume@0.11.1", + "registry+https://github.com/rust-lang/crates.io-index#foyer-common@0.17.4", + "registry+https://github.com/rust-lang/crates.io-index#foyer-memory@0.17.4", + "registry+https://github.com/rust-lang/crates.io-index#fs4@0.13.1", + "registry+https://github.com/rust-lang/crates.io-index#futures-core@0.3.32", + "registry+https://github.com/rust-lang/crates.io-index#futures-util@0.3.32", + "registry+https://github.com/rust-lang/crates.io-index#itertools@0.14.0", + "registry+https://github.com/rust-lang/crates.io-index#libc@0.2.183", + "registry+https://github.com/rust-lang/crates.io-index#lz4@1.28.1", + "registry+https://github.com/rust-lang/crates.io-index#ordered_hash_map@0.4.0", + "registry+https://github.com/rust-lang/crates.io-index#parking_lot@0.12.5", + "registry+https://github.com/rust-lang/crates.io-index#paste@1.0.15", + "registry+https://github.com/rust-lang/crates.io-index#pin-project@1.1.11", + "registry+https://github.com/rust-lang/crates.io-index#rand@0.9.2", + "registry+https://github.com/rust-lang/crates.io-index#serde@1.0.228", + "registry+https://github.com/rust-lang/crates.io-index#thiserror@2.0.18", + "registry+https://github.com/rust-lang/crates.io-index#tokio@1.50.0", + "registry+https://github.com/rust-lang/crates.io-index#tracing@0.1.44", + "registry+https://github.com/rust-lang/crates.io-index#twox-hash@2.1.2", + "registry+https://github.com/rust-lang/crates.io-index#zstd@0.13.3" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#foyer@0.17.4", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#anyhow@1.0.102", + "registry+https://github.com/rust-lang/crates.io-index#equivalent@1.0.2", + "registry+https://github.com/rust-lang/crates.io-index#fastrace@0.7.8", + "registry+https://github.com/rust-lang/crates.io-index#foyer-common@0.17.4", + "registry+https://github.com/rust-lang/crates.io-index#foyer-memory@0.17.4", + "registry+https://github.com/rust-lang/crates.io-index#foyer-storage@0.17.4", + "registry+https://github.com/rust-lang/crates.io-index#mixtrics@0.1.0", + "registry+https://github.com/rust-lang/crates.io-index#pin-project@1.1.11", + "registry+https://github.com/rust-lang/crates.io-index#serde@1.0.228", + "registry+https://github.com/rust-lang/crates.io-index#tokio@1.50.0", + "registry+https://github.com/rust-lang/crates.io-index#tracing@0.1.44" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#fs4@0.13.1", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#windows-sys@0.59.0" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#fs4@0.8.4", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#windows-sys@0.52.0" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#fs_extra@1.3.0" + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#funty@2.0.0" + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#futures-channel@0.3.32", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#futures-core@0.3.32", + "registry+https://github.com/rust-lang/crates.io-index#futures-sink@0.3.32" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#futures-core@0.3.32" + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#futures-executor@0.3.32", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#futures-core@0.3.32", + "registry+https://github.com/rust-lang/crates.io-index#futures-task@0.3.32", + "registry+https://github.com/rust-lang/crates.io-index#futures-util@0.3.32" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#futures-intrusive@0.5.0", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#futures-core@0.3.32", + "registry+https://github.com/rust-lang/crates.io-index#lock_api@0.4.14", + "registry+https://github.com/rust-lang/crates.io-index#parking_lot@0.12.5" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#futures-io@0.3.32" + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#futures-macro@0.3.32", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#proc-macro2@1.0.106", + "registry+https://github.com/rust-lang/crates.io-index#quote@1.0.45", + "registry+https://github.com/rust-lang/crates.io-index#syn@2.0.117" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#futures-sink@0.3.32" + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#futures-task@0.3.32" + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#futures-util@0.3.32", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#futures-channel@0.3.32", + "registry+https://github.com/rust-lang/crates.io-index#futures-core@0.3.32", + "registry+https://github.com/rust-lang/crates.io-index#futures-io@0.3.32", + "registry+https://github.com/rust-lang/crates.io-index#futures-macro@0.3.32", + "registry+https://github.com/rust-lang/crates.io-index#futures-sink@0.3.32", + "registry+https://github.com/rust-lang/crates.io-index#futures-task@0.3.32", + "registry+https://github.com/rust-lang/crates.io-index#memchr@2.8.0", + "registry+https://github.com/rust-lang/crates.io-index#pin-project-lite@0.2.17", + "registry+https://github.com/rust-lang/crates.io-index#slab@0.4.12" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#futures@0.3.32", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#futures-channel@0.3.32", + "registry+https://github.com/rust-lang/crates.io-index#futures-core@0.3.32", + "registry+https://github.com/rust-lang/crates.io-index#futures-executor@0.3.32", + "registry+https://github.com/rust-lang/crates.io-index#futures-io@0.3.32", + "registry+https://github.com/rust-lang/crates.io-index#futures-sink@0.3.32", + "registry+https://github.com/rust-lang/crates.io-index#futures-task@0.3.32", + "registry+https://github.com/rust-lang/crates.io-index#futures-util@0.3.32" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#gemm-c32@0.19.0", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#dyn-stack@0.13.2", + "registry+https://github.com/rust-lang/crates.io-index#gemm-common@0.19.0", + "registry+https://github.com/rust-lang/crates.io-index#num-complex@0.4.6", + "registry+https://github.com/rust-lang/crates.io-index#num-traits@0.2.19", + "registry+https://github.com/rust-lang/crates.io-index#paste@1.0.15", + "registry+https://github.com/rust-lang/crates.io-index#raw-cpuid@11.6.0", + "registry+https://github.com/rust-lang/crates.io-index#seq-macro@0.3.6" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#gemm-c64@0.19.0", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#dyn-stack@0.13.2", + "registry+https://github.com/rust-lang/crates.io-index#gemm-common@0.19.0", + "registry+https://github.com/rust-lang/crates.io-index#num-complex@0.4.6", + "registry+https://github.com/rust-lang/crates.io-index#num-traits@0.2.19", + "registry+https://github.com/rust-lang/crates.io-index#paste@1.0.15", + "registry+https://github.com/rust-lang/crates.io-index#raw-cpuid@11.6.0", + "registry+https://github.com/rust-lang/crates.io-index#seq-macro@0.3.6" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#gemm-common@0.19.0", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#bytemuck@1.25.0", + "registry+https://github.com/rust-lang/crates.io-index#dyn-stack@0.13.2", + "registry+https://github.com/rust-lang/crates.io-index#half@2.7.1", + "registry+https://github.com/rust-lang/crates.io-index#libm@0.2.16", + "registry+https://github.com/rust-lang/crates.io-index#num-complex@0.4.6", + "registry+https://github.com/rust-lang/crates.io-index#num-traits@0.2.19", + "registry+https://github.com/rust-lang/crates.io-index#once_cell@1.21.4", + "registry+https://github.com/rust-lang/crates.io-index#paste@1.0.15", + "registry+https://github.com/rust-lang/crates.io-index#pulp@0.22.2", + "registry+https://github.com/rust-lang/crates.io-index#raw-cpuid@11.6.0", + "registry+https://github.com/rust-lang/crates.io-index#seq-macro@0.3.6" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#gemm-f16@0.19.0", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#dyn-stack@0.13.2", + "registry+https://github.com/rust-lang/crates.io-index#gemm-common@0.19.0", + "registry+https://github.com/rust-lang/crates.io-index#gemm-f32@0.19.0", + "registry+https://github.com/rust-lang/crates.io-index#half@2.7.1", + "registry+https://github.com/rust-lang/crates.io-index#num-complex@0.4.6", + "registry+https://github.com/rust-lang/crates.io-index#num-traits@0.2.19", + "registry+https://github.com/rust-lang/crates.io-index#paste@1.0.15", + "registry+https://github.com/rust-lang/crates.io-index#raw-cpuid@11.6.0", + "registry+https://github.com/rust-lang/crates.io-index#seq-macro@0.3.6" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#gemm-f32@0.19.0", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#dyn-stack@0.13.2", + "registry+https://github.com/rust-lang/crates.io-index#gemm-common@0.19.0", + "registry+https://github.com/rust-lang/crates.io-index#num-complex@0.4.6", + "registry+https://github.com/rust-lang/crates.io-index#num-traits@0.2.19", + "registry+https://github.com/rust-lang/crates.io-index#paste@1.0.15", + "registry+https://github.com/rust-lang/crates.io-index#raw-cpuid@11.6.0", + "registry+https://github.com/rust-lang/crates.io-index#seq-macro@0.3.6" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#gemm-f64@0.19.0", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#dyn-stack@0.13.2", + "registry+https://github.com/rust-lang/crates.io-index#gemm-common@0.19.0", + "registry+https://github.com/rust-lang/crates.io-index#num-complex@0.4.6", + "registry+https://github.com/rust-lang/crates.io-index#num-traits@0.2.19", + "registry+https://github.com/rust-lang/crates.io-index#paste@1.0.15", + "registry+https://github.com/rust-lang/crates.io-index#raw-cpuid@11.6.0", + "registry+https://github.com/rust-lang/crates.io-index#seq-macro@0.3.6" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#gemm@0.19.0", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#dyn-stack@0.13.2", + "registry+https://github.com/rust-lang/crates.io-index#gemm-c32@0.19.0", + "registry+https://github.com/rust-lang/crates.io-index#gemm-c64@0.19.0", + "registry+https://github.com/rust-lang/crates.io-index#gemm-common@0.19.0", + "registry+https://github.com/rust-lang/crates.io-index#gemm-f16@0.19.0", + "registry+https://github.com/rust-lang/crates.io-index#gemm-f32@0.19.0", + "registry+https://github.com/rust-lang/crates.io-index#gemm-f64@0.19.0", + "registry+https://github.com/rust-lang/crates.io-index#num-complex@0.4.6", + "registry+https://github.com/rust-lang/crates.io-index#num-traits@0.2.19", + "registry+https://github.com/rust-lang/crates.io-index#paste@1.0.15", + "registry+https://github.com/rust-lang/crates.io-index#raw-cpuid@11.6.0", + "registry+https://github.com/rust-lang/crates.io-index#seq-macro@0.3.6" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#generativity@1.1.0" + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#generator@0.8.8", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#cc@1.2.57", + "registry+https://github.com/rust-lang/crates.io-index#cfg-if@1.0.4", + "registry+https://github.com/rust-lang/crates.io-index#log@0.4.29", + "registry+https://github.com/rust-lang/crates.io-index#rustversion@1.0.22", + "registry+https://github.com/rust-lang/crates.io-index#windows-link@0.2.1", + "registry+https://github.com/rust-lang/crates.io-index#windows-result@0.4.1" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#generic-array@0.14.7", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#typenum@1.19.0", + "registry+https://github.com/rust-lang/crates.io-index#version_check@0.9.5" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#getrandom@0.2.17", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#cfg-if@1.0.4" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#getrandom@0.3.4", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#cfg-if@1.0.4" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#getrandom@0.4.2", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#cfg-if@1.0.4", + "registry+https://github.com/rust-lang/crates.io-index#rand_core@0.10.0" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#glob@0.3.3" + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#globset@0.4.18", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#aho-corasick@1.1.4", + "registry+https://github.com/rust-lang/crates.io-index#bstr@1.12.1", + "registry+https://github.com/rust-lang/crates.io-index#log@0.4.29", + "registry+https://github.com/rust-lang/crates.io-index#regex-automata@0.4.14", + "registry+https://github.com/rust-lang/crates.io-index#regex-syntax@0.8.10" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#group@0.12.1", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#ff@0.12.1", + "registry+https://github.com/rust-lang/crates.io-index#rand_core@0.6.4", + "registry+https://github.com/rust-lang/crates.io-index#subtle@2.6.1" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#h2@0.3.27", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#bytes@1.11.1", + "registry+https://github.com/rust-lang/crates.io-index#fnv@1.0.7", + "registry+https://github.com/rust-lang/crates.io-index#futures-core@0.3.32", + "registry+https://github.com/rust-lang/crates.io-index#futures-sink@0.3.32", + "registry+https://github.com/rust-lang/crates.io-index#futures-util@0.3.32", + "registry+https://github.com/rust-lang/crates.io-index#http@0.2.12", + "registry+https://github.com/rust-lang/crates.io-index#indexmap@2.13.0", + "registry+https://github.com/rust-lang/crates.io-index#slab@0.4.12", + "registry+https://github.com/rust-lang/crates.io-index#tokio@1.50.0", + "registry+https://github.com/rust-lang/crates.io-index#tokio-util@0.7.18", + "registry+https://github.com/rust-lang/crates.io-index#tracing@0.1.44" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#h2@0.4.13", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#atomic-waker@1.1.2", + "registry+https://github.com/rust-lang/crates.io-index#bytes@1.11.1", + "registry+https://github.com/rust-lang/crates.io-index#fnv@1.0.7", + "registry+https://github.com/rust-lang/crates.io-index#futures-core@0.3.32", + "registry+https://github.com/rust-lang/crates.io-index#futures-sink@0.3.32", + "registry+https://github.com/rust-lang/crates.io-index#http@1.4.0", + "registry+https://github.com/rust-lang/crates.io-index#indexmap@2.13.0", + "registry+https://github.com/rust-lang/crates.io-index#slab@0.4.12", + "registry+https://github.com/rust-lang/crates.io-index#tokio@1.50.0", + "registry+https://github.com/rust-lang/crates.io-index#tokio-util@0.7.18", + "registry+https://github.com/rust-lang/crates.io-index#tracing@0.1.44" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#half@2.7.1", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#bytemuck@1.25.0", + "registry+https://github.com/rust-lang/crates.io-index#cfg-if@1.0.4", + "registry+https://github.com/rust-lang/crates.io-index#num-traits@0.2.19", + "registry+https://github.com/rust-lang/crates.io-index#zerocopy@0.8.47" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#hashbrown@0.12.3" + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#hashbrown@0.13.2", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#ahash@0.8.12" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#hashbrown@0.14.5", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#ahash@0.8.12", + "registry+https://github.com/rust-lang/crates.io-index#allocator-api2@0.2.21" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#hashbrown@0.15.5", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#allocator-api2@0.2.21", + "registry+https://github.com/rust-lang/crates.io-index#equivalent@1.0.2", + "registry+https://github.com/rust-lang/crates.io-index#foldhash@0.1.5" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#hashbrown@0.16.1" + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#hashlink@0.10.0", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#hashbrown@0.15.5" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#heck@0.4.1" + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#heck@0.5.0" + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#hex@0.4.3" + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#hkdf@0.12.4", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#hmac@0.12.1" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#hmac@0.12.1", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#digest@0.10.7" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#home@0.5.12", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#windows-sys@0.61.2" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#htmlescape@0.3.1" + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#http-body-util@0.1.3", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#bytes@1.11.1", + "registry+https://github.com/rust-lang/crates.io-index#futures-core@0.3.32", + "registry+https://github.com/rust-lang/crates.io-index#http@1.4.0", + "registry+https://github.com/rust-lang/crates.io-index#http-body@1.0.1", + "registry+https://github.com/rust-lang/crates.io-index#pin-project-lite@0.2.17" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#http-body@0.4.6", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#bytes@1.11.1", + "registry+https://github.com/rust-lang/crates.io-index#http@0.2.12", + "registry+https://github.com/rust-lang/crates.io-index#pin-project-lite@0.2.17" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#http-body@1.0.1", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#bytes@1.11.1", + "registry+https://github.com/rust-lang/crates.io-index#http@1.4.0" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#http-range-header@0.3.1" + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#http@0.2.12", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#bytes@1.11.1", + "registry+https://github.com/rust-lang/crates.io-index#fnv@1.0.7", + "registry+https://github.com/rust-lang/crates.io-index#itoa@1.0.18" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#http@1.4.0", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#bytes@1.11.1", + "registry+https://github.com/rust-lang/crates.io-index#itoa@1.0.18" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#httparse@1.10.1" + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#httpdate@1.0.3" + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#humantime@2.3.0" + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#hyper-rustls@0.24.2", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#futures-util@0.3.32", + "registry+https://github.com/rust-lang/crates.io-index#http@0.2.12", + "registry+https://github.com/rust-lang/crates.io-index#hyper@0.14.32", + "registry+https://github.com/rust-lang/crates.io-index#log@0.4.29", + "registry+https://github.com/rust-lang/crates.io-index#rustls@0.21.12", + "registry+https://github.com/rust-lang/crates.io-index#rustls-native-certs@0.6.3", + "registry+https://github.com/rust-lang/crates.io-index#tokio@1.50.0", + "registry+https://github.com/rust-lang/crates.io-index#tokio-rustls@0.24.1" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#hyper-rustls@0.27.7", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#http@1.4.0", + "registry+https://github.com/rust-lang/crates.io-index#hyper@1.8.1", + "registry+https://github.com/rust-lang/crates.io-index#hyper-util@0.1.20", + "registry+https://github.com/rust-lang/crates.io-index#rustls@0.23.37", + "registry+https://github.com/rust-lang/crates.io-index#rustls-native-certs@0.8.3", + "registry+https://github.com/rust-lang/crates.io-index#rustls-pki-types@1.14.0", + "registry+https://github.com/rust-lang/crates.io-index#tokio@1.50.0", + "registry+https://github.com/rust-lang/crates.io-index#tokio-rustls@0.26.4", + "registry+https://github.com/rust-lang/crates.io-index#tower-service@0.3.3", + "registry+https://github.com/rust-lang/crates.io-index#webpki-roots@1.0.6" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#hyper-timeout@0.4.1", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#hyper@0.14.32", + "registry+https://github.com/rust-lang/crates.io-index#pin-project-lite@0.2.17", + "registry+https://github.com/rust-lang/crates.io-index#tokio@1.50.0", + "registry+https://github.com/rust-lang/crates.io-index#tokio-io-timeout@1.2.1" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#hyper-timeout@0.5.2", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#hyper@1.8.1", + "registry+https://github.com/rust-lang/crates.io-index#hyper-util@0.1.20", + "registry+https://github.com/rust-lang/crates.io-index#pin-project-lite@0.2.17", + "registry+https://github.com/rust-lang/crates.io-index#tokio@1.50.0", + "registry+https://github.com/rust-lang/crates.io-index#tower-service@0.3.3" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#hyper-tls@0.6.0", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#bytes@1.11.1", + "registry+https://github.com/rust-lang/crates.io-index#http-body-util@0.1.3", + "registry+https://github.com/rust-lang/crates.io-index#hyper@1.8.1", + "registry+https://github.com/rust-lang/crates.io-index#hyper-util@0.1.20", + "registry+https://github.com/rust-lang/crates.io-index#native-tls@0.2.18", + "registry+https://github.com/rust-lang/crates.io-index#tokio@1.50.0", + "registry+https://github.com/rust-lang/crates.io-index#tokio-native-tls@0.3.1", + "registry+https://github.com/rust-lang/crates.io-index#tower-service@0.3.3" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#hyper-util@0.1.20", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#base64@0.22.1", + "registry+https://github.com/rust-lang/crates.io-index#bytes@1.11.1", + "registry+https://github.com/rust-lang/crates.io-index#futures-channel@0.3.32", + "registry+https://github.com/rust-lang/crates.io-index#futures-util@0.3.32", + "registry+https://github.com/rust-lang/crates.io-index#http@1.4.0", + "registry+https://github.com/rust-lang/crates.io-index#http-body@1.0.1", + "registry+https://github.com/rust-lang/crates.io-index#hyper@1.8.1", + "registry+https://github.com/rust-lang/crates.io-index#ipnet@2.12.0", + "registry+https://github.com/rust-lang/crates.io-index#libc@0.2.183", + "registry+https://github.com/rust-lang/crates.io-index#percent-encoding@2.3.2", + "registry+https://github.com/rust-lang/crates.io-index#pin-project-lite@0.2.17", + "registry+https://github.com/rust-lang/crates.io-index#socket2@0.6.3", + "registry+https://github.com/rust-lang/crates.io-index#tokio@1.50.0", + "registry+https://github.com/rust-lang/crates.io-index#tower-service@0.3.3", + "registry+https://github.com/rust-lang/crates.io-index#tracing@0.1.44", + "registry+https://github.com/rust-lang/crates.io-index#windows-registry@0.6.1" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#hyper@0.14.32", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#bytes@1.11.1", + "registry+https://github.com/rust-lang/crates.io-index#futures-channel@0.3.32", + "registry+https://github.com/rust-lang/crates.io-index#futures-core@0.3.32", + "registry+https://github.com/rust-lang/crates.io-index#futures-util@0.3.32", + "registry+https://github.com/rust-lang/crates.io-index#h2@0.3.27", + "registry+https://github.com/rust-lang/crates.io-index#http@0.2.12", + "registry+https://github.com/rust-lang/crates.io-index#http-body@0.4.6", + "registry+https://github.com/rust-lang/crates.io-index#httparse@1.10.1", + "registry+https://github.com/rust-lang/crates.io-index#httpdate@1.0.3", + "registry+https://github.com/rust-lang/crates.io-index#itoa@1.0.18", + "registry+https://github.com/rust-lang/crates.io-index#pin-project-lite@0.2.17", + "registry+https://github.com/rust-lang/crates.io-index#socket2@0.5.10", + "registry+https://github.com/rust-lang/crates.io-index#tokio@1.50.0", + "registry+https://github.com/rust-lang/crates.io-index#tower-service@0.3.3", + "registry+https://github.com/rust-lang/crates.io-index#tracing@0.1.44", + "registry+https://github.com/rust-lang/crates.io-index#want@0.3.1" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#hyper@1.8.1", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#atomic-waker@1.1.2", + "registry+https://github.com/rust-lang/crates.io-index#bytes@1.11.1", + "registry+https://github.com/rust-lang/crates.io-index#futures-channel@0.3.32", + "registry+https://github.com/rust-lang/crates.io-index#futures-core@0.3.32", + "registry+https://github.com/rust-lang/crates.io-index#h2@0.4.13", + "registry+https://github.com/rust-lang/crates.io-index#http@1.4.0", + "registry+https://github.com/rust-lang/crates.io-index#http-body@1.0.1", + "registry+https://github.com/rust-lang/crates.io-index#httparse@1.10.1", + "registry+https://github.com/rust-lang/crates.io-index#httpdate@1.0.3", + "registry+https://github.com/rust-lang/crates.io-index#itoa@1.0.18", + "registry+https://github.com/rust-lang/crates.io-index#pin-project-lite@0.2.17", + "registry+https://github.com/rust-lang/crates.io-index#pin-utils@0.1.0", + "registry+https://github.com/rust-lang/crates.io-index#smallvec@1.15.1", + "registry+https://github.com/rust-lang/crates.io-index#tokio@1.50.0", + "registry+https://github.com/rust-lang/crates.io-index#want@0.3.1" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#icu_collections@2.1.1", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#displaydoc@0.2.5", + "registry+https://github.com/rust-lang/crates.io-index#potential_utf@0.1.4", + "registry+https://github.com/rust-lang/crates.io-index#yoke@0.8.1", + "registry+https://github.com/rust-lang/crates.io-index#zerofrom@0.1.6", + "registry+https://github.com/rust-lang/crates.io-index#zerovec@0.11.5" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#icu_locale_core@2.1.1", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#displaydoc@0.2.5", + "registry+https://github.com/rust-lang/crates.io-index#litemap@0.8.1", + "registry+https://github.com/rust-lang/crates.io-index#tinystr@0.8.2", + "registry+https://github.com/rust-lang/crates.io-index#writeable@0.6.2", + "registry+https://github.com/rust-lang/crates.io-index#zerovec@0.11.5" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#icu_normalizer@2.1.1", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#icu_collections@2.1.1", + "registry+https://github.com/rust-lang/crates.io-index#icu_normalizer_data@2.1.1", + "registry+https://github.com/rust-lang/crates.io-index#icu_properties@2.1.2", + "registry+https://github.com/rust-lang/crates.io-index#icu_provider@2.1.1", + "registry+https://github.com/rust-lang/crates.io-index#smallvec@1.15.1", + "registry+https://github.com/rust-lang/crates.io-index#zerovec@0.11.5" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#icu_normalizer_data@2.1.1" + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#icu_properties@2.1.2", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#icu_collections@2.1.1", + "registry+https://github.com/rust-lang/crates.io-index#icu_locale_core@2.1.1", + "registry+https://github.com/rust-lang/crates.io-index#icu_properties_data@2.1.2", + "registry+https://github.com/rust-lang/crates.io-index#icu_provider@2.1.1", + "registry+https://github.com/rust-lang/crates.io-index#zerotrie@0.2.3", + "registry+https://github.com/rust-lang/crates.io-index#zerovec@0.11.5" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#icu_properties_data@2.1.2" + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#icu_provider@2.1.1", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#displaydoc@0.2.5", + "registry+https://github.com/rust-lang/crates.io-index#icu_locale_core@2.1.1", + "registry+https://github.com/rust-lang/crates.io-index#writeable@0.6.2", + "registry+https://github.com/rust-lang/crates.io-index#yoke@0.8.1", + "registry+https://github.com/rust-lang/crates.io-index#zerofrom@0.1.6", + "registry+https://github.com/rust-lang/crates.io-index#zerotrie@0.2.3", + "registry+https://github.com/rust-lang/crates.io-index#zerovec@0.11.5" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#ident_case@1.0.1" + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#idna@1.1.0", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#idna_adapter@1.2.1", + "registry+https://github.com/rust-lang/crates.io-index#smallvec@1.15.1", + "registry+https://github.com/rust-lang/crates.io-index#utf8_iter@1.0.4" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#idna_adapter@1.2.1", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#icu_normalizer@2.1.1", + "registry+https://github.com/rust-lang/crates.io-index#icu_properties@2.1.2" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#image@0.25.10", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#bytemuck@1.25.0", + "registry+https://github.com/rust-lang/crates.io-index#byteorder-lite@0.1.0", + "registry+https://github.com/rust-lang/crates.io-index#moxcms@0.8.1", + "registry+https://github.com/rust-lang/crates.io-index#num-traits@0.2.19", + "registry+https://github.com/rust-lang/crates.io-index#png@0.18.1", + "registry+https://github.com/rust-lang/crates.io-index#tiff@0.11.3" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#indexmap@1.9.3", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#autocfg@1.5.0", + "registry+https://github.com/rust-lang/crates.io-index#hashbrown@0.12.3" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#indexmap@2.13.0", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#equivalent@1.0.2", + "registry+https://github.com/rust-lang/crates.io-index#hashbrown@0.16.1", + "registry+https://github.com/rust-lang/crates.io-index#serde_core@1.0.228" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#indicatif@0.17.11", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#console@0.15.11", + "registry+https://github.com/rust-lang/crates.io-index#number_prefix@0.4.0", + "registry+https://github.com/rust-lang/crates.io-index#portable-atomic@1.13.1", + "registry+https://github.com/rust-lang/crates.io-index#rayon@1.11.0", + "registry+https://github.com/rust-lang/crates.io-index#unicode-width@0.2.0" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#indoc@2.0.7", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#rustversion@1.0.22" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#inherent@1.0.13", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#proc-macro2@1.0.106", + "registry+https://github.com/rust-lang/crates.io-index#quote@1.0.45", + "registry+https://github.com/rust-lang/crates.io-index#syn@2.0.117" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#inlinable_string@0.1.15" + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#inout@0.1.4", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#generic-array@0.14.7" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#instability@0.3.12", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#darling@0.23.0", + "registry+https://github.com/rust-lang/crates.io-index#indoc@2.0.7", + "registry+https://github.com/rust-lang/crates.io-index#proc-macro2@1.0.106", + "registry+https://github.com/rust-lang/crates.io-index#quote@1.0.45", + "registry+https://github.com/rust-lang/crates.io-index#syn@2.0.117" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#instant@0.1.13", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#cfg-if@1.0.4" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#integer-encoding@3.0.4" + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#interpol@0.2.1", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#proc-macro2@1.0.106", + "registry+https://github.com/rust-lang/crates.io-index#quote@1.0.45", + "registry+https://github.com/rust-lang/crates.io-index#syn@1.0.109" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#ipnet@2.12.0" + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#iri-string@0.7.10", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#memchr@2.8.0", + "registry+https://github.com/rust-lang/crates.io-index#serde@1.0.228" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#is_ci@1.2.0" + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#is_terminal_polyfill@1.70.2" + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#iter-read@1.1.0" + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#itertools@0.12.1", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#either@1.15.0" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#itertools@0.13.0", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#either@1.15.0" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#itertools@0.14.0", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#either@1.15.0" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#itoa@1.0.18" + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#jobserver@0.1.34", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#getrandom@0.3.4" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#json-patch@1.4.0", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#serde@1.0.228", + "registry+https://github.com/rust-lang/crates.io-index#serde_json@1.0.149", + "registry+https://github.com/rust-lang/crates.io-index#thiserror@1.0.69" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#jsonpath-rust@0.3.5", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#pest@2.8.6", + "registry+https://github.com/rust-lang/crates.io-index#pest_derive@2.8.6", + "registry+https://github.com/rust-lang/crates.io-index#regex@1.12.3", + "registry+https://github.com/rust-lang/crates.io-index#serde_json@1.0.149", + "registry+https://github.com/rust-lang/crates.io-index#thiserror@1.0.69" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#k8s-openapi@0.20.0", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#base64@0.21.7", + "registry+https://github.com/rust-lang/crates.io-index#bytes@1.11.1", + "registry+https://github.com/rust-lang/crates.io-index#chrono@0.4.44", + "registry+https://github.com/rust-lang/crates.io-index#serde@1.0.228", + "registry+https://github.com/rust-lang/crates.io-index#serde-value@0.7.0", + "registry+https://github.com/rust-lang/crates.io-index#serde_json@1.0.149" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#kube-client@0.87.2", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#base64@0.21.7", + "registry+https://github.com/rust-lang/crates.io-index#bytes@1.11.1", + "registry+https://github.com/rust-lang/crates.io-index#chrono@0.4.44", + "registry+https://github.com/rust-lang/crates.io-index#either@1.15.0", + "registry+https://github.com/rust-lang/crates.io-index#futures@0.3.32", + "registry+https://github.com/rust-lang/crates.io-index#home@0.5.12", + "registry+https://github.com/rust-lang/crates.io-index#http@0.2.12", + "registry+https://github.com/rust-lang/crates.io-index#http-body@0.4.6", + "registry+https://github.com/rust-lang/crates.io-index#hyper@0.14.32", + "registry+https://github.com/rust-lang/crates.io-index#hyper-rustls@0.24.2", + "registry+https://github.com/rust-lang/crates.io-index#hyper-timeout@0.4.1", + "registry+https://github.com/rust-lang/crates.io-index#jsonpath-rust@0.3.5", + "registry+https://github.com/rust-lang/crates.io-index#k8s-openapi@0.20.0", + "registry+https://github.com/rust-lang/crates.io-index#kube-core@0.87.2", + "registry+https://github.com/rust-lang/crates.io-index#pem@3.0.6", + "registry+https://github.com/rust-lang/crates.io-index#pin-project@1.1.11", + "registry+https://github.com/rust-lang/crates.io-index#rustls@0.21.12", + "registry+https://github.com/rust-lang/crates.io-index#rustls-pemfile@1.0.4", + "registry+https://github.com/rust-lang/crates.io-index#secrecy@0.8.0", + "registry+https://github.com/rust-lang/crates.io-index#serde@1.0.228", + "registry+https://github.com/rust-lang/crates.io-index#serde_json@1.0.149", + "registry+https://github.com/rust-lang/crates.io-index#serde_yaml@0.9.34+deprecated", + "registry+https://github.com/rust-lang/crates.io-index#thiserror@1.0.69", + "registry+https://github.com/rust-lang/crates.io-index#tokio@1.50.0", + "registry+https://github.com/rust-lang/crates.io-index#tokio-util@0.7.18", + "registry+https://github.com/rust-lang/crates.io-index#tower@0.4.13", + "registry+https://github.com/rust-lang/crates.io-index#tower-http@0.4.4", + "registry+https://github.com/rust-lang/crates.io-index#tracing@0.1.44" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#kube-core@0.87.2", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#chrono@0.4.44", + "registry+https://github.com/rust-lang/crates.io-index#form_urlencoded@1.2.2", + "registry+https://github.com/rust-lang/crates.io-index#http@0.2.12", + "registry+https://github.com/rust-lang/crates.io-index#json-patch@1.4.0", + "registry+https://github.com/rust-lang/crates.io-index#k8s-openapi@0.20.0", + "registry+https://github.com/rust-lang/crates.io-index#once_cell@1.21.4", + "registry+https://github.com/rust-lang/crates.io-index#schemars@0.8.22", + "registry+https://github.com/rust-lang/crates.io-index#serde@1.0.228", + "registry+https://github.com/rust-lang/crates.io-index#serde_json@1.0.149", + "registry+https://github.com/rust-lang/crates.io-index#thiserror@1.0.69" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#kube-derive@0.87.2", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#darling@0.20.11", + "registry+https://github.com/rust-lang/crates.io-index#proc-macro2@1.0.106", + "registry+https://github.com/rust-lang/crates.io-index#quote@1.0.45", + "registry+https://github.com/rust-lang/crates.io-index#serde_json@1.0.149", + "registry+https://github.com/rust-lang/crates.io-index#syn@2.0.117" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#kube-runtime@0.87.2", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#ahash@0.8.12", + "registry+https://github.com/rust-lang/crates.io-index#async-trait@0.1.89", + "registry+https://github.com/rust-lang/crates.io-index#backoff@0.4.0", + "registry+https://github.com/rust-lang/crates.io-index#derivative@2.2.0", + "registry+https://github.com/rust-lang/crates.io-index#futures@0.3.32", + "registry+https://github.com/rust-lang/crates.io-index#hashbrown@0.14.5", + "registry+https://github.com/rust-lang/crates.io-index#json-patch@1.4.0", + "registry+https://github.com/rust-lang/crates.io-index#k8s-openapi@0.20.0", + "registry+https://github.com/rust-lang/crates.io-index#kube-client@0.87.2", + "registry+https://github.com/rust-lang/crates.io-index#parking_lot@0.12.5", + "registry+https://github.com/rust-lang/crates.io-index#pin-project@1.1.11", + "registry+https://github.com/rust-lang/crates.io-index#serde@1.0.228", + "registry+https://github.com/rust-lang/crates.io-index#serde_json@1.0.149", + "registry+https://github.com/rust-lang/crates.io-index#smallvec@1.15.1", + "registry+https://github.com/rust-lang/crates.io-index#thiserror@1.0.69", + "registry+https://github.com/rust-lang/crates.io-index#tokio@1.50.0", + "registry+https://github.com/rust-lang/crates.io-index#tokio-util@0.7.18", + "registry+https://github.com/rust-lang/crates.io-index#tracing@0.1.44" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#kube@0.87.2", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#k8s-openapi@0.20.0", + "registry+https://github.com/rust-lang/crates.io-index#kube-client@0.87.2", + "registry+https://github.com/rust-lang/crates.io-index#kube-core@0.87.2", + "registry+https://github.com/rust-lang/crates.io-index#kube-derive@0.87.2", + "registry+https://github.com/rust-lang/crates.io-index#kube-runtime@0.87.2" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#lazy_static@1.5.0", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#spin@0.9.8" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#levenshtein_automata@0.2.1" + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#lexical-core@1.0.6", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#lexical-parse-float@1.0.6", + "registry+https://github.com/rust-lang/crates.io-index#lexical-parse-integer@1.0.6", + "registry+https://github.com/rust-lang/crates.io-index#lexical-util@1.0.7", + "registry+https://github.com/rust-lang/crates.io-index#lexical-write-float@1.0.6", + "registry+https://github.com/rust-lang/crates.io-index#lexical-write-integer@1.0.6" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#lexical-parse-float@1.0.6", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#lexical-parse-integer@1.0.6", + "registry+https://github.com/rust-lang/crates.io-index#lexical-util@1.0.7" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#lexical-parse-integer@1.0.6", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#lexical-util@1.0.7" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#lexical-util@1.0.7" + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#lexical-write-float@1.0.6", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#lexical-util@1.0.7", + "registry+https://github.com/rust-lang/crates.io-index#lexical-write-integer@1.0.6" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#lexical-write-integer@1.0.6", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#lexical-util@1.0.7" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#libbz2-rs-sys@0.2.2" + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#libc@0.2.183" + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#libm@0.2.16" + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#libsqlite3-sys@0.30.1", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#cc@1.2.57", + "registry+https://github.com/rust-lang/crates.io-index#pkg-config@0.3.32", + "registry+https://github.com/rust-lang/crates.io-index#vcpkg@0.2.15" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#link-cplusplus@1.0.12", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#cc@1.2.57" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#litemap@0.8.1" + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#litrs@1.0.0" + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#lock_api@0.4.14", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#scopeguard@1.2.0", + "registry+https://github.com/rust-lang/crates.io-index#serde@1.0.228" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#log@0.4.29" + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#lru-slab@0.1.2" + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#lru@0.12.5", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#hashbrown@0.15.5" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#lz4-sys@1.11.1+lz4-1.10.0", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#cc@1.2.57", + "registry+https://github.com/rust-lang/crates.io-index#libc@0.2.183" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#lz4@1.28.1", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#lz4-sys@1.11.1+lz4-1.10.0" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#lz4_flex@0.11.6", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#twox-hash@2.1.2" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#lzma-rust2@0.16.2", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#sha2@0.10.9" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#matchers@0.2.0", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#regex-automata@0.4.14" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#matchit@0.7.3" + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#matchit@0.8.4" + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#matrixmultiply@0.3.10", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#autocfg@1.5.0", + "registry+https://github.com/rust-lang/crates.io-index#rawpointer@0.2.1" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#md-5@0.10.6", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#cfg-if@1.0.4", + "registry+https://github.com/rust-lang/crates.io-index#digest@0.10.7" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#md5@0.7.0" + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#measure_time@0.8.3", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#instant@0.1.13", + "registry+https://github.com/rust-lang/crates.io-index#log@0.4.29" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#memchr@2.8.0" + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#memmap2@0.9.10" + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#memoffset@0.9.1", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#autocfg@1.5.0" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#mime@0.3.17" + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#mime_guess@2.0.5", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#mime@0.3.17", + "registry+https://github.com/rust-lang/crates.io-index#unicase@2.9.0" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#minimal-lexical@0.2.1" + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#miniz_oxide@0.8.9", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#adler2@2.0.1", + "registry+https://github.com/rust-lang/crates.io-index#simd-adler32@0.3.8" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#mio@1.1.1", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#log@0.4.29", + "registry+https://github.com/rust-lang/crates.io-index#windows-sys@0.61.2" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#mixtrics@0.1.0", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#itertools@0.14.0", + "registry+https://github.com/rust-lang/crates.io-index#opentelemetry@0.27.1", + "registry+https://github.com/rust-lang/crates.io-index#parking_lot@0.12.5" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#moxcms@0.8.1", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#num-traits@0.2.19", + "registry+https://github.com/rust-lang/crates.io-index#pxfm@0.1.28" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#multimap@0.10.1" + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#murmur3@0.5.2" + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#murmurhash32@0.3.1" + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#nano-gemm-c32@0.2.1", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#nano-gemm-codegen@0.2.1", + "registry+https://github.com/rust-lang/crates.io-index#nano-gemm-core@0.2.1", + "registry+https://github.com/rust-lang/crates.io-index#num-complex@0.4.6" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#nano-gemm-c64@0.2.1", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#nano-gemm-codegen@0.2.1", + "registry+https://github.com/rust-lang/crates.io-index#nano-gemm-core@0.2.1", + "registry+https://github.com/rust-lang/crates.io-index#num-complex@0.4.6" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#nano-gemm-codegen@0.2.1" + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#nano-gemm-core@0.2.1" + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#nano-gemm-f32@0.2.1", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#nano-gemm-codegen@0.2.1", + "registry+https://github.com/rust-lang/crates.io-index#nano-gemm-core@0.2.1" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#nano-gemm-f64@0.2.1", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#nano-gemm-codegen@0.2.1", + "registry+https://github.com/rust-lang/crates.io-index#nano-gemm-core@0.2.1" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#nano-gemm@0.2.2", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#equator@0.2.2", + "registry+https://github.com/rust-lang/crates.io-index#nano-gemm-c32@0.2.1", + "registry+https://github.com/rust-lang/crates.io-index#nano-gemm-c64@0.2.1", + "registry+https://github.com/rust-lang/crates.io-index#nano-gemm-codegen@0.2.1", + "registry+https://github.com/rust-lang/crates.io-index#nano-gemm-core@0.2.1", + "registry+https://github.com/rust-lang/crates.io-index#nano-gemm-f32@0.2.1", + "registry+https://github.com/rust-lang/crates.io-index#nano-gemm-f64@0.2.1", + "registry+https://github.com/rust-lang/crates.io-index#num-complex@0.4.6" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#nanorand@0.7.0", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#getrandom@0.2.17" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#native-tls@0.2.18", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#schannel@0.1.29" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#ndarray@0.17.2", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#matrixmultiply@0.3.10", + "registry+https://github.com/rust-lang/crates.io-index#num-complex@0.4.6", + "registry+https://github.com/rust-lang/crates.io-index#num-integer@0.1.46", + "registry+https://github.com/rust-lang/crates.io-index#num-traits@0.2.19", + "registry+https://github.com/rust-lang/crates.io-index#rawpointer@0.2.1" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#nom@7.1.3", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#memchr@2.8.0", + "registry+https://github.com/rust-lang/crates.io-index#minimal-lexical@0.2.1" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#nu-ansi-term@0.50.3", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#windows-sys@0.61.2" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#num-bigint-dig@0.8.6", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#lazy_static@1.5.0", + "registry+https://github.com/rust-lang/crates.io-index#libm@0.2.16", + "registry+https://github.com/rust-lang/crates.io-index#num-integer@0.1.46", + "registry+https://github.com/rust-lang/crates.io-index#num-iter@0.1.45", + "registry+https://github.com/rust-lang/crates.io-index#num-traits@0.2.19", + "registry+https://github.com/rust-lang/crates.io-index#rand@0.8.5", + "registry+https://github.com/rust-lang/crates.io-index#smallvec@1.15.1", + "registry+https://github.com/rust-lang/crates.io-index#zeroize@1.8.2" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#num-bigint@0.4.6", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#num-integer@0.1.46", + "registry+https://github.com/rust-lang/crates.io-index#num-traits@0.2.19" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#num-complex@0.2.4", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#autocfg@1.5.0", + "registry+https://github.com/rust-lang/crates.io-index#num-traits@0.2.19" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#num-complex@0.4.6", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#bytemuck@1.25.0", + "registry+https://github.com/rust-lang/crates.io-index#num-traits@0.2.19", + "registry+https://github.com/rust-lang/crates.io-index#rand@0.8.5" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#num-conv@0.2.0" + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#num-integer@0.1.46", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#num-traits@0.2.19" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#num-iter@0.1.45", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#autocfg@1.5.0", + "registry+https://github.com/rust-lang/crates.io-index#num-integer@0.1.46", + "registry+https://github.com/rust-lang/crates.io-index#num-traits@0.2.19" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#num-rational@0.4.2", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#num-bigint@0.4.6", + "registry+https://github.com/rust-lang/crates.io-index#num-integer@0.1.46", + "registry+https://github.com/rust-lang/crates.io-index#num-traits@0.2.19" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#num-traits@0.2.19", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#autocfg@1.5.0", + "registry+https://github.com/rust-lang/crates.io-index#libm@0.2.16" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#num@0.4.3", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#num-bigint@0.4.6", + "registry+https://github.com/rust-lang/crates.io-index#num-complex@0.4.6", + "registry+https://github.com/rust-lang/crates.io-index#num-integer@0.1.46", + "registry+https://github.com/rust-lang/crates.io-index#num-iter@0.1.45", + "registry+https://github.com/rust-lang/crates.io-index#num-rational@0.4.2", + "registry+https://github.com/rust-lang/crates.io-index#num-traits@0.2.19" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#num_cpus@1.17.0" + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#number_prefix@0.4.0" + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#object_store@0.12.5", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#async-trait@0.1.89", + "registry+https://github.com/rust-lang/crates.io-index#base64@0.22.1", + "registry+https://github.com/rust-lang/crates.io-index#bytes@1.11.1", + "registry+https://github.com/rust-lang/crates.io-index#chrono@0.4.44", + "registry+https://github.com/rust-lang/crates.io-index#form_urlencoded@1.2.2", + "registry+https://github.com/rust-lang/crates.io-index#futures@0.3.32", + "registry+https://github.com/rust-lang/crates.io-index#http@1.4.0", + "registry+https://github.com/rust-lang/crates.io-index#http-body-util@0.1.3", + "registry+https://github.com/rust-lang/crates.io-index#humantime@2.3.0", + "registry+https://github.com/rust-lang/crates.io-index#hyper@1.8.1", + "registry+https://github.com/rust-lang/crates.io-index#itertools@0.14.0", + "registry+https://github.com/rust-lang/crates.io-index#parking_lot@0.12.5", + "registry+https://github.com/rust-lang/crates.io-index#percent-encoding@2.3.2", + "registry+https://github.com/rust-lang/crates.io-index#quick-xml@0.38.4", + "registry+https://github.com/rust-lang/crates.io-index#rand@0.9.2", + "registry+https://github.com/rust-lang/crates.io-index#reqwest@0.12.28", + "registry+https://github.com/rust-lang/crates.io-index#ring@0.17.14", + "registry+https://github.com/rust-lang/crates.io-index#rustls-pemfile@2.2.0", + "registry+https://github.com/rust-lang/crates.io-index#serde@1.0.228", + "registry+https://github.com/rust-lang/crates.io-index#serde_json@1.0.149", + "registry+https://github.com/rust-lang/crates.io-index#serde_urlencoded@0.7.1", + "registry+https://github.com/rust-lang/crates.io-index#thiserror@2.0.18", + "registry+https://github.com/rust-lang/crates.io-index#tokio@1.50.0", + "registry+https://github.com/rust-lang/crates.io-index#tracing@0.1.44", + "registry+https://github.com/rust-lang/crates.io-index#url@2.5.8", + "registry+https://github.com/rust-lang/crates.io-index#walkdir@2.5.0" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#once_cell@1.21.4" + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#once_cell_polyfill@1.70.2" + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#oneshot@0.1.13" + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#oorandom@11.1.5" + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#opentelemetry-http@0.27.0", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#async-trait@0.1.89", + "registry+https://github.com/rust-lang/crates.io-index#bytes@1.11.1", + "registry+https://github.com/rust-lang/crates.io-index#http@1.4.0", + "registry+https://github.com/rust-lang/crates.io-index#opentelemetry@0.27.1" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#opentelemetry-otlp@0.27.0", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#async-trait@0.1.89", + "registry+https://github.com/rust-lang/crates.io-index#futures-core@0.3.32", + "registry+https://github.com/rust-lang/crates.io-index#http@1.4.0", + "registry+https://github.com/rust-lang/crates.io-index#opentelemetry@0.27.1", + "registry+https://github.com/rust-lang/crates.io-index#opentelemetry-http@0.27.0", + "registry+https://github.com/rust-lang/crates.io-index#opentelemetry-proto@0.27.0", + "registry+https://github.com/rust-lang/crates.io-index#opentelemetry_sdk@0.27.1", + "registry+https://github.com/rust-lang/crates.io-index#prost@0.13.5", + "registry+https://github.com/rust-lang/crates.io-index#thiserror@1.0.69", + "registry+https://github.com/rust-lang/crates.io-index#tokio@1.50.0", + "registry+https://github.com/rust-lang/crates.io-index#tonic@0.12.3", + "registry+https://github.com/rust-lang/crates.io-index#tracing@0.1.44" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#opentelemetry-proto@0.27.0", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#opentelemetry@0.27.1", + "registry+https://github.com/rust-lang/crates.io-index#opentelemetry_sdk@0.27.1", + "registry+https://github.com/rust-lang/crates.io-index#prost@0.13.5", + "registry+https://github.com/rust-lang/crates.io-index#tonic@0.12.3" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#opentelemetry@0.27.1", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#futures-core@0.3.32", + "registry+https://github.com/rust-lang/crates.io-index#futures-sink@0.3.32", + "registry+https://github.com/rust-lang/crates.io-index#pin-project-lite@0.2.17", + "registry+https://github.com/rust-lang/crates.io-index#thiserror@1.0.69", + "registry+https://github.com/rust-lang/crates.io-index#tracing@0.1.44" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#opentelemetry_sdk@0.27.1", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#async-trait@0.1.89", + "registry+https://github.com/rust-lang/crates.io-index#futures-channel@0.3.32", + "registry+https://github.com/rust-lang/crates.io-index#futures-executor@0.3.32", + "registry+https://github.com/rust-lang/crates.io-index#futures-util@0.3.32", + "registry+https://github.com/rust-lang/crates.io-index#glob@0.3.3", + "registry+https://github.com/rust-lang/crates.io-index#opentelemetry@0.27.1", + "registry+https://github.com/rust-lang/crates.io-index#percent-encoding@2.3.2", + "registry+https://github.com/rust-lang/crates.io-index#rand@0.8.5", + "registry+https://github.com/rust-lang/crates.io-index#serde_json@1.0.149", + "registry+https://github.com/rust-lang/crates.io-index#thiserror@1.0.69", + "registry+https://github.com/rust-lang/crates.io-index#tokio@1.50.0", + "registry+https://github.com/rust-lang/crates.io-index#tokio-stream@0.1.18", + "registry+https://github.com/rust-lang/crates.io-index#tracing@0.1.44" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#option-ext@0.2.0" + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#ordered-float@2.10.1", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#num-traits@0.2.19" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#ordered_hash_map@0.4.0", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#hashbrown@0.13.2" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#outref@0.5.2" + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#ownedbytes@0.7.0", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#stable_deref_trait@1.2.1" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#owo-colors@3.5.0" + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#p256@0.11.1", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#ecdsa@0.14.8", + "registry+https://github.com/rust-lang/crates.io-index#elliptic-curve@0.12.3", + "registry+https://github.com/rust-lang/crates.io-index#sha2@0.10.9" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#parking@2.2.1" + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#parking_lot@0.12.5", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#lock_api@0.4.14", + "registry+https://github.com/rust-lang/crates.io-index#parking_lot_core@0.9.12" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#parking_lot_core@0.9.12", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#cfg-if@1.0.4", + "registry+https://github.com/rust-lang/crates.io-index#smallvec@1.15.1", + "registry+https://github.com/rust-lang/crates.io-index#windows-link@0.2.1" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#parquet@55.2.0", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#ahash@0.8.12", + "registry+https://github.com/rust-lang/crates.io-index#arrow-array@55.2.0", + "registry+https://github.com/rust-lang/crates.io-index#arrow-buffer@55.2.0", + "registry+https://github.com/rust-lang/crates.io-index#arrow-cast@55.2.0", + "registry+https://github.com/rust-lang/crates.io-index#arrow-data@55.2.0", + "registry+https://github.com/rust-lang/crates.io-index#arrow-ipc@55.2.0", + "registry+https://github.com/rust-lang/crates.io-index#arrow-schema@55.2.0", + "registry+https://github.com/rust-lang/crates.io-index#arrow-select@55.2.0", + "registry+https://github.com/rust-lang/crates.io-index#base64@0.22.1", + "registry+https://github.com/rust-lang/crates.io-index#brotli@8.0.2", + "registry+https://github.com/rust-lang/crates.io-index#bytes@1.11.1", + "registry+https://github.com/rust-lang/crates.io-index#chrono@0.4.44", + "registry+https://github.com/rust-lang/crates.io-index#flate2@1.1.9", + "registry+https://github.com/rust-lang/crates.io-index#futures@0.3.32", + "registry+https://github.com/rust-lang/crates.io-index#half@2.7.1", + "registry+https://github.com/rust-lang/crates.io-index#hashbrown@0.15.5", + "registry+https://github.com/rust-lang/crates.io-index#lz4_flex@0.11.6", + "registry+https://github.com/rust-lang/crates.io-index#num@0.4.3", + "registry+https://github.com/rust-lang/crates.io-index#num-bigint@0.4.6", + "registry+https://github.com/rust-lang/crates.io-index#paste@1.0.15", + "registry+https://github.com/rust-lang/crates.io-index#seq-macro@0.3.6", + "registry+https://github.com/rust-lang/crates.io-index#simdutf8@0.1.5", + "registry+https://github.com/rust-lang/crates.io-index#snap@1.1.1", + "registry+https://github.com/rust-lang/crates.io-index#thrift@0.17.0", + "registry+https://github.com/rust-lang/crates.io-index#tokio@1.50.0", + "registry+https://github.com/rust-lang/crates.io-index#twox-hash@2.1.2", + "registry+https://github.com/rust-lang/crates.io-index#zstd@0.13.3" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#paste@1.0.15" + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#pbkdf2@0.12.2", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#digest@0.10.7", + "registry+https://github.com/rust-lang/crates.io-index#hmac@0.12.1" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#pear@0.2.9", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#inlinable_string@0.1.15", + "registry+https://github.com/rust-lang/crates.io-index#pear_codegen@0.2.9", + "registry+https://github.com/rust-lang/crates.io-index#yansi@1.0.1" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#pear_codegen@0.2.9", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#proc-macro2@1.0.106", + "registry+https://github.com/rust-lang/crates.io-index#proc-macro2-diagnostics@0.10.1", + "registry+https://github.com/rust-lang/crates.io-index#quote@1.0.45", + "registry+https://github.com/rust-lang/crates.io-index#syn@2.0.117" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#pem-rfc7468@0.7.0", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#base64ct@1.8.3" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#pem@3.0.6", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#base64@0.22.1", + "registry+https://github.com/rust-lang/crates.io-index#serde_core@1.0.228" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#percent-encoding@2.3.2" + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#pest@2.8.6", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#memchr@2.8.0", + "registry+https://github.com/rust-lang/crates.io-index#ucd-trie@0.1.7" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#pest_derive@2.8.6", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#pest@2.8.6", + "registry+https://github.com/rust-lang/crates.io-index#pest_generator@2.8.6" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#pest_generator@2.8.6", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#pest@2.8.6", + "registry+https://github.com/rust-lang/crates.io-index#pest_meta@2.8.6", + "registry+https://github.com/rust-lang/crates.io-index#proc-macro2@1.0.106", + "registry+https://github.com/rust-lang/crates.io-index#quote@1.0.45", + "registry+https://github.com/rust-lang/crates.io-index#syn@2.0.117" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#pest_meta@2.8.6", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#pest@2.8.6", + "registry+https://github.com/rust-lang/crates.io-index#sha2@0.10.9" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#petgraph@0.8.3", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#fixedbitset@0.5.7", + "registry+https://github.com/rust-lang/crates.io-index#hashbrown@0.15.5", + "registry+https://github.com/rust-lang/crates.io-index#indexmap@2.13.0", + "registry+https://github.com/rust-lang/crates.io-index#serde@1.0.228" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#pin-project-internal@1.1.11", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#proc-macro2@1.0.106", + "registry+https://github.com/rust-lang/crates.io-index#quote@1.0.45", + "registry+https://github.com/rust-lang/crates.io-index#syn@2.0.117" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#pin-project-lite@0.2.17" + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#pin-project@1.1.11", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#pin-project-internal@1.1.11" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#pin-utils@0.1.0" + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#pkcs1@0.7.5", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#der@0.7.10", + "registry+https://github.com/rust-lang/crates.io-index#pkcs8@0.10.2", + "registry+https://github.com/rust-lang/crates.io-index#spki@0.7.3" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#pkcs8@0.10.2", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#der@0.7.10", + "registry+https://github.com/rust-lang/crates.io-index#spki@0.7.3" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#pkcs8@0.9.0", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#der@0.6.1", + "registry+https://github.com/rust-lang/crates.io-index#spki@0.6.0" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#pkg-config@0.3.32" + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#plotters-backend@0.3.7" + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#plotters-svg@0.3.7", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#plotters-backend@0.3.7" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#plotters@0.3.7", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#num-traits@0.2.19", + "registry+https://github.com/rust-lang/crates.io-index#plotters-backend@0.3.7", + "registry+https://github.com/rust-lang/crates.io-index#plotters-svg@0.3.7" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#png@0.18.1", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#bitflags@2.11.0", + "registry+https://github.com/rust-lang/crates.io-index#crc32fast@1.5.0", + "registry+https://github.com/rust-lang/crates.io-index#fdeflate@0.3.7", + "registry+https://github.com/rust-lang/crates.io-index#flate2@1.1.9", + "registry+https://github.com/rust-lang/crates.io-index#miniz_oxide@0.8.9" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#pollster@0.4.0" + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#portable-atomic@1.13.1", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#serde@1.0.228" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#potential_utf@0.1.4", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#zerovec@0.11.5" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#powerfmt@0.2.0" + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#ppmd-rust@1.4.0" + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#ppv-lite86@0.2.21", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#zerocopy@0.8.47" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#prettyplease@0.2.37", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#proc-macro2@1.0.106", + "registry+https://github.com/rust-lang/crates.io-index#syn@2.0.117" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#private-gemm-x86@0.1.20", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#defer@0.2.1", + "registry+https://github.com/rust-lang/crates.io-index#interpol@0.2.1", + "registry+https://github.com/rust-lang/crates.io-index#num_cpus@1.17.0", + "registry+https://github.com/rust-lang/crates.io-index#raw-cpuid@11.6.0" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#proc-macro-error-attr2@2.0.0", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#proc-macro2@1.0.106", + "registry+https://github.com/rust-lang/crates.io-index#quote@1.0.45" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#proc-macro-error2@2.0.1", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#proc-macro-error-attr2@2.0.0", + "registry+https://github.com/rust-lang/crates.io-index#proc-macro2@1.0.106", + "registry+https://github.com/rust-lang/crates.io-index#quote@1.0.45", + "registry+https://github.com/rust-lang/crates.io-index#syn@2.0.117" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#proc-macro2-diagnostics@0.10.1", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#proc-macro2@1.0.106", + "registry+https://github.com/rust-lang/crates.io-index#quote@1.0.45", + "registry+https://github.com/rust-lang/crates.io-index#syn@2.0.117", + "registry+https://github.com/rust-lang/crates.io-index#version_check@0.9.5", + "registry+https://github.com/rust-lang/crates.io-index#yansi@1.0.1" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#proc-macro2@1.0.106", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#unicode-ident@1.0.24" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#proptest-derive@0.5.1", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#proc-macro2@1.0.106", + "registry+https://github.com/rust-lang/crates.io-index#quote@1.0.45", + "registry+https://github.com/rust-lang/crates.io-index#syn@2.0.117" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#proptest@1.10.0", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#bit-set@0.8.0", + "registry+https://github.com/rust-lang/crates.io-index#bit-vec@0.8.0", + "registry+https://github.com/rust-lang/crates.io-index#bitflags@2.11.0", + "registry+https://github.com/rust-lang/crates.io-index#num-traits@0.2.19", + "registry+https://github.com/rust-lang/crates.io-index#rand@0.9.2", + "registry+https://github.com/rust-lang/crates.io-index#rand_chacha@0.9.0", + "registry+https://github.com/rust-lang/crates.io-index#rand_xorshift@0.4.0", + "registry+https://github.com/rust-lang/crates.io-index#regex-syntax@0.8.10", + "registry+https://github.com/rust-lang/crates.io-index#rusty-fork@0.3.1", + "registry+https://github.com/rust-lang/crates.io-index#tempfile@3.27.0", + "registry+https://github.com/rust-lang/crates.io-index#unarray@0.1.4" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#prost-build@0.14.3", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#heck@0.5.0", + "registry+https://github.com/rust-lang/crates.io-index#itertools@0.14.0", + "registry+https://github.com/rust-lang/crates.io-index#log@0.4.29", + "registry+https://github.com/rust-lang/crates.io-index#multimap@0.10.1", + "registry+https://github.com/rust-lang/crates.io-index#petgraph@0.8.3", + "registry+https://github.com/rust-lang/crates.io-index#prettyplease@0.2.37", + "registry+https://github.com/rust-lang/crates.io-index#prost@0.14.3", + "registry+https://github.com/rust-lang/crates.io-index#prost-types@0.14.3", + "registry+https://github.com/rust-lang/crates.io-index#pulldown-cmark@0.13.1", + "registry+https://github.com/rust-lang/crates.io-index#pulldown-cmark-to-cmark@22.0.0", + "registry+https://github.com/rust-lang/crates.io-index#regex@1.12.3", + "registry+https://github.com/rust-lang/crates.io-index#syn@2.0.117", + "registry+https://github.com/rust-lang/crates.io-index#tempfile@3.27.0" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#prost-derive@0.13.5", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#anyhow@1.0.102", + "registry+https://github.com/rust-lang/crates.io-index#itertools@0.14.0", + "registry+https://github.com/rust-lang/crates.io-index#proc-macro2@1.0.106", + "registry+https://github.com/rust-lang/crates.io-index#quote@1.0.45", + "registry+https://github.com/rust-lang/crates.io-index#syn@2.0.117" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#prost-derive@0.14.3", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#anyhow@1.0.102", + "registry+https://github.com/rust-lang/crates.io-index#itertools@0.14.0", + "registry+https://github.com/rust-lang/crates.io-index#proc-macro2@1.0.106", + "registry+https://github.com/rust-lang/crates.io-index#quote@1.0.45", + "registry+https://github.com/rust-lang/crates.io-index#syn@2.0.117" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#prost-types@0.14.3", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#prost@0.14.3" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#prost@0.13.5", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#bytes@1.11.1", + "registry+https://github.com/rust-lang/crates.io-index#prost-derive@0.13.5" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#prost@0.14.3", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#bytes@1.11.1", + "registry+https://github.com/rust-lang/crates.io-index#prost-derive@0.14.3" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#pulldown-cmark-to-cmark@22.0.0", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#pulldown-cmark@0.13.1" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#pulldown-cmark@0.13.1", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#bitflags@2.11.0", + "registry+https://github.com/rust-lang/crates.io-index#memchr@2.8.0", + "registry+https://github.com/rust-lang/crates.io-index#unicase@2.9.0" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#pulp-wasm-simd-flag@0.1.0" + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#pulp@0.22.2", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#bytemuck@1.25.0", + "registry+https://github.com/rust-lang/crates.io-index#cfg-if@1.0.4", + "registry+https://github.com/rust-lang/crates.io-index#libm@0.2.16", + "registry+https://github.com/rust-lang/crates.io-index#num-complex@0.4.6", + "registry+https://github.com/rust-lang/crates.io-index#paste@1.0.15", + "registry+https://github.com/rust-lang/crates.io-index#pulp-wasm-simd-flag@0.1.0", + "registry+https://github.com/rust-lang/crates.io-index#raw-cpuid@11.6.0", + "registry+https://github.com/rust-lang/crates.io-index#reborrow@0.5.5", + "registry+https://github.com/rust-lang/crates.io-index#version_check@0.9.5" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#pxfm@0.1.28" + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#pyo3-build-config@0.24.2", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#once_cell@1.21.4", + "registry+https://github.com/rust-lang/crates.io-index#target-lexicon@0.13.5" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#pyo3-ffi@0.24.2", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#libc@0.2.183", + "registry+https://github.com/rust-lang/crates.io-index#pyo3-build-config@0.24.2" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#pyo3-macros-backend@0.24.2", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#heck@0.5.0", + "registry+https://github.com/rust-lang/crates.io-index#proc-macro2@1.0.106", + "registry+https://github.com/rust-lang/crates.io-index#pyo3-build-config@0.24.2", + "registry+https://github.com/rust-lang/crates.io-index#quote@1.0.45", + "registry+https://github.com/rust-lang/crates.io-index#syn@2.0.117" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#pyo3-macros@0.24.2", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#proc-macro2@1.0.106", + "registry+https://github.com/rust-lang/crates.io-index#pyo3-macros-backend@0.24.2", + "registry+https://github.com/rust-lang/crates.io-index#quote@1.0.45", + "registry+https://github.com/rust-lang/crates.io-index#syn@2.0.117" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#pyo3@0.24.2", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#cfg-if@1.0.4", + "registry+https://github.com/rust-lang/crates.io-index#indoc@2.0.7", + "registry+https://github.com/rust-lang/crates.io-index#libc@0.2.183", + "registry+https://github.com/rust-lang/crates.io-index#memoffset@0.9.1", + "registry+https://github.com/rust-lang/crates.io-index#once_cell@1.21.4", + "registry+https://github.com/rust-lang/crates.io-index#pyo3-build-config@0.24.2", + "registry+https://github.com/rust-lang/crates.io-index#pyo3-ffi@0.24.2", + "registry+https://github.com/rust-lang/crates.io-index#pyo3-macros@0.24.2", + "registry+https://github.com/rust-lang/crates.io-index#unindent@0.2.4" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#qd@0.8.0", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#bytemuck@1.25.0", + "registry+https://github.com/rust-lang/crates.io-index#libm@0.2.16", + "registry+https://github.com/rust-lang/crates.io-index#num-traits@0.2.19", + "registry+https://github.com/rust-lang/crates.io-index#pulp@0.22.2" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#quick-error@1.2.3" + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#quick-error@2.0.1" + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#quick-xml@0.38.4", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#memchr@2.8.0", + "registry+https://github.com/rust-lang/crates.io-index#serde@1.0.228" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#quinn-proto@0.11.14", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#aws-lc-rs@1.16.2", + "registry+https://github.com/rust-lang/crates.io-index#bytes@1.11.1", + "registry+https://github.com/rust-lang/crates.io-index#lru-slab@0.1.2", + "registry+https://github.com/rust-lang/crates.io-index#rand@0.9.2", + "registry+https://github.com/rust-lang/crates.io-index#ring@0.17.14", + "registry+https://github.com/rust-lang/crates.io-index#rustc-hash@2.1.1", + "registry+https://github.com/rust-lang/crates.io-index#rustls@0.23.37", + "registry+https://github.com/rust-lang/crates.io-index#slab@0.4.12", + "registry+https://github.com/rust-lang/crates.io-index#thiserror@2.0.18", + "registry+https://github.com/rust-lang/crates.io-index#tinyvec@1.11.0", + "registry+https://github.com/rust-lang/crates.io-index#tracing@0.1.44" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#quinn-udp@0.5.14", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#cfg_aliases@0.2.1", + "registry+https://github.com/rust-lang/crates.io-index#libc@0.2.183", + "registry+https://github.com/rust-lang/crates.io-index#once_cell@1.21.4", + "registry+https://github.com/rust-lang/crates.io-index#socket2@0.6.3", + "registry+https://github.com/rust-lang/crates.io-index#tracing@0.1.44", + "registry+https://github.com/rust-lang/crates.io-index#windows-sys@0.60.2" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#quinn@0.11.9", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#bytes@1.11.1", + "registry+https://github.com/rust-lang/crates.io-index#cfg_aliases@0.2.1", + "registry+https://github.com/rust-lang/crates.io-index#pin-project-lite@0.2.17", + "registry+https://github.com/rust-lang/crates.io-index#quinn-proto@0.11.14", + "registry+https://github.com/rust-lang/crates.io-index#quinn-udp@0.5.14", + "registry+https://github.com/rust-lang/crates.io-index#rustc-hash@2.1.1", + "registry+https://github.com/rust-lang/crates.io-index#rustls@0.23.37", + "registry+https://github.com/rust-lang/crates.io-index#socket2@0.6.3", + "registry+https://github.com/rust-lang/crates.io-index#thiserror@2.0.18", + "registry+https://github.com/rust-lang/crates.io-index#tokio@1.50.0", + "registry+https://github.com/rust-lang/crates.io-index#tracing@0.1.44" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#quote@1.0.45", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#proc-macro2@1.0.106" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#radium@0.7.0" + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#rand@0.10.0", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#chacha20@0.10.0", + "registry+https://github.com/rust-lang/crates.io-index#getrandom@0.4.2", + "registry+https://github.com/rust-lang/crates.io-index#rand_core@0.10.0" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#rand@0.8.5", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#rand_chacha@0.3.1", + "registry+https://github.com/rust-lang/crates.io-index#rand_core@0.6.4" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#rand@0.9.2", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#rand_chacha@0.9.0", + "registry+https://github.com/rust-lang/crates.io-index#rand_core@0.9.5" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#rand_chacha@0.3.1", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#ppv-lite86@0.2.21", + "registry+https://github.com/rust-lang/crates.io-index#rand_core@0.6.4" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#rand_chacha@0.9.0", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#ppv-lite86@0.2.21", + "registry+https://github.com/rust-lang/crates.io-index#rand_core@0.9.5" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#rand_core@0.10.0" + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#rand_core@0.6.4", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#getrandom@0.2.17" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#rand_core@0.9.5", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#getrandom@0.3.4" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#rand_distr@0.4.3", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#num-traits@0.2.19", + "registry+https://github.com/rust-lang/crates.io-index#rand@0.8.5" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#rand_distr@0.5.1", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#num-traits@0.2.19", + "registry+https://github.com/rust-lang/crates.io-index#rand@0.9.2" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#rand_pcg@0.3.1", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#rand_core@0.6.4" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#rand_xorshift@0.4.0", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#rand_core@0.9.5" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#ratatui@0.29.0", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#bitflags@2.11.0", + "registry+https://github.com/rust-lang/crates.io-index#cassowary@0.3.0", + "registry+https://github.com/rust-lang/crates.io-index#compact_str@0.8.1", + "registry+https://github.com/rust-lang/crates.io-index#crossterm@0.28.1", + "registry+https://github.com/rust-lang/crates.io-index#indoc@2.0.7", + "registry+https://github.com/rust-lang/crates.io-index#instability@0.3.12", + "registry+https://github.com/rust-lang/crates.io-index#itertools@0.13.0", + "registry+https://github.com/rust-lang/crates.io-index#lru@0.12.5", + "registry+https://github.com/rust-lang/crates.io-index#paste@1.0.15", + "registry+https://github.com/rust-lang/crates.io-index#strum@0.26.3", + "registry+https://github.com/rust-lang/crates.io-index#unicode-segmentation@1.12.0", + "registry+https://github.com/rust-lang/crates.io-index#unicode-truncate@1.1.0", + "registry+https://github.com/rust-lang/crates.io-index#unicode-width@0.2.0" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#raw-cpuid@11.6.0", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#bitflags@2.11.0" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#rawpointer@0.2.1" + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#rayon-core@1.13.0", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#crossbeam-deque@0.8.6", + "registry+https://github.com/rust-lang/crates.io-index#crossbeam-utils@0.8.21" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#rayon@1.11.0", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#either@1.15.0", + "registry+https://github.com/rust-lang/crates.io-index#rayon-core@1.13.0" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#reborrow@0.5.5" + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#regex-automata@0.4.14", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#aho-corasick@1.1.4", + "registry+https://github.com/rust-lang/crates.io-index#memchr@2.8.0", + "registry+https://github.com/rust-lang/crates.io-index#regex-syntax@0.8.10" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#regex-lite@0.1.9" + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#regex-syntax@0.8.10" + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#regex@1.12.3", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#aho-corasick@1.1.4", + "registry+https://github.com/rust-lang/crates.io-index#memchr@2.8.0", + "registry+https://github.com/rust-lang/crates.io-index#regex-automata@0.4.14", + "registry+https://github.com/rust-lang/crates.io-index#regex-syntax@0.8.10" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#reqwest@0.12.28", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#base64@0.22.1", + "registry+https://github.com/rust-lang/crates.io-index#bytes@1.11.1", + "registry+https://github.com/rust-lang/crates.io-index#encoding_rs@0.8.35", + "registry+https://github.com/rust-lang/crates.io-index#futures-core@0.3.32", + "registry+https://github.com/rust-lang/crates.io-index#futures-util@0.3.32", + "registry+https://github.com/rust-lang/crates.io-index#h2@0.4.13", + "registry+https://github.com/rust-lang/crates.io-index#http@1.4.0", + "registry+https://github.com/rust-lang/crates.io-index#http-body@1.0.1", + "registry+https://github.com/rust-lang/crates.io-index#http-body-util@0.1.3", + "registry+https://github.com/rust-lang/crates.io-index#hyper@1.8.1", + "registry+https://github.com/rust-lang/crates.io-index#hyper-rustls@0.27.7", + "registry+https://github.com/rust-lang/crates.io-index#hyper-tls@0.6.0", + "registry+https://github.com/rust-lang/crates.io-index#hyper-util@0.1.20", + "registry+https://github.com/rust-lang/crates.io-index#log@0.4.29", + "registry+https://github.com/rust-lang/crates.io-index#mime@0.3.17", + "registry+https://github.com/rust-lang/crates.io-index#native-tls@0.2.18", + "registry+https://github.com/rust-lang/crates.io-index#percent-encoding@2.3.2", + "registry+https://github.com/rust-lang/crates.io-index#pin-project-lite@0.2.17", + "registry+https://github.com/rust-lang/crates.io-index#quinn@0.11.9", + "registry+https://github.com/rust-lang/crates.io-index#rustls@0.23.37", + "registry+https://github.com/rust-lang/crates.io-index#rustls-native-certs@0.8.3", + "registry+https://github.com/rust-lang/crates.io-index#rustls-pki-types@1.14.0", + "registry+https://github.com/rust-lang/crates.io-index#serde@1.0.228", + "registry+https://github.com/rust-lang/crates.io-index#serde_json@1.0.149", + "registry+https://github.com/rust-lang/crates.io-index#serde_urlencoded@0.7.1", + "registry+https://github.com/rust-lang/crates.io-index#sync_wrapper@1.0.2", + "registry+https://github.com/rust-lang/crates.io-index#tokio@1.50.0", + "registry+https://github.com/rust-lang/crates.io-index#tokio-native-tls@0.3.1", + "registry+https://github.com/rust-lang/crates.io-index#tokio-rustls@0.26.4", + "registry+https://github.com/rust-lang/crates.io-index#tokio-util@0.7.18", + "registry+https://github.com/rust-lang/crates.io-index#tower@0.5.3", + "registry+https://github.com/rust-lang/crates.io-index#tower-http@0.6.8", + "registry+https://github.com/rust-lang/crates.io-index#tower-service@0.3.3", + "registry+https://github.com/rust-lang/crates.io-index#url@2.5.8", + "registry+https://github.com/rust-lang/crates.io-index#webpki-roots@1.0.6" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#reqwest@0.13.2", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#base64@0.22.1", + "registry+https://github.com/rust-lang/crates.io-index#bytes@1.11.1", + "registry+https://github.com/rust-lang/crates.io-index#encoding_rs@0.8.35", + "registry+https://github.com/rust-lang/crates.io-index#futures-core@0.3.32", + "registry+https://github.com/rust-lang/crates.io-index#futures-util@0.3.32", + "registry+https://github.com/rust-lang/crates.io-index#h2@0.4.13", + "registry+https://github.com/rust-lang/crates.io-index#http@1.4.0", + "registry+https://github.com/rust-lang/crates.io-index#http-body@1.0.1", + "registry+https://github.com/rust-lang/crates.io-index#http-body-util@0.1.3", + "registry+https://github.com/rust-lang/crates.io-index#hyper@1.8.1", + "registry+https://github.com/rust-lang/crates.io-index#hyper-rustls@0.27.7", + "registry+https://github.com/rust-lang/crates.io-index#hyper-util@0.1.20", + "registry+https://github.com/rust-lang/crates.io-index#log@0.4.29", + "registry+https://github.com/rust-lang/crates.io-index#mime@0.3.17", + "registry+https://github.com/rust-lang/crates.io-index#percent-encoding@2.3.2", + "registry+https://github.com/rust-lang/crates.io-index#pin-project-lite@0.2.17", + "registry+https://github.com/rust-lang/crates.io-index#quinn@0.11.9", + "registry+https://github.com/rust-lang/crates.io-index#rustls@0.23.37", + "registry+https://github.com/rust-lang/crates.io-index#rustls-pki-types@1.14.0", + "registry+https://github.com/rust-lang/crates.io-index#rustls-platform-verifier@0.6.2", + "registry+https://github.com/rust-lang/crates.io-index#serde@1.0.228", + "registry+https://github.com/rust-lang/crates.io-index#serde_json@1.0.149", + "registry+https://github.com/rust-lang/crates.io-index#serde_urlencoded@0.7.1", + "registry+https://github.com/rust-lang/crates.io-index#sync_wrapper@1.0.2", + "registry+https://github.com/rust-lang/crates.io-index#tokio@1.50.0", + "registry+https://github.com/rust-lang/crates.io-index#tokio-rustls@0.26.4", + "registry+https://github.com/rust-lang/crates.io-index#tokio-util@0.7.18", + "registry+https://github.com/rust-lang/crates.io-index#tower@0.5.3", + "registry+https://github.com/rust-lang/crates.io-index#tower-http@0.6.8", + "registry+https://github.com/rust-lang/crates.io-index#tower-service@0.3.3", + "registry+https://github.com/rust-lang/crates.io-index#url@2.5.8" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#rfc6979@0.3.1", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#crypto-bigint@0.4.9", + "registry+https://github.com/rust-lang/crates.io-index#hmac@0.12.1", + "registry+https://github.com/rust-lang/crates.io-index#zeroize@1.8.2" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#ring@0.17.14", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#cc@1.2.57", + "registry+https://github.com/rust-lang/crates.io-index#cfg-if@1.0.4", + "registry+https://github.com/rust-lang/crates.io-index#getrandom@0.2.17", + "registry+https://github.com/rust-lang/crates.io-index#untrusted@0.9.0" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#roaring@0.10.12", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#bytemuck@1.25.0", + "registry+https://github.com/rust-lang/crates.io-index#byteorder@1.5.0" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#rsa@0.9.10", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#const-oid@0.9.6", + "registry+https://github.com/rust-lang/crates.io-index#digest@0.10.7", + "registry+https://github.com/rust-lang/crates.io-index#num-bigint-dig@0.8.6", + "registry+https://github.com/rust-lang/crates.io-index#num-integer@0.1.46", + "registry+https://github.com/rust-lang/crates.io-index#num-traits@0.2.19", + "registry+https://github.com/rust-lang/crates.io-index#pkcs1@0.7.5", + "registry+https://github.com/rust-lang/crates.io-index#pkcs8@0.10.2", + "registry+https://github.com/rust-lang/crates.io-index#rand_core@0.6.4", + "registry+https://github.com/rust-lang/crates.io-index#signature@2.2.0", + "registry+https://github.com/rust-lang/crates.io-index#spki@0.7.3", + "registry+https://github.com/rust-lang/crates.io-index#subtle@2.6.1", + "registry+https://github.com/rust-lang/crates.io-index#zeroize@1.8.2" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#rtrb@0.3.3" + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#rust-embed-impl@8.11.0", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#proc-macro2@1.0.106", + "registry+https://github.com/rust-lang/crates.io-index#quote@1.0.45", + "registry+https://github.com/rust-lang/crates.io-index#rust-embed-utils@8.11.0", + "registry+https://github.com/rust-lang/crates.io-index#syn@2.0.117", + "registry+https://github.com/rust-lang/crates.io-index#walkdir@2.5.0" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#rust-embed-utils@8.11.0", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#globset@0.4.18", + "registry+https://github.com/rust-lang/crates.io-index#sha2@0.10.9", + "registry+https://github.com/rust-lang/crates.io-index#walkdir@2.5.0" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#rust-embed@8.11.0", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#rust-embed-impl@8.11.0", + "registry+https://github.com/rust-lang/crates.io-index#rust-embed-utils@8.11.0", + "registry+https://github.com/rust-lang/crates.io-index#walkdir@2.5.0" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#rust-stemmers@1.2.0", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#serde@1.0.228", + "registry+https://github.com/rust-lang/crates.io-index#serde_derive@1.0.228" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#rustc-hash@1.1.0" + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#rustc-hash@2.1.1" + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#rustc_version@0.4.1", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#semver@1.0.27" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#rustls-native-certs@0.6.3", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#rustls-pemfile@1.0.4", + "registry+https://github.com/rust-lang/crates.io-index#schannel@0.1.29" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#rustls-native-certs@0.8.3", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#rustls-pki-types@1.14.0", + "registry+https://github.com/rust-lang/crates.io-index#schannel@0.1.29" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#rustls-pemfile@1.0.4", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#base64@0.21.7" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#rustls-pemfile@2.2.0", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#rustls-pki-types@1.14.0" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#rustls-pki-types@1.14.0", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#zeroize@1.8.2" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#rustls-platform-verifier@0.6.2", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#log@0.4.29", + "registry+https://github.com/rust-lang/crates.io-index#rustls@0.23.37", + "registry+https://github.com/rust-lang/crates.io-index#windows-sys@0.61.2" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#rustls-webpki@0.101.7", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#ring@0.17.14", + "registry+https://github.com/rust-lang/crates.io-index#untrusted@0.9.0" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#rustls-webpki@0.103.9", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#aws-lc-rs@1.16.2", + "registry+https://github.com/rust-lang/crates.io-index#ring@0.17.14", + "registry+https://github.com/rust-lang/crates.io-index#rustls-pki-types@1.14.0", + "registry+https://github.com/rust-lang/crates.io-index#untrusted@0.9.0" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#rustls@0.21.12", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#log@0.4.29", + "registry+https://github.com/rust-lang/crates.io-index#ring@0.17.14", + "registry+https://github.com/rust-lang/crates.io-index#rustls-webpki@0.101.7", + "registry+https://github.com/rust-lang/crates.io-index#sct@0.7.1" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#rustls@0.23.37", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#aws-lc-rs@1.16.2", + "registry+https://github.com/rust-lang/crates.io-index#log@0.4.29", + "registry+https://github.com/rust-lang/crates.io-index#once_cell@1.21.4", + "registry+https://github.com/rust-lang/crates.io-index#ring@0.17.14", + "registry+https://github.com/rust-lang/crates.io-index#rustls-pki-types@1.14.0", + "registry+https://github.com/rust-lang/crates.io-index#rustls-webpki@0.103.9", + "registry+https://github.com/rust-lang/crates.io-index#subtle@2.6.1", + "registry+https://github.com/rust-lang/crates.io-index#zeroize@1.8.2" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#rustversion@1.0.22" + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#rusty-fork@0.3.1", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#fnv@1.0.7", + "registry+https://github.com/rust-lang/crates.io-index#quick-error@1.2.3", + "registry+https://github.com/rust-lang/crates.io-index#tempfile@3.27.0", + "registry+https://github.com/rust-lang/crates.io-index#wait-timeout@0.2.1" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#ryu@1.0.23" + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#same-file@1.0.6", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#winapi-util@0.1.11" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#schannel@0.1.29", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#windows-sys@0.61.2" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#schemars@0.8.22", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#dyn-clone@1.0.20", + "registry+https://github.com/rust-lang/crates.io-index#schemars_derive@0.8.22", + "registry+https://github.com/rust-lang/crates.io-index#serde@1.0.228", + "registry+https://github.com/rust-lang/crates.io-index#serde_json@1.0.149" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#schemars_derive@0.8.22", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#proc-macro2@1.0.106", + "registry+https://github.com/rust-lang/crates.io-index#quote@1.0.45", + "registry+https://github.com/rust-lang/crates.io-index#serde_derive_internals@0.29.1", + "registry+https://github.com/rust-lang/crates.io-index#syn@2.0.117" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#scoped-tls@1.0.1" + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#scopeguard@1.2.0" + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#scratch@1.0.9" + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#sct@0.7.1", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#ring@0.17.14", + "registry+https://github.com/rust-lang/crates.io-index#untrusted@0.9.0" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#sea-query-binder@0.7.0", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#sea-query@0.32.7", + "registry+https://github.com/rust-lang/crates.io-index#sqlx@0.8.6" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#sea-query-derive@0.4.3", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#darling@0.20.11", + "registry+https://github.com/rust-lang/crates.io-index#heck@0.4.1", + "registry+https://github.com/rust-lang/crates.io-index#proc-macro2@1.0.106", + "registry+https://github.com/rust-lang/crates.io-index#quote@1.0.45", + "registry+https://github.com/rust-lang/crates.io-index#syn@2.0.117", + "registry+https://github.com/rust-lang/crates.io-index#thiserror@2.0.18" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#sea-query@0.32.7", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#inherent@1.0.13", + "registry+https://github.com/rust-lang/crates.io-index#sea-query-derive@0.4.3" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#sec1@0.3.0", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#base16ct@0.1.1", + "registry+https://github.com/rust-lang/crates.io-index#der@0.6.1", + "registry+https://github.com/rust-lang/crates.io-index#generic-array@0.14.7", + "registry+https://github.com/rust-lang/crates.io-index#pkcs8@0.9.0", + "registry+https://github.com/rust-lang/crates.io-index#subtle@2.6.1", + "registry+https://github.com/rust-lang/crates.io-index#zeroize@1.8.2" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#secrecy@0.8.0", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#serde@1.0.228", + "registry+https://github.com/rust-lang/crates.io-index#zeroize@1.8.2" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#semver@1.0.27" + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#seq-macro@0.3.6" + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#serde-pickle@1.2.0", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#byteorder@1.5.0", + "registry+https://github.com/rust-lang/crates.io-index#iter-read@1.1.0", + "registry+https://github.com/rust-lang/crates.io-index#num-bigint@0.4.6", + "registry+https://github.com/rust-lang/crates.io-index#num-traits@0.2.19", + "registry+https://github.com/rust-lang/crates.io-index#serde@1.0.228" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#serde-value@0.7.0", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#ordered-float@2.10.1", + "registry+https://github.com/rust-lang/crates.io-index#serde@1.0.228" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#serde@1.0.228", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#serde_core@1.0.228", + "registry+https://github.com/rust-lang/crates.io-index#serde_derive@1.0.228" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#serde_bytes@0.11.19", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#serde_core@1.0.228" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#serde_core@1.0.228" + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#serde_derive@1.0.228", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#proc-macro2@1.0.106", + "registry+https://github.com/rust-lang/crates.io-index#quote@1.0.45", + "registry+https://github.com/rust-lang/crates.io-index#syn@2.0.117" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#serde_derive_internals@0.29.1", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#proc-macro2@1.0.106", + "registry+https://github.com/rust-lang/crates.io-index#quote@1.0.45", + "registry+https://github.com/rust-lang/crates.io-index#syn@2.0.117" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#serde_json@1.0.149", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#itoa@1.0.18", + "registry+https://github.com/rust-lang/crates.io-index#memchr@2.8.0", + "registry+https://github.com/rust-lang/crates.io-index#serde_core@1.0.228", + "registry+https://github.com/rust-lang/crates.io-index#zmij@1.0.21" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#serde_path_to_error@0.1.20", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#itoa@1.0.18", + "registry+https://github.com/rust-lang/crates.io-index#serde_core@1.0.228" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#serde_spanned@0.6.9", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#serde@1.0.228" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#serde_urlencoded@0.7.1", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#form_urlencoded@1.2.2", + "registry+https://github.com/rust-lang/crates.io-index#itoa@1.0.18", + "registry+https://github.com/rust-lang/crates.io-index#ryu@1.0.23", + "registry+https://github.com/rust-lang/crates.io-index#serde@1.0.228" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#serde_yaml@0.9.34+deprecated", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#indexmap@2.13.0", + "registry+https://github.com/rust-lang/crates.io-index#itoa@1.0.18", + "registry+https://github.com/rust-lang/crates.io-index#ryu@1.0.23", + "registry+https://github.com/rust-lang/crates.io-index#serde@1.0.228", + "registry+https://github.com/rust-lang/crates.io-index#unsafe-libyaml@0.2.11" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#sha1@0.10.6", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#cfg-if@1.0.4", + "registry+https://github.com/rust-lang/crates.io-index#cpufeatures@0.2.17", + "registry+https://github.com/rust-lang/crates.io-index#digest@0.10.7" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#sha2@0.10.9", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#cfg-if@1.0.4", + "registry+https://github.com/rust-lang/crates.io-index#cpufeatures@0.2.17", + "registry+https://github.com/rust-lang/crates.io-index#digest@0.10.7" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#sharded-slab@0.1.7", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#lazy_static@1.5.0" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#shell-words@1.1.1" + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#shlex@1.3.0" + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#shuttle@0.7.1", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#assoc@0.1.3", + "registry+https://github.com/rust-lang/crates.io-index#bitvec@1.0.1", + "registry+https://github.com/rust-lang/crates.io-index#generator@0.8.8", + "registry+https://github.com/rust-lang/crates.io-index#hex@0.4.3", + "registry+https://github.com/rust-lang/crates.io-index#owo-colors@3.5.0", + "registry+https://github.com/rust-lang/crates.io-index#rand@0.8.5", + "registry+https://github.com/rust-lang/crates.io-index#rand_core@0.6.4", + "registry+https://github.com/rust-lang/crates.io-index#rand_pcg@0.3.1", + "registry+https://github.com/rust-lang/crates.io-index#scoped-tls@1.0.1", + "registry+https://github.com/rust-lang/crates.io-index#smallvec@1.15.1", + "registry+https://github.com/rust-lang/crates.io-index#tracing@0.1.44" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#signature@1.6.4", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#digest@0.10.7", + "registry+https://github.com/rust-lang/crates.io-index#rand_core@0.6.4" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#signature@2.2.0", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#digest@0.10.7", + "registry+https://github.com/rust-lang/crates.io-index#rand_core@0.6.4" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#simd-adler32@0.3.8" + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#simdutf8@0.1.5" + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#simsimd@6.5.16", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#cc@1.2.57" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#siphasher@1.0.2", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#serde@1.0.228" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#sketches-ddsketch@0.2.2", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#serde@1.0.228" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#slab@0.4.12" + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#small_ctor@0.1.2" + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#smallvec@1.15.1", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#serde@1.0.228" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#smawk@0.3.2" + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#snap@1.1.1" + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#socket2@0.5.10", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#windows-sys@0.52.0" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#socket2@0.6.3", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#windows-sys@0.61.2" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#spin@0.9.8", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#lock_api@0.4.14" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#spki@0.6.0", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#base64ct@1.8.3", + "registry+https://github.com/rust-lang/crates.io-index#der@0.6.1" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#spki@0.7.3", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#base64ct@1.8.3", + "registry+https://github.com/rust-lang/crates.io-index#der@0.7.10" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#sprs@0.11.4", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#alga@0.9.3", + "registry+https://github.com/rust-lang/crates.io-index#ndarray@0.17.2", + "registry+https://github.com/rust-lang/crates.io-index#num-complex@0.4.6", + "registry+https://github.com/rust-lang/crates.io-index#num-traits@0.2.19", + "registry+https://github.com/rust-lang/crates.io-index#num_cpus@1.17.0", + "registry+https://github.com/rust-lang/crates.io-index#rayon@1.11.0", + "registry+https://github.com/rust-lang/crates.io-index#smallvec@1.15.1" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#sqlx-core@0.8.6", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#base64@0.22.1", + "registry+https://github.com/rust-lang/crates.io-index#bytes@1.11.1", + "registry+https://github.com/rust-lang/crates.io-index#chrono@0.4.44", + "registry+https://github.com/rust-lang/crates.io-index#crc@3.4.0", + "registry+https://github.com/rust-lang/crates.io-index#crossbeam-queue@0.3.12", + "registry+https://github.com/rust-lang/crates.io-index#either@1.15.0", + "registry+https://github.com/rust-lang/crates.io-index#event-listener@5.4.1", + "registry+https://github.com/rust-lang/crates.io-index#futures-core@0.3.32", + "registry+https://github.com/rust-lang/crates.io-index#futures-intrusive@0.5.0", + "registry+https://github.com/rust-lang/crates.io-index#futures-io@0.3.32", + "registry+https://github.com/rust-lang/crates.io-index#futures-util@0.3.32", + "registry+https://github.com/rust-lang/crates.io-index#hashbrown@0.15.5", + "registry+https://github.com/rust-lang/crates.io-index#hashlink@0.10.0", + "registry+https://github.com/rust-lang/crates.io-index#indexmap@2.13.0", + "registry+https://github.com/rust-lang/crates.io-index#log@0.4.29", + "registry+https://github.com/rust-lang/crates.io-index#memchr@2.8.0", + "registry+https://github.com/rust-lang/crates.io-index#once_cell@1.21.4", + "registry+https://github.com/rust-lang/crates.io-index#percent-encoding@2.3.2", + "registry+https://github.com/rust-lang/crates.io-index#serde@1.0.228", + "registry+https://github.com/rust-lang/crates.io-index#serde_json@1.0.149", + "registry+https://github.com/rust-lang/crates.io-index#sha2@0.10.9", + "registry+https://github.com/rust-lang/crates.io-index#smallvec@1.15.1", + "registry+https://github.com/rust-lang/crates.io-index#thiserror@2.0.18", + "registry+https://github.com/rust-lang/crates.io-index#tokio@1.50.0", + "registry+https://github.com/rust-lang/crates.io-index#tokio-stream@0.1.18", + "registry+https://github.com/rust-lang/crates.io-index#tracing@0.1.44", + "registry+https://github.com/rust-lang/crates.io-index#url@2.5.8" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#sqlx-macros-core@0.8.6", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#dotenvy@0.15.7", + "registry+https://github.com/rust-lang/crates.io-index#either@1.15.0", + "registry+https://github.com/rust-lang/crates.io-index#heck@0.5.0", + "registry+https://github.com/rust-lang/crates.io-index#hex@0.4.3", + "registry+https://github.com/rust-lang/crates.io-index#once_cell@1.21.4", + "registry+https://github.com/rust-lang/crates.io-index#proc-macro2@1.0.106", + "registry+https://github.com/rust-lang/crates.io-index#quote@1.0.45", + "registry+https://github.com/rust-lang/crates.io-index#serde@1.0.228", + "registry+https://github.com/rust-lang/crates.io-index#serde_json@1.0.149", + "registry+https://github.com/rust-lang/crates.io-index#sha2@0.10.9", + "registry+https://github.com/rust-lang/crates.io-index#sqlx-core@0.8.6", + "registry+https://github.com/rust-lang/crates.io-index#sqlx-mysql@0.8.6", + "registry+https://github.com/rust-lang/crates.io-index#sqlx-postgres@0.8.6", + "registry+https://github.com/rust-lang/crates.io-index#sqlx-sqlite@0.8.6", + "registry+https://github.com/rust-lang/crates.io-index#syn@2.0.117", + "registry+https://github.com/rust-lang/crates.io-index#tokio@1.50.0", + "registry+https://github.com/rust-lang/crates.io-index#url@2.5.8" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#sqlx-macros@0.8.6", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#proc-macro2@1.0.106", + "registry+https://github.com/rust-lang/crates.io-index#quote@1.0.45", + "registry+https://github.com/rust-lang/crates.io-index#sqlx-core@0.8.6", + "registry+https://github.com/rust-lang/crates.io-index#sqlx-macros-core@0.8.6", + "registry+https://github.com/rust-lang/crates.io-index#syn@2.0.117" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#sqlx-mysql@0.8.6", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#atoi@2.0.0", + "registry+https://github.com/rust-lang/crates.io-index#base64@0.22.1", + "registry+https://github.com/rust-lang/crates.io-index#bitflags@2.11.0", + "registry+https://github.com/rust-lang/crates.io-index#byteorder@1.5.0", + "registry+https://github.com/rust-lang/crates.io-index#bytes@1.11.1", + "registry+https://github.com/rust-lang/crates.io-index#chrono@0.4.44", + "registry+https://github.com/rust-lang/crates.io-index#crc@3.4.0", + "registry+https://github.com/rust-lang/crates.io-index#digest@0.10.7", + "registry+https://github.com/rust-lang/crates.io-index#dotenvy@0.15.7", + "registry+https://github.com/rust-lang/crates.io-index#either@1.15.0", + "registry+https://github.com/rust-lang/crates.io-index#futures-channel@0.3.32", + "registry+https://github.com/rust-lang/crates.io-index#futures-core@0.3.32", + "registry+https://github.com/rust-lang/crates.io-index#futures-io@0.3.32", + "registry+https://github.com/rust-lang/crates.io-index#futures-util@0.3.32", + "registry+https://github.com/rust-lang/crates.io-index#generic-array@0.14.7", + "registry+https://github.com/rust-lang/crates.io-index#hex@0.4.3", + "registry+https://github.com/rust-lang/crates.io-index#hkdf@0.12.4", + "registry+https://github.com/rust-lang/crates.io-index#hmac@0.12.1", + "registry+https://github.com/rust-lang/crates.io-index#itoa@1.0.18", + "registry+https://github.com/rust-lang/crates.io-index#log@0.4.29", + "registry+https://github.com/rust-lang/crates.io-index#md-5@0.10.6", + "registry+https://github.com/rust-lang/crates.io-index#memchr@2.8.0", + "registry+https://github.com/rust-lang/crates.io-index#once_cell@1.21.4", + "registry+https://github.com/rust-lang/crates.io-index#percent-encoding@2.3.2", + "registry+https://github.com/rust-lang/crates.io-index#rand@0.8.5", + "registry+https://github.com/rust-lang/crates.io-index#rsa@0.9.10", + "registry+https://github.com/rust-lang/crates.io-index#serde@1.0.228", + "registry+https://github.com/rust-lang/crates.io-index#sha1@0.10.6", + "registry+https://github.com/rust-lang/crates.io-index#sha2@0.10.9", + "registry+https://github.com/rust-lang/crates.io-index#smallvec@1.15.1", + "registry+https://github.com/rust-lang/crates.io-index#sqlx-core@0.8.6", + "registry+https://github.com/rust-lang/crates.io-index#stringprep@0.1.5", + "registry+https://github.com/rust-lang/crates.io-index#thiserror@2.0.18", + "registry+https://github.com/rust-lang/crates.io-index#tracing@0.1.44", + "registry+https://github.com/rust-lang/crates.io-index#whoami@1.6.1" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#sqlx-postgres@0.8.6", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#atoi@2.0.0", + "registry+https://github.com/rust-lang/crates.io-index#base64@0.22.1", + "registry+https://github.com/rust-lang/crates.io-index#bitflags@2.11.0", + "registry+https://github.com/rust-lang/crates.io-index#byteorder@1.5.0", + "registry+https://github.com/rust-lang/crates.io-index#chrono@0.4.44", + "registry+https://github.com/rust-lang/crates.io-index#crc@3.4.0", + "registry+https://github.com/rust-lang/crates.io-index#dotenvy@0.15.7", + "registry+https://github.com/rust-lang/crates.io-index#etcetera@0.8.0", + "registry+https://github.com/rust-lang/crates.io-index#futures-channel@0.3.32", + "registry+https://github.com/rust-lang/crates.io-index#futures-core@0.3.32", + "registry+https://github.com/rust-lang/crates.io-index#futures-util@0.3.32", + "registry+https://github.com/rust-lang/crates.io-index#hex@0.4.3", + "registry+https://github.com/rust-lang/crates.io-index#hkdf@0.12.4", + "registry+https://github.com/rust-lang/crates.io-index#hmac@0.12.1", + "registry+https://github.com/rust-lang/crates.io-index#home@0.5.12", + "registry+https://github.com/rust-lang/crates.io-index#itoa@1.0.18", + "registry+https://github.com/rust-lang/crates.io-index#log@0.4.29", + "registry+https://github.com/rust-lang/crates.io-index#md-5@0.10.6", + "registry+https://github.com/rust-lang/crates.io-index#memchr@2.8.0", + "registry+https://github.com/rust-lang/crates.io-index#once_cell@1.21.4", + "registry+https://github.com/rust-lang/crates.io-index#rand@0.8.5", + "registry+https://github.com/rust-lang/crates.io-index#serde@1.0.228", + "registry+https://github.com/rust-lang/crates.io-index#serde_json@1.0.149", + "registry+https://github.com/rust-lang/crates.io-index#sha2@0.10.9", + "registry+https://github.com/rust-lang/crates.io-index#smallvec@1.15.1", + "registry+https://github.com/rust-lang/crates.io-index#sqlx-core@0.8.6", + "registry+https://github.com/rust-lang/crates.io-index#stringprep@0.1.5", + "registry+https://github.com/rust-lang/crates.io-index#thiserror@2.0.18", + "registry+https://github.com/rust-lang/crates.io-index#tracing@0.1.44", + "registry+https://github.com/rust-lang/crates.io-index#whoami@1.6.1" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#sqlx-sqlite@0.8.6", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#atoi@2.0.0", + "registry+https://github.com/rust-lang/crates.io-index#chrono@0.4.44", + "registry+https://github.com/rust-lang/crates.io-index#flume@0.11.1", + "registry+https://github.com/rust-lang/crates.io-index#futures-channel@0.3.32", + "registry+https://github.com/rust-lang/crates.io-index#futures-core@0.3.32", + "registry+https://github.com/rust-lang/crates.io-index#futures-executor@0.3.32", + "registry+https://github.com/rust-lang/crates.io-index#futures-intrusive@0.5.0", + "registry+https://github.com/rust-lang/crates.io-index#futures-util@0.3.32", + "registry+https://github.com/rust-lang/crates.io-index#libsqlite3-sys@0.30.1", + "registry+https://github.com/rust-lang/crates.io-index#log@0.4.29", + "registry+https://github.com/rust-lang/crates.io-index#percent-encoding@2.3.2", + "registry+https://github.com/rust-lang/crates.io-index#regex@1.12.3", + "registry+https://github.com/rust-lang/crates.io-index#serde@1.0.228", + "registry+https://github.com/rust-lang/crates.io-index#serde_urlencoded@0.7.1", + "registry+https://github.com/rust-lang/crates.io-index#sqlx-core@0.8.6", + "registry+https://github.com/rust-lang/crates.io-index#thiserror@2.0.18", + "registry+https://github.com/rust-lang/crates.io-index#tracing@0.1.44", + "registry+https://github.com/rust-lang/crates.io-index#url@2.5.8" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#sqlx@0.8.6", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#sqlx-core@0.8.6", + "registry+https://github.com/rust-lang/crates.io-index#sqlx-macros@0.8.6", + "registry+https://github.com/rust-lang/crates.io-index#sqlx-mysql@0.8.6", + "registry+https://github.com/rust-lang/crates.io-index#sqlx-postgres@0.8.6", + "registry+https://github.com/rust-lang/crates.io-index#sqlx-sqlite@0.8.6" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#stable_deref_trait@1.2.1" + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#static_assertions@1.1.0" + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#stringprep@0.1.5", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#unicode-bidi@0.3.18", + "registry+https://github.com/rust-lang/crates.io-index#unicode-normalization@0.1.25", + "registry+https://github.com/rust-lang/crates.io-index#unicode-properties@0.1.4" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#strsim@0.11.1" + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#strum@0.26.3", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#strum_macros@0.26.4" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#strum@0.27.2" + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#strum_macros@0.26.4", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#heck@0.5.0", + "registry+https://github.com/rust-lang/crates.io-index#proc-macro2@1.0.106", + "registry+https://github.com/rust-lang/crates.io-index#quote@1.0.45", + "registry+https://github.com/rust-lang/crates.io-index#rustversion@1.0.22", + "registry+https://github.com/rust-lang/crates.io-index#syn@2.0.117" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#strum_macros@0.27.2", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#heck@0.5.0", + "registry+https://github.com/rust-lang/crates.io-index#proc-macro2@1.0.106", + "registry+https://github.com/rust-lang/crates.io-index#quote@1.0.45", + "registry+https://github.com/rust-lang/crates.io-index#syn@2.0.117" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#subtle@2.6.1" + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#supports-color@3.0.2", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#is_ci@1.2.0" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#syn@1.0.109", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#proc-macro2@1.0.106", + "registry+https://github.com/rust-lang/crates.io-index#quote@1.0.45", + "registry+https://github.com/rust-lang/crates.io-index#unicode-ident@1.0.24" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#syn@2.0.117", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#proc-macro2@1.0.106", + "registry+https://github.com/rust-lang/crates.io-index#quote@1.0.45", + "registry+https://github.com/rust-lang/crates.io-index#unicode-ident@1.0.24" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#sync_wrapper@1.0.2", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#futures-core@0.3.32" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#synstructure@0.13.2", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#proc-macro2@1.0.106", + "registry+https://github.com/rust-lang/crates.io-index#quote@1.0.45", + "registry+https://github.com/rust-lang/crates.io-index#syn@2.0.117" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#tantivy-bitpacker@0.6.0", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#bitpacking@0.9.3" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#tantivy-columnar@0.3.0", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#downcast-rs@1.2.1", + "registry+https://github.com/rust-lang/crates.io-index#fastdivide@0.4.2", + "registry+https://github.com/rust-lang/crates.io-index#itertools@0.12.1", + "registry+https://github.com/rust-lang/crates.io-index#serde@1.0.228", + "registry+https://github.com/rust-lang/crates.io-index#tantivy-bitpacker@0.6.0", + "registry+https://github.com/rust-lang/crates.io-index#tantivy-common@0.7.0", + "registry+https://github.com/rust-lang/crates.io-index#tantivy-sstable@0.3.0", + "registry+https://github.com/rust-lang/crates.io-index#tantivy-stacker@0.3.0" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#tantivy-common@0.7.0", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#async-trait@0.1.89", + "registry+https://github.com/rust-lang/crates.io-index#byteorder@1.5.0", + "registry+https://github.com/rust-lang/crates.io-index#ownedbytes@0.7.0", + "registry+https://github.com/rust-lang/crates.io-index#serde@1.0.228", + "registry+https://github.com/rust-lang/crates.io-index#time@0.3.47" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#tantivy-fst@0.5.0", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#byteorder@1.5.0", + "registry+https://github.com/rust-lang/crates.io-index#regex-syntax@0.8.10", + "registry+https://github.com/rust-lang/crates.io-index#utf8-ranges@1.0.5" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#tantivy-query-grammar@0.22.0", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#nom@7.1.3" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#tantivy-sstable@0.3.0", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#tantivy-bitpacker@0.6.0", + "registry+https://github.com/rust-lang/crates.io-index#tantivy-common@0.7.0", + "registry+https://github.com/rust-lang/crates.io-index#tantivy-fst@0.5.0", + "registry+https://github.com/rust-lang/crates.io-index#zstd@0.13.3" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#tantivy-stacker@0.3.0", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#murmurhash32@0.3.1", + "registry+https://github.com/rust-lang/crates.io-index#rand_distr@0.4.3", + "registry+https://github.com/rust-lang/crates.io-index#tantivy-common@0.7.0" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#tantivy-tokenizer-api@0.3.0", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#serde@1.0.228" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#tantivy@0.22.1", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#aho-corasick@1.1.4", + "registry+https://github.com/rust-lang/crates.io-index#arc-swap@1.8.2", + "registry+https://github.com/rust-lang/crates.io-index#base64@0.22.1", + "registry+https://github.com/rust-lang/crates.io-index#bitpacking@0.9.3", + "registry+https://github.com/rust-lang/crates.io-index#byteorder@1.5.0", + "registry+https://github.com/rust-lang/crates.io-index#census@0.4.2", + "registry+https://github.com/rust-lang/crates.io-index#crc32fast@1.5.0", + "registry+https://github.com/rust-lang/crates.io-index#crossbeam-channel@0.5.15", + "registry+https://github.com/rust-lang/crates.io-index#downcast-rs@1.2.1", + "registry+https://github.com/rust-lang/crates.io-index#fastdivide@0.4.2", + "registry+https://github.com/rust-lang/crates.io-index#fnv@1.0.7", + "registry+https://github.com/rust-lang/crates.io-index#fs4@0.8.4", + "registry+https://github.com/rust-lang/crates.io-index#htmlescape@0.3.1", + "registry+https://github.com/rust-lang/crates.io-index#itertools@0.12.1", + "registry+https://github.com/rust-lang/crates.io-index#levenshtein_automata@0.2.1", + "registry+https://github.com/rust-lang/crates.io-index#log@0.4.29", + "registry+https://github.com/rust-lang/crates.io-index#lru@0.12.5", + "registry+https://github.com/rust-lang/crates.io-index#lz4_flex@0.11.6", + "registry+https://github.com/rust-lang/crates.io-index#measure_time@0.8.3", + "registry+https://github.com/rust-lang/crates.io-index#memmap2@0.9.10", + "registry+https://github.com/rust-lang/crates.io-index#num_cpus@1.17.0", + "registry+https://github.com/rust-lang/crates.io-index#once_cell@1.21.4", + "registry+https://github.com/rust-lang/crates.io-index#oneshot@0.1.13", + "registry+https://github.com/rust-lang/crates.io-index#rayon@1.11.0", + "registry+https://github.com/rust-lang/crates.io-index#regex@1.12.3", + "registry+https://github.com/rust-lang/crates.io-index#rust-stemmers@1.2.0", + "registry+https://github.com/rust-lang/crates.io-index#rustc-hash@1.1.0", + "registry+https://github.com/rust-lang/crates.io-index#serde@1.0.228", + "registry+https://github.com/rust-lang/crates.io-index#serde_json@1.0.149", + "registry+https://github.com/rust-lang/crates.io-index#sketches-ddsketch@0.2.2", + "registry+https://github.com/rust-lang/crates.io-index#smallvec@1.15.1", + "registry+https://github.com/rust-lang/crates.io-index#tantivy-bitpacker@0.6.0", + "registry+https://github.com/rust-lang/crates.io-index#tantivy-columnar@0.3.0", + "registry+https://github.com/rust-lang/crates.io-index#tantivy-common@0.7.0", + "registry+https://github.com/rust-lang/crates.io-index#tantivy-fst@0.5.0", + "registry+https://github.com/rust-lang/crates.io-index#tantivy-query-grammar@0.22.0", + "registry+https://github.com/rust-lang/crates.io-index#tantivy-stacker@0.3.0", + "registry+https://github.com/rust-lang/crates.io-index#tantivy-tokenizer-api@0.3.0", + "registry+https://github.com/rust-lang/crates.io-index#tempfile@3.27.0", + "registry+https://github.com/rust-lang/crates.io-index#thiserror@1.0.69", + "registry+https://github.com/rust-lang/crates.io-index#time@0.3.47", + "registry+https://github.com/rust-lang/crates.io-index#uuid@1.22.0", + "registry+https://github.com/rust-lang/crates.io-index#winapi@0.3.9" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#tap@1.0.1" + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#target-lexicon@0.13.5" + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#tempfile@3.27.0", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#fastrand@2.3.0", + "registry+https://github.com/rust-lang/crates.io-index#getrandom@0.4.2", + "registry+https://github.com/rust-lang/crates.io-index#once_cell@1.21.4", + "registry+https://github.com/rust-lang/crates.io-index#windows-sys@0.61.2" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#termcolor@1.4.1", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#winapi-util@0.1.11" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#textwrap@0.16.2", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#smawk@0.3.2", + "registry+https://github.com/rust-lang/crates.io-index#unicode-linebreak@0.1.5", + "registry+https://github.com/rust-lang/crates.io-index#unicode-width@0.2.0" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#thiserror-impl@1.0.69", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#proc-macro2@1.0.106", + "registry+https://github.com/rust-lang/crates.io-index#quote@1.0.45", + "registry+https://github.com/rust-lang/crates.io-index#syn@2.0.117" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#thiserror-impl@2.0.18", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#proc-macro2@1.0.106", + "registry+https://github.com/rust-lang/crates.io-index#quote@1.0.45", + "registry+https://github.com/rust-lang/crates.io-index#syn@2.0.117" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#thiserror@1.0.69", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#thiserror-impl@1.0.69" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#thiserror@2.0.18", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#thiserror-impl@2.0.18" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#thread_local@1.1.9", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#cfg-if@1.0.4" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#thrift@0.17.0", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#byteorder@1.5.0", + "registry+https://github.com/rust-lang/crates.io-index#integer-encoding@3.0.4", + "registry+https://github.com/rust-lang/crates.io-index#ordered-float@2.10.1" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#tiff@0.11.3", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#fax@0.2.6", + "registry+https://github.com/rust-lang/crates.io-index#flate2@1.1.9", + "registry+https://github.com/rust-lang/crates.io-index#half@2.7.1", + "registry+https://github.com/rust-lang/crates.io-index#quick-error@2.0.1", + "registry+https://github.com/rust-lang/crates.io-index#weezl@0.1.12", + "registry+https://github.com/rust-lang/crates.io-index#zune-jpeg@0.5.13" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#time-core@0.1.8" + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#time-macros@0.2.27", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#num-conv@0.2.0", + "registry+https://github.com/rust-lang/crates.io-index#time-core@0.1.8" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#time@0.3.47", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#deranged@0.5.8", + "registry+https://github.com/rust-lang/crates.io-index#itoa@1.0.18", + "registry+https://github.com/rust-lang/crates.io-index#num-conv@0.2.0", + "registry+https://github.com/rust-lang/crates.io-index#powerfmt@0.2.0", + "registry+https://github.com/rust-lang/crates.io-index#serde_core@1.0.228", + "registry+https://github.com/rust-lang/crates.io-index#time-core@0.1.8", + "registry+https://github.com/rust-lang/crates.io-index#time-macros@0.2.27" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#tiny-keccak@2.0.2", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#crunchy@0.2.4" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#tinystr@0.8.2", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#displaydoc@0.2.5", + "registry+https://github.com/rust-lang/crates.io-index#zerovec@0.11.5" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#tinytemplate@1.2.1", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#serde@1.0.228", + "registry+https://github.com/rust-lang/crates.io-index#serde_json@1.0.149" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#tinyvec@1.11.0", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#tinyvec_macros@0.1.1" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#tinyvec_macros@0.1.1" + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#tokio-io-timeout@1.2.1", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#pin-project-lite@0.2.17", + "registry+https://github.com/rust-lang/crates.io-index#tokio@1.50.0" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#tokio-macros@2.6.1", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#proc-macro2@1.0.106", + "registry+https://github.com/rust-lang/crates.io-index#quote@1.0.45", + "registry+https://github.com/rust-lang/crates.io-index#syn@2.0.117" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#tokio-native-tls@0.3.1", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#native-tls@0.2.18", + "registry+https://github.com/rust-lang/crates.io-index#tokio@1.50.0" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#tokio-rustls@0.24.1", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#rustls@0.21.12", + "registry+https://github.com/rust-lang/crates.io-index#tokio@1.50.0" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#tokio-rustls@0.26.4", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#rustls@0.23.37", + "registry+https://github.com/rust-lang/crates.io-index#tokio@1.50.0" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#tokio-stream@0.1.18", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#futures-core@0.3.32", + "registry+https://github.com/rust-lang/crates.io-index#pin-project-lite@0.2.17", + "registry+https://github.com/rust-lang/crates.io-index#tokio@1.50.0", + "registry+https://github.com/rust-lang/crates.io-index#tokio-util@0.7.18" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#tokio-util@0.7.18", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#bytes@1.11.1", + "registry+https://github.com/rust-lang/crates.io-index#futures-core@0.3.32", + "registry+https://github.com/rust-lang/crates.io-index#futures-sink@0.3.32", + "registry+https://github.com/rust-lang/crates.io-index#pin-project-lite@0.2.17", + "registry+https://github.com/rust-lang/crates.io-index#slab@0.4.12", + "registry+https://github.com/rust-lang/crates.io-index#tokio@1.50.0" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#tokio@1.50.0", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#bytes@1.11.1", + "registry+https://github.com/rust-lang/crates.io-index#mio@1.1.1", + "registry+https://github.com/rust-lang/crates.io-index#parking_lot@0.12.5", + "registry+https://github.com/rust-lang/crates.io-index#pin-project-lite@0.2.17", + "registry+https://github.com/rust-lang/crates.io-index#socket2@0.6.3", + "registry+https://github.com/rust-lang/crates.io-index#tokio-macros@2.6.1", + "registry+https://github.com/rust-lang/crates.io-index#windows-sys@0.61.2" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#toml@0.8.23", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#serde@1.0.228", + "registry+https://github.com/rust-lang/crates.io-index#serde_spanned@0.6.9", + "registry+https://github.com/rust-lang/crates.io-index#toml_datetime@0.6.11", + "registry+https://github.com/rust-lang/crates.io-index#toml_edit@0.22.27" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#toml_datetime@0.6.11", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#serde@1.0.228" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#toml_edit@0.22.27", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#indexmap@2.13.0", + "registry+https://github.com/rust-lang/crates.io-index#serde@1.0.228", + "registry+https://github.com/rust-lang/crates.io-index#serde_spanned@0.6.9", + "registry+https://github.com/rust-lang/crates.io-index#toml_datetime@0.6.11", + "registry+https://github.com/rust-lang/crates.io-index#toml_write@0.1.2", + "registry+https://github.com/rust-lang/crates.io-index#winnow@0.7.15" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#toml_write@0.1.2" + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#tonic-build@0.14.5", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#prettyplease@0.2.37", + "registry+https://github.com/rust-lang/crates.io-index#proc-macro2@1.0.106", + "registry+https://github.com/rust-lang/crates.io-index#quote@1.0.45", + "registry+https://github.com/rust-lang/crates.io-index#syn@2.0.117" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#tonic-prost-build@0.14.5", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#prettyplease@0.2.37", + "registry+https://github.com/rust-lang/crates.io-index#proc-macro2@1.0.106", + "registry+https://github.com/rust-lang/crates.io-index#prost-build@0.14.3", + "registry+https://github.com/rust-lang/crates.io-index#prost-types@0.14.3", + "registry+https://github.com/rust-lang/crates.io-index#quote@1.0.45", + "registry+https://github.com/rust-lang/crates.io-index#syn@2.0.117", + "registry+https://github.com/rust-lang/crates.io-index#tempfile@3.27.0", + "registry+https://github.com/rust-lang/crates.io-index#tonic-build@0.14.5" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#tonic-prost@0.14.5", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#bytes@1.11.1", + "registry+https://github.com/rust-lang/crates.io-index#prost@0.14.3", + "registry+https://github.com/rust-lang/crates.io-index#tonic@0.14.5" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#tonic@0.12.3", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#async-stream@0.3.6", + "registry+https://github.com/rust-lang/crates.io-index#async-trait@0.1.89", + "registry+https://github.com/rust-lang/crates.io-index#axum@0.7.9", + "registry+https://github.com/rust-lang/crates.io-index#base64@0.22.1", + "registry+https://github.com/rust-lang/crates.io-index#bytes@1.11.1", + "registry+https://github.com/rust-lang/crates.io-index#h2@0.4.13", + "registry+https://github.com/rust-lang/crates.io-index#http@1.4.0", + "registry+https://github.com/rust-lang/crates.io-index#http-body@1.0.1", + "registry+https://github.com/rust-lang/crates.io-index#http-body-util@0.1.3", + "registry+https://github.com/rust-lang/crates.io-index#hyper@1.8.1", + "registry+https://github.com/rust-lang/crates.io-index#hyper-timeout@0.5.2", + "registry+https://github.com/rust-lang/crates.io-index#hyper-util@0.1.20", + "registry+https://github.com/rust-lang/crates.io-index#percent-encoding@2.3.2", + "registry+https://github.com/rust-lang/crates.io-index#pin-project@1.1.11", + "registry+https://github.com/rust-lang/crates.io-index#prost@0.13.5", + "registry+https://github.com/rust-lang/crates.io-index#socket2@0.5.10", + "registry+https://github.com/rust-lang/crates.io-index#tokio@1.50.0", + "registry+https://github.com/rust-lang/crates.io-index#tokio-stream@0.1.18", + "registry+https://github.com/rust-lang/crates.io-index#tower@0.4.13", + "registry+https://github.com/rust-lang/crates.io-index#tower-layer@0.3.3", + "registry+https://github.com/rust-lang/crates.io-index#tower-service@0.3.3", + "registry+https://github.com/rust-lang/crates.io-index#tracing@0.1.44" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#tonic@0.14.5", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#async-trait@0.1.89", + "registry+https://github.com/rust-lang/crates.io-index#axum@0.8.8", + "registry+https://github.com/rust-lang/crates.io-index#base64@0.22.1", + "registry+https://github.com/rust-lang/crates.io-index#bytes@1.11.1", + "registry+https://github.com/rust-lang/crates.io-index#flate2@1.1.9", + "registry+https://github.com/rust-lang/crates.io-index#h2@0.4.13", + "registry+https://github.com/rust-lang/crates.io-index#http@1.4.0", + "registry+https://github.com/rust-lang/crates.io-index#http-body@1.0.1", + "registry+https://github.com/rust-lang/crates.io-index#http-body-util@0.1.3", + "registry+https://github.com/rust-lang/crates.io-index#hyper@1.8.1", + "registry+https://github.com/rust-lang/crates.io-index#hyper-timeout@0.5.2", + "registry+https://github.com/rust-lang/crates.io-index#hyper-util@0.1.20", + "registry+https://github.com/rust-lang/crates.io-index#percent-encoding@2.3.2", + "registry+https://github.com/rust-lang/crates.io-index#pin-project@1.1.11", + "registry+https://github.com/rust-lang/crates.io-index#socket2@0.6.3", + "registry+https://github.com/rust-lang/crates.io-index#sync_wrapper@1.0.2", + "registry+https://github.com/rust-lang/crates.io-index#tokio@1.50.0", + "registry+https://github.com/rust-lang/crates.io-index#tokio-rustls@0.26.4", + "registry+https://github.com/rust-lang/crates.io-index#tokio-stream@0.1.18", + "registry+https://github.com/rust-lang/crates.io-index#tower@0.5.3", + "registry+https://github.com/rust-lang/crates.io-index#tower-layer@0.3.3", + "registry+https://github.com/rust-lang/crates.io-index#tower-service@0.3.3", + "registry+https://github.com/rust-lang/crates.io-index#tracing@0.1.44", + "registry+https://github.com/rust-lang/crates.io-index#webpki-roots@1.0.6" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#tower-http@0.4.4", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#base64@0.21.7", + "registry+https://github.com/rust-lang/crates.io-index#bitflags@2.11.0", + "registry+https://github.com/rust-lang/crates.io-index#bytes@1.11.1", + "registry+https://github.com/rust-lang/crates.io-index#futures-core@0.3.32", + "registry+https://github.com/rust-lang/crates.io-index#futures-util@0.3.32", + "registry+https://github.com/rust-lang/crates.io-index#http@0.2.12", + "registry+https://github.com/rust-lang/crates.io-index#http-body@0.4.6", + "registry+https://github.com/rust-lang/crates.io-index#http-range-header@0.3.1", + "registry+https://github.com/rust-lang/crates.io-index#mime@0.3.17", + "registry+https://github.com/rust-lang/crates.io-index#pin-project-lite@0.2.17", + "registry+https://github.com/rust-lang/crates.io-index#tower-layer@0.3.3", + "registry+https://github.com/rust-lang/crates.io-index#tower-service@0.3.3", + "registry+https://github.com/rust-lang/crates.io-index#tracing@0.1.44" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#tower-http@0.6.8", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#bitflags@2.11.0", + "registry+https://github.com/rust-lang/crates.io-index#bytes@1.11.1", + "registry+https://github.com/rust-lang/crates.io-index#futures-util@0.3.32", + "registry+https://github.com/rust-lang/crates.io-index#http@1.4.0", + "registry+https://github.com/rust-lang/crates.io-index#http-body@1.0.1", + "registry+https://github.com/rust-lang/crates.io-index#iri-string@0.7.10", + "registry+https://github.com/rust-lang/crates.io-index#pin-project-lite@0.2.17", + "registry+https://github.com/rust-lang/crates.io-index#tower@0.5.3", + "registry+https://github.com/rust-lang/crates.io-index#tower-layer@0.3.3", + "registry+https://github.com/rust-lang/crates.io-index#tower-service@0.3.3", + "registry+https://github.com/rust-lang/crates.io-index#tracing@0.1.44" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#tower-layer@0.3.3" + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#tower-service@0.3.3" + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#tower@0.4.13", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#futures-core@0.3.32", + "registry+https://github.com/rust-lang/crates.io-index#futures-util@0.3.32", + "registry+https://github.com/rust-lang/crates.io-index#indexmap@1.9.3", + "registry+https://github.com/rust-lang/crates.io-index#pin-project@1.1.11", + "registry+https://github.com/rust-lang/crates.io-index#pin-project-lite@0.2.17", + "registry+https://github.com/rust-lang/crates.io-index#rand@0.8.5", + "registry+https://github.com/rust-lang/crates.io-index#slab@0.4.12", + "registry+https://github.com/rust-lang/crates.io-index#tokio@1.50.0", + "registry+https://github.com/rust-lang/crates.io-index#tokio-util@0.7.18", + "registry+https://github.com/rust-lang/crates.io-index#tower-layer@0.3.3", + "registry+https://github.com/rust-lang/crates.io-index#tower-service@0.3.3", + "registry+https://github.com/rust-lang/crates.io-index#tracing@0.1.44" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#tower@0.5.3", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#futures-core@0.3.32", + "registry+https://github.com/rust-lang/crates.io-index#futures-util@0.3.32", + "registry+https://github.com/rust-lang/crates.io-index#indexmap@2.13.0", + "registry+https://github.com/rust-lang/crates.io-index#pin-project-lite@0.2.17", + "registry+https://github.com/rust-lang/crates.io-index#slab@0.4.12", + "registry+https://github.com/rust-lang/crates.io-index#sync_wrapper@1.0.2", + "registry+https://github.com/rust-lang/crates.io-index#tokio@1.50.0", + "registry+https://github.com/rust-lang/crates.io-index#tokio-util@0.7.18", + "registry+https://github.com/rust-lang/crates.io-index#tower-layer@0.3.3", + "registry+https://github.com/rust-lang/crates.io-index#tower-service@0.3.3", + "registry+https://github.com/rust-lang/crates.io-index#tracing@0.1.44" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#tracing-attributes@0.1.31", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#proc-macro2@1.0.106", + "registry+https://github.com/rust-lang/crates.io-index#quote@1.0.45", + "registry+https://github.com/rust-lang/crates.io-index#syn@2.0.117" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#tracing-core@0.1.36", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#once_cell@1.21.4" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#tracing-log@0.2.0", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#log@0.4.29", + "registry+https://github.com/rust-lang/crates.io-index#once_cell@1.21.4", + "registry+https://github.com/rust-lang/crates.io-index#tracing-core@0.1.36" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#tracing-opentelemetry@0.28.0", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#once_cell@1.21.4", + "registry+https://github.com/rust-lang/crates.io-index#opentelemetry@0.27.1", + "registry+https://github.com/rust-lang/crates.io-index#opentelemetry_sdk@0.27.1", + "registry+https://github.com/rust-lang/crates.io-index#smallvec@1.15.1", + "registry+https://github.com/rust-lang/crates.io-index#tracing@0.1.44", + "registry+https://github.com/rust-lang/crates.io-index#tracing-core@0.1.36", + "registry+https://github.com/rust-lang/crates.io-index#tracing-log@0.2.0", + "registry+https://github.com/rust-lang/crates.io-index#tracing-subscriber@0.3.23" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#tracing-subscriber@0.3.23", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#matchers@0.2.0", + "registry+https://github.com/rust-lang/crates.io-index#nu-ansi-term@0.50.3", + "registry+https://github.com/rust-lang/crates.io-index#once_cell@1.21.4", + "registry+https://github.com/rust-lang/crates.io-index#regex-automata@0.4.14", + "registry+https://github.com/rust-lang/crates.io-index#sharded-slab@0.1.7", + "registry+https://github.com/rust-lang/crates.io-index#smallvec@1.15.1", + "registry+https://github.com/rust-lang/crates.io-index#thread_local@1.1.9", + "registry+https://github.com/rust-lang/crates.io-index#tracing@0.1.44", + "registry+https://github.com/rust-lang/crates.io-index#tracing-core@0.1.36", + "registry+https://github.com/rust-lang/crates.io-index#tracing-log@0.2.0" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#tracing@0.1.44", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#log@0.4.29", + "registry+https://github.com/rust-lang/crates.io-index#pin-project-lite@0.2.17", + "registry+https://github.com/rust-lang/crates.io-index#tracing-attributes@0.1.31", + "registry+https://github.com/rust-lang/crates.io-index#tracing-core@0.1.36" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#try-lock@0.2.5" + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#tui-input@0.12.1", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#crossterm@0.29.0", + "registry+https://github.com/rust-lang/crates.io-index#unicode-width@0.2.0" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#twox-hash@2.1.2", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#rand@0.9.2" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#typed-path@0.12.3" + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#typenum@1.19.0" + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#ucd-trie@0.1.7" + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#unarray@0.1.4" + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#uncased@0.9.10", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#version_check@0.9.5" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#unicase@2.9.0" + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#unicode-bidi@0.3.18" + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#unicode-ident@1.0.24" + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#unicode-linebreak@0.1.5" + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#unicode-normalization@0.1.25", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#tinyvec@1.11.0" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#unicode-properties@0.1.4" + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#unicode-segmentation@1.12.0" + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#unicode-truncate@1.1.0", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#itertools@0.13.0", + "registry+https://github.com/rust-lang/crates.io-index#unicode-segmentation@1.12.0", + "registry+https://github.com/rust-lang/crates.io-index#unicode-width@0.1.14" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#unicode-width@0.1.14" + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#unicode-width@0.2.0" + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#unindent@0.2.4" + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#unsafe-libyaml@0.2.11" + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#untrusted@0.7.1" + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#untrusted@0.9.0" + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#url@2.5.8", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#form_urlencoded@1.2.2", + "registry+https://github.com/rust-lang/crates.io-index#idna@1.1.0", + "registry+https://github.com/rust-lang/crates.io-index#percent-encoding@2.3.2", + "registry+https://github.com/rust-lang/crates.io-index#serde@1.0.228" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#urlencoding@2.1.3" + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#usearch@2.23.0", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#cxx@1.0.194", + "registry+https://github.com/rust-lang/crates.io-index#cxx-build@1.0.194" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#utf8-ranges@1.0.5" + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#utf8_iter@1.0.4" + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#utf8parse@0.2.2" + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#utoipa-axum@0.2.0", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#axum@0.8.8", + "registry+https://github.com/rust-lang/crates.io-index#paste@1.0.15", + "registry+https://github.com/rust-lang/crates.io-index#tower-layer@0.3.3", + "registry+https://github.com/rust-lang/crates.io-index#tower-service@0.3.3", + "registry+https://github.com/rust-lang/crates.io-index#utoipa@5.4.0" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#utoipa-gen@5.4.0", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#proc-macro2@1.0.106", + "registry+https://github.com/rust-lang/crates.io-index#quote@1.0.45", + "registry+https://github.com/rust-lang/crates.io-index#regex@1.12.3", + "registry+https://github.com/rust-lang/crates.io-index#syn@2.0.117", + "registry+https://github.com/rust-lang/crates.io-index#uuid@1.22.0" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#utoipa-swagger-ui@9.0.2", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#axum@0.8.8", + "registry+https://github.com/rust-lang/crates.io-index#base64@0.22.1", + "registry+https://github.com/rust-lang/crates.io-index#mime_guess@2.0.5", + "registry+https://github.com/rust-lang/crates.io-index#regex@1.12.3", + "registry+https://github.com/rust-lang/crates.io-index#rust-embed@8.11.0", + "registry+https://github.com/rust-lang/crates.io-index#serde@1.0.228", + "registry+https://github.com/rust-lang/crates.io-index#serde_json@1.0.149", + "registry+https://github.com/rust-lang/crates.io-index#url@2.5.8", + "registry+https://github.com/rust-lang/crates.io-index#utoipa@5.4.0", + "registry+https://github.com/rust-lang/crates.io-index#zip@3.0.0" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#utoipa@5.4.0", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#indexmap@2.13.0", + "registry+https://github.com/rust-lang/crates.io-index#serde@1.0.228", + "registry+https://github.com/rust-lang/crates.io-index#serde_json@1.0.149", + "registry+https://github.com/rust-lang/crates.io-index#utoipa-gen@5.4.0" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#uuid@1.22.0", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#getrandom@0.4.2", + "registry+https://github.com/rust-lang/crates.io-index#rand@0.10.0", + "registry+https://github.com/rust-lang/crates.io-index#serde_core@1.0.228" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#validator@0.19.0", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#idna@1.1.0", + "registry+https://github.com/rust-lang/crates.io-index#once_cell@1.21.4", + "registry+https://github.com/rust-lang/crates.io-index#regex@1.12.3", + "registry+https://github.com/rust-lang/crates.io-index#serde@1.0.228", + "registry+https://github.com/rust-lang/crates.io-index#serde_derive@1.0.228", + "registry+https://github.com/rust-lang/crates.io-index#serde_json@1.0.149", + "registry+https://github.com/rust-lang/crates.io-index#url@2.5.8", + "registry+https://github.com/rust-lang/crates.io-index#validator_derive@0.19.0" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#validator_derive@0.19.0", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#darling@0.20.11", + "registry+https://github.com/rust-lang/crates.io-index#once_cell@1.21.4", + "registry+https://github.com/rust-lang/crates.io-index#proc-macro-error2@2.0.1", + "registry+https://github.com/rust-lang/crates.io-index#proc-macro2@1.0.106", + "registry+https://github.com/rust-lang/crates.io-index#quote@1.0.45", + "registry+https://github.com/rust-lang/crates.io-index#syn@2.0.117" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#vcpkg@0.2.15" + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#version_check@0.9.5" + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#vsimd@0.8.0" + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#wait-timeout@0.2.1" + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#walkdir@2.5.0", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#same-file@1.0.6", + "registry+https://github.com/rust-lang/crates.io-index#winapi-util@0.1.11" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#want@0.3.1", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#try-lock@0.2.5" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#web-time@1.1.0" + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#webbrowser@1.2.0", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#log@0.4.29", + "registry+https://github.com/rust-lang/crates.io-index#url@2.5.8" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#webpki-roots@1.0.6", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#rustls-pki-types@1.14.0" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#weezl@0.1.12" + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#whoami@1.6.1" + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#winapi-util@0.1.11", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#windows-sys@0.61.2" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#winapi@0.3.9" + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#windows-link@0.2.1" + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#windows-registry@0.6.1", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#windows-link@0.2.1", + "registry+https://github.com/rust-lang/crates.io-index#windows-result@0.4.1", + "registry+https://github.com/rust-lang/crates.io-index#windows-strings@0.5.1" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#windows-result@0.4.1", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#windows-link@0.2.1" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#windows-strings@0.5.1", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#windows-link@0.2.1" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#windows-sys@0.48.0", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#windows-targets@0.48.5" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#windows-sys@0.52.0", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#windows-targets@0.52.6" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#windows-sys@0.59.0", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#windows-targets@0.52.6" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#windows-sys@0.60.2", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#windows-targets@0.53.5" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#windows-sys@0.61.2", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#windows-link@0.2.1" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#windows-targets@0.48.5", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#windows_x86_64_msvc@0.48.5" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#windows-targets@0.52.6", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#windows_x86_64_msvc@0.52.6" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#windows-targets@0.53.5", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#windows_x86_64_msvc@0.53.1" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#windows_x86_64_msvc@0.48.5" + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#windows_x86_64_msvc@0.52.6" + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#windows_x86_64_msvc@0.53.1" + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#winnow@0.7.15", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#memchr@2.8.0" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#writeable@0.6.2" + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#wyz@0.5.1", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#tap@1.0.1" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#xmlparser@0.13.6" + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#yansi@1.0.1" + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#yoke-derive@0.8.1", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#proc-macro2@1.0.106", + "registry+https://github.com/rust-lang/crates.io-index#quote@1.0.45", + "registry+https://github.com/rust-lang/crates.io-index#syn@2.0.117", + "registry+https://github.com/rust-lang/crates.io-index#synstructure@0.13.2" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#yoke@0.8.1", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#stable_deref_trait@1.2.1", + "registry+https://github.com/rust-lang/crates.io-index#yoke-derive@0.8.1", + "registry+https://github.com/rust-lang/crates.io-index#zerofrom@0.1.6" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#zerocopy-derive@0.8.47", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#proc-macro2@1.0.106", + "registry+https://github.com/rust-lang/crates.io-index#quote@1.0.45", + "registry+https://github.com/rust-lang/crates.io-index#syn@2.0.117" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#zerocopy@0.8.47", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#zerocopy-derive@0.8.47" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#zerofrom-derive@0.1.6", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#proc-macro2@1.0.106", + "registry+https://github.com/rust-lang/crates.io-index#quote@1.0.45", + "registry+https://github.com/rust-lang/crates.io-index#syn@2.0.117", + "registry+https://github.com/rust-lang/crates.io-index#synstructure@0.13.2" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#zerofrom@0.1.6", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#zerofrom-derive@0.1.6" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#zeroize@1.8.2" + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#zerotrie@0.2.3", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#displaydoc@0.2.5", + "registry+https://github.com/rust-lang/crates.io-index#yoke@0.8.1", + "registry+https://github.com/rust-lang/crates.io-index#zerofrom@0.1.6" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#zerovec-derive@0.11.2", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#proc-macro2@1.0.106", + "registry+https://github.com/rust-lang/crates.io-index#quote@1.0.45", + "registry+https://github.com/rust-lang/crates.io-index#syn@2.0.117" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#zerovec@0.11.5", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#yoke@0.8.1", + "registry+https://github.com/rust-lang/crates.io-index#zerofrom@0.1.6", + "registry+https://github.com/rust-lang/crates.io-index#zerovec-derive@0.11.2" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#zip-extract@0.2.3", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#log@0.4.29", + "registry+https://github.com/rust-lang/crates.io-index#thiserror@2.0.18", + "registry+https://github.com/rust-lang/crates.io-index#zip@8.3.0" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#zip@3.0.0", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#crc32fast@1.5.0", + "registry+https://github.com/rust-lang/crates.io-index#flate2@1.1.9", + "registry+https://github.com/rust-lang/crates.io-index#indexmap@2.13.0", + "registry+https://github.com/rust-lang/crates.io-index#memchr@2.8.0", + "registry+https://github.com/rust-lang/crates.io-index#zopfli@0.8.3" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#zip@8.3.0", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#aes@0.8.4", + "registry+https://github.com/rust-lang/crates.io-index#bzip2@0.6.1", + "registry+https://github.com/rust-lang/crates.io-index#constant_time_eq@0.4.2", + "registry+https://github.com/rust-lang/crates.io-index#crc32fast@1.5.0", + "registry+https://github.com/rust-lang/crates.io-index#deflate64@0.1.11", + "registry+https://github.com/rust-lang/crates.io-index#flate2@1.1.9", + "registry+https://github.com/rust-lang/crates.io-index#getrandom@0.4.2", + "registry+https://github.com/rust-lang/crates.io-index#hmac@0.12.1", + "registry+https://github.com/rust-lang/crates.io-index#indexmap@2.13.0", + "registry+https://github.com/rust-lang/crates.io-index#lzma-rust2@0.16.2", + "registry+https://github.com/rust-lang/crates.io-index#memchr@2.8.0", + "registry+https://github.com/rust-lang/crates.io-index#pbkdf2@0.12.2", + "registry+https://github.com/rust-lang/crates.io-index#ppmd-rust@1.4.0", + "registry+https://github.com/rust-lang/crates.io-index#sha1@0.10.6", + "registry+https://github.com/rust-lang/crates.io-index#time@0.3.47", + "registry+https://github.com/rust-lang/crates.io-index#typed-path@0.12.3", + "registry+https://github.com/rust-lang/crates.io-index#zeroize@1.8.2", + "registry+https://github.com/rust-lang/crates.io-index#zopfli@0.8.3", + "registry+https://github.com/rust-lang/crates.io-index#zstd@0.13.3" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#zlib-rs@0.6.3" + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#zmij@1.0.21" + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#zopfli@0.8.3", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#bumpalo@3.20.2", + "registry+https://github.com/rust-lang/crates.io-index#crc32fast@1.5.0", + "registry+https://github.com/rust-lang/crates.io-index#log@0.4.29", + "registry+https://github.com/rust-lang/crates.io-index#simd-adler32@0.3.8" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#zstd-safe@7.2.4", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#zstd-sys@2.0.16+zstd.1.5.7" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#zstd-sys@2.0.16+zstd.1.5.7", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#cc@1.2.57", + "registry+https://github.com/rust-lang/crates.io-index#pkg-config@0.3.32" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#zstd@0.13.3", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#zstd-safe@7.2.4" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#zune-core@0.5.1" + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#zune-jpeg@0.5.13", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#zune-core@0.5.1" + ] + } + ] +} \ No newline at end of file diff --git a/python/user_packages/Python313/site-packages/chromadb/__pycache__/__init__.cpython-313.pyc b/python/user_packages/Python313/site-packages/chromadb/__pycache__/__init__.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0057c0567d0175575bbc80056f51c0ed98b6f26d Binary files /dev/null and b/python/user_packages/Python313/site-packages/chromadb/__pycache__/__init__.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/chromadb/__pycache__/app.cpython-313.pyc b/python/user_packages/Python313/site-packages/chromadb/__pycache__/app.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a14a4f59da70175ce0255f8c5e061f48812e9311 Binary files /dev/null and b/python/user_packages/Python313/site-packages/chromadb/__pycache__/app.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/chromadb/__pycache__/base_types.cpython-313.pyc b/python/user_packages/Python313/site-packages/chromadb/__pycache__/base_types.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..409d369407bae0aa88bb60348b155791c49abc79 Binary files /dev/null and b/python/user_packages/Python313/site-packages/chromadb/__pycache__/base_types.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/chromadb/__pycache__/config.cpython-313.pyc b/python/user_packages/Python313/site-packages/chromadb/__pycache__/config.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..41f26cc9cfd11f2a5b30201bffacfdd81a5a43a0 Binary files /dev/null and b/python/user_packages/Python313/site-packages/chromadb/__pycache__/config.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/chromadb/__pycache__/errors.cpython-313.pyc b/python/user_packages/Python313/site-packages/chromadb/__pycache__/errors.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..42be8cab000bff57d4a188036f8420459672c0ff Binary files /dev/null and b/python/user_packages/Python313/site-packages/chromadb/__pycache__/errors.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/chromadb/__pycache__/serde.cpython-313.pyc b/python/user_packages/Python313/site-packages/chromadb/__pycache__/serde.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..cc28ddda6e0a8032090ba667ecfc99245903b005 Binary files /dev/null and b/python/user_packages/Python313/site-packages/chromadb/__pycache__/serde.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/chromadb/__pycache__/types.cpython-313.pyc b/python/user_packages/Python313/site-packages/chromadb/__pycache__/types.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..be84fd3bb5206564230cca8356232554d7a9e678 Binary files /dev/null and b/python/user_packages/Python313/site-packages/chromadb/__pycache__/types.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/chromadb/api/__init__.py b/python/user_packages/Python313/site-packages/chromadb/api/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..443289406663683317064a218b38917da2699ed2 --- /dev/null +++ b/python/user_packages/Python313/site-packages/chromadb/api/__init__.py @@ -0,0 +1,973 @@ +from chromadb.api.types import * # noqa: F401, F403 +from chromadb.execution.expression import ( # noqa: F401, F403 + Search, + Key, + K, + SearchWhere, + And, + Or, + Eq, + Ne, + Gt, + Gte, + Lt, + Lte, + In, + Nin, + Regex, + NotRegex, + Contains, + NotContains, + Limit, + Select, + Rank, + Abs, + Div, + Exp, + Log, + Max, + Min, + Mul, + Knn, + Rrf, + Sub, + Sum, + Val, + Aggregate, + MinK, + MaxK, + GroupBy, +) + +from abc import ABC, abstractmethod +from typing import Sequence, Optional, List, Dict, Any, Tuple +from uuid import UUID + +from overrides import override +from chromadb.api.collection_configuration import ( + CreateCollectionConfiguration, + UpdateCollectionConfiguration, +) +from chromadb.config import DEFAULT_DATABASE, DEFAULT_TENANT +from chromadb.api.types import ( + CollectionMetadata, + DeleteResult, + Documents, + Embeddable, + EmbeddingFunction, + DataLoader, + Embeddings, + IDs, + Include, + IncludeMetadataDocumentsDistances, + IncludeMetadataDocuments, + Loadable, + Metadatas, + ReadLevel, + Schema, + URIs, + Where, + QueryResult, + GetResult, + WhereDocument, + SearchResult, + DefaultEmbeddingFunction, +) + +from chromadb.auth import UserIdentity +from chromadb.config import Component, Settings +from chromadb.types import Database, Tenant, Collection as CollectionModel +from chromadb.api.models.Collection import Collection +from chromadb.api.models.AttachedFunction import AttachedFunction + +# Re-export the async version +from chromadb.api.async_api import ( # noqa: F401 + AsyncBaseAPI as AsyncBaseAPI, + AsyncClientAPI as AsyncClientAPI, + AsyncAdminAPI as AsyncAdminAPI, + AsyncServerAPI as AsyncServerAPI, +) + + +class BaseAPI(ABC): + @abstractmethod + def heartbeat(self) -> int: + """Get the current time in nanoseconds since epoch. + Used to check if the server is alive. + + Returns: + int: The current time in nanoseconds since epoch + + """ + pass + + # + # COLLECTION METHODS + # + @abstractmethod + def count_collections(self) -> int: + """Count the number of collections. + + Returns: + int: The number of collections. + + Examples: + ```python + client.count_collections() + # 1 + ``` + """ + pass + + def _modify( + self, + id: UUID, + new_name: Optional[str] = None, + new_metadata: Optional[CollectionMetadata] = None, + new_configuration: Optional[UpdateCollectionConfiguration] = None, + ) -> None: + """[Internal] Modify a collection by UUID. Can update the name and/or metadata. + + Args: + id: The internal UUID of the collection to modify. + new_name: The new name of the collection. + If None, the existing name will remain. Defaults to None. + new_metadata: The new metadata to associate with the collection. + Defaults to None. + new_configuration: The new configuration to associate with the collection. + Defaults to None. + """ + pass + + @abstractmethod + def delete_collection( + self, + name: str, + ) -> None: + """Delete a collection with the given name. + Args: + name: The name of the collection to delete. + + Raises: + ValueError: If the collection does not exist. + + Examples: + ```python + client.delete_collection("my_collection") + ``` + """ + pass + + # + # ITEM METHODS + # + + @abstractmethod + def _add( + self, + ids: IDs, + collection_id: UUID, + embeddings: Embeddings, + metadatas: Optional[Metadatas] = None, + documents: Optional[Documents] = None, + uris: Optional[URIs] = None, + ) -> bool: + """[Internal] Add embeddings to a collection specified by UUID. + If (some) ids already exist, only the new embeddings will be added. + + Args: + ids: The ids to associate with the embeddings. + collection_id: The UUID of the collection to add the embeddings to. + embedding: The sequence of embeddings to add. + metadata: The metadata to associate with the embeddings. Defaults to None. + documents: The documents to associate with the embeddings. Defaults to None. + uris: URIs of data sources for each embedding. Defaults to None. + + Returns: + True if the embeddings were added successfully. + """ + pass + + @abstractmethod + def _update( + self, + collection_id: UUID, + ids: IDs, + embeddings: Optional[Embeddings] = None, + metadatas: Optional[Metadatas] = None, + documents: Optional[Documents] = None, + uris: Optional[URIs] = None, + ) -> bool: + """[Internal] Update entries in a collection specified by UUID. + + Args: + collection_id: The UUID of the collection to update the embeddings in. + ids: The IDs of the entries to update. + embeddings: The sequence of embeddings to update. Defaults to None. + metadatas: The metadata to associate with the embeddings. Defaults to None. + documents: The documents to associate with the embeddings. Defaults to None. + uris: URIs of data sources for each embedding. Defaults to None. + Returns: + True if the embeddings were updated successfully. + """ + pass + + @abstractmethod + def _upsert( + self, + collection_id: UUID, + ids: IDs, + embeddings: Embeddings, + metadatas: Optional[Metadatas] = None, + documents: Optional[Documents] = None, + uris: Optional[URIs] = None, + ) -> bool: + """[Internal] Add or update entries in the a collection specified by UUID. + If an entry with the same id already exists, it will be updated, + otherwise it will be added. + + Args: + collection_id: The collection to add the embeddings to + ids: The ids to associate with the embeddings. Defaults to None. + embeddings: The sequence of embeddings to add + metadatas: The metadata to associate with the embeddings. Defaults to None. + documents: The documents to associate with the embeddings. Defaults to None. + uris: URIs of data sources for each embedding. Defaults to None. + """ + pass + + @abstractmethod + def _count(self, collection_id: UUID) -> int: + """[Internal] Returns the number of entries in a collection specified by UUID. + + Args: + collection_id: The UUID of the collection to count the embeddings in. + + Returns: + int: The number of embeddings in the collection + + """ + pass + + @abstractmethod + def _peek(self, collection_id: UUID, n: int = 10) -> GetResult: + """[Internal] Returns the first n entries in a collection specified by UUID. + + Args: + collection_id: The UUID of the collection to peek into. + n: The number of entries to peek. Defaults to 10. + + Returns: + GetResult: The first n entries in the collection. + + """ + + pass + + @abstractmethod + def _get( + self, + collection_id: UUID, + ids: Optional[IDs] = None, + where: Optional[Where] = None, + limit: Optional[int] = None, + offset: Optional[int] = None, + where_document: Optional[WhereDocument] = None, + include: Include = IncludeMetadataDocuments, + ) -> GetResult: + """[Internal] Returns entries from a collection specified by UUID. + + Args: + ids: The IDs of the entries to get. Defaults to None. + where: Conditional filtering on metadata. Defaults to None. + limit: The maximum number of entries to return. Defaults to None. + offset: The number of entries to skip before returning. Defaults to None. + where_document: Conditional filtering on documents. Defaults to None. + include: The fields to include in the response. + Defaults to ["metadatas", "documents"]. + Returns: + GetResult: The entries in the collection that match the query. + + """ + pass + + @abstractmethod + def _delete( + self, + collection_id: UUID, + ids: Optional[IDs], + where: Optional[Where] = None, + where_document: Optional[WhereDocument] = None, + limit: Optional[int] = None, + ) -> DeleteResult: + """[Internal] Deletes entries from a collection specified by UUID. + + Args: + collection_id: The UUID of the collection to delete the entries from. + ids: The IDs of the entries to delete. Defaults to None. + where: Conditional filtering on metadata. Defaults to None. + where_document: Conditional filtering on documents. Defaults to None. + limit: Maximum number of records to delete. Can only be used with + where or where_document. Defaults to None (no limit). + + Returns: + DeleteResult: A dict containing the number of records deleted. + """ + pass + + @abstractmethod + def _query( + self, + collection_id: UUID, + query_embeddings: Embeddings, + ids: Optional[IDs] = None, + n_results: int = 10, + where: Optional[Where] = None, + where_document: Optional[WhereDocument] = None, + include: Include = IncludeMetadataDocumentsDistances, + ) -> QueryResult: + """[Internal] Performs a nearest neighbors query on a collection specified by UUID. + + Args: + collection_id: The UUID of the collection to query. + query_embeddings: The embeddings to use as the query. + ids: The IDs to filter by during the query. Defaults to None. + n_results: The number of results to return. Defaults to 10. + where: Conditional filtering on metadata. Defaults to None. + where_document: Conditional filtering on documents. Defaults to None. + include: The fields to include in the response. + Defaults to ["metadatas", "documents", "distances"]. + + Returns: + QueryResult: The results of the query. + """ + pass + + @abstractmethod + def reset(self) -> bool: + """Resets the database. This will delete all collections and entries. + + Returns: + bool: True if the database was reset successfully. + """ + pass + + @abstractmethod + def get_version(self) -> str: + """Get the version of Chroma. + + Returns: + str: The version of Chroma + + """ + pass + + @abstractmethod + def get_settings(self) -> Settings: + """Get the settings used to initialize. + + Returns: + Settings: The settings used to initialize. + + """ + pass + + @abstractmethod + def get_max_batch_size(self) -> int: + """Return the maximum number of records that can be created or mutated in a single call.""" + pass + + @abstractmethod + def get_user_identity(self) -> UserIdentity: + """Resolve the tenant and databases for the client. Returns the default + values if can't be resolved. + + """ + pass + + +class ClientAPI(BaseAPI, ABC): + tenant: str + database: str + + @abstractmethod + def list_collections( + self, + limit: Optional[int] = None, + offset: Optional[int] = None, + ) -> Sequence[Collection]: + """List all collections. + Args: + limit: The maximum number of entries to return. Defaults to None. + offset: The number of entries to skip before returning. Defaults to None. + + Returns: + Sequence[Collection]: A list of collections + + Examples: + ```python + client.list_collections() + # [collection(name="my_collection", metadata={})] + ``` + """ + pass + + @abstractmethod + def create_collection( + self, + name: str, + schema: Optional[Schema] = None, + configuration: Optional[CreateCollectionConfiguration] = None, + metadata: Optional[CollectionMetadata] = None, + embedding_function: Optional[ + EmbeddingFunction[Embeddable] + ] = DefaultEmbeddingFunction(), # type: ignore + data_loader: Optional[DataLoader[Loadable]] = None, + get_or_create: bool = False, + ) -> Collection: + """Create a new collection with the given name and metadata. + Args: + name: The name of the collection to create. + metadata: Optional metadata to associate with the collection. + embedding_function: Optional function to use to embed documents. + Uses the default embedding function if not provided. + get_or_create: If True, return the existing collection if it exists. + data_loader: Optional function to use to load records (documents, images, etc.) + + Returns: + Collection: The newly created collection. + + Raises: + ValueError: If the collection already exists and get_or_create is False. + ValueError: If the collection name is invalid. + + Examples: + ```python + client.create_collection("my_collection") + # collection(name="my_collection", metadata={}) + + client.create_collection("my_collection", metadata={"foo": "bar"}) + # collection(name="my_collection", metadata={"foo": "bar"}) + ``` + """ + pass + + @abstractmethod + def get_collection( + self, + name: str, + embedding_function: Optional[ + EmbeddingFunction[Embeddable] + ] = DefaultEmbeddingFunction(), # type: ignore + data_loader: Optional[DataLoader[Loadable]] = None, + ) -> Collection: + """Get a collection with the given name. + Args: + name: The name of the collection to get + embedding_function: Optional function to use to embed documents. + Uses the default embedding function if not provided. + data_loader: Optional function to use to load records (documents, images, etc.) + + Returns: + Collection: The collection + + Raises: + ValueError: If the collection does not exist + + Examples: + ```python + client.get_collection("my_collection") + # collection(name="my_collection", metadata={}) + ``` + """ + pass + + @abstractmethod + def get_collection_by_id( + self, + id: UUID, + embedding_function: Optional[ + EmbeddingFunction[Embeddable] + ] = DefaultEmbeddingFunction(), # type: ignore + data_loader: Optional[DataLoader[Loadable]] = None, + ) -> Collection: + """Get a collection by its ID. + + Args: + id: The UUID of the collection to get. + embedding_function: Optional function to use to embed documents. + Uses the default embedding function if not provided. + data_loader: Optional function to use to load records (documents, images, etc.) + + Returns: + Collection: The collection + + Raises: + NotFoundError: If no collection with the given ID exists. + + Examples: + ```python + client.get_collection_by_id(uuid.UUID("...")) + # collection(name="my_collection", metadata={}) + ``` + """ + pass + + @abstractmethod + def get_or_create_collection( + self, + name: str, + schema: Optional[Schema] = None, + configuration: Optional[CreateCollectionConfiguration] = None, + metadata: Optional[CollectionMetadata] = None, + embedding_function: Optional[ + EmbeddingFunction[Embeddable] + ] = DefaultEmbeddingFunction(), # type: ignore + data_loader: Optional[DataLoader[Loadable]] = None, + ) -> Collection: + """Get or create a collection with the given name and metadata. + Args: + name: The name of the collection to get or create + metadata: Optional metadata to associate with the collection. If + the collection already exists, the metadata provided is ignored. + If the collection does not exist, the new collection will be created + with the provided metadata. + embedding_function: Optional function to use to embed documents + data_loader: Optional function to use to load records (documents, images, etc.) + + Returns: + The collection + + Examples: + ```python + client.get_or_create_collection("my_collection") + # collection(name="my_collection", metadata={}) + ``` + """ + pass + + @abstractmethod + def set_tenant(self, tenant: str, database: str = DEFAULT_DATABASE) -> None: + """Set the tenant and database for the client. Raises an error if the tenant or + database does not exist. + + Args: + tenant: The tenant to set. + database: The database to set. + + """ + pass + + @abstractmethod + def set_database(self, database: str) -> None: + """Set the database for the client. Raises an error if the database does not exist. + + Args: + database: The database to set. + + """ + pass + + @staticmethod + @abstractmethod + def clear_system_cache() -> None: + """Clear the system cache so that new systems can be created for an existing path. + This should only be used for testing purposes.""" + pass + + +class AdminAPI(ABC): + @abstractmethod + def create_database(self, name: str, tenant: str = DEFAULT_TENANT) -> None: + """Create a new database. Raises an error if the database already exists. + + Args: + database: The name of the database to create. + + """ + pass + + @abstractmethod + def get_database(self, name: str, tenant: str = DEFAULT_TENANT) -> Database: + """Get a database. Raises an error if the database does not exist. + + Args: + database: The name of the database to get. + tenant: The tenant of the database to get. + + """ + pass + + @abstractmethod + def delete_database(self, name: str, tenant: str = DEFAULT_TENANT) -> None: + """Delete a database. Raises an error if the database does not exist. + + Args: + database: The name of the database to delete. + tenant: The tenant of the database to delete. + + """ + pass + + @abstractmethod + def list_databases( + self, + limit: Optional[int] = None, + offset: Optional[int] = None, + tenant: str = DEFAULT_TENANT, + ) -> Sequence[Database]: + """List all databases for a tenant. Raises an error if the tenant does not exist. + + Args: + tenant: The tenant to list databases for. + + """ + pass + + @abstractmethod + def create_tenant(self, name: str) -> None: + """Create a new tenant. Raises an error if the tenant already exists. + + Args: + tenant: The name of the tenant to create. + + """ + pass + + @abstractmethod + def get_tenant(self, name: str) -> Tenant: + """Get a tenant. Raises an error if the tenant does not exist. + + Args: + tenant: The name of the tenant to get. + + """ + pass + + +class ServerAPI(BaseAPI, AdminAPI, Component): + """An API instance that extends the relevant Base API methods by passing + in a tenant and database. This is the root component of the Chroma System""" + + @abstractmethod + @override + def count_collections( + self, tenant: str = DEFAULT_TENANT, database: str = DEFAULT_DATABASE + ) -> int: + pass + + @abstractmethod + def list_collections( + self, + limit: Optional[int] = None, + offset: Optional[int] = None, + tenant: str = DEFAULT_TENANT, + database: str = DEFAULT_DATABASE, + ) -> Sequence[CollectionModel]: + pass + + @abstractmethod + def create_collection( + self, + name: str, + schema: Optional[Schema] = None, + configuration: Optional[CreateCollectionConfiguration] = None, + metadata: Optional[CollectionMetadata] = None, + get_or_create: bool = False, + tenant: str = DEFAULT_TENANT, + database: str = DEFAULT_DATABASE, + ) -> CollectionModel: + pass + + @abstractmethod + def get_collection( + self, + name: str, + tenant: str = DEFAULT_TENANT, + database: str = DEFAULT_DATABASE, + ) -> CollectionModel: + pass + + @abstractmethod + def get_collection_by_id( + self, + collection_id: UUID, + tenant: str = DEFAULT_TENANT, + database: str = DEFAULT_DATABASE, + ) -> CollectionModel: + """Get a collection by its ID. + + Args: + collection_id: The UUID of the collection to retrieve. + tenant: The tenant to search within. + database: The database to search within. + + Returns: + CollectionModel: The collection with the given ID. + + Raises: + NotFoundError: If no collection with the given ID exists. + """ + pass + + @abstractmethod + def get_or_create_collection( + self, + name: str, + schema: Optional[Schema] = None, + configuration: Optional[CreateCollectionConfiguration] = None, + metadata: Optional[CollectionMetadata] = None, + tenant: str = DEFAULT_TENANT, + database: str = DEFAULT_DATABASE, + ) -> CollectionModel: + pass + + @abstractmethod + @override + def delete_collection( + self, + name: str, + tenant: str = DEFAULT_TENANT, + database: str = DEFAULT_DATABASE, + ) -> None: + pass + + @abstractmethod + @override + def _modify( + self, + id: UUID, + new_name: Optional[str] = None, + new_metadata: Optional[CollectionMetadata] = None, + new_configuration: Optional[UpdateCollectionConfiguration] = None, + tenant: str = DEFAULT_TENANT, + database: str = DEFAULT_DATABASE, + ) -> None: + pass + + @abstractmethod + def _fork( + self, + collection_id: UUID, + new_name: str, + tenant: str = DEFAULT_TENANT, + database: str = DEFAULT_DATABASE, + ) -> CollectionModel: + pass + + @abstractmethod + def _fork_count( + self, + collection_id: UUID, + tenant: str = DEFAULT_TENANT, + database: str = DEFAULT_DATABASE, + ) -> int: + pass + + @abstractmethod + def _get_indexing_status( + self, + collection_id: UUID, + tenant: str = DEFAULT_TENANT, + database: str = DEFAULT_DATABASE, + ) -> "IndexingStatus": + pass + + @abstractmethod + def _search( + self, + collection_id: UUID, + searches: List[Search], + tenant: str = DEFAULT_TENANT, + database: str = DEFAULT_DATABASE, + read_level: ReadLevel = ReadLevel.INDEX_AND_WAL, + ) -> SearchResult: + pass + + @abstractmethod + @override + def _count( + self, + collection_id: UUID, + tenant: str = DEFAULT_TENANT, + database: str = DEFAULT_DATABASE, + read_level: ReadLevel = ReadLevel.INDEX_AND_WAL, + ) -> int: + pass + + @abstractmethod + @override + def _peek( + self, + collection_id: UUID, + n: int = 10, + tenant: str = DEFAULT_TENANT, + database: str = DEFAULT_DATABASE, + ) -> GetResult: + pass + + @abstractmethod + @override + def _get( + self, + collection_id: UUID, + ids: Optional[IDs] = None, + where: Optional[Where] = None, + limit: Optional[int] = None, + offset: Optional[int] = None, + where_document: Optional[WhereDocument] = None, + include: Include = IncludeMetadataDocuments, + tenant: str = DEFAULT_TENANT, + database: str = DEFAULT_DATABASE, + ) -> GetResult: + pass + + @abstractmethod + @override + def _add( + self, + ids: IDs, + collection_id: UUID, + embeddings: Embeddings, + metadatas: Optional[Metadatas] = None, + documents: Optional[Documents] = None, + uris: Optional[URIs] = None, + tenant: str = DEFAULT_TENANT, + database: str = DEFAULT_DATABASE, + ) -> bool: + pass + + @abstractmethod + @override + def _update( + self, + collection_id: UUID, + ids: IDs, + embeddings: Optional[Embeddings] = None, + metadatas: Optional[Metadatas] = None, + documents: Optional[Documents] = None, + uris: Optional[URIs] = None, + tenant: str = DEFAULT_TENANT, + database: str = DEFAULT_DATABASE, + ) -> bool: + pass + + @abstractmethod + @override + def _upsert( + self, + collection_id: UUID, + ids: IDs, + embeddings: Embeddings, + metadatas: Optional[Metadatas] = None, + documents: Optional[Documents] = None, + uris: Optional[URIs] = None, + tenant: str = DEFAULT_TENANT, + database: str = DEFAULT_DATABASE, + ) -> bool: + pass + + @abstractmethod + @override + def _query( + self, + collection_id: UUID, + query_embeddings: Embeddings, + ids: Optional[IDs] = None, + n_results: int = 10, + where: Optional[Where] = None, + where_document: Optional[WhereDocument] = None, + include: Include = IncludeMetadataDocumentsDistances, + tenant: str = DEFAULT_TENANT, + database: str = DEFAULT_DATABASE, + ) -> QueryResult: + pass + + @abstractmethod + @override + def _delete( + self, + collection_id: UUID, + ids: Optional[IDs] = None, + where: Optional[Where] = None, + where_document: Optional[WhereDocument] = None, + limit: Optional[int] = None, + tenant: str = DEFAULT_TENANT, + database: str = DEFAULT_DATABASE, + ) -> DeleteResult: + pass + + @abstractmethod + def attach_function( + self, + function_id: str, + name: str, + input_collection_id: UUID, + output_collection: str, + params: Optional[Dict[str, Any]] = None, + tenant: str = DEFAULT_TENANT, + database: str = DEFAULT_DATABASE, + ) -> Tuple["AttachedFunction", bool]: + """Attach a function to a collection. + + Args: + function_id: Built-in function identifier + name: Unique name for this attached function + input_collection_id: Source collection that triggers the function + output_collection: Target collection where function output is stored + params: Optional dictionary with function-specific parameters + tenant: The tenant name + database: The database name + + Returns: + Tuple of (AttachedFunction, created) where created is True if newly created, + False if already existed (idempotent request) + """ + pass + + @abstractmethod + def get_attached_function( + self, + name: str, + input_collection_id: UUID, + tenant: str = DEFAULT_TENANT, + database: str = DEFAULT_DATABASE, + ) -> "AttachedFunction": + """Get an attached function by name for a specific collection. + + Args: + name: Name of the attached function + input_collection_id: The collection ID + tenant: The tenant name + database: The database name + + Returns: + AttachedFunction: The attached function object + + Raises: + NotFoundError: If the attached function doesn't exist + """ + pass + + @abstractmethod + def detach_function( + self, + name: str, + input_collection_id: UUID, + delete_output: bool = False, + tenant: str = DEFAULT_TENANT, + database: str = DEFAULT_DATABASE, + ) -> bool: + """Detach a function and prevent any further runs. + + Args: + name: Name of the attached function to remove + input_collection_id: ID of the input collection + delete_output: Whether to also delete the output collection + tenant: The tenant name + database: The database name + + Returns: + bool: True if successful + """ + pass diff --git a/python/user_packages/Python313/site-packages/chromadb/api/async_api.py b/python/user_packages/Python313/site-packages/chromadb/api/async_api.py new file mode 100644 index 0000000000000000000000000000000000000000..faabd1b69909cbf39f4edd3a725bda05ea358de0 --- /dev/null +++ b/python/user_packages/Python313/site-packages/chromadb/api/async_api.py @@ -0,0 +1,850 @@ +from abc import ABC, abstractmethod +from typing import Sequence, Optional, List +from uuid import UUID + +from overrides import override +from chromadb.api.collection_configuration import ( + CreateCollectionConfiguration, + UpdateCollectionConfiguration, +) +from chromadb.auth import UserIdentity +from chromadb.api.models.AsyncCollection import AsyncCollection +from chromadb.config import DEFAULT_DATABASE, DEFAULT_TENANT +from chromadb.api.types import ( + CollectionMetadata, + DeleteResult, + Documents, + Embeddable, + EmbeddingFunction, + DataLoader, + Embeddings, + IDs, + Include, + IndexingStatus, + Loadable, + Metadatas, + ReadLevel, + Schema, + URIs, + Where, + QueryResult, + GetResult, + WhereDocument, + IncludeMetadataDocuments, + IncludeMetadataDocumentsDistances, + SearchResult, + DefaultEmbeddingFunction, +) +from chromadb.execution.expression.plan import Search +from chromadb.config import Component, Settings +from chromadb.types import Database, Tenant, Collection as CollectionModel + + +class AsyncBaseAPI(ABC): + @abstractmethod + async def heartbeat(self) -> int: + """Get the current time in nanoseconds since epoch. + Used to check if the server is alive. + + Returns: + int: The current time in nanoseconds since epoch + + """ + pass + + # + # COLLECTION METHODS + # + + @abstractmethod + async def count_collections(self) -> int: + """Count the number of collections. + + Returns: + int: The number of collections. + + Examples: + ```python + await client.count_collections() + # 1 + ``` + """ + pass + + @abstractmethod + async def _modify( + self, + id: UUID, + new_name: Optional[str] = None, + new_metadata: Optional[CollectionMetadata] = None, + new_configuration: Optional[UpdateCollectionConfiguration] = None, + ) -> None: + """[Internal] Modify a collection by UUID. Can update the name and/or metadata. + + Args: + id: The internal UUID of the collection to modify. + new_name: The new name of the collection. + If None, the existing name will remain. Defaults to None. + new_metadata: The new metadata to associate with the collection. + Defaults to None. + new_configuration: The new configuration to associate with the collection. + Defaults to None. + """ + pass + + @abstractmethod + async def delete_collection( + self, + name: str, + ) -> None: + """Delete a collection with the given name. + Args: + name: The name of the collection to delete. + + Raises: + ValueError: If the collection does not exist. + + Examples: + ```python + await client.delete_collection("my_collection") + ``` + """ + pass + + # + # ITEM METHODS + # + + @abstractmethod + async def _add( + self, + ids: IDs, + collection_id: UUID, + embeddings: Embeddings, + metadatas: Optional[Metadatas] = None, + documents: Optional[Documents] = None, + uris: Optional[URIs] = None, + ) -> bool: + """[Internal] Add embeddings to a collection specified by UUID. + If (some) ids already exist, only the new embeddings will be added. + + Args: + ids: The ids to associate with the embeddings. + collection_id: The UUID of the collection to add the embeddings to. + embedding: The sequence of embeddings to add. + metadata: The metadata to associate with the embeddings. Defaults to None. + documents: The documents to associate with the embeddings. Defaults to None. + uris: URIs of data sources for each embedding. Defaults to None. + + Returns: + True if the embeddings were added successfully. + """ + pass + + @abstractmethod + async def _update( + self, + collection_id: UUID, + ids: IDs, + embeddings: Optional[Embeddings] = None, + metadatas: Optional[Metadatas] = None, + documents: Optional[Documents] = None, + uris: Optional[URIs] = None, + ) -> bool: + """[Internal] Update entries in a collection specified by UUID. + + Args: + collection_id: The UUID of the collection to update the embeddings in. + ids: The IDs of the entries to update. + embeddings: The sequence of embeddings to update. Defaults to None. + metadatas: The metadata to associate with the embeddings. Defaults to None. + documents: The documents to associate with the embeddings. Defaults to None. + uris: URIs of data sources for each embedding. Defaults to None. + Returns: + True if the embeddings were updated successfully. + """ + pass + + @abstractmethod + async def _upsert( + self, + collection_id: UUID, + ids: IDs, + embeddings: Embeddings, + metadatas: Optional[Metadatas] = None, + documents: Optional[Documents] = None, + uris: Optional[URIs] = None, + ) -> bool: + """[Internal] Add or update entries in the a collection specified by UUID. + If an entry with the same id already exists, it will be updated, + otherwise it will be added. + + Args: + collection_id: The collection to add the embeddings to + ids: The ids to associate with the embeddings. Defaults to None. + embeddings: The sequence of embeddings to add + metadatas: The metadata to associate with the embeddings. Defaults to None. + documents: The documents to associate with the embeddings. Defaults to None. + uris: URIs of data sources for each embedding. Defaults to None. + """ + pass + + @abstractmethod + async def _count(self, collection_id: UUID) -> int: + """[Internal] Returns the number of entries in a collection specified by UUID. + + Args: + collection_id: The UUID of the collection to count the embeddings in. + + Returns: + int: The number of embeddings in the collection + + """ + pass + + @abstractmethod + async def _peek(self, collection_id: UUID, n: int = 10) -> GetResult: + """[Internal] Returns the first n entries in a collection specified by UUID. + + Args: + collection_id: The UUID of the collection to peek into. + n: The number of entries to peek. Defaults to 10. + + Returns: + GetResult: The first n entries in the collection. + + """ + + pass + + @abstractmethod + async def _get( + self, + collection_id: UUID, + ids: Optional[IDs] = None, + where: Optional[Where] = None, + limit: Optional[int] = None, + offset: Optional[int] = None, + where_document: Optional[WhereDocument] = None, + include: Include = IncludeMetadataDocuments, + ) -> GetResult: + """[Internal] Returns entries from a collection specified by UUID. + + Args: + ids: The IDs of the entries to get. Defaults to None. + where: Conditional filtering on metadata. Defaults to None. + limit: The maximum number of entries to return. Defaults to None. + offset: The number of entries to skip before returning. Defaults to None. + where_document: Conditional filtering on documents. Defaults to None. + include: The fields to include in the response. + Defaults to ["embeddings", "metadatas", "documents"]. + Returns: + GetResult: The entries in the collection that match the query. + + """ + pass + + @abstractmethod + async def _delete( + self, + collection_id: UUID, + ids: Optional[IDs], + where: Optional[Where] = None, + where_document: Optional[WhereDocument] = None, + limit: Optional[int] = None, + ) -> DeleteResult: + """[Internal] Deletes entries from a collection specified by UUID. + + Args: + collection_id: The UUID of the collection to delete the entries from. + ids: The IDs of the entries to delete. Defaults to None. + where: Conditional filtering on metadata. Defaults to None. + where_document: Conditional filtering on documents. Defaults to None. + limit: Maximum number of records to delete. Can only be used with + where or where_document. Defaults to None (no limit). + + Returns: + DeleteResult: A dict containing the number of records deleted. + """ + pass + + @abstractmethod + async def _query( + self, + collection_id: UUID, + query_embeddings: Embeddings, + ids: Optional[IDs] = None, + n_results: int = 10, + where: Optional[Where] = None, + where_document: Optional[WhereDocument] = None, + include: Include = IncludeMetadataDocumentsDistances, + ) -> QueryResult: + """[Internal] Performs a nearest neighbors query on a collection specified by UUID. + + Args: + collection_id: The UUID of the collection to query. + query_embeddings: The embeddings to use as the query. + n_results: The number of results to return. Defaults to 10. + where: Conditional filtering on metadata. Defaults to None. + where_document: Conditional filtering on documents. Defaults to None. + include: The fields to include in the response. + Defaults to ["embeddings", "metadatas", "documents", "distances"]. + + Returns: + QueryResult: The results of the query. + """ + pass + + @abstractmethod + async def reset(self) -> bool: + """Resets the database. This will delete all collections and entries. + + Returns: + bool: True if the database was reset successfully. + """ + pass + + @abstractmethod + async def get_version(self) -> str: + """Get the version of Chroma. + + Returns: + str: The version of Chroma + + """ + pass + + @abstractmethod + def get_settings(self) -> Settings: + """Get the settings used to initialize. + + Returns: + Settings: The settings used to initialize. + + """ + pass + + @abstractmethod + async def get_max_batch_size(self) -> int: + """Return the maximum number of records that can be created or mutated in a single call.""" + pass + + @abstractmethod + async def get_user_identity(self) -> UserIdentity: + """Resolve the tenant and databases for the client. Returns the default + values if can't be resolved. + + """ + pass + + +class AsyncClientAPI(AsyncBaseAPI, ABC): + tenant: str + database: str + + @abstractmethod + async def list_collections( + self, + limit: Optional[int] = None, + offset: Optional[int] = None, + ) -> Sequence[AsyncCollection]: + """List all collections. + Args: + limit: The maximum number of entries to return. Defaults to None. + offset: The number of entries to skip before returning. Defaults to None. + + Returns: + Sequence[AsyncCollection]: A list of collections. + + Examples: + ```python + await client.list_collections() + # [collection(name="my_collection", metadata={})] + ``` + """ + pass + + @abstractmethod + async def create_collection( + self, + name: str, + schema: Optional[Schema] = None, + configuration: Optional[CreateCollectionConfiguration] = None, + metadata: Optional[CollectionMetadata] = None, + embedding_function: Optional[ + EmbeddingFunction[Embeddable] + ] = DefaultEmbeddingFunction(), # type: ignore + data_loader: Optional[DataLoader[Loadable]] = None, + get_or_create: bool = False, + ) -> AsyncCollection: + """Create a new collection with the given name and metadata. + Args: + name: The name of the collection to create. + metadata: Optional metadata to associate with the collection. + embedding_function: Optional function to use to embed documents. + Uses the default embedding function if not provided. + get_or_create: If True, return the existing collection if it exists. + data_loader: Optional function to use to load records (documents, images, etc.) + + Returns: + Collection: The newly created collection. + + Raises: + ValueError: If the collection already exists and get_or_create is False. + ValueError: If the collection name is invalid. + + Examples: + ```python + await client.create_collection("my_collection") + # collection(name="my_collection", metadata={}) + + await client.create_collection("my_collection", metadata={"foo": "bar"}) + # collection(name="my_collection", metadata={"foo": "bar"}) + ``` + """ + pass + + @abstractmethod + async def get_collection( + self, + name: str, + embedding_function: Optional[ + EmbeddingFunction[Embeddable] + ] = DefaultEmbeddingFunction(), # type: ignore + data_loader: Optional[DataLoader[Loadable]] = None, + ) -> AsyncCollection: + """Get a collection with the given name. + Args: + name: The name of the collection to get + embedding_function: Optional function to use to embed documents. + Uses the default embedding function if not provided. + data_loader: Optional function to use to load records (documents, images, etc.) + + Returns: + Collection: The collection + + Raises: + ValueError: If the collection does not exist + + Examples: + ```python + await client.get_collection("my_collection") + # collection(name="my_collection", metadata={}) + ``` + """ + pass + + @abstractmethod + async def get_collection_by_id( + self, + id: UUID, + embedding_function: Optional[ + EmbeddingFunction[Embeddable] + ] = DefaultEmbeddingFunction(), # type: ignore + data_loader: Optional[DataLoader[Loadable]] = None, + ) -> AsyncCollection: + """Get a collection by its ID. + + Args: + id: The UUID of the collection to get. + embedding_function: Optional function to use to embed documents. + Uses the default embedding function if not provided. + data_loader: Optional function to use to load records (documents, images, etc.) + + Returns: + Collection: The collection + + Raises: + NotFoundError: If no collection with the given ID exists. + + Examples: + ```python + await client.get_collection_by_id(uuid.UUID("...")) + # collection(name="my_collection", metadata={}) + ``` + """ + pass + + @abstractmethod + async def get_or_create_collection( + self, + name: str, + schema: Optional[Schema] = None, + configuration: Optional[CreateCollectionConfiguration] = None, + metadata: Optional[CollectionMetadata] = None, + embedding_function: Optional[ + EmbeddingFunction[Embeddable] + ] = DefaultEmbeddingFunction(), # type: ignore + data_loader: Optional[DataLoader[Loadable]] = None, + ) -> AsyncCollection: + """Get or create a collection with the given name and metadata. + Args: + name: The name of the collection to get or create + metadata: Optional metadata to associate with the collection. If + the collection already exists, the metadata provided is ignored. + If the collection does not exist, the new collection will be created + with the provided metadata. + embedding_function: Optional function to use to embed documents + data_loader: Optional function to use to load records (documents, images, etc.) + + Returns: + The collection + + Examples: + ```python + await client.get_or_create_collection("my_collection") + # collection(name="my_collection", metadata={}) + ``` + """ + pass + + @abstractmethod + async def set_tenant(self, tenant: str, database: str = DEFAULT_DATABASE) -> None: + """Set the tenant and database for the client. Raises an error if the tenant or + database does not exist. + + Args: + tenant: The tenant to set. + database: The database to set. + + """ + pass + + @abstractmethod + async def set_database(self, database: str) -> None: + """Set the database for the client. Raises an error if the database does not exist. + + Args: + database: The database to set. + + """ + pass + + @staticmethod + @abstractmethod + def clear_system_cache() -> None: + """Clear the system cache so that new systems can be created for an existing path. + This should only be used for testing purposes.""" + pass + + +class AsyncAdminAPI(ABC): + @abstractmethod + async def create_database(self, name: str, tenant: str = DEFAULT_TENANT) -> None: + """Create a new database. Raises an error if the database already exists. + + Args: + database: The name of the database to create. + + """ + pass + + @abstractmethod + async def get_database(self, name: str, tenant: str = DEFAULT_TENANT) -> Database: + """Get a database. Raises an error if the database does not exist. + + Args: + database: The name of the database to get. + tenant: The tenant of the database to get. + + """ + pass + + @abstractmethod + async def delete_database(self, name: str, tenant: str = DEFAULT_TENANT) -> None: + """Delete a database. Raises an error if the database does not exist. + + Args: + database: The name of the database to delete. + tenant: The tenant of the database to delete. + + """ + pass + + @abstractmethod + async def list_databases( + self, + limit: Optional[int] = None, + offset: Optional[int] = None, + tenant: str = DEFAULT_TENANT, + ) -> Sequence[Database]: + """List all databases for a tenant. Raises an error if the tenant does not exist. + + Args: + tenant: The tenant to list databases for. + + """ + pass + + @abstractmethod + async def create_tenant(self, name: str) -> None: + """Create a new tenant. Raises an error if the tenant already exists. + + Args: + tenant: The name of the tenant to create. + + """ + pass + + @abstractmethod + async def get_tenant(self, name: str) -> Tenant: + """Get a tenant. Raises an error if the tenant does not exist. + + Args: + tenant: The name of the tenant to get. + + """ + pass + + +class AsyncServerAPI(AsyncBaseAPI, AsyncAdminAPI, Component): + """An API instance that extends the relevant Base API methods by passing + in a tenant and database. This is the root component of the Chroma System""" + + @abstractmethod + async def list_collections( + self, + limit: Optional[int] = None, + offset: Optional[int] = None, + tenant: str = DEFAULT_TENANT, + database: str = DEFAULT_DATABASE, + ) -> Sequence[CollectionModel]: + pass + + @abstractmethod + @override + async def count_collections( + self, tenant: str = DEFAULT_TENANT, database: str = DEFAULT_DATABASE + ) -> int: + pass + + @abstractmethod + async def create_collection( + self, + name: str, + schema: Optional[Schema] = None, + configuration: Optional[CreateCollectionConfiguration] = None, + metadata: Optional[CollectionMetadata] = None, + get_or_create: bool = False, + tenant: str = DEFAULT_TENANT, + database: str = DEFAULT_DATABASE, + ) -> CollectionModel: + pass + + @abstractmethod + async def get_collection( + self, + name: str, + tenant: str = DEFAULT_TENANT, + database: str = DEFAULT_DATABASE, + ) -> CollectionModel: + pass + + @abstractmethod + async def get_collection_by_id( + self, + collection_id: UUID, + tenant: str = DEFAULT_TENANT, + database: str = DEFAULT_DATABASE, + ) -> CollectionModel: + """Get a collection by its ID. + + Args: + collection_id: The UUID of the collection to retrieve. + tenant: The tenant to search within. + database: The database to search within. + + Returns: + CollectionModel: The collection with the given ID. + + Raises: + NotFoundError: If no collection with the given ID exists. + """ + pass + + @abstractmethod + async def get_or_create_collection( + self, + name: str, + schema: Optional[Schema] = None, + configuration: Optional[CreateCollectionConfiguration] = None, + metadata: Optional[CollectionMetadata] = None, + tenant: str = DEFAULT_TENANT, + database: str = DEFAULT_DATABASE, + ) -> CollectionModel: + pass + + @abstractmethod + @override + async def delete_collection( + self, + name: str, + tenant: str = DEFAULT_TENANT, + database: str = DEFAULT_DATABASE, + ) -> None: + pass + + @abstractmethod + @override + async def _modify( + self, + id: UUID, + new_name: Optional[str] = None, + new_metadata: Optional[CollectionMetadata] = None, + new_configuration: Optional[UpdateCollectionConfiguration] = None, + tenant: str = DEFAULT_TENANT, + database: str = DEFAULT_DATABASE, + ) -> None: + pass + + @abstractmethod + async def _fork( + self, + collection_id: UUID, + new_name: str, + tenant: str = DEFAULT_TENANT, + database: str = DEFAULT_DATABASE, + ) -> CollectionModel: + pass + + @abstractmethod + async def _fork_count( + self, + collection_id: UUID, + tenant: str = DEFAULT_TENANT, + database: str = DEFAULT_DATABASE, + ) -> int: + pass + + @abstractmethod + async def _get_indexing_status( + self, + collection_id: UUID, + tenant: str = DEFAULT_TENANT, + database: str = DEFAULT_DATABASE, + ) -> "IndexingStatus": + pass + + @abstractmethod + async def _search( + self, + collection_id: UUID, + searches: List[Search], + tenant: str = DEFAULT_TENANT, + database: str = DEFAULT_DATABASE, + read_level: ReadLevel = ReadLevel.INDEX_AND_WAL, + ) -> SearchResult: + pass + + @abstractmethod + @override + async def _count( + self, + collection_id: UUID, + tenant: str = DEFAULT_TENANT, + database: str = DEFAULT_DATABASE, + read_level: ReadLevel = ReadLevel.INDEX_AND_WAL, + ) -> int: + pass + + @abstractmethod + @override + async def _peek( + self, + collection_id: UUID, + n: int = 10, + tenant: str = DEFAULT_TENANT, + database: str = DEFAULT_DATABASE, + ) -> GetResult: + pass + + @abstractmethod + @override + async def _get( + self, + collection_id: UUID, + ids: Optional[IDs] = None, + where: Optional[Where] = None, + limit: Optional[int] = None, + offset: Optional[int] = None, + where_document: Optional[WhereDocument] = None, + include: Include = IncludeMetadataDocuments, + tenant: str = DEFAULT_TENANT, + database: str = DEFAULT_DATABASE, + ) -> GetResult: + pass + + @abstractmethod + @override + async def _add( + self, + ids: IDs, + collection_id: UUID, + embeddings: Embeddings, + metadatas: Optional[Metadatas] = None, + documents: Optional[Documents] = None, + uris: Optional[URIs] = None, + tenant: str = DEFAULT_TENANT, + database: str = DEFAULT_DATABASE, + ) -> bool: + pass + + @abstractmethod + @override + async def _update( + self, + collection_id: UUID, + ids: IDs, + embeddings: Optional[Embeddings] = None, + metadatas: Optional[Metadatas] = None, + documents: Optional[Documents] = None, + uris: Optional[URIs] = None, + tenant: str = DEFAULT_TENANT, + database: str = DEFAULT_DATABASE, + ) -> bool: + pass + + @abstractmethod + @override + async def _upsert( + self, + collection_id: UUID, + ids: IDs, + embeddings: Embeddings, + metadatas: Optional[Metadatas] = None, + documents: Optional[Documents] = None, + uris: Optional[URIs] = None, + tenant: str = DEFAULT_TENANT, + database: str = DEFAULT_DATABASE, + ) -> bool: + pass + + @abstractmethod + @override + async def _query( + self, + collection_id: UUID, + query_embeddings: Embeddings, + ids: Optional[IDs] = None, + n_results: int = 10, + where: Optional[Where] = None, + where_document: Optional[WhereDocument] = None, + include: Include = IncludeMetadataDocumentsDistances, + tenant: str = DEFAULT_TENANT, + database: str = DEFAULT_DATABASE, + ) -> QueryResult: + pass + + @abstractmethod + @override + async def _delete( + self, + collection_id: UUID, + ids: Optional[IDs] = None, + where: Optional[Where] = None, + where_document: Optional[WhereDocument] = None, + limit: Optional[int] = None, + tenant: str = DEFAULT_TENANT, + database: str = DEFAULT_DATABASE, + ) -> DeleteResult: + pass diff --git a/python/user_packages/Python313/site-packages/chromadb/api/async_client.py b/python/user_packages/Python313/site-packages/chromadb/api/async_client.py new file mode 100644 index 0000000000000000000000000000000000000000..b3742fdedebf1c4dc501b4c80062b2e0a3e6f8bf --- /dev/null +++ b/python/user_packages/Python313/site-packages/chromadb/api/async_client.py @@ -0,0 +1,569 @@ +import httpx +from typing import Optional, Sequence +from uuid import UUID +from overrides import override + +from chromadb.auth import UserIdentity +from chromadb.auth.utils import maybe_set_tenant_and_database +from chromadb.api import AsyncAdminAPI, AsyncClientAPI, AsyncServerAPI +from chromadb.api.collection_configuration import ( + CreateCollectionConfiguration, + UpdateCollectionConfiguration, + validate_embedding_function_conflict_on_create, + validate_embedding_function_conflict_on_get, +) +from chromadb.api.models.AsyncCollection import AsyncCollection +from chromadb.api.shared_system_client import SharedSystemClient +from chromadb.api.types import ( + CollectionMetadata, + DataLoader, + Documents, + Embeddable, + EmbeddingFunction, + Embeddings, + GetResult, + IDs, + Include, + IncludeMetadataDocuments, + IncludeMetadataDocumentsDistances, + Loadable, + Metadatas, + QueryResult, + Schema, + URIs, + DefaultEmbeddingFunction, + DeleteResult, +) +from chromadb.config import DEFAULT_DATABASE, DEFAULT_TENANT, Settings, System +from chromadb.errors import ChromaError +from chromadb.types import Database, Tenant, Where, WhereDocument + + +class AsyncClient(SharedSystemClient, AsyncClientAPI): + """A client for Chroma. This is the main entrypoint for interacting with Chroma. + A client internally stores its tenant and database and proxies calls to a + Server API instance of Chroma. It treats the Server API and corresponding System + as a singleton, so multiple clients connecting to the same resource will share the + same API instance. + + Client implementations should be implement their own API-caching strategies. + """ + + # An internal admin client for verifying that databases and tenants exist + _admin_client: AsyncAdminAPI + + tenant: str = DEFAULT_TENANT + database: str = DEFAULT_DATABASE + + _server: AsyncServerAPI + + @classmethod + async def create( + cls, + tenant: str = DEFAULT_TENANT, + database: str = DEFAULT_DATABASE, + settings: Settings = Settings(), + ) -> "AsyncClient": + # Create an admin client for verifying that databases and tenants exist + self = cls(settings=settings) + SharedSystemClient._populate_data_from_system(self._system) + + self.tenant = tenant + self.database = database + + # Get the root system component we want to interact with + self._server = self._system.instance(AsyncServerAPI) + + user_identity = await self.get_user_identity() + + maybe_tenant, maybe_database = maybe_set_tenant_and_database( + user_identity, + overwrite_singleton_tenant_database_access_from_auth=settings.chroma_overwrite_singleton_tenant_database_access_from_auth, + user_provided_tenant=tenant, + user_provided_database=database, + ) + if maybe_tenant: + self.tenant = maybe_tenant + if maybe_database: + self.database = maybe_database + + self._admin_client = AsyncAdminClient.from_system(self._system) + await self._validate_tenant_database(tenant=self.tenant, database=self.database) + + self._submit_client_start_event() + + return self + + @classmethod + # (we can't override and use from_system() because it's synchronous) + async def from_system_async( + cls, + system: System, + tenant: str = DEFAULT_TENANT, + database: str = DEFAULT_DATABASE, + ) -> "AsyncClient": + """Create a client from an existing system. This is useful for testing and debugging.""" + return await AsyncClient.create(tenant, database, system.settings) + + @classmethod + @override + def from_system( + cls, + system: System, + ) -> "SharedSystemClient": + """AsyncClient cannot be created synchronously. Use .from_system_async() instead.""" + raise NotImplementedError( + "AsyncClient cannot be created synchronously. Use .from_system_async() instead." + ) + + @override + async def get_user_identity(self) -> UserIdentity: + return await self._server.get_user_identity() + + @override + async def set_tenant(self, tenant: str, database: str = DEFAULT_DATABASE) -> None: + await self._validate_tenant_database(tenant=tenant, database=database) + self.tenant = tenant + self.database = database + + @override + async def set_database(self, database: str) -> None: + await self._validate_tenant_database(tenant=self.tenant, database=database) + self.database = database + + async def _validate_tenant_database(self, tenant: str, database: str) -> None: + try: + await self._admin_client.get_tenant(name=tenant) + except httpx.ConnectError: + raise ValueError( + "Could not connect to a Chroma server. Are you sure it is running?" + ) + # Propagate ChromaErrors + except ChromaError as e: + raise e + except Exception: + raise ValueError( + f"Could not connect to tenant {tenant}. Are you sure it exists?" + ) + + try: + await self._admin_client.get_database(name=database, tenant=tenant) + except httpx.ConnectError: + raise ValueError( + "Could not connect to a Chroma server. Are you sure it is running?" + ) + + # region BaseAPI Methods + # Note - we could do this in less verbose ways, but they break type checking + @override + async def heartbeat(self) -> int: + return await self._server.heartbeat() + + @override + async def list_collections( + self, limit: Optional[int] = None, offset: Optional[int] = None + ) -> Sequence[AsyncCollection]: + models = await self._server.list_collections( + limit, offset, tenant=self.tenant, database=self.database + ) + return [AsyncCollection(client=self._server, model=model) for model in models] + + @override + async def count_collections(self) -> int: + return await self._server.count_collections( + tenant=self.tenant, database=self.database + ) + + @override + async def create_collection( + self, + name: str, + schema: Optional[Schema] = None, + configuration: Optional[CreateCollectionConfiguration] = None, + metadata: Optional[CollectionMetadata] = None, + embedding_function: Optional[ + EmbeddingFunction[Embeddable] + ] = DefaultEmbeddingFunction(), # type: ignore + data_loader: Optional[DataLoader[Loadable]] = None, + get_or_create: bool = False, + ) -> AsyncCollection: + if configuration is None: + configuration = {} + + configuration_ef = configuration.get("embedding_function") + + validate_embedding_function_conflict_on_create( + embedding_function, configuration_ef + ) + + # If ef provided in function params and collection config ef is None, + # set the collection config ef to the function params + if embedding_function is not None and configuration_ef is None: + configuration["embedding_function"] = embedding_function + + model = await self._server.create_collection( + name=name, + schema=schema, + configuration=configuration, + metadata=metadata, + tenant=self.tenant, + database=self.database, + get_or_create=get_or_create, + ) + return AsyncCollection( + client=self._server, + model=model, + embedding_function=embedding_function, + data_loader=data_loader, + ) + + @override + async def get_collection( + self, + name: str, + embedding_function: Optional[ + EmbeddingFunction[Embeddable] + ] = DefaultEmbeddingFunction(), # type: ignore + data_loader: Optional[DataLoader[Loadable]] = None, + ) -> AsyncCollection: + model = await self._server.get_collection( + name=name, + tenant=self.tenant, + database=self.database, + ) + persisted_ef_config = model.configuration_json.get("embedding_function") + + validate_embedding_function_conflict_on_get( + embedding_function, persisted_ef_config + ) + + return AsyncCollection( + client=self._server, + model=model, + embedding_function=embedding_function, + data_loader=data_loader, + ) + + @override + async def get_collection_by_id( + self, + id: UUID, + embedding_function: Optional[ + EmbeddingFunction[Embeddable] + ] = DefaultEmbeddingFunction(), # type: ignore + data_loader: Optional[DataLoader[Loadable]] = None, + ) -> AsyncCollection: + """Get a collection by its ID. + + Args: + id: The UUID of the collection. + embedding_function: Optional embedding function for the collection. + data_loader: Optional data loader for documents with URIs. + + Returns: + AsyncCollection: The requested collection. + + Raises: + ValueError: If the embedding function conflicts with configuration. + """ + model = await self._server.get_collection_by_id( + collection_id=id, + tenant=self.tenant, + database=self.database, + ) + persisted_ef_config = model.configuration_json.get("embedding_function") + + validate_embedding_function_conflict_on_get( + embedding_function, persisted_ef_config + ) + + return AsyncCollection( + client=self._server, + model=model, + embedding_function=embedding_function, + data_loader=data_loader, + ) + + @override + async def get_or_create_collection( + self, + name: str, + schema: Optional[Schema] = None, + configuration: Optional[CreateCollectionConfiguration] = None, + metadata: Optional[CollectionMetadata] = None, + embedding_function: Optional[ + EmbeddingFunction[Embeddable] + ] = DefaultEmbeddingFunction(), # type: ignore + data_loader: Optional[DataLoader[Loadable]] = None, + ) -> AsyncCollection: + if configuration is None: + configuration = {} + + configuration_ef = configuration.get("embedding_function") + + validate_embedding_function_conflict_on_create( + embedding_function, configuration_ef + ) + + if embedding_function is not None and configuration_ef is None: + configuration["embedding_function"] = embedding_function + model = await self._server.get_or_create_collection( + name=name, + schema=schema, + configuration=configuration, + metadata=metadata, + tenant=self.tenant, + database=self.database, + ) + + persisted_ef_config = model.configuration_json.get("embedding_function") + + validate_embedding_function_conflict_on_get( + embedding_function, persisted_ef_config + ) + + return AsyncCollection( + client=self._server, + model=model, + embedding_function=embedding_function, + data_loader=data_loader, + ) + + @override + async def _modify( + self, + id: UUID, + new_name: Optional[str] = None, + new_metadata: Optional[CollectionMetadata] = None, + new_configuration: Optional[UpdateCollectionConfiguration] = None, + ) -> None: + return await self._server._modify( + id=id, + new_name=new_name, + new_metadata=new_metadata, + new_configuration=new_configuration, + tenant=self.tenant, + database=self.database, + ) + + @override + async def delete_collection( + self, + name: str, + ) -> None: + return await self._server.delete_collection( + name=name, + tenant=self.tenant, + database=self.database, + ) + + # + # ITEM METHODS + # + + @override + async def _add( + self, + ids: IDs, + collection_id: UUID, + embeddings: Embeddings, + metadatas: Optional[Metadatas] = None, + documents: Optional[Documents] = None, + uris: Optional[URIs] = None, + ) -> bool: + return await self._server._add( + ids=ids, + collection_id=collection_id, + embeddings=embeddings, + metadatas=metadatas, + documents=documents, + uris=uris, + tenant=self.tenant, + database=self.database, + ) + + @override + async def _update( + self, + collection_id: UUID, + ids: IDs, + embeddings: Optional[Embeddings] = None, + metadatas: Optional[Metadatas] = None, + documents: Optional[Documents] = None, + uris: Optional[URIs] = None, + ) -> bool: + return await self._server._update( + collection_id=collection_id, + ids=ids, + embeddings=embeddings, + metadatas=metadatas, + documents=documents, + uris=uris, + tenant=self.tenant, + database=self.database, + ) + + @override + async def _upsert( + self, + collection_id: UUID, + ids: IDs, + embeddings: Embeddings, + metadatas: Optional[Metadatas] = None, + documents: Optional[Documents] = None, + uris: Optional[URIs] = None, + ) -> bool: + return await self._server._upsert( + collection_id=collection_id, + ids=ids, + embeddings=embeddings, + metadatas=metadatas, + documents=documents, + uris=uris, + tenant=self.tenant, + database=self.database, + ) + + @override + async def _count(self, collection_id: UUID) -> int: + return await self._server._count( + collection_id=collection_id, + ) + + @override + async def _peek(self, collection_id: UUID, n: int = 10) -> GetResult: + return await self._server._peek( + collection_id=collection_id, + n=n, + ) + + @override + async def _get( + self, + collection_id: UUID, + ids: Optional[IDs] = None, + where: Optional[Where] = None, + limit: Optional[int] = None, + offset: Optional[int] = None, + where_document: Optional[WhereDocument] = None, + include: Include = IncludeMetadataDocuments, + ) -> GetResult: + return await self._server._get( + collection_id=collection_id, + ids=ids, + where=where, + limit=limit, + offset=offset, + where_document=where_document, + include=include, + tenant=self.tenant, + database=self.database, + ) + + async def _delete( + self, + collection_id: UUID, + ids: Optional[IDs], + where: Optional[Where] = None, + where_document: Optional[WhereDocument] = None, + limit: Optional[int] = None, + ) -> DeleteResult: + return await self._server._delete( + collection_id=collection_id, + ids=ids, + where=where, + where_document=where_document, + limit=limit, + tenant=self.tenant, + database=self.database, + ) + + @override + async def _query( + self, + collection_id: UUID, + query_embeddings: Embeddings, + ids: Optional[IDs] = None, + n_results: int = 10, + where: Optional[Where] = None, + where_document: Optional[WhereDocument] = None, + include: Include = IncludeMetadataDocumentsDistances, + ) -> QueryResult: + return await self._server._query( + collection_id=collection_id, + query_embeddings=query_embeddings, + ids=ids, + n_results=n_results, + where=where, + where_document=where_document, + include=include, + tenant=self.tenant, + database=self.database, + ) + + @override + async def reset(self) -> bool: + return await self._server.reset() + + @override + async def get_version(self) -> str: + return await self._server.get_version() + + @override + def get_settings(self) -> Settings: + return self._server.get_settings() + + @override + async def get_max_batch_size(self) -> int: + return await self._server.get_max_batch_size() + + # endregion + + +class AsyncAdminClient(SharedSystemClient, AsyncAdminAPI): + _server: AsyncServerAPI + + def __init__(self, settings: Settings = Settings()) -> None: + super().__init__(settings) + self._server = self._system.instance(AsyncServerAPI) + + @override + async def create_database(self, name: str, tenant: str = DEFAULT_TENANT) -> None: + return await self._server.create_database(name=name, tenant=tenant) + + @override + async def get_database(self, name: str, tenant: str = DEFAULT_TENANT) -> Database: + return await self._server.get_database(name=name, tenant=tenant) + + @override + async def delete_database(self, name: str, tenant: str = DEFAULT_TENANT) -> None: + return await self._server.delete_database(name=name, tenant=tenant) + + @override + async def list_databases( + self, + limit: Optional[int] = None, + offset: Optional[int] = None, + tenant: str = DEFAULT_TENANT, + ) -> Sequence[Database]: + return await self._server.list_databases( + limit=limit, offset=offset, tenant=tenant + ) + + @override + async def create_tenant(self, name: str) -> None: + return await self._server.create_tenant(name=name) + + @override + async def get_tenant(self, name: str) -> Tenant: + return await self._server.get_tenant(name=name) + + @classmethod + @override + def from_system( + cls, + system: System, + ) -> "AsyncAdminClient": + SharedSystemClient._populate_data_from_system(system) + instance = cls(settings=system.settings) + return instance diff --git a/python/user_packages/Python313/site-packages/chromadb/api/async_fastapi.py b/python/user_packages/Python313/site-packages/chromadb/api/async_fastapi.py new file mode 100644 index 0000000000000000000000000000000000000000..64548b3c17d0016a59f0392fe3d886014ef9ebfd --- /dev/null +++ b/python/user_packages/Python313/site-packages/chromadb/api/async_fastapi.py @@ -0,0 +1,848 @@ +import asyncio +from uuid import UUID +import urllib.parse +import orjson +from typing import Any, Mapping, Optional, cast, Tuple, Sequence, Dict, List +import logging +import httpx +from overrides import override +from chromadb import __version__ +from chromadb.auth import UserIdentity +from chromadb.api.async_api import AsyncServerAPI +from chromadb.api.base_http_client import BaseHTTPClient +from chromadb.api.collection_configuration import ( + CreateCollectionConfiguration, + UpdateCollectionConfiguration, + create_collection_configuration_to_json, + update_collection_configuration_to_json, +) +from chromadb.config import DEFAULT_DATABASE, DEFAULT_TENANT, System, Settings +from chromadb.telemetry.opentelemetry import ( + OpenTelemetryClient, + OpenTelemetryGranularity, + trace_method, +) +from chromadb.telemetry.product import ProductTelemetryClient +from chromadb.utils.async_to_sync import async_to_sync +from chromadb.types import Database, Tenant, Collection as CollectionModel +from chromadb.execution.expression.plan import Search + +from chromadb.api.types import ( + DeleteResult, + Documents, + Embeddings, + IDs, + Include, + IndexingStatus, + Schema, + Metadatas, + ReadLevel, + URIs, + Where, + WhereDocument, + GetResult, + QueryResult, + SearchResult, + CollectionMetadata, + optional_embeddings_to_base64_strings, + validate_batch, + convert_np_embeddings_to_list, + IncludeMetadataDocuments, + IncludeMetadataDocumentsDistances, +) + +from chromadb.api.types import ( + IncludeMetadataDocumentsEmbeddings, + serialize_metadata, + deserialize_metadata, +) + + +logger = logging.getLogger(__name__) + + +class AsyncFastAPI(BaseHTTPClient, AsyncServerAPI): + # We make one client per event loop to avoid unexpected issues if a client + # is shared between event loops. + # For example, if a client is constructed in the main thread, then passed + # (or a returned Collection is passed) to a new thread, the client would + # normally throw an obscure asyncio error. + # Mixing asyncio and threading in this manner usually discouraged, but + # this gives a better user experience with practically no downsides. + # https://github.com/encode/httpx/issues/2058 + _clients: Dict[int, httpx.AsyncClient] = {} + + def __init__(self, system: System): + super().__init__(system) + + system.settings.require("chroma_server_host") + system.settings.require("chroma_server_http_port") + + self._opentelemetry_client = self.require(OpenTelemetryClient) + self._product_telemetry_client = self.require(ProductTelemetryClient) + self._settings = system.settings + + self._api_url = AsyncFastAPI.resolve_url( + chroma_server_host=str(system.settings.chroma_server_host), + chroma_server_http_port=system.settings.chroma_server_http_port, + chroma_server_ssl_enabled=system.settings.chroma_server_ssl_enabled, + default_api_path=system.settings.chroma_server_api_default_path, + ) + + async def __aenter__(self) -> "AsyncFastAPI": + self._get_client() + return self + + async def _cleanup(self) -> None: + while len(self._clients) > 0: + (_, client) = self._clients.popitem() + await client.aclose() + + async def __aexit__(self, exc_type: Any, exc_value: Any, traceback: Any) -> None: + await self._cleanup() + + @override + def stop(self) -> None: + super().stop() + + @async_to_sync + async def sync_cleanup() -> None: + await self._cleanup() + + sync_cleanup() + + def _get_client(self) -> httpx.AsyncClient: + # Ideally this would use anyio to be compatible with both + # asyncio and trio, but anyio does not expose any way to identify + # the current event loop. + # We attempt to get the loop assuming the environment is asyncio, and + # otherwise gracefully fall back to using a singleton client. + loop_hash = None + try: + loop = asyncio.get_event_loop() + loop_hash = loop.__hash__() + except RuntimeError: + loop_hash = 0 + + if loop_hash not in self._clients: + headers = (self._settings.chroma_server_headers or {}).copy() + headers["Content-Type"] = "application/json" + headers["User-Agent"] = ( + "Chroma Python Client v" + + __version__ + + " (https://github.com/chroma-core/chroma)" + ) + + self._clients[loop_hash] = httpx.AsyncClient( + timeout=None, + headers=headers, + verify=self._settings.chroma_server_ssl_verify or False, + limits=self.http_limits, + ) + + return self._clients[loop_hash] + + @override + def get_request_headers(self) -> Mapping[str, str]: + return dict(self._get_client().headers) + + @override + def get_api_url(self) -> str: + return self._api_url + + async def _make_request( + self, method: str, path: str, **kwargs: Dict[str, Any] + ) -> Any: + # If the request has json in kwargs, use orjson to serialize it, + # remove it from kwargs, and add it to the content parameter + # This is because httpx uses a slower json serializer + if "json" in kwargs: + data = orjson.dumps(kwargs.pop("json"), option=orjson.OPT_SERIALIZE_NUMPY) + kwargs["content"] = data + + # Unlike requests, httpx does not automatically escape the path + escaped_path = urllib.parse.quote(path, safe="/", encoding=None, errors=None) + url = self._api_url + escaped_path + + response = await self._get_client().request(method, url, **cast(Any, kwargs)) + BaseHTTPClient._raise_chroma_error(response) + return orjson.loads(response.text) + + @trace_method("AsyncFastAPI.heartbeat", OpenTelemetryGranularity.OPERATION) + @override + async def heartbeat(self) -> int: + response = await self._make_request("get", "") + return int(response["nanosecond heartbeat"]) + + @trace_method("AsyncFastAPI.create_database", OpenTelemetryGranularity.OPERATION) + @override + async def create_database( + self, + name: str, + tenant: str = DEFAULT_TENANT, + ) -> None: + await self._make_request( + "post", + f"/tenants/{tenant}/databases", + json={"name": name}, + ) + + @trace_method("AsyncFastAPI.get_database", OpenTelemetryGranularity.OPERATION) + @override + async def get_database( + self, + name: str, + tenant: str = DEFAULT_TENANT, + ) -> Database: + response = await self._make_request( + "get", + f"/tenants/{tenant}/databases/{name}", + params={"tenant": tenant}, + ) + + return Database( + id=response["id"], name=response["name"], tenant=response["tenant"] + ) + + @trace_method("AsyncFastAPI.delete_database", OpenTelemetryGranularity.OPERATION) + @override + async def delete_database( + self, + name: str, + tenant: str = DEFAULT_TENANT, + ) -> None: + await self._make_request( + "delete", + f"/tenants/{tenant}/databases/{name}", + ) + + @trace_method("AsyncFastAPI.list_databases", OpenTelemetryGranularity.OPERATION) + @override + async def list_databases( + self, + limit: Optional[int] = None, + offset: Optional[int] = None, + tenant: str = DEFAULT_TENANT, + ) -> Sequence[Database]: + response = await self._make_request( + "get", + f"/tenants/{tenant}/databases", + params=BaseHTTPClient._clean_params( + { + "limit": limit, + "offset": offset, + } + ), + ) + + return [ + Database(id=db["id"], name=db["name"], tenant=db["tenant"]) + for db in response + ] + + @trace_method("AsyncFastAPI.create_tenant", OpenTelemetryGranularity.OPERATION) + @override + async def create_tenant(self, name: str) -> None: + await self._make_request( + "post", + "/tenants", + json={"name": name}, + ) + + @trace_method("AsyncFastAPI.get_tenant", OpenTelemetryGranularity.OPERATION) + @override + async def get_tenant(self, name: str) -> Tenant: + resp_json = await self._make_request( + "get", + "/tenants/" + name, + ) + + return Tenant(name=resp_json["name"]) + + @trace_method("AsyncFastAPI.get_user_identity", OpenTelemetryGranularity.OPERATION) + @override + async def get_user_identity(self) -> UserIdentity: + return UserIdentity(**(await self._make_request("get", "/auth/identity"))) + + @trace_method("AsyncFastAPI.list_collections", OpenTelemetryGranularity.OPERATION) + @override + async def list_collections( + self, + limit: Optional[int] = None, + offset: Optional[int] = None, + tenant: str = DEFAULT_TENANT, + database: str = DEFAULT_DATABASE, + ) -> Sequence[CollectionModel]: + resp_json = await self._make_request( + "get", + f"/tenants/{tenant}/databases/{database}/collections", + params=BaseHTTPClient._clean_params( + { + "limit": limit, + "offset": offset, + } + ), + ) + + models = [ + CollectionModel.from_json(json_collection) for json_collection in resp_json + ] + return models + + @trace_method("AsyncFastAPI.count_collections", OpenTelemetryGranularity.OPERATION) + @override + async def count_collections( + self, tenant: str = DEFAULT_TENANT, database: str = DEFAULT_DATABASE + ) -> int: + resp_json = await self._make_request( + "get", + f"/tenants/{tenant}/databases/{database}/collections_count", + ) + + return cast(int, resp_json) + + @trace_method("AsyncFastAPI.create_collection", OpenTelemetryGranularity.OPERATION) + @override + async def create_collection( + self, + name: str, + schema: Optional[Schema] = None, + configuration: Optional[CreateCollectionConfiguration] = None, + metadata: Optional[CollectionMetadata] = None, + get_or_create: bool = False, + tenant: str = DEFAULT_TENANT, + database: str = DEFAULT_DATABASE, + ) -> CollectionModel: + """Creates a collection""" + config_json = ( + create_collection_configuration_to_json(configuration, metadata) + if configuration + else None + ) + serialized_schema = schema.serialize_to_json() if schema else None + resp_json = await self._make_request( + "post", + f"/tenants/{tenant}/databases/{database}/collections", + json={ + "name": name, + "metadata": metadata, + "configuration": config_json, + "schema": serialized_schema, + "get_or_create": get_or_create, + }, + ) + model = CollectionModel.from_json(resp_json) + + return model + + @trace_method("AsyncFastAPI.get_collection", OpenTelemetryGranularity.OPERATION) + @override + async def get_collection( + self, + name: str, + tenant: str = DEFAULT_TENANT, + database: str = DEFAULT_DATABASE, + ) -> CollectionModel: + resp_json = await self._make_request( + "get", + f"/tenants/{tenant}/databases/{database}/collections/{name}", + ) + + model = CollectionModel.from_json(resp_json) + + return model + + @trace_method( + "AsyncFastAPI.get_collection_by_id", OpenTelemetryGranularity.OPERATION + ) + @override + async def get_collection_by_id( + self, + collection_id: UUID, + tenant: str = DEFAULT_TENANT, + database: str = DEFAULT_DATABASE, + ) -> CollectionModel: + """Returns a collection by its ID""" + resp_json = await self._make_request( + "get", + f"/tenants/{tenant}/databases/{database}/collections/by-id/{collection_id}", + ) + + model = CollectionModel.from_json(resp_json) + + return model + + @trace_method( + "AsyncFastAPI.get_or_create_collection", OpenTelemetryGranularity.OPERATION + ) + @override + async def get_or_create_collection( + self, + name: str, + schema: Optional[Schema] = None, + configuration: Optional[CreateCollectionConfiguration] = None, + metadata: Optional[CollectionMetadata] = None, + tenant: str = DEFAULT_TENANT, + database: str = DEFAULT_DATABASE, + ) -> CollectionModel: + return await self.create_collection( + name=name, + schema=schema, + configuration=configuration, + metadata=metadata, + get_or_create=True, + tenant=tenant, + database=database, + ) + + @trace_method("AsyncFastAPI._modify", OpenTelemetryGranularity.OPERATION) + @override + async def _modify( + self, + id: UUID, + new_name: Optional[str] = None, + new_metadata: Optional[CollectionMetadata] = None, + new_configuration: Optional[UpdateCollectionConfiguration] = None, + tenant: str = DEFAULT_TENANT, + database: str = DEFAULT_DATABASE, + ) -> None: + await self._make_request( + "put", + f"/tenants/{tenant}/databases/{database}/collections/{id}", + json={ + "new_metadata": new_metadata, + "new_name": new_name, + "new_configuration": update_collection_configuration_to_json( + new_configuration + ) + if new_configuration + else None, + }, + ) + + @trace_method("AsyncFastAPI._fork", OpenTelemetryGranularity.OPERATION) + @override + async def _fork( + self, + collection_id: UUID, + new_name: str, + tenant: str = DEFAULT_TENANT, + database: str = DEFAULT_DATABASE, + ) -> CollectionModel: + resp_json = await self._make_request( + "post", + f"/tenants/{tenant}/databases/{database}/collections/{collection_id}/fork", + json={"new_name": new_name}, + ) + model = CollectionModel.from_json(resp_json) + return model + + @trace_method("AsyncFastAPI._fork_count", OpenTelemetryGranularity.OPERATION) + @override + async def _fork_count( + self, + collection_id: UUID, + tenant: str = DEFAULT_TENANT, + database: str = DEFAULT_DATABASE, + ) -> int: + resp_json = await self._make_request( + "get", + f"/tenants/{tenant}/databases/{database}/collections/{collection_id}/fork_count", + ) + return int(resp_json["count"]) + + @trace_method( + "AsyncFastAPI._get_indexing_status", OpenTelemetryGranularity.OPERATION + ) + @override + async def _get_indexing_status( + self, + collection_id: UUID, + tenant: str = DEFAULT_TENANT, + database: str = DEFAULT_DATABASE, + ) -> IndexingStatus: + resp_json = await self._make_request( + "get", + f"/tenants/{tenant}/databases/{database}/collections/{collection_id}/indexing_status", + ) + return IndexingStatus( + num_indexed_ops=resp_json["num_indexed_ops"], + num_unindexed_ops=resp_json["num_unindexed_ops"], + total_ops=resp_json["total_ops"], + op_indexing_progress=resp_json["op_indexing_progress"], + ) + + @trace_method("AsyncFastAPI._search", OpenTelemetryGranularity.OPERATION) + @override + async def _search( + self, + collection_id: UUID, + searches: List[Search], + tenant: str = DEFAULT_TENANT, + database: str = DEFAULT_DATABASE, + read_level: ReadLevel = ReadLevel.INDEX_AND_WAL, + ) -> SearchResult: + """Performs hybrid search on a collection""" + payload = { + "searches": [s.to_dict() for s in searches], + "read_level": read_level, + } + + resp_json = await self._make_request( + "post", + f"/tenants/{tenant}/databases/{database}/collections/{collection_id}/search", + json=payload, + ) + + metadata_batches = resp_json.get("metadatas", None) + if metadata_batches is not None: + resp_json["metadatas"] = [ + [ + deserialize_metadata(metadata) if metadata is not None else None + for metadata in metadatas + ] + if metadatas is not None + else None + for metadatas in metadata_batches + ] + + return SearchResult(resp_json) + + @trace_method("AsyncFastAPI.delete_collection", OpenTelemetryGranularity.OPERATION) + @override + async def delete_collection( + self, + name: str, + tenant: str = DEFAULT_TENANT, + database: str = DEFAULT_DATABASE, + ) -> None: + await self._make_request( + "delete", + f"/tenants/{tenant}/databases/{database}/collections/{name}", + ) + + @trace_method("AsyncFastAPI._count", OpenTelemetryGranularity.OPERATION) + @override + async def _count( + self, + collection_id: UUID, + tenant: str = DEFAULT_TENANT, + database: str = DEFAULT_DATABASE, + read_level: ReadLevel = ReadLevel.INDEX_AND_WAL, + ) -> int: + """Returns the number of embeddings in the database""" + resp_json = await self._make_request( + "get", + f"/tenants/{tenant}/databases/{database}/collections/{collection_id}/count", + params={"read_level": read_level.value}, + ) + + return cast(int, resp_json) + + @trace_method("AsyncFastAPI._peek", OpenTelemetryGranularity.OPERATION) + @override + async def _peek( + self, + collection_id: UUID, + n: int = 10, + tenant: str = DEFAULT_TENANT, + database: str = DEFAULT_DATABASE, + ) -> GetResult: + resp = await self._get( + collection_id, + tenant=tenant, + database=database, + limit=n, + include=IncludeMetadataDocumentsEmbeddings, + ) + + return resp + + @trace_method("AsyncFastAPI._get", OpenTelemetryGranularity.OPERATION) + @override + async def _get( + self, + collection_id: UUID, + ids: Optional[IDs] = None, + where: Optional[Where] = None, + limit: Optional[int] = None, + offset: Optional[int] = None, + where_document: Optional[WhereDocument] = None, + include: Include = IncludeMetadataDocuments, + tenant: str = DEFAULT_TENANT, + database: str = DEFAULT_DATABASE, + ) -> GetResult: + # Servers do not support the "data" include, as that is hydrated on the client side + filtered_include = [i for i in include if i != "data"] + + resp_json = await self._make_request( + "post", + f"/tenants/{tenant}/databases/{database}/collections/{collection_id}/get", + json={ + "ids": ids, + "where": where, + "limit": limit, + "offset": offset, + "where_document": where_document, + "include": filtered_include, + }, + ) + + metadatas = resp_json.get("metadatas", None) + if metadatas is not None: + metadatas = [ + deserialize_metadata(metadata) if metadata is not None else None + for metadata in metadatas + ] + + return GetResult( + ids=resp_json["ids"], + embeddings=resp_json.get("embeddings", None), + metadatas=metadatas, + documents=resp_json.get("documents", None), + data=None, + uris=resp_json.get("uris", None), + included=include, + ) + + @trace_method("AsyncFastAPI._delete", OpenTelemetryGranularity.OPERATION) + @override + async def _delete( + self, + collection_id: UUID, + ids: Optional[IDs] = None, + where: Optional[Where] = None, + where_document: Optional[WhereDocument] = None, + limit: Optional[int] = None, + tenant: str = DEFAULT_TENANT, + database: str = DEFAULT_DATABASE, + ) -> DeleteResult: + body: dict = {"where": where, "ids": ids, "where_document": where_document} + if limit is not None: + body["limit"] = limit + resp = await self._make_request( + "post", + f"/tenants/{tenant}/databases/{database}/collections/{collection_id}/delete", + json=body, + ) + return DeleteResult(deleted=resp.get("deleted", 0) if resp else 0) + + @trace_method("AsyncFastAPI._submit_batch", OpenTelemetryGranularity.ALL) + async def _submit_batch( + self, + batch: Tuple[ + IDs, + Optional[Embeddings], + Optional[Metadatas], + Optional[Documents], + Optional[URIs], + ], + url: str, + ) -> Any: + """ + Submits a batch of embeddings to the database + """ + supports_base64_encoding = await self.supports_base64_encoding() + + serialized_metadatas = None + if batch[2] is not None: + serialized_metadatas = [ + serialize_metadata(metadata) if metadata is not None else None + for metadata in batch[2] + ] + + data = { + "ids": batch[0], + "embeddings": optional_embeddings_to_base64_strings(batch[1]) + if supports_base64_encoding + else batch[1], + "metadatas": serialized_metadatas, + "documents": batch[3], + "uris": batch[4], + } + + return await self._make_request( + "post", + url, + json=data, + ) + + @trace_method("AsyncFastAPI._add", OpenTelemetryGranularity.ALL) + @override + async def _add( + self, + ids: IDs, + collection_id: UUID, + embeddings: Embeddings, + metadatas: Optional[Metadatas] = None, + documents: Optional[Documents] = None, + uris: Optional[URIs] = None, + tenant: str = DEFAULT_TENANT, + database: str = DEFAULT_DATABASE, + ) -> bool: + batch = ( + ids, + embeddings, + metadatas, + documents, + uris, + ) + validate_batch(batch, {"max_batch_size": await self.get_max_batch_size()}) + await self._submit_batch( + batch, + f"/tenants/{tenant}/databases/{database}/collections/{str(collection_id)}/add", + ) + return True + + @trace_method("AsyncFastAPI._update", OpenTelemetryGranularity.ALL) + @override + async def _update( + self, + collection_id: UUID, + ids: IDs, + embeddings: Optional[Embeddings] = None, + metadatas: Optional[Metadatas] = None, + documents: Optional[Documents] = None, + uris: Optional[URIs] = None, + tenant: str = DEFAULT_TENANT, + database: str = DEFAULT_DATABASE, + ) -> bool: + batch = ( + ids, + embeddings if embeddings is not None else None, + metadatas, + documents, + uris, + ) + validate_batch(batch, {"max_batch_size": await self.get_max_batch_size()}) + + await self._submit_batch( + batch, + f"/tenants/{tenant}/databases/{database}/collections/{str(collection_id)}/update", + ) + + return True + + @trace_method("AsyncFastAPI._upsert", OpenTelemetryGranularity.ALL) + @override + async def _upsert( + self, + collection_id: UUID, + ids: IDs, + embeddings: Embeddings, + metadatas: Optional[Metadatas] = None, + documents: Optional[Documents] = None, + uris: Optional[URIs] = None, + tenant: str = DEFAULT_TENANT, + database: str = DEFAULT_DATABASE, + ) -> bool: + batch = ( + ids, + embeddings, + metadatas, + documents, + uris, + ) + validate_batch(batch, {"max_batch_size": await self.get_max_batch_size()}) + await self._submit_batch( + batch, + f"/tenants/{tenant}/databases/{database}/collections/{str(collection_id)}/upsert", + ) + return True + + @trace_method("AsyncFastAPI._query", OpenTelemetryGranularity.ALL) + @override + async def _query( + self, + collection_id: UUID, + query_embeddings: Embeddings, + ids: Optional[IDs] = None, + n_results: int = 10, + where: Optional[Where] = None, + where_document: Optional[WhereDocument] = None, + include: Include = IncludeMetadataDocumentsDistances, + tenant: str = DEFAULT_TENANT, + database: str = DEFAULT_DATABASE, + ) -> QueryResult: + # Servers do not support the "data" include, as that is hydrated on the client side + filtered_include = [i for i in include if i != "data"] + + resp_json = await self._make_request( + "post", + f"/tenants/{tenant}/databases/{database}/collections/{collection_id}/query", + json={ + "ids": ids, + "query_embeddings": convert_np_embeddings_to_list(query_embeddings) + if query_embeddings is not None + else None, + "n_results": n_results, + "where": where, + "where_document": where_document, + "include": filtered_include, + }, + ) + + metadata_batches = resp_json.get("metadatas", None) + if metadata_batches is not None: + metadata_batches = [ + [ + deserialize_metadata(metadata) if metadata is not None else None + for metadata in metadatas + ] + if metadatas is not None + else None + for metadatas in metadata_batches + ] + + return QueryResult( + ids=resp_json["ids"], + distances=resp_json.get("distances", None), + embeddings=resp_json.get("embeddings", None), + metadatas=metadata_batches, + documents=resp_json.get("documents", None), + uris=resp_json.get("uris", None), + data=None, + included=include, + ) + + @trace_method("AsyncFastAPI.reset", OpenTelemetryGranularity.ALL) + @override + async def reset(self) -> bool: + resp_json = await self._make_request("post", "/reset") + return cast(bool, resp_json) + + @trace_method("AsyncFastAPI.get_version", OpenTelemetryGranularity.OPERATION) + @override + async def get_version(self) -> str: + resp_json = await self._make_request("get", "/version") + return cast(str, resp_json) + + @override + def get_settings(self) -> Settings: + return self._settings + + @trace_method( + "AsyncFastAPI.get_pre_flight_checks", OpenTelemetryGranularity.OPERATION + ) + async def get_pre_flight_checks(self) -> Any: + if self.pre_flight_checks is None: + resp_json = await self._make_request("get", "/pre-flight-checks") + self.pre_flight_checks = resp_json + return self.pre_flight_checks + + @trace_method( + "AsyncFastAPI.supports_base64_encoding", OpenTelemetryGranularity.OPERATION + ) + async def supports_base64_encoding(self) -> bool: + pre_flight_checks = await self.get_pre_flight_checks() + b64_encoding_enabled = cast( + bool, pre_flight_checks.get("supports_base64_encoding", False) + ) + return b64_encoding_enabled + + @trace_method("AsyncFastAPI.get_max_batch_size", OpenTelemetryGranularity.OPERATION) + @override + async def get_max_batch_size(self) -> int: + pre_flight_checks = await self.get_pre_flight_checks() + max_batch_size = cast(int, pre_flight_checks.get("max_batch_size", -1)) + return max_batch_size diff --git a/python/user_packages/Python313/site-packages/chromadb/api/base_http_client.py b/python/user_packages/Python313/site-packages/chromadb/api/base_http_client.py new file mode 100644 index 0000000000000000000000000000000000000000..6e7bb7f09f485ce68de9937dd6bd4cf0f7750b7c --- /dev/null +++ b/python/user_packages/Python313/site-packages/chromadb/api/base_http_client.py @@ -0,0 +1,145 @@ +from typing import Any, Dict, Mapping, Optional, TypeVar +from urllib.parse import quote, urlparse, urlunparse +import logging +import orjson as json +import httpx + +import chromadb.errors as errors +from chromadb.config import Component, Settings, System + +logger = logging.getLogger(__name__) + + +# inherits from Component so that it can create an init function to use system +# this way it can build limits from the settings in System +class BaseHTTPClient(Component): + _settings: Settings + pre_flight_checks: Any = None + DEFAULT_KEEPALIVE_SECS: float = 40.0 + + def __init__(self, system: System): + super().__init__(system) + self._settings = system.settings + keepalive_setting = self._settings.chroma_http_keepalive_secs + self.keepalive_secs: Optional[float] = ( + keepalive_setting + if keepalive_setting is not None + else BaseHTTPClient.DEFAULT_KEEPALIVE_SECS + ) + self._http_limits = self._build_limits() + + def _build_limits(self) -> httpx.Limits: + limit_kwargs: Dict[str, Any] = {} + if self.keepalive_secs is not None: + limit_kwargs["keepalive_expiry"] = self.keepalive_secs + + max_connections = self._settings.chroma_http_max_connections + if max_connections is not None: + limit_kwargs["max_connections"] = max_connections + + max_keepalive_connections = self._settings.chroma_http_max_keepalive_connections + if max_keepalive_connections is not None: + limit_kwargs["max_keepalive_connections"] = max_keepalive_connections + + return httpx.Limits(**limit_kwargs) + + @property + def http_limits(self) -> httpx.Limits: + return self._http_limits + + @staticmethod + def _validate_host(host: str) -> None: + parsed = urlparse(host) + if "/" in host and parsed.scheme not in {"http", "https"}: + raise ValueError( + "Invalid URL. " f"Unrecognized protocol - {parsed.scheme}." + ) + if "/" in host and (not host.startswith("http")): + raise ValueError( + "Invalid URL. " + "Seems that you are trying to pass URL as a host but without \ + specifying the protocol. " + "Please add http:// or https:// to the host." + ) + + @staticmethod + def resolve_url( + chroma_server_host: str, + chroma_server_ssl_enabled: Optional[bool] = False, + default_api_path: Optional[str] = "", + chroma_server_http_port: Optional[int] = 8000, + ) -> str: + _skip_port = False + _chroma_server_host = chroma_server_host + BaseHTTPClient._validate_host(_chroma_server_host) + if _chroma_server_host.startswith("http"): + logger.debug("Skipping port as the user is passing a full URL") + _skip_port = True + parsed = urlparse(_chroma_server_host) + + scheme = "https" if chroma_server_ssl_enabled else parsed.scheme or "http" + net_loc = parsed.netloc or parsed.hostname or chroma_server_host + port = ( + ":" + str(parsed.port or chroma_server_http_port) if not _skip_port else "" + ) + path = parsed.path or default_api_path + + if not path or path == net_loc: + path = default_api_path if default_api_path else "" + if not path.endswith(default_api_path or ""): + path = path + default_api_path if default_api_path else "" + full_url = urlunparse( + (scheme, f"{net_loc}{port}", quote(path.replace("//", "/")), "", "", "") + ) + + return full_url + + # requests removes None values from the built query string, but httpx includes it as an empty value + T = TypeVar("T", bound=Dict[Any, Any]) + + @staticmethod + def _clean_params(params: T) -> T: + """Remove None values from provided dict.""" + return {k: v for k, v in params.items() if v is not None} # type: ignore + + @staticmethod + def _raise_chroma_error(resp: httpx.Response) -> None: + """Raises an error if the response is not ok, using a ChromaError if possible.""" + try: + resp.raise_for_status() + return + except httpx.HTTPStatusError: + pass + + chroma_error = None + try: + body = json.loads(resp.text) + if "error" in body: + if body["error"] in errors.error_types: + chroma_error = errors.error_types[body["error"]](body["message"]) + + trace_id = resp.headers.get("chroma-trace-id") + if trace_id: + chroma_error.trace_id = trace_id + + except BaseException: + pass + + if chroma_error: + raise chroma_error + + try: + resp.raise_for_status() + except httpx.HTTPStatusError: + trace_id = resp.headers.get("chroma-trace-id") + if trace_id: + raise Exception(f"{resp.text} (trace ID: {trace_id})") + raise (Exception(resp.text)) + + def get_request_headers(self) -> Mapping[str, str]: + """Return headers used for HTTP requests.""" + return {} + + def get_api_url(self) -> str: + """Return the API URL for this client.""" + return "" diff --git a/python/user_packages/Python313/site-packages/chromadb/api/client.py b/python/user_packages/Python313/site-packages/chromadb/api/client.py new file mode 100644 index 0000000000000000000000000000000000000000..ec7b73c81d529b7f79a9133c1b6aa166b4974c97 --- /dev/null +++ b/python/user_packages/Python313/site-packages/chromadb/api/client.py @@ -0,0 +1,731 @@ +from typing import Optional, Sequence +from types import TracebackType +from uuid import UUID + +from overrides import override +import httpx +from chromadb.api import AdminAPI, ClientAPI, ServerAPI +from chromadb.api.collection_configuration import ( + CreateCollectionConfiguration, + UpdateCollectionConfiguration, + validate_embedding_function_conflict_on_create, + validate_embedding_function_conflict_on_get, +) +from chromadb.api.shared_system_client import SharedSystemClient +from chromadb.api.types import ( + CollectionMetadata, + DataLoader, + Documents, + Embeddable, + EmbeddingFunction, + Embeddings, + GetResult, + IDs, + Include, + Loadable, + Metadatas, + QueryResult, + Schema, + URIs, + IncludeMetadataDocuments, + IncludeMetadataDocumentsDistances, + DefaultEmbeddingFunction, + DeleteResult, +) +from chromadb.auth import UserIdentity +from chromadb.auth.utils import maybe_set_tenant_and_database +from chromadb.config import Settings, System +from chromadb.config import DEFAULT_TENANT, DEFAULT_DATABASE +from chromadb.api.models.Collection import Collection +from chromadb.errors import ChromaAuthError, ChromaError +from chromadb.types import Database, Tenant, Where, WhereDocument + + +class Client(SharedSystemClient, ClientAPI): + """A client for Chroma. This is the main entrypoint for interacting with Chroma. + A client internally stores its tenant and database and proxies calls to a + Server API instance of Chroma. It treats the Server API and corresponding System + as a singleton, so multiple clients connecting to the same resource will share the + same API instance. + + Client implementations should be implement their own API-caching strategies. + """ + + tenant: str = DEFAULT_TENANT + database: str = DEFAULT_DATABASE + + _server: ServerAPI + # An internal admin client for verifying that databases and tenants exist + _admin_client: AdminAPI + _closed: bool = False + + # region Initialization + def __init__( + self, + tenant: Optional[str] = DEFAULT_TENANT, + database: Optional[str] = DEFAULT_DATABASE, + settings: Settings = Settings(), + ) -> None: + super().__init__(settings=settings) + try: + if tenant is not None: + self.tenant = tenant + if database is not None: + self.database = database + + # Get the root system component we want to interact with + self._server = self._system.instance(ServerAPI) + + user_identity = self.get_user_identity() + + maybe_tenant, maybe_database = maybe_set_tenant_and_database( + user_identity, + overwrite_singleton_tenant_database_access_from_auth=settings.chroma_overwrite_singleton_tenant_database_access_from_auth, + user_provided_tenant=tenant, + user_provided_database=database, + ) + + # this should not happen unless types are invalidated + if maybe_tenant is None and tenant is None: + raise ChromaAuthError( + "Could not determine a tenant from the current authentication method. Please provide a tenant." + ) + if maybe_database is None and database is None: + raise ChromaAuthError( + "Could not determine a database name from the current authentication method. Please provide a database name." + ) + + if maybe_tenant: + self.tenant = maybe_tenant + if maybe_database: + self.database = maybe_database + + # Create an admin client for verifying that databases and tenants exist + self._admin_client = AdminClient.from_system(self._system) + self._validate_tenant_database(tenant=self.tenant, database=self.database) + + self._submit_client_start_event() + except Exception: + # If init fails after refcount was incremented, release references + # to avoid a resource leak (the caller never receives the object to + # call close() on it). + if hasattr(self, "_admin_client"): + SharedSystemClient._release_system(self._admin_client._identifier) + SharedSystemClient._release_system(self._identifier) + raise + + @classmethod + @override + def from_system( + cls, + system: System, + tenant: str = DEFAULT_TENANT, + database: str = DEFAULT_DATABASE, + ) -> "Client": + SharedSystemClient._populate_data_from_system(system) + instance = cls(tenant=tenant, database=database, settings=system.settings) + return instance + + # endregion + + @override + def get_user_identity(self) -> UserIdentity: + try: + return self._server.get_user_identity() + except httpx.ConnectError: + raise ValueError( + "Could not connect to a Chroma server. Are you sure it is running?" + ) + # Propagate ChromaErrors + except ChromaError as e: + raise e + except Exception as e: + raise ValueError(str(e)) + + # region BaseAPI Methods + # Note - we could do this in less verbose ways, but they break type checking + @override + def heartbeat(self) -> int: + """Return the server time in nanoseconds since epoch.""" + return self._server.heartbeat() + + @override + def list_collections( + self, limit: Optional[int] = None, offset: Optional[int] = None + ) -> Sequence[Collection]: + """List collections for the current tenant and database, with pagination. + + Returns: + Sequence[Collection]: Collection objects for the current tenant. + """ + return [ + Collection(client=self._server, model=model) + for model in self._server.list_collections( + limit, offset, tenant=self.tenant, database=self.database + ) + ] + + @override + def count_collections(self) -> int: + """Return the number of collections in the current database.""" + return self._server.count_collections( + tenant=self.tenant, database=self.database + ) + + @override + def create_collection( + self, + name: str, + schema: Optional[Schema] = None, + configuration: Optional[CreateCollectionConfiguration] = None, + metadata: Optional[CollectionMetadata] = None, + embedding_function: Optional[ + EmbeddingFunction[Embeddable] + ] = DefaultEmbeddingFunction(), # type: ignore + data_loader: Optional[DataLoader[Loadable]] = None, + get_or_create: bool = False, + ) -> Collection: + """Create a collection with optional configuration and metadata. + + If using a schema, do not provide `embedding_function`. Instead, + provide the `embedding_function` as part of the schema. + + Args: + name: Collection name. + schema: Optional collection schema for indexes and encryption. + configuration: Optional collection configuration. + metadata: Optional collection metadata. + embedding_function: Optional embedding function for the collection. + data_loader: Optional data loader for documents with URIs. + get_or_create: Whether to return an existing collection if present. + + Returns: + Collection: The created collection. + + Raises: + ValueError: If the embedding function conflicts with configuration. + """ + if configuration is None: + configuration = {} + + configuration_ef = configuration.get("embedding_function") + + validate_embedding_function_conflict_on_create( + embedding_function, configuration_ef + ) + + # If ef provided in function params and collection config ef is None, + # set the collection config ef to the function params + if embedding_function is not None and configuration_ef is None: + configuration["embedding_function"] = embedding_function + + model = self._server.create_collection( + name=name, + schema=schema, + metadata=metadata, + tenant=self.tenant, + database=self.database, + get_or_create=get_or_create, + configuration=configuration, + ) + return Collection( + client=self._server, + model=model, + embedding_function=embedding_function, + data_loader=data_loader, + ) + + @override + def get_collection( + self, + name: str, + embedding_function: Optional[ + EmbeddingFunction[Embeddable] + ] = DefaultEmbeddingFunction(), # type: ignore + data_loader: Optional[DataLoader[Loadable]] = None, + ) -> Collection: + """Get a collection by name. + + Args: + name: Collection name. + embedding_function: Optional embedding function for the collection. + data_loader: Optional data loader for documents with URIs. + + Returns: + Collection: The requested collection. + + Raises: + ValueError: If the embedding function conflicts with configuration. + """ + model = self._server.get_collection( + name=name, + tenant=self.tenant, + database=self.database, + ) + persisted_ef_config = model.configuration_json.get("embedding_function") + + validate_embedding_function_conflict_on_get( + embedding_function, persisted_ef_config + ) + + return Collection( + client=self._server, + model=model, + embedding_function=embedding_function, + data_loader=data_loader, + ) + + @override + def get_collection_by_id( + self, + id: UUID, + embedding_function: Optional[ + EmbeddingFunction[Embeddable] + ] = DefaultEmbeddingFunction(), # type: ignore + data_loader: Optional[DataLoader[Loadable]] = None, + ) -> Collection: + """Get a collection by its ID. + + Args: + id: The UUID of the collection. + embedding_function: Optional embedding function for the collection. + data_loader: Optional data loader for documents with URIs. + + Returns: + Collection: The requested collection. + + Raises: + ValueError: If the embedding function conflicts with configuration. + """ + model = self._server.get_collection_by_id( + collection_id=id, + tenant=self.tenant, + database=self.database, + ) + persisted_ef_config = model.configuration_json.get("embedding_function") + + validate_embedding_function_conflict_on_get( + embedding_function, persisted_ef_config + ) + + return Collection( + client=self._server, + model=model, + embedding_function=embedding_function, + data_loader=data_loader, + ) + + @override + def get_or_create_collection( + self, + name: str, + schema: Optional[Schema] = None, + configuration: Optional[CreateCollectionConfiguration] = None, + metadata: Optional[CollectionMetadata] = None, + embedding_function: Optional[ + EmbeddingFunction[Embeddable] + ] = DefaultEmbeddingFunction(), # type: ignore + data_loader: Optional[DataLoader[Loadable]] = None, + ) -> Collection: + """Get an existing collection or create a new one. + + If the collection does not exist, it will be created. If the collection + already exists, the schema, configuration, and metadata arguments + will be ignored. + + Args: + name: Collection name. + schema: Optional collection schema for indexes and encryption. + configuration: Optional collection configuration. + metadata: Optional collection metadata. + embedding_function: Optional embedding function for the collection. + data_loader: Optional data loader for URI-backed data. + + Returns: + Collection: The existing or newly created collection. + + Raises: + ValueError: If the embedding function does not match the collection's embedding function. + """ + if configuration is None: + configuration = {} + + configuration_ef = configuration.get("embedding_function") + + validate_embedding_function_conflict_on_create( + embedding_function, configuration_ef + ) + + if embedding_function is not None and configuration_ef is None: + configuration["embedding_function"] = embedding_function + model = self._server.get_or_create_collection( + name=name, + schema=schema, + metadata=metadata, + tenant=self.tenant, + database=self.database, + configuration=configuration, + ) + + persisted_ef_config = model.configuration_json.get("embedding_function") + + validate_embedding_function_conflict_on_get( + embedding_function, persisted_ef_config + ) + + return Collection( + client=self._server, + model=model, + embedding_function=embedding_function, + data_loader=data_loader, + ) + + @override + def _modify( + self, + id: UUID, + new_name: Optional[str] = None, + new_metadata: Optional[CollectionMetadata] = None, + new_configuration: Optional[UpdateCollectionConfiguration] = None, + ) -> None: + return self._server._modify( + id=id, + tenant=self.tenant, + database=self.database, + new_name=new_name, + new_metadata=new_metadata, + new_configuration=new_configuration, + ) + + @override + def delete_collection( + self, + name: str, + ) -> None: + return self._server.delete_collection( + name=name, + tenant=self.tenant, + database=self.database, + ) + + # + # ITEM METHODS + # + + @override + def _add( + self, + ids: IDs, + collection_id: UUID, + embeddings: Embeddings, + metadatas: Optional[Metadatas] = None, + documents: Optional[Documents] = None, + uris: Optional[URIs] = None, + ) -> bool: + return self._server._add( + ids=ids, + tenant=self.tenant, + database=self.database, + collection_id=collection_id, + embeddings=embeddings, + metadatas=metadatas, + documents=documents, + uris=uris, + ) + + @override + def _update( + self, + collection_id: UUID, + ids: IDs, + embeddings: Optional[Embeddings] = None, + metadatas: Optional[Metadatas] = None, + documents: Optional[Documents] = None, + uris: Optional[URIs] = None, + ) -> bool: + return self._server._update( + collection_id=collection_id, + tenant=self.tenant, + database=self.database, + ids=ids, + embeddings=embeddings, + metadatas=metadatas, + documents=documents, + uris=uris, + ) + + @override + def _upsert( + self, + collection_id: UUID, + ids: IDs, + embeddings: Embeddings, + metadatas: Optional[Metadatas] = None, + documents: Optional[Documents] = None, + uris: Optional[URIs] = None, + ) -> bool: + return self._server._upsert( + collection_id=collection_id, + tenant=self.tenant, + database=self.database, + ids=ids, + embeddings=embeddings, + metadatas=metadatas, + documents=documents, + uris=uris, + ) + + @override + def _count(self, collection_id: UUID) -> int: + return self._server._count( + collection_id=collection_id, + tenant=self.tenant, + database=self.database, + ) + + @override + def _peek(self, collection_id: UUID, n: int = 10) -> GetResult: + return self._server._peek( + collection_id=collection_id, + n=n, + tenant=self.tenant, + database=self.database, + ) + + @override + def _get( + self, + collection_id: UUID, + ids: Optional[IDs] = None, + where: Optional[Where] = None, + limit: Optional[int] = None, + offset: Optional[int] = None, + where_document: Optional[WhereDocument] = None, + include: Include = IncludeMetadataDocuments, + ) -> GetResult: + return self._server._get( + collection_id=collection_id, + tenant=self.tenant, + database=self.database, + ids=ids, + where=where, + limit=limit, + offset=offset, + where_document=where_document, + include=include, + ) + + def _delete( + self, + collection_id: UUID, + ids: Optional[IDs], + where: Optional[Where] = None, + where_document: Optional[WhereDocument] = None, + limit: Optional[int] = None, + ) -> DeleteResult: + return self._server._delete( + collection_id=collection_id, + tenant=self.tenant, + database=self.database, + ids=ids, + where=where, + where_document=where_document, + limit=limit, + ) + + @override + def _query( + self, + collection_id: UUID, + query_embeddings: Embeddings, + ids: Optional[IDs] = None, + n_results: int = 10, + where: Optional[Where] = None, + where_document: Optional[WhereDocument] = None, + include: Include = IncludeMetadataDocumentsDistances, + ) -> QueryResult: + return self._server._query( + collection_id=collection_id, + ids=ids, + tenant=self.tenant, + database=self.database, + query_embeddings=query_embeddings, + n_results=n_results, + where=where, + where_document=where_document, + include=include, + ) + + @override + def reset(self) -> bool: + return self._server.reset() + + @override + def get_version(self) -> str: + return self._server.get_version() + + @override + def get_settings(self) -> Settings: + return self._server.get_settings() + + @override + def get_max_batch_size(self) -> int: + return self._server.get_max_batch_size() + + # endregion + + # region ClientAPI Methods + + @override + def set_tenant(self, tenant: str, database: str = DEFAULT_DATABASE) -> None: + self._validate_tenant_database(tenant=tenant, database=database) + self.tenant = tenant + self.database = database + + @override + def set_database(self, database: str) -> None: + self._validate_tenant_database(tenant=self.tenant, database=database) + self.database = database + + def close(self) -> None: + """Close the client and release all resources. + + This method decrements the reference count for the underlying System. + When the last client using a shared System calls close(), the System + is stopped and all resources (database connections, etc.) are released. + + This is particularly important for PersistentClient to avoid SQLite + file locking issues. + + Note: If multiple clients share the same System (e.g., multiple PersistentClient + instances with the same path), the System will only be stopped when the last + client is closed. This allows safe use of context managers with multiple clients. + + Example: + >>> client = chromadb.PersistentClient(path="./chroma_db") + >>> # ... use client ... + >>> client.close() + + Or using context manager: + >>> with chromadb.PersistentClient(path="./chroma_db") as client: + ... # ... use client ... + """ + # Make close() idempotent - a second call is a safe no-op + if self._closed: + return + self._closed = True + + # Release the internal admin client's reference first, since it also + # incremented the refcount for the shared system on creation. + if hasattr(self, "_admin_client"): + SharedSystemClient._release_system(self._admin_client._identifier) + + # Release our own reference; stops system if this was the last client + SharedSystemClient._release_system(self._identifier) + + def __enter__(self) -> "Client": + """Context manager entry.""" + return self + + def __exit__( + self, + exc_type: Optional[type[BaseException]], + exc_val: Optional[BaseException], + exc_tb: Optional[TracebackType], + ) -> None: + """Context manager exit.""" + self.close() + + def _validate_tenant_database(self, tenant: str, database: str) -> None: + try: + self._admin_client.get_tenant(name=tenant) + except httpx.ConnectError: + raise ValueError( + "Could not connect to a Chroma server. Are you sure it is running?" + ) + # Propagate ChromaErrors + except ChromaError as e: + raise e + except Exception: + raise ValueError( + f"Could not connect to tenant {tenant}. Are you sure it exists?" + ) + + try: + self._admin_client.get_database(name=database, tenant=tenant) + except httpx.ConnectError: + raise ValueError( + "Could not connect to a Chroma server. Are you sure it is running?" + ) + + # endregion + + +class AdminClient(SharedSystemClient, AdminAPI): + """Admin client for managing tenants and databases.""" + + _server: ServerAPI + + def __init__(self, settings: Settings = Settings()) -> None: + super().__init__(settings) + self._server = self._system.instance(ServerAPI) + + @override + def create_database(self, name: str, tenant: str = DEFAULT_TENANT) -> None: + """Create a database in a tenant. + + Args: + name: Database name. + tenant: Tenant that owns the database. + """ + return self._server.create_database(name=name, tenant=tenant) + + @override + def get_database(self, name: str, tenant: str = DEFAULT_TENANT) -> Database: + """Get a database by name. + + Args: + name: Database name. + tenant: Tenant that owns the database. + + Returns: + Database: The database record. + """ + return self._server.get_database(name=name, tenant=tenant) + + @override + def delete_database(self, name: str, tenant: str = DEFAULT_TENANT) -> None: + """Delete a database by name. + + Args: + name: Database name. + tenant: Tenant that owns the database. + """ + return self._server.delete_database(name=name, tenant=tenant) + + @override + def list_databases( + self, + limit: Optional[int] = None, + offset: Optional[int] = None, + tenant: str = DEFAULT_TENANT, + ) -> Sequence[Database]: + return self._server.list_databases(limit, offset, tenant=tenant) + + @override + def create_tenant(self, name: str) -> None: + return self._server.create_tenant(name=name) + + @override + def get_tenant(self, name: str) -> Tenant: + return self._server.get_tenant(name=name) + + @classmethod + @override + def from_system( + cls, + system: System, + ) -> "AdminClient": + SharedSystemClient._populate_data_from_system(system) + instance = cls(settings=system.settings) + return instance diff --git a/python/user_packages/Python313/site-packages/chromadb/api/collection_configuration.py b/python/user_packages/Python313/site-packages/chromadb/api/collection_configuration.py new file mode 100644 index 0000000000000000000000000000000000000000..269c353b85fe084cad3a182fc7ad1d2503bc0e40 --- /dev/null +++ b/python/user_packages/Python313/site-packages/chromadb/api/collection_configuration.py @@ -0,0 +1,882 @@ +from typing import TypedDict, Dict, Any, Optional, cast, get_args +import json +from chromadb.api.types import ( + Space, + CollectionMetadata, + UpdateMetadata, + EmbeddingFunction, +) +from chromadb.utils.embedding_functions import ( + known_embedding_functions, + register_embedding_function, +) +from multiprocessing import cpu_count +import warnings + +from chromadb.api.types import Schema + + +class HNSWConfiguration(TypedDict, total=False): + space: Space + ef_construction: int + max_neighbors: int + ef_search: int + num_threads: int + batch_size: int + sync_threshold: int + resize_factor: float + + +class SpannConfiguration(TypedDict, total=False): + search_nprobe: int + write_nprobe: int + space: Space + ef_construction: int + ef_search: int + max_neighbors: int + reassign_neighbor_count: int + split_threshold: int + merge_threshold: int + + +class CollectionConfiguration(TypedDict, total=True): + hnsw: Optional[HNSWConfiguration] + spann: Optional[SpannConfiguration] + embedding_function: Optional[EmbeddingFunction] # type: ignore + + +def load_collection_configuration_from_json_str( + config_json_str: str, +) -> CollectionConfiguration: + config_json_map = json.loads(config_json_str) + return load_collection_configuration_from_json(config_json_map) + + +# TODO: make warnings prettier and add link to migration docs +def load_collection_configuration_from_json( + config_json_map: Dict[str, Any] +) -> CollectionConfiguration: + if ( + config_json_map.get("spann") is not None + and config_json_map.get("hnsw") is not None + ): + raise ValueError("hnsw and spann cannot both be provided") + + hnsw_config = None + spann_config = None + ef_config = None + + # Process vector index configuration (HNSW or SPANN) + if config_json_map.get("hnsw") is not None: + hnsw_config = cast(HNSWConfiguration, config_json_map["hnsw"]) + if config_json_map.get("spann") is not None: + spann_config = cast(SpannConfiguration, config_json_map["spann"]) + + # Process embedding function configuration + if config_json_map.get("embedding_function") is not None: + ef_config = config_json_map["embedding_function"] + if ef_config["type"] == "legacy": + warnings.warn( + "legacy embedding function config", + DeprecationWarning, + stacklevel=2, + ) + ef = None + else: + try: + ef_name = ef_config["name"] + except KeyError: + raise ValueError( + f"Embedding function name not found in config: {ef_config}" + ) + try: + ef = known_embedding_functions[ef_name] + except KeyError: + raise ValueError( + f"Embedding function {ef_name} not found. Add @register_embedding_function decorator to the class definition." + ) + try: + ef = ef.build_from_config(ef_config["config"]) # type: ignore + except Exception as e: + raise ValueError( + f"Could not build embedding function {ef_config['name']} from config {ef_config['config']}: {e}" + ) + else: + ef = None + + return CollectionConfiguration( + hnsw=hnsw_config, + spann=spann_config, + embedding_function=ef, # type: ignore + ) + + +def collection_configuration_to_json_str(config: CollectionConfiguration) -> str: + return json.dumps(collection_configuration_to_json(config)) + + +def collection_configuration_to_json(config: CollectionConfiguration) -> Dict[str, Any]: + if isinstance(config, dict): + hnsw_config = config.get("hnsw") + spann_config = config.get("spann") + ef = config.get("embedding_function") + else: + try: + hnsw_config = config.get_parameter("hnsw").value + except ValueError: + hnsw_config = None + try: + spann_config = config.get_parameter("spann").value + except ValueError: + spann_config = None + try: + ef = config.get_parameter("embedding_function").value + except ValueError: + ef = None + + ef_config: Dict[str, Any] | None = None + if hnsw_config is not None: + try: + hnsw_config = cast(HNSWConfiguration, hnsw_config) + except Exception as e: + raise ValueError(f"not a valid hnsw config: {e}") + if spann_config is not None: + try: + spann_config = cast(SpannConfiguration, spann_config) + except Exception as e: + raise ValueError(f"not a valid spann config: {e}") + + if ef is None: + ef = None + ef_config = {"type": "legacy"} + + if ef is not None: + try: + if ef.is_legacy(): + ef_config = {"type": "legacy"} + else: + ef_config = { + "name": ef.name(), + "type": "known", + "config": ef.get_config(), + } + register_embedding_function(type(ef)) # type: ignore + except Exception as e: + warnings.warn( + f"legacy embedding function config: {e}", + DeprecationWarning, + stacklevel=2, + ) + ef = None + ef_config = {"type": "legacy"} + + return { + "hnsw": hnsw_config, + "spann": spann_config, + "embedding_function": ef_config, + } + + +class CreateHNSWConfiguration(TypedDict, total=False): + space: Space + ef_construction: int + max_neighbors: int + ef_search: int + num_threads: int + batch_size: int + sync_threshold: int + resize_factor: float + + +def json_to_create_hnsw_configuration( + json_map: Dict[str, Any] +) -> CreateHNSWConfiguration: + config: CreateHNSWConfiguration = {} + if "space" in json_map: + space_value = json_map["space"] + if space_value in get_args(Space): + config["space"] = space_value + else: + raise ValueError(f"not a valid space: {space_value}") + if "ef_construction" in json_map: + config["ef_construction"] = json_map["ef_construction"] + if "max_neighbors" in json_map: + config["max_neighbors"] = json_map["max_neighbors"] + if "ef_search" in json_map: + config["ef_search"] = json_map["ef_search"] + if "num_threads" in json_map: + config["num_threads"] = json_map["num_threads"] + if "batch_size" in json_map: + config["batch_size"] = json_map["batch_size"] + if "sync_threshold" in json_map: + config["sync_threshold"] = json_map["sync_threshold"] + if "resize_factor" in json_map: + config["resize_factor"] = json_map["resize_factor"] + return config + + +class CreateSpannConfiguration(TypedDict, total=False): + search_nprobe: int + write_nprobe: int + space: Space + ef_construction: int + ef_search: int + max_neighbors: int + reassign_neighbor_count: int + split_threshold: int + merge_threshold: int + + +def json_to_create_spann_configuration( + json_map: Dict[str, Any] +) -> CreateSpannConfiguration: + config: CreateSpannConfiguration = {} + if "search_nprobe" in json_map: + config["search_nprobe"] = json_map["search_nprobe"] + if "write_nprobe" in json_map: + config["write_nprobe"] = json_map["write_nprobe"] + if "space" in json_map: + space_value = json_map["space"] + if space_value in get_args(Space): + config["space"] = space_value + else: + raise ValueError(f"not a valid space: {space_value}") + if "ef_construction" in json_map: + config["ef_construction"] = json_map["ef_construction"] + if "ef_search" in json_map: + config["ef_search"] = json_map["ef_search"] + if "max_neighbors" in json_map: + config["max_neighbors"] = json_map["max_neighbors"] + return config + + +class CreateCollectionConfiguration(TypedDict, total=False): + hnsw: Optional[CreateHNSWConfiguration] + spann: Optional[CreateSpannConfiguration] + embedding_function: Optional[EmbeddingFunction] # type: ignore + + +def create_collection_configuration_from_legacy_collection_metadata( + metadata: CollectionMetadata, +) -> CreateCollectionConfiguration: + """Create a CreateCollectionConfiguration from legacy collection metadata""" + return create_collection_configuration_from_legacy_metadata_dict(metadata) + + +def create_collection_configuration_from_legacy_metadata_dict( + metadata: Dict[str, Any], +) -> CreateCollectionConfiguration: + """Create a CreateCollectionConfiguration from legacy collection metadata""" + old_to_new = { + "hnsw:space": "space", + "hnsw:construction_ef": "ef_construction", + "hnsw:M": "max_neighbors", + "hnsw:search_ef": "ef_search", + "hnsw:num_threads": "num_threads", + "hnsw:batch_size": "batch_size", + "hnsw:sync_threshold": "sync_threshold", + "hnsw:resize_factor": "resize_factor", + } + json_map = {} + for name, value in metadata.items(): + if name in old_to_new: + json_map[old_to_new[name]] = value + hnsw_config = json_to_create_hnsw_configuration(json_map) + hnsw_config = populate_create_hnsw_defaults(hnsw_config) + + return CreateCollectionConfiguration(hnsw=hnsw_config) + + +# TODO: make warnings prettier and add link to migration docs +def load_create_collection_configuration_from_json( + json_map: Dict[str, Any] +) -> CreateCollectionConfiguration: + if json_map.get("hnsw") is not None and json_map.get("spann") is not None: + raise ValueError("hnsw and spann cannot both be provided") + + result = CreateCollectionConfiguration() + + # Handle vector index configuration + if json_map.get("hnsw") is not None: + result["hnsw"] = json_to_create_hnsw_configuration(json_map["hnsw"]) + + if json_map.get("spann") is not None: + result["spann"] = json_to_create_spann_configuration(json_map["spann"]) + + # Handle embedding function configuration + if json_map.get("embedding_function") is not None: + ef_config = json_map["embedding_function"] + if ef_config["type"] == "legacy": + warnings.warn( + "legacy embedding function config", + DeprecationWarning, + stacklevel=2, + ) + else: + ef = known_embedding_functions[ef_config["name"]] + result["embedding_function"] = ef.build_from_config(ef_config["config"]) + + return result + + +def create_collection_configuration_to_json_str( + config: CreateCollectionConfiguration, + metadata: Optional[CollectionMetadata] = None, +) -> str: + """Convert a CreateCollection configuration to a JSON-serializable string""" + return json.dumps(create_collection_configuration_to_json(config, metadata)) + + +# TODO: make warnings prettier and add link to migration docs +def create_collection_configuration_to_json( + config: CreateCollectionConfiguration, + metadata: Optional[CollectionMetadata] = None, +) -> Dict[str, Any]: + """Convert a CreateCollection configuration to a JSON-serializable dict""" + ef_config: Dict[str, Any] | None = None + hnsw_config = config.get("hnsw") + spann_config = config.get("spann") + if hnsw_config is not None: + try: + hnsw_config = cast(CreateHNSWConfiguration, hnsw_config) + except Exception as e: + raise ValueError(f"not a valid hnsw config: {e}") + if spann_config is not None: + try: + spann_config = cast(CreateSpannConfiguration, spann_config) + except Exception as e: + raise ValueError(f"not a valid spann config: {e}") + + if hnsw_config is not None and spann_config is not None: + raise ValueError("hnsw and spann cannot both be provided") + + if config.get("embedding_function") is None: + ef = None + ef_config = {"type": "legacy"} + return { + "hnsw": hnsw_config, + "spann": spann_config, + "embedding_function": ef_config, + } + + try: + ef = cast(EmbeddingFunction, config.get("embedding_function")) # type: ignore + if ef.is_legacy(): + ef_config = {"type": "legacy"} + else: + # default space logic: if neither hnsw nor spann config is provided and metadata doesn't have space, + # then populate space from ef + # otherwise dont use default space from ef + + # then validate the space afterwards based on the supported spaces of the embedding function, + # warn if space is not supported + + if hnsw_config is None and spann_config is None: + if metadata is None or metadata.get("hnsw:space") is None: + # this populates space from ef if not provided in either config + hnsw_config = CreateHNSWConfiguration(space=ef.default_space()) + + # if hnsw config or spann config exists but space is not provided, populate it from ef + if hnsw_config is not None and hnsw_config.get("space") is None: + hnsw_config["space"] = ef.default_space() + if spann_config is not None and spann_config.get("space") is None: + spann_config["space"] = ef.default_space() + + # Validate space compatibility with embedding function + if hnsw_config is not None: + if hnsw_config.get("space") not in ef.supported_spaces(): + warnings.warn( + f"space {hnsw_config.get('space')} is not supported by {ef.name()}. Supported spaces: {ef.supported_spaces()}", + UserWarning, + stacklevel=2, + ) + if spann_config is not None: + if spann_config.get("space") not in ef.supported_spaces(): + warnings.warn( + f"space {spann_config.get('space')} is not supported by {ef.name()}. Supported spaces: {ef.supported_spaces()}", + UserWarning, + stacklevel=2, + ) + + # only validate space from metadata if config is not provided + if ( + hnsw_config is None + and spann_config is None + and metadata is not None + and metadata.get("hnsw:space") is not None + ): + if metadata.get("hnsw:space") not in ef.supported_spaces(): + warnings.warn( + f"space {metadata.get('hnsw:space')} is not supported by {ef.name()}. Supported spaces: {ef.supported_spaces()}", + UserWarning, + stacklevel=2, + ) + + ef_config = { + "name": ef.name(), + "type": "known", + "config": ef.get_config(), + } + register_embedding_function(type(ef)) # type: ignore + except Exception as e: + warnings.warn( + f"legacy embedding function config: {e}", + DeprecationWarning, + stacklevel=2, + ) + ef = None + ef_config = {"type": "legacy"} + + return { + "hnsw": hnsw_config, + "spann": spann_config, + "embedding_function": ef_config, + } + + +def populate_create_hnsw_defaults( + config: CreateHNSWConfiguration, ef: Optional[EmbeddingFunction] = None # type: ignore +) -> CreateHNSWConfiguration: + """Populate a CreateHNSW configuration with default values""" + if config.get("space") is None: + config["space"] = ef.default_space() if ef else "l2" + if config.get("ef_construction") is None: + config["ef_construction"] = 100 + if config.get("max_neighbors") is None: + config["max_neighbors"] = 16 + if config.get("ef_search") is None: + config["ef_search"] = 100 + if config.get("num_threads") is None: + config["num_threads"] = cpu_count() + if config.get("batch_size") is None: + config["batch_size"] = 100 + if config.get("sync_threshold") is None: + config["sync_threshold"] = 1000 + if config.get("resize_factor") is None: + config["resize_factor"] = 1.2 + return config + + +class UpdateHNSWConfiguration(TypedDict, total=False): + ef_search: int + num_threads: int + batch_size: int + sync_threshold: int + resize_factor: float + + +def json_to_update_hnsw_configuration( + json_map: Dict[str, Any] +) -> UpdateHNSWConfiguration: + config: UpdateHNSWConfiguration = {} + if "ef_search" in json_map: + config["ef_search"] = json_map["ef_search"] + if "num_threads" in json_map: + config["num_threads"] = json_map["num_threads"] + if "batch_size" in json_map: + config["batch_size"] = json_map["batch_size"] + if "sync_threshold" in json_map: + config["sync_threshold"] = json_map["sync_threshold"] + if "resize_factor" in json_map: + config["resize_factor"] = json_map["resize_factor"] + return config + + +class UpdateSpannConfiguration(TypedDict, total=False): + search_nprobe: int + ef_search: int + + +def json_to_update_spann_configuration( + json_map: Dict[str, Any] +) -> UpdateSpannConfiguration: + config: UpdateSpannConfiguration = {} + if "search_nprobe" in json_map: + config["search_nprobe"] = json_map["search_nprobe"] + if "ef_search" in json_map: + config["ef_search"] = json_map["ef_search"] + return config + + +class UpdateCollectionConfiguration(TypedDict, total=False): + hnsw: Optional[UpdateHNSWConfiguration] + spann: Optional[UpdateSpannConfiguration] + embedding_function: Optional[EmbeddingFunction] # type: ignore + + +def update_collection_configuration_from_legacy_collection_metadata( + metadata: CollectionMetadata, +) -> UpdateCollectionConfiguration: + """Create an UpdateCollectionConfiguration from legacy collection metadata""" + old_to_new = { + "hnsw:search_ef": "ef_search", + "hnsw:num_threads": "num_threads", + "hnsw:batch_size": "batch_size", + "hnsw:sync_threshold": "sync_threshold", + "hnsw:resize_factor": "resize_factor", + } + json_map = {} + for name, value in metadata.items(): + if name in old_to_new: + json_map[old_to_new[name]] = value + hnsw_config = json_to_update_hnsw_configuration(json_map) + return UpdateCollectionConfiguration(hnsw=hnsw_config) + + +def update_collection_configuration_from_legacy_update_metadata( + metadata: UpdateMetadata, +) -> UpdateCollectionConfiguration: + """Create an UpdateCollectionConfiguration from legacy update metadata""" + old_to_new = { + "hnsw:search_ef": "ef_search", + "hnsw:num_threads": "num_threads", + "hnsw:batch_size": "batch_size", + "hnsw:sync_threshold": "sync_threshold", + "hnsw:resize_factor": "resize_factor", + } + json_map = {} + for name, value in metadata.items(): + if name in old_to_new: + json_map[old_to_new[name]] = value + hnsw_config = json_to_update_hnsw_configuration(json_map) + return UpdateCollectionConfiguration(hnsw=hnsw_config) + + +def update_collection_configuration_to_json_str( + config: UpdateCollectionConfiguration, +) -> str: + """Convert an UpdateCollectionConfiguration to a JSON-serializable string""" + json_dict = update_collection_configuration_to_json(config) + return json.dumps(json_dict) + + +def update_collection_configuration_to_json( + config: UpdateCollectionConfiguration, +) -> Dict[str, Any]: + """Convert an UpdateCollectionConfiguration to a JSON-serializable dict""" + hnsw_config = config.get("hnsw") + spann_config = config.get("spann") + ef = config.get("embedding_function") + if hnsw_config is None and spann_config is None and ef is None: + return {} + + if hnsw_config is not None: + try: + hnsw_config = cast(UpdateHNSWConfiguration, hnsw_config) + except Exception as e: + raise ValueError(f"not a valid hnsw config: {e}") + + if spann_config is not None: + try: + spann_config = cast(UpdateSpannConfiguration, spann_config) + except Exception as e: + raise ValueError(f"not a valid spann config: {e}") + + ef_config: Dict[str, Any] | None = None + if ef is not None: + if ef.is_legacy(): + ef_config = {"type": "legacy"} + else: + ef.validate_config(ef.get_config()) + ef_config = { + "name": ef.name(), + "type": "known", + "config": ef.get_config(), + } + register_embedding_function(type(ef)) # type: ignore + else: + ef_config = None + + return { + "hnsw": hnsw_config, + "spann": spann_config, + "embedding_function": ef_config, + } + + +def load_update_collection_configuration_from_json_str( + json_str: str, +) -> UpdateCollectionConfiguration: + json_map = json.loads(json_str) + return load_update_collection_configuration_from_json(json_map) + + +# TODO: make warnings prettier and add link to migration docs +def load_update_collection_configuration_from_json( + json_map: Dict[str, Any] +) -> UpdateCollectionConfiguration: + """Convert a JSON dict to an UpdateCollectionConfiguration""" + if json_map.get("hnsw") is not None and json_map.get("spann") is not None: + raise ValueError("hnsw and spann cannot both be provided") + + result = UpdateCollectionConfiguration() + + # Handle vector index configurations + if json_map.get("hnsw") is not None: + result["hnsw"] = json_to_update_hnsw_configuration(json_map["hnsw"]) + + if json_map.get("spann") is not None: + result["spann"] = json_to_update_spann_configuration(json_map["spann"]) + + # Handle embedding function + if json_map.get("embedding_function") is not None: + if json_map["embedding_function"]["type"] == "legacy": + warnings.warn( + "legacy embedding function config", + DeprecationWarning, + stacklevel=2, + ) + else: + ef = known_embedding_functions[json_map["embedding_function"]["name"]] + result["embedding_function"] = ef.build_from_config( + json_map["embedding_function"]["config"] + ) + + return result + + +def overwrite_hnsw_configuration( + existing_hnsw_config: HNSWConfiguration, update_hnsw_config: UpdateHNSWConfiguration +) -> HNSWConfiguration: + """Overwrite a HNSWConfiguration with a new configuration""" + # Create a copy of the existing config and update with new values + result = dict(existing_hnsw_config) + update_fields = [ + "ef_search", + "num_threads", + "batch_size", + "sync_threshold", + "resize_factor", + ] + + for field in update_fields: + if field in update_hnsw_config: + result[field] = update_hnsw_config[field] # type: ignore + + return cast(HNSWConfiguration, result) + + +def overwrite_spann_configuration( + existing_spann_config: SpannConfiguration, + update_spann_config: UpdateSpannConfiguration, +) -> SpannConfiguration: + """Overwrite a SpannConfiguration with a new configuration""" + result = dict(existing_spann_config) + update_fields = [ + "search_nprobe", + "ef_search", + ] + + for field in update_fields: + if field in update_spann_config: + result[field] = update_spann_config[field] # type: ignore + + return cast(SpannConfiguration, result) + + +# TODO: make warnings prettier and add link to migration docs +def overwrite_embedding_function( + existing_embedding_function: EmbeddingFunction, # type: ignore + update_embedding_function: EmbeddingFunction, # type: ignore +) -> EmbeddingFunction: # type: ignore + """Overwrite an EmbeddingFunction with a new configuration""" + # Check for legacy embedding functions + if existing_embedding_function.is_legacy() or update_embedding_function.is_legacy(): + warnings.warn( + "cannot update legacy embedding function config", + DeprecationWarning, + stacklevel=2, + ) + return existing_embedding_function + + # Validate function compatibility + if existing_embedding_function.name() != update_embedding_function.name(): + raise ValueError( + f"Cannot update embedding function: incompatible types " + f"({existing_embedding_function.name()} vs {update_embedding_function.name()})" + ) + + # Validate and apply the configuration update + update_embedding_function.validate_config_update( + existing_embedding_function.get_config(), update_embedding_function.get_config() + ) + return update_embedding_function + + +def overwrite_collection_configuration( + existing_config: CollectionConfiguration, + update_config: UpdateCollectionConfiguration, +) -> CollectionConfiguration: + """Overwrite a CollectionConfiguration with a new configuration""" + update_spann = update_config.get("spann") + update_hnsw = update_config.get("hnsw") + if update_spann is not None and update_hnsw is not None: + raise ValueError("hnsw and spann cannot both be provided") + + # Handle HNSW configuration update + + updated_hnsw_config = existing_config.get("hnsw") + if updated_hnsw_config is not None and update_hnsw is not None: + updated_hnsw_config = overwrite_hnsw_configuration( + updated_hnsw_config, update_hnsw + ) + + # Handle SPANN configuration update + updated_spann_config = existing_config.get("spann") + if updated_spann_config is not None and update_spann is not None: + updated_spann_config = overwrite_spann_configuration( + updated_spann_config, update_spann + ) + + # Handle embedding function update + updated_embedding_function = existing_config.get("embedding_function") + update_ef = update_config.get("embedding_function") + if update_ef is not None: + if updated_embedding_function is not None: + updated_embedding_function = overwrite_embedding_function( + updated_embedding_function, update_ef + ) + else: + updated_embedding_function = update_ef + + return CollectionConfiguration( + hnsw=updated_hnsw_config, + spann=updated_spann_config, + embedding_function=updated_embedding_function, + ) + + +def validate_embedding_function_conflict_on_create( + embedding_function: Optional[EmbeddingFunction], # type: ignore + configuration_ef: Optional[EmbeddingFunction], # type: ignore +) -> None: + """ + Validates that there are no conflicting embedding functions between function parameter + and collection configuration. + + Args: + embedding_function: The embedding function provided as a parameter + configuration_ef: The embedding function from collection configuration + + Returns: + bool: True if there is a conflict, False otherwise + """ + # If ef provided in function params and collection config, check if they are the same + # If not, there's a conflict + # ef is by default "default" if not provided, so ignore that case. + if embedding_function is not None and configuration_ef is not None: + if ( + embedding_function.name() != "default" + and embedding_function.name() != configuration_ef.name() + ): + raise ValueError( + f"Multiple embedding functions provided. Please provide only one. Embedding function conflict: {embedding_function.name()} vs {configuration_ef.name()}" + ) + return None + + +# The reason to use the config on get, rather than build the ef is because +# if there is an issue with deserializing the config, an error shouldn't be raised +# at get time. CollectionCommon.py will raise an error at _embed time if there is an issue deserializing. +def validate_embedding_function_conflict_on_get( + embedding_function: Optional[EmbeddingFunction], # type: ignore + persisted_ef_config: Optional[Dict[str, Any]], +) -> None: + """ + Validates that there are no conflicting embedding functions between function parameter + and collection configuration. + """ + if persisted_ef_config is not None and embedding_function is not None: + if ( + embedding_function.name() != "default" + and persisted_ef_config.get("name") is not None + and persisted_ef_config.get("name") != embedding_function.name() + ): + raise ValueError( + f"An embedding function already exists in the collection configuration, and a new one is provided. If this is intentional, please embed documents separately. Embedding function conflict: new: {embedding_function.name()} vs persisted: {persisted_ef_config.get('name')}" + ) + return None + + +def update_schema_from_collection_configuration( + schema: "Schema", configuration: "UpdateCollectionConfiguration" +) -> "Schema": + """ + Updates a schema with configuration changes. + Only updates fields that are present in the configuration update. + + Args: + schema: The existing Schema object + configuration: The configuration updates to apply + + Returns: + Updated Schema object + """ + + # Get the vector index from defaults and #embedding key + if ( + schema.defaults.float_list is None + or schema.defaults.float_list.vector_index is None + ): + raise ValueError("Schema is missing defaults.float_list.vector_index") + + embedding_key = "#embedding" + if embedding_key not in schema.keys: + raise ValueError(f"Schema is missing keys[{embedding_key}]") + + embedding_value_types = schema.keys[embedding_key] + if ( + embedding_value_types.float_list is None + or embedding_value_types.float_list.vector_index is None + ): + raise ValueError( + f"Schema is missing keys[{embedding_key}].float_list.vector_index" + ) + + # Update vector index config in both locations + for vector_index in [ + schema.defaults.float_list.vector_index, + embedding_value_types.float_list.vector_index, + ]: + if "hnsw" in configuration and configuration["hnsw"] is not None: + # Update HNSW config + if vector_index.config.hnsw is None: + raise ValueError("Trying to update HNSW config but schema has SPANN") + + hnsw_config = vector_index.config.hnsw + update_hnsw = configuration["hnsw"] + + # Only update fields that are present in the update + if "ef_search" in update_hnsw: + hnsw_config.ef_search = update_hnsw["ef_search"] + if "num_threads" in update_hnsw: + hnsw_config.num_threads = update_hnsw["num_threads"] + if "batch_size" in update_hnsw: + hnsw_config.batch_size = update_hnsw["batch_size"] + if "sync_threshold" in update_hnsw: + hnsw_config.sync_threshold = update_hnsw["sync_threshold"] + if "resize_factor" in update_hnsw: + hnsw_config.resize_factor = update_hnsw["resize_factor"] + + elif "spann" in configuration and configuration["spann"] is not None: + # Update SPANN config + if vector_index.config.spann is None: + raise ValueError("Trying to update SPANN config but schema has HNSW") + + spann_config = vector_index.config.spann + update_spann = configuration["spann"] + + # Only update fields that are present in the update + if "search_nprobe" in update_spann: + spann_config.search_nprobe = update_spann["search_nprobe"] + if "ef_search" in update_spann: + spann_config.ef_search = update_spann["ef_search"] + + # Update embedding function if present + if ( + "embedding_function" in configuration + and configuration["embedding_function"] is not None + ): + vector_index.config.embedding_function = configuration["embedding_function"] + + return schema diff --git a/python/user_packages/Python313/site-packages/chromadb/api/configuration.py b/python/user_packages/Python313/site-packages/chromadb/api/configuration.py new file mode 100644 index 0000000000000000000000000000000000000000..7a95510f2eb49ae3491185c55b81496dd9869736 --- /dev/null +++ b/python/user_packages/Python313/site-packages/chromadb/api/configuration.py @@ -0,0 +1,410 @@ +from abc import abstractmethod +import json +from overrides import override +from typing import ( + Any, + ClassVar, + Dict, + List, + Optional, + Protocol, + Union, + TypeVar, + cast, +) +from typing_extensions import Self +from multiprocessing import cpu_count + +from chromadb.serde import JSONSerializable + +# TODO: move out of API + + +class StaticParameterError(Exception): + """Represents an error that occurs when a static parameter is set.""" + + pass + + +class InvalidConfigurationError(ValueError): + """Represents an error that occurs when a configuration is invalid.""" + + pass + + +ParameterValue = Union[str, int, float, bool, "ConfigurationInternal"] + + +class ParameterValidator(Protocol): + """Represents an abstract parameter validator.""" + + @abstractmethod + def __call__(self, value: ParameterValue) -> bool: + """Returns whether the given value is valid.""" + raise NotImplementedError() + + +class ConfigurationDefinition: + """Represents the definition of a configuration.""" + + name: str + validator: ParameterValidator + is_static: bool + default_value: ParameterValue + + def __init__( + self, + name: str, + validator: ParameterValidator, + is_static: bool, + default_value: ParameterValue, + ): + self.name = name + self.validator = validator + self.is_static = is_static + self.default_value = default_value + + +class ConfigurationParameter: + """Represents a parameter of a configuration.""" + + name: str + value: ParameterValue + + def __init__(self, name: str, value: ParameterValue): + self.name = name + self.value = value + + def __repr__(self) -> str: + return f"ConfigurationParameter({self.name}, {self.value})" + + def __eq__(self, __value: object) -> bool: + if not isinstance(__value, ConfigurationParameter): + return NotImplemented + return self.name == __value.name and self.value == __value.value + + +T = TypeVar("T", bound="ConfigurationInternal") + + +class ConfigurationInternal(JSONSerializable["ConfigurationInternal"]): + """Represents an abstract configuration, used internally by Chroma.""" + + # The internal data structure used to store the parameters + # All expected parameters must be present with defaults or None values at initialization + parameter_map: Dict[str, ConfigurationParameter] + definitions: ClassVar[Dict[str, ConfigurationDefinition]] + + def __init__(self, parameters: Optional[List[ConfigurationParameter]] = None): + """Initializes a new instance of the Configuration class. Respecting defaults and + validators.""" + self.parameter_map = {} + if parameters is not None: + for parameter in parameters: + if parameter.name not in self.definitions: + raise ValueError(f"Invalid parameter name: {parameter.name}") + + definition = self.definitions[parameter.name] + # Handle the case where we have a recursive configuration definition + if isinstance(parameter.value, dict): + child_type = globals().get(parameter.value.get("_type", None)) + if child_type is None: + raise ValueError( + f"Invalid configuration type: {parameter.value}" + ) + parameter.value = child_type.from_json(parameter.value) + if not isinstance(parameter.value, type(definition.default_value)): + raise ValueError(f"Invalid parameter value: {parameter.value}") + + parameter_validator = definition.validator + if not parameter_validator(parameter.value): + raise ValueError(f"Invalid parameter value: {parameter.value}") + self.parameter_map[parameter.name] = parameter + # Apply the defaults for any missing parameters + for name, definition in self.definitions.items(): + if name not in self.parameter_map: + self.parameter_map[name] = ConfigurationParameter( + name=name, value=definition.default_value + ) + + self.configuration_validator() + + def __repr__(self) -> str: + return f"Configuration({self.parameter_map.values()})" + + def __eq__(self, __value: object) -> bool: + if not isinstance(__value, ConfigurationInternal): + return NotImplemented + return self.parameter_map == __value.parameter_map + + @abstractmethod + def configuration_validator(self) -> None: + """Perform custom validation when parameters are dependent on each other. + + Raises an InvalidConfigurationError if the configuration is invalid. + """ + pass + + def get_parameters(self) -> List[ConfigurationParameter]: + """Returns the parameters of the configuration.""" + return list(self.parameter_map.values()) + + def get_parameter(self, name: str) -> ConfigurationParameter: + """Returns the parameter with the given name, or except if it doesn't exist.""" + if name not in self.parameter_map: + raise ValueError( + f"Invalid parameter name: {name} for configuration {self.__class__.__name__}" + ) + param_value = cast(ConfigurationParameter, self.parameter_map.get(name)) + return param_value + + def set_parameter(self, name: str, value: Union[str, int, float, bool]) -> None: + """Sets the parameter with the given name to the given value.""" + if name not in self.definitions: + raise ValueError(f"Invalid parameter name: {name}") + definition = self.definitions[name] + parameter = self.parameter_map[name] + if definition.is_static: + raise StaticParameterError(f"Cannot set static parameter: {name}") + if not definition.validator(value): + raise ValueError(f"Invalid value for parameter {name}: {value}") + parameter.value = value + + @override + def to_json_str(self) -> str: + """Returns the JSON representation of the configuration.""" + return json.dumps(self.to_json()) + + @classmethod + @override + def from_json_str(cls, json_str: str) -> Self: + """Returns a configuration from the given JSON string.""" + try: + config_json = json.loads(json_str) + except json.JSONDecodeError: + raise ValueError( + f"Unable to decode configuration from JSON string: {json_str}" + ) + return cls.from_json(config_json) if config_json else cls() + + @override + def to_json(self) -> Dict[str, Any]: + """Returns the JSON compatible dictionary representation of the configuration.""" + json_dict = { + name: parameter.value.to_json() + if isinstance(parameter.value, ConfigurationInternal) + else parameter.value + for name, parameter in self.parameter_map.items() + } + # What kind of configuration is this? + json_dict["_type"] = self.__class__.__name__ + return json_dict + + @classmethod + @override + def from_json(cls, json_map: Dict[str, Any]) -> Self: + """Returns a configuration from the given JSON string.""" + if cls.__name__ != json_map.get("_type", None): + raise ValueError( + f"Trying to instantiate configuration of type {cls.__name__} from JSON with type {json_map['_type']}" + ) + parameters = [] + for name, value in json_map.items(): + # Type value is only for storage + if name == "_type": + continue + parameters.append(ConfigurationParameter(name=name, value=value)) + return cls(parameters=parameters) + + +class HNSWConfigurationInternal(ConfigurationInternal): + """Internal representation of the HNSW configuration. + Used for validation, defaults, serialization and deserialization.""" + + definitions = { + "space": ConfigurationDefinition( + name="space", + validator=lambda value: isinstance(value, str) + and value in ["l2", "ip", "cosine"], + is_static=True, + default_value="l2", + ), + "ef_construction": ConfigurationDefinition( + name="ef_construction", + validator=lambda value: isinstance(value, int) and value >= 1, + is_static=True, + default_value=100, + ), + "ef_search": ConfigurationDefinition( + name="ef_search", + validator=lambda value: isinstance(value, int) and value >= 1, + is_static=False, + default_value=100, + ), + "num_threads": ConfigurationDefinition( + name="num_threads", + validator=lambda value: isinstance(value, int) and value >= 1, + is_static=False, + default_value=cpu_count(), # By default use all cores available + ), + "M": ConfigurationDefinition( + name="M", + validator=lambda value: isinstance(value, int) and value >= 1, + is_static=True, + default_value=16, + ), + "resize_factor": ConfigurationDefinition( + name="resize_factor", + validator=lambda value: isinstance(value, float) and value >= 1, + is_static=True, + default_value=1.2, + ), + "batch_size": ConfigurationDefinition( + name="batch_size", + validator=lambda value: isinstance(value, int) and value >= 1, + is_static=True, + default_value=100, + ), + "sync_threshold": ConfigurationDefinition( + name="sync_threshold", + validator=lambda value: isinstance(value, int) and value >= 1, + is_static=True, + default_value=1000, + ), + } + + @override + def configuration_validator(self) -> None: + batch_size = self.parameter_map.get("batch_size") + sync_threshold = self.parameter_map.get("sync_threshold") + + if ( + batch_size + and sync_threshold + and cast(int, batch_size.value) > cast(int, sync_threshold.value) + ): + raise InvalidConfigurationError( + "batch_size must be less than or equal to sync_threshold" + ) + + @classmethod + def from_legacy_params(cls, params: Dict[str, Any]) -> Self: + """Returns an HNSWConfiguration from a metadata dict containing legacy HNSW parameters. Used for migration.""" + + # We maintain this map to avoid a circular import with HnswParams, and + # because then names won't change since we intend to deprecate HNSWParams + # in favor of this type of configuration. + old_to_new = { + "hnsw:space": "space", + "hnsw:construction_ef": "ef_construction", + "hnsw:search_ef": "ef_search", + "hnsw:M": "M", + "hnsw:num_threads": "num_threads", + "hnsw:resize_factor": "resize_factor", + "hnsw:batch_size": "batch_size", + "hnsw:sync_threshold": "sync_threshold", + } + + parameters = [] + for name, value in params.items(): + if name not in old_to_new: + raise ValueError(f"Invalid legacy HNSW parameter name: {name}") + parameters.append( + ConfigurationParameter(name=old_to_new[name], value=value) + ) + return cls(parameters) + + +# This is the user-facing interface for HNSW index configuration parameters. +# Internally, we pass around HNSWConfigurationInternal objects, which perform +# validation, serialization and deserialization. Users don't need to know +# about that and instead get a clean constructor with default arguments. +class HNSWConfigurationInterface(HNSWConfigurationInternal): + """HNSW index configuration parameters. + See https://docs.trychroma.com/guides#changing-the-distance-function for more information. + """ + + def __init__( + self, + space: str = "l2", + ef_construction: int = 100, + ef_search: int = 100, + num_threads: int = cpu_count(), + M: int = 16, + resize_factor: float = 1.2, + batch_size: int = 100, + sync_threshold: int = 1000, + ): + parameters = [ + ConfigurationParameter(name="space", value=space), + ConfigurationParameter(name="ef_construction", value=ef_construction), + ConfigurationParameter(name="ef_search", value=ef_search), + ConfigurationParameter(name="num_threads", value=num_threads), + ConfigurationParameter(name="M", value=M), + ConfigurationParameter(name="resize_factor", value=resize_factor), + ConfigurationParameter(name="batch_size", value=batch_size), + ConfigurationParameter(name="sync_threshold", value=sync_threshold), + ] + + super().__init__(parameters=parameters) + + +# Alias for user convenience - the user doesn't need to know this is an 'Interface' +HNSWConfiguration = HNSWConfigurationInterface + + +class CollectionConfigurationInternal(ConfigurationInternal): + """Internal representation of the collection configuration. + Used for validation, defaults, and serialization / deserialization.""" + + definitions = { + "hnsw_configuration": ConfigurationDefinition( + name="hnsw_configuration", + validator=lambda value: isinstance(value, HNSWConfigurationInternal), + is_static=True, + default_value=HNSWConfigurationInternal(), + ), + } + + @override + def configuration_validator(self) -> None: + pass + + +# This is the user-facing interface for HNSW index configuration parameters. +# Internally, we pass around HNSWConfigurationInternal objects, which perform +# validation, serialization and deserialization. Users don't need to know +# about that and instead get a clean constructor with default arguments. +class CollectionConfigurationInterface(CollectionConfigurationInternal): + """Configuration parameters for creating a collection.""" + + def __init__(self, hnsw_configuration: Optional[HNSWConfigurationInternal]): + """Initializes a new instance of the CollectionConfiguration class. + Args: + hnsw_configuration: The HNSW configuration to use for the collection. + """ + if hnsw_configuration is None: + hnsw_configuration = HNSWConfigurationInternal() + parameters = [ + ConfigurationParameter(name="hnsw_configuration", value=hnsw_configuration) + ] + super().__init__(parameters=parameters) + + +# Alias for user convenience - the user doesn't need to know this is an 'Interface'. +CollectionConfiguration = CollectionConfigurationInterface + + +class EmbeddingsQueueConfigurationInternal(ConfigurationInternal): + definitions = { + "automatically_purge": ConfigurationDefinition( + name="automatically_purge", + validator=lambda value: isinstance(value, bool), + is_static=False, + default_value=True, + ), + } + + @override + def configuration_validator(self) -> None: + pass diff --git a/python/user_packages/Python313/site-packages/chromadb/api/fastapi.py b/python/user_packages/Python313/site-packages/chromadb/api/fastapi.py new file mode 100644 index 0000000000000000000000000000000000000000..0abf573cc524b09561797e9d34edc3ba178f845c --- /dev/null +++ b/python/user_packages/Python313/site-packages/chromadb/api/fastapi.py @@ -0,0 +1,915 @@ +import orjson +import logging +from typing import Any, Dict, Mapping, Optional, cast, Tuple, List +from typing import Sequence +from uuid import UUID +import httpx +import urllib.parse +from overrides import override + +from chromadb.api.models.AttachedFunction import AttachedFunction + +from chromadb.api.collection_configuration import ( + CreateCollectionConfiguration, + UpdateCollectionConfiguration, + update_collection_configuration_to_json, + create_collection_configuration_to_json, +) +from chromadb import __version__ +from chromadb.api.base_http_client import BaseHTTPClient +from chromadb.types import Database, Tenant, Collection as CollectionModel +from chromadb.api import ServerAPI +from chromadb.execution.expression.plan import Search + +from chromadb.api.types import ( + DeleteResult, + Documents, + Embeddings, + IDs, + Include, + IndexingStatus, + Schema, + Metadatas, + ReadLevel, + URIs, + Where, + WhereDocument, + GetResult, + QueryResult, + SearchResult, + CollectionMetadata, + validate_batch, + convert_np_embeddings_to_list, + IncludeMetadataDocuments, + IncludeMetadataDocumentsDistances, +) + +from chromadb.api.types import ( + IncludeMetadataDocumentsEmbeddings, + optional_embeddings_to_base64_strings, + serialize_metadata, + deserialize_metadata, +) +from chromadb.auth import UserIdentity +from chromadb.auth import ( + ClientAuthProvider, +) +from chromadb.config import DEFAULT_DATABASE, DEFAULT_TENANT, Settings, System +from chromadb.telemetry.opentelemetry import ( + OpenTelemetryClient, + OpenTelemetryGranularity, + trace_method, +) +from chromadb.telemetry.product import ProductTelemetryClient + +logger = logging.getLogger(__name__) + + +class FastAPI(BaseHTTPClient, ServerAPI): + def __init__(self, system: System): + super().__init__(system) + system.settings.require("chroma_server_host") + system.settings.require("chroma_server_http_port") + + self._opentelemetry_client = self.require(OpenTelemetryClient) + self._product_telemetry_client = self.require(ProductTelemetryClient) + self._settings = system.settings + + self._api_url = FastAPI.resolve_url( + chroma_server_host=str(system.settings.chroma_server_host), + chroma_server_http_port=system.settings.chroma_server_http_port, + chroma_server_ssl_enabled=system.settings.chroma_server_ssl_enabled, + default_api_path=system.settings.chroma_server_api_default_path, + ) + + if self._settings.chroma_server_ssl_verify is not None: + self._session = httpx.Client( + timeout=None, + limits=self.http_limits, + verify=self._settings.chroma_server_ssl_verify, + ) + else: + self._session = httpx.Client(timeout=None, limits=self.http_limits) + + self._header = system.settings.chroma_server_headers or {} + self._header["Content-Type"] = "application/json" + self._header["User-Agent"] = ( + "Chroma Python Client v" + + __version__ + + " (https://github.com/chroma-core/chroma)" + ) + + if self._header is not None: + self._session.headers.update(self._header) + + if system.settings.chroma_client_auth_provider: + self._auth_provider = self.require(ClientAuthProvider) + _headers = self._auth_provider.authenticate() + for header, value in _headers.items(): + self._session.headers[header] = value.get_secret_value() + + @override + def get_request_headers(self) -> Mapping[str, str]: + return dict(self._session.headers) + + @override + def get_api_url(self) -> str: + return self._api_url + + def _make_request(self, method: str, path: str, **kwargs: Dict[str, Any]) -> Any: + # If the request has json in kwargs, use orjson to serialize it, + # remove it from kwargs, and add it to the content parameter + # This is because httpx uses a slower json serializer + if "json" in kwargs: + data = orjson.dumps(kwargs.pop("json"), option=orjson.OPT_SERIALIZE_NUMPY) + kwargs["content"] = data + + # Unlike requests, httpx does not automatically escape the path + escaped_path = urllib.parse.quote(path, safe="/", encoding=None, errors=None) + url = self._api_url + escaped_path + + response = self._session.request(method, url, **cast(Any, kwargs)) + BaseHTTPClient._raise_chroma_error(response) + return orjson.loads(response.text) + + @trace_method("FastAPI.heartbeat", OpenTelemetryGranularity.OPERATION) + @override + def heartbeat(self) -> int: + """Returns the current server time in nanoseconds to check if the server is alive""" + resp_json = self._make_request("get", "/heartbeat") + return int(resp_json["nanosecond heartbeat"]) + + # Migrated to rust in distributed. + @trace_method("FastAPI.create_database", OpenTelemetryGranularity.OPERATION) + @override + def create_database( + self, + name: str, + tenant: str = DEFAULT_TENANT, + ) -> None: + """Creates a database""" + self._make_request( + "post", + f"/tenants/{tenant}/databases", + json={"name": name}, + ) + + # Migrated to rust in distributed. + @trace_method("FastAPI.get_database", OpenTelemetryGranularity.OPERATION) + @override + def get_database( + self, + name: str, + tenant: str = DEFAULT_TENANT, + ) -> Database: + """Returns a database""" + resp_json = self._make_request( + "get", + f"/tenants/{tenant}/databases/{name}", + ) + return Database( + id=resp_json["id"], name=resp_json["name"], tenant=resp_json["tenant"] + ) + + @trace_method("FastAPI.delete_database", OpenTelemetryGranularity.OPERATION) + @override + def delete_database( + self, + name: str, + tenant: str = DEFAULT_TENANT, + ) -> None: + """Deletes a database""" + self._make_request( + "delete", + f"/tenants/{tenant}/databases/{name}", + ) + + @trace_method("FastAPI.list_databases", OpenTelemetryGranularity.OPERATION) + @override + def list_databases( + self, + limit: Optional[int] = None, + offset: Optional[int] = None, + tenant: str = DEFAULT_TENANT, + ) -> Sequence[Database]: + """Returns a list of all databases""" + json_databases = self._make_request( + "get", + f"/tenants/{tenant}/databases", + params=BaseHTTPClient._clean_params( + { + "limit": limit, + "offset": offset, + } + ), + ) + databases = [ + Database(id=db["id"], name=db["name"], tenant=db["tenant"]) + for db in json_databases + ] + return databases + + @trace_method("FastAPI.create_tenant", OpenTelemetryGranularity.OPERATION) + @override + def create_tenant(self, name: str) -> None: + self._make_request("post", "/tenants", json={"name": name}) + + @trace_method("FastAPI.get_tenant", OpenTelemetryGranularity.OPERATION) + @override + def get_tenant(self, name: str) -> Tenant: + resp_json = self._make_request("get", "/tenants/" + name) + return Tenant(name=resp_json["name"]) + + @trace_method("FastAPI.get_user_identity", OpenTelemetryGranularity.OPERATION) + @override + def get_user_identity(self) -> UserIdentity: + return UserIdentity(**self._make_request("get", "/auth/identity")) + + @trace_method("FastAPI.list_collections", OpenTelemetryGranularity.OPERATION) + @override + def list_collections( + self, + limit: Optional[int] = None, + offset: Optional[int] = None, + tenant: str = DEFAULT_TENANT, + database: str = DEFAULT_DATABASE, + ) -> Sequence[CollectionModel]: + """Returns a list of all collections""" + json_collections = self._make_request( + "get", + f"/tenants/{tenant}/databases/{database}/collections", + params=BaseHTTPClient._clean_params( + { + "limit": limit, + "offset": offset, + } + ), + ) + collection_models = [ + CollectionModel.from_json(json_collection) + for json_collection in json_collections + ] + + return collection_models + + @trace_method("FastAPI.count_collections", OpenTelemetryGranularity.OPERATION) + @override + def count_collections( + self, tenant: str = DEFAULT_TENANT, database: str = DEFAULT_DATABASE + ) -> int: + """Returns a count of collections""" + resp_json = self._make_request( + "get", + f"/tenants/{tenant}/databases/{database}/collections_count", + ) + return cast(int, resp_json) + + @trace_method("FastAPI.create_collection", OpenTelemetryGranularity.OPERATION) + @override + def create_collection( + self, + name: str, + schema: Optional[Schema] = None, + configuration: Optional[CreateCollectionConfiguration] = None, + metadata: Optional[CollectionMetadata] = None, + get_or_create: bool = False, + tenant: str = DEFAULT_TENANT, + database: str = DEFAULT_DATABASE, + ) -> CollectionModel: + """Creates a collection""" + config_json = ( + create_collection_configuration_to_json(configuration, metadata) + if configuration + else None + ) + serialized_schema = schema.serialize_to_json() if schema else None + resp_json = self._make_request( + "post", + f"/tenants/{tenant}/databases/{database}/collections", + json={ + "name": name, + "metadata": metadata, + "configuration": config_json, + "schema": serialized_schema, + "get_or_create": get_or_create, + }, + ) + model = CollectionModel.from_json(resp_json) + + return model + + @trace_method("FastAPI.get_collection", OpenTelemetryGranularity.OPERATION) + @override + def get_collection( + self, + name: str, + tenant: str = DEFAULT_TENANT, + database: str = DEFAULT_DATABASE, + ) -> CollectionModel: + """Returns a collection""" + resp_json = self._make_request( + "get", + f"/tenants/{tenant}/databases/{database}/collections/{name}", + ) + + model = CollectionModel.from_json(resp_json) + return model + + @trace_method("FastAPI.get_collection_by_id", OpenTelemetryGranularity.OPERATION) + @override + def get_collection_by_id( + self, + collection_id: UUID, + tenant: str = DEFAULT_TENANT, + database: str = DEFAULT_DATABASE, + ) -> CollectionModel: + """Returns a collection by its ID""" + resp_json = self._make_request( + "get", + f"/tenants/{tenant}/databases/{database}/collections/by-id/{collection_id}", + ) + + model = CollectionModel.from_json(resp_json) + return model + + @trace_method( + "FastAPI.get_or_create_collection", OpenTelemetryGranularity.OPERATION + ) + @override + def get_or_create_collection( + self, + name: str, + schema: Optional[Schema] = None, + configuration: Optional[CreateCollectionConfiguration] = None, + metadata: Optional[CollectionMetadata] = None, + tenant: str = DEFAULT_TENANT, + database: str = DEFAULT_DATABASE, + ) -> CollectionModel: + return self.create_collection( + name=name, + metadata=metadata, + configuration=configuration, + schema=schema, + get_or_create=True, + tenant=tenant, + database=database, + ) + + @trace_method("FastAPI._modify", OpenTelemetryGranularity.OPERATION) + @override + def _modify( + self, + id: UUID, + new_name: Optional[str] = None, + new_metadata: Optional[CollectionMetadata] = None, + new_configuration: Optional[UpdateCollectionConfiguration] = None, + tenant: str = DEFAULT_TENANT, + database: str = DEFAULT_DATABASE, + ) -> None: + """Updates a collection""" + self._make_request( + "put", + f"/tenants/{tenant}/databases/{database}/collections/{id}", + json={ + "new_metadata": new_metadata, + "new_name": new_name, + "new_configuration": update_collection_configuration_to_json( + new_configuration + ) + if new_configuration + else None, + }, + ) + + @trace_method("FastAPI._fork", OpenTelemetryGranularity.OPERATION) + @override + def _fork( + self, + collection_id: UUID, + new_name: str, + tenant: str = DEFAULT_TENANT, + database: str = DEFAULT_DATABASE, + ) -> CollectionModel: + """Forks a collection""" + resp_json = self._make_request( + "post", + f"/tenants/{tenant}/databases/{database}/collections/{collection_id}/fork", + json={"new_name": new_name}, + ) + model = CollectionModel.from_json(resp_json) + return model + + @trace_method("FastAPI._fork_count", OpenTelemetryGranularity.OPERATION) + @override + def _fork_count( + self, + collection_id: UUID, + tenant: str = DEFAULT_TENANT, + database: str = DEFAULT_DATABASE, + ) -> int: + """Gets the number of forks for a collection""" + resp_json = self._make_request( + "get", + f"/tenants/{tenant}/databases/{database}/collections/{collection_id}/fork_count", + ) + return int(resp_json["count"]) + + @trace_method("FastAPI._get_indexing_status", OpenTelemetryGranularity.OPERATION) + @override + def _get_indexing_status( + self, + collection_id: UUID, + tenant: str = DEFAULT_TENANT, + database: str = DEFAULT_DATABASE, + ) -> IndexingStatus: + resp_json = self._make_request( + "get", + f"/tenants/{tenant}/databases/{database}/collections/{collection_id}/indexing_status", + ) + return IndexingStatus( + num_indexed_ops=resp_json["num_indexed_ops"], + num_unindexed_ops=resp_json["num_unindexed_ops"], + total_ops=resp_json["total_ops"], + op_indexing_progress=resp_json["op_indexing_progress"], + ) + + @trace_method("FastAPI._search", OpenTelemetryGranularity.OPERATION) + @override + def _search( + self, + collection_id: UUID, + searches: List[Search], + tenant: str = DEFAULT_TENANT, + database: str = DEFAULT_DATABASE, + read_level: ReadLevel = ReadLevel.INDEX_AND_WAL, + ) -> SearchResult: + """Performs hybrid search on a collection""" + # Convert Search objects to dictionaries + payload = { + "searches": [s.to_dict() for s in searches], + "read_level": read_level, + } + + resp_json = self._make_request( + "post", + f"/tenants/{tenant}/databases/{database}/collections/{collection_id}/search", + json=payload, + ) + + # Deserialize metadatas: convert transport format to SparseVector instances + metadata_batches = resp_json.get("metadatas", None) + if metadata_batches is not None: + # SearchResult has nested structure: List[Optional[List[Optional[Metadata]]]] + resp_json["metadatas"] = [ + [ + deserialize_metadata(metadata) if metadata is not None else None + for metadata in metadatas + ] + if metadatas is not None + else None + for metadatas in metadata_batches + ] + + return SearchResult(resp_json) + + @trace_method("FastAPI.delete_collection", OpenTelemetryGranularity.OPERATION) + @override + def delete_collection( + self, + name: str, + tenant: str = DEFAULT_TENANT, + database: str = DEFAULT_DATABASE, + ) -> None: + """Deletes a collection""" + self._make_request( + "delete", + f"/tenants/{tenant}/databases/{database}/collections/{name}", + ) + + @trace_method("FastAPI._count", OpenTelemetryGranularity.OPERATION) + @override + def _count( + self, + collection_id: UUID, + tenant: str = DEFAULT_TENANT, + database: str = DEFAULT_DATABASE, + read_level: ReadLevel = ReadLevel.INDEX_AND_WAL, + ) -> int: + """Returns the number of embeddings in the database""" + resp_json = self._make_request( + "get", + f"/tenants/{tenant}/databases/{database}/collections/{collection_id}/count", + params={"read_level": read_level.value}, + ) + return cast(int, resp_json) + + @trace_method("FastAPI._peek", OpenTelemetryGranularity.OPERATION) + @override + def _peek( + self, + collection_id: UUID, + n: int = 10, + tenant: str = DEFAULT_TENANT, + database: str = DEFAULT_DATABASE, + ) -> GetResult: + return cast( + GetResult, + self._get( + collection_id, + tenant=tenant, + database=database, + limit=n, + include=IncludeMetadataDocumentsEmbeddings, + ), + ) + + @trace_method("FastAPI._get", OpenTelemetryGranularity.OPERATION) + @override + def _get( + self, + collection_id: UUID, + ids: Optional[IDs] = None, + where: Optional[Where] = None, + limit: Optional[int] = None, + offset: Optional[int] = None, + where_document: Optional[WhereDocument] = None, + include: Include = IncludeMetadataDocuments, + tenant: str = DEFAULT_TENANT, + database: str = DEFAULT_DATABASE, + ) -> GetResult: + # Servers do not support receiving "data", as that is hydrated by the client as a loadable + filtered_include = [i for i in include if i != "data"] + + resp_json = self._make_request( + "post", + f"/tenants/{tenant}/databases/{database}/collections/{collection_id}/get", + json={ + "ids": ids, + "where": where, + "limit": limit, + "offset": offset, + "where_document": where_document, + "include": filtered_include, + }, + ) + + # Deserialize metadatas: convert transport format to SparseVector instances + metadatas = resp_json.get("metadatas", None) + if metadatas is not None: + metadatas = [ + deserialize_metadata(metadata) if metadata is not None else None + for metadata in metadatas + ] + + return GetResult( + ids=resp_json["ids"], + embeddings=resp_json.get("embeddings", None), + metadatas=metadatas, + documents=resp_json.get("documents", None), + data=None, + uris=resp_json.get("uris", None), + included=include, + ) + + @trace_method("FastAPI._delete", OpenTelemetryGranularity.OPERATION) + @override + def _delete( + self, + collection_id: UUID, + ids: Optional[IDs] = None, + where: Optional[Where] = None, + where_document: Optional[WhereDocument] = None, + limit: Optional[int] = None, + tenant: str = DEFAULT_TENANT, + database: str = DEFAULT_DATABASE, + ) -> DeleteResult: + """Deletes embeddings from the database""" + body: dict = { + "ids": ids, + "where": where, + "where_document": where_document, + } + if limit is not None: + body["limit"] = limit + resp = self._make_request( + "post", + f"/tenants/{tenant}/databases/{database}/collections/{collection_id}/delete", + json=body, + ) + return DeleteResult(deleted=resp.get("deleted", 0) if resp else 0) + + @trace_method("FastAPI._submit_batch", OpenTelemetryGranularity.ALL) + def _submit_batch( + self, + batch: Tuple[ + IDs, + Optional[Embeddings], + Optional[Metadatas], + Optional[Documents], + Optional[URIs], + ], + url: str, + ) -> None: + """ + Submits a batch of embeddings to the database + """ + # Serialize metadatas: convert SparseVector instances to transport format + serialized_metadatas = None + if batch[2] is not None: + serialized_metadatas = [ + serialize_metadata(metadata) if metadata is not None else None + for metadata in batch[2] + ] + + data = { + "ids": batch[0], + "embeddings": optional_embeddings_to_base64_strings(batch[1]) + if self.supports_base64_encoding() + else batch[1], + "metadatas": serialized_metadatas, + "documents": batch[3], + "uris": batch[4], + } + + self._make_request("post", url, json=data) + + @trace_method("FastAPI._add", OpenTelemetryGranularity.ALL) + @override + def _add( + self, + ids: IDs, + collection_id: UUID, + embeddings: Embeddings, + metadatas: Optional[Metadatas] = None, + documents: Optional[Documents] = None, + uris: Optional[URIs] = None, + tenant: str = DEFAULT_TENANT, + database: str = DEFAULT_DATABASE, + ) -> bool: + """ + Adds a batch of embeddings to the database + - pass in column oriented data lists + """ + batch = ( + ids, + embeddings, + metadatas, + documents, + uris, + ) + validate_batch(batch, {"max_batch_size": self.get_max_batch_size()}) + self._submit_batch( + batch, + f"/tenants/{tenant}/databases/{database}/collections/{str(collection_id)}/add", + ) + return True + + @trace_method("FastAPI._update", OpenTelemetryGranularity.ALL) + @override + def _update( + self, + collection_id: UUID, + ids: IDs, + embeddings: Optional[Embeddings] = None, + metadatas: Optional[Metadatas] = None, + documents: Optional[Documents] = None, + uris: Optional[URIs] = None, + tenant: str = DEFAULT_TENANT, + database: str = DEFAULT_DATABASE, + ) -> bool: + """ + Updates a batch of embeddings in the database + - pass in column oriented data lists + """ + batch = ( + ids, + embeddings if embeddings is not None else None, + metadatas, + documents, + uris, + ) + validate_batch(batch, {"max_batch_size": self.get_max_batch_size()}) + self._submit_batch( + batch, + f"/tenants/{tenant}/databases/{database}/collections/{str(collection_id)}/update", + ) + return True + + @trace_method("FastAPI._upsert", OpenTelemetryGranularity.ALL) + @override + def _upsert( + self, + collection_id: UUID, + ids: IDs, + embeddings: Embeddings, + metadatas: Optional[Metadatas] = None, + documents: Optional[Documents] = None, + uris: Optional[URIs] = None, + tenant: str = DEFAULT_TENANT, + database: str = DEFAULT_DATABASE, + ) -> bool: + """ + Upserts a batch of embeddings in the database + - pass in column oriented data lists + """ + batch = ( + ids, + embeddings, + metadatas, + documents, + uris, + ) + validate_batch(batch, {"max_batch_size": self.get_max_batch_size()}) + self._submit_batch( + batch, + f"/tenants/{tenant}/databases/{database}/collections/{str(collection_id)}/upsert", + ) + return True + + @trace_method("FastAPI._query", OpenTelemetryGranularity.ALL) + @override + def _query( + self, + collection_id: UUID, + query_embeddings: Embeddings, + ids: Optional[IDs] = None, + n_results: int = 10, + where: Optional[Where] = None, + where_document: Optional[WhereDocument] = None, + include: Include = IncludeMetadataDocumentsDistances, + tenant: str = DEFAULT_TENANT, + database: str = DEFAULT_DATABASE, + ) -> QueryResult: + # Clients do not support receiving "data", as that is hydrated by the client as a loadable + filtered_include = [i for i in include if i != "data"] + + """Gets the nearest neighbors of a single embedding""" + resp_json = self._make_request( + "post", + f"/tenants/{tenant}/databases/{database}/collections/{collection_id}/query", + json={ + "ids": ids, + "query_embeddings": convert_np_embeddings_to_list(query_embeddings) + if query_embeddings is not None + else None, + "n_results": n_results, + "where": where, + "where_document": where_document, + "include": filtered_include, + }, + ) + + # Deserialize metadatas: convert transport format to SparseVector instances + metadata_batches = resp_json.get("metadatas", None) + if metadata_batches is not None: + metadata_batches = [ + [ + deserialize_metadata(metadata) if metadata is not None else None + for metadata in metadatas + ] + if metadatas is not None + else None + for metadatas in metadata_batches + ] + + return QueryResult( + ids=resp_json["ids"], + distances=resp_json.get("distances", None), + embeddings=resp_json.get("embeddings", None), + metadatas=metadata_batches, + documents=resp_json.get("documents", None), + uris=resp_json.get("uris", None), + data=None, + included=include, + ) + + @trace_method("FastAPI.reset", OpenTelemetryGranularity.ALL) + @override + def reset(self) -> bool: + """Resets the database""" + resp_json = self._make_request("post", "/reset") + return cast(bool, resp_json) + + @trace_method("FastAPI.get_version", OpenTelemetryGranularity.OPERATION) + @override + def get_version(self) -> str: + """Returns the version of the server""" + resp_json = self._make_request("get", "/version") + return cast(str, resp_json) + + @override + def get_settings(self) -> Settings: + """Returns the settings of the client""" + return self._settings + + @trace_method("FastAPI.get_pre_flight_checks", OpenTelemetryGranularity.OPERATION) + def get_pre_flight_checks(self) -> Any: + if self.pre_flight_checks is None: + resp_json = self._make_request("get", "/pre-flight-checks") + self.pre_flight_checks = resp_json + return self.pre_flight_checks + + @trace_method( + "FastAPI.supports_base64_encoding", OpenTelemetryGranularity.OPERATION + ) + def supports_base64_encoding(self) -> bool: + pre_flight_checks = self.get_pre_flight_checks() + b64_encoding_enabled = cast( + bool, pre_flight_checks.get("supports_base64_encoding", False) + ) + return b64_encoding_enabled + + @trace_method("FastAPI.get_max_batch_size", OpenTelemetryGranularity.OPERATION) + @override + def get_max_batch_size(self) -> int: + pre_flight_checks = self.get_pre_flight_checks() + max_batch_size = cast(int, pre_flight_checks.get("max_batch_size", -1)) + return max_batch_size + + @trace_method("FastAPI.attach_function", OpenTelemetryGranularity.ALL) + @override + def attach_function( + self, + function_id: str, + name: str, + input_collection_id: UUID, + output_collection: str, + params: Optional[Dict[str, Any]] = None, + tenant: str = DEFAULT_TENANT, + database: str = DEFAULT_DATABASE, + ) -> Tuple["AttachedFunction", bool]: + """Attach a function to a collection.""" + resp_json = self._make_request( + "post", + f"/tenants/{tenant}/databases/{database}/collections/{input_collection_id}/functions/attach", + json={ + "name": name, + "function_id": function_id, + "output_collection": output_collection, + "params": params, + }, + ) + + attached_function = AttachedFunction( + client=self, + id=UUID(resp_json["attached_function"]["id"]), + name=resp_json["attached_function"]["name"], + function_name=resp_json["attached_function"]["function_name"], + input_collection_id=input_collection_id, + output_collection=output_collection, + params=params, + tenant=tenant, + database=database, + ) + created = resp_json.get( + "created", True + ) # Default to True for backwards compatibility + return (attached_function, created) + + @trace_method("FastAPI.get_attached_function", OpenTelemetryGranularity.ALL) + @override + def get_attached_function( + self, + name: str, + input_collection_id: UUID, + tenant: str = DEFAULT_TENANT, + database: str = DEFAULT_DATABASE, + ) -> "AttachedFunction": + """Get an attached function by name for a specific collection.""" + resp_json = self._make_request( + "get", + f"/tenants/{tenant}/databases/{database}/collections/{input_collection_id}/functions/{name}", + ) + + af = resp_json["attached_function"] + return AttachedFunction( + client=self, + id=UUID(af["id"]), + name=af["name"], + function_name=af["function_name"], + input_collection_id=input_collection_id, + output_collection=af["output_collection"], + params=af.get("params"), + tenant=tenant, + database=database, + ) + + @trace_method("FastAPI.detach_function", OpenTelemetryGranularity.ALL) + @override + def detach_function( + self, + name: str, + input_collection_id: UUID, + delete_output: bool = False, + tenant: str = DEFAULT_TENANT, + database: str = DEFAULT_DATABASE, + ) -> bool: + """Detach a function and prevent any further runs.""" + resp_json = self._make_request( + "post", + f"/tenants/{tenant}/databases/{database}/collections/{input_collection_id}/attached_functions/{name}/detach", + json={ + "delete_output": delete_output, + }, + ) + return cast(bool, resp_json["success"]) diff --git a/python/user_packages/Python313/site-packages/chromadb/api/functions.py b/python/user_packages/Python313/site-packages/chromadb/api/functions.py new file mode 100644 index 0000000000000000000000000000000000000000..5cc4ee4812ad5e7a4f5af1185a293ac7e2edf27f --- /dev/null +++ b/python/user_packages/Python313/site-packages/chromadb/api/functions.py @@ -0,0 +1,33 @@ +"""Attachable function definitions for ChromaDB collections. + +This module provides function constants that can be attached to collections +to perform automatic computations on collection data. + +Example: + >>> from chromadb.api.functions import STATISTICS_FUNCTION + >>> attached_fn = collection.attach_function( + ... function=STATISTICS_FUNCTION, + ... name="my_stats", + ... output_collection="my_stats_output" + ... ) +""" + +from enum import Enum + + +class Function(str, Enum): + """Available functions that can be attached to collections.""" + + STATISTICS = "statistics" + """Computes metadata value frequencies for a collection.""" + + RECORD_COUNTER = "record_counter" + """Counts records in a collection.""" + + # Used only for failure testing - not a real function + _NONEXISTENT_TEST_ONLY = "nonexistent_function" + + +# Convenience aliases for cleaner imports +STATISTICS_FUNCTION = Function.STATISTICS +RECORD_COUNTER_FUNCTION = Function.RECORD_COUNTER diff --git a/python/user_packages/Python313/site-packages/chromadb/api/rust.py b/python/user_packages/Python313/site-packages/chromadb/api/rust.py new file mode 100644 index 0000000000000000000000000000000000000000..1d6ff19b8cf2fbe140bfc31db6fd4d3ece5b789a --- /dev/null +++ b/python/user_packages/Python313/site-packages/chromadb/api/rust.py @@ -0,0 +1,704 @@ +from typing import TYPE_CHECKING + +from chromadb import ( + CollectionMetadata, + Embeddings, + GetResult, + IDs, + Where, + WhereDocument, + Include, + Documents, + Metadatas, + QueryResult, + URIs, +) +from chromadb.api import ServerAPI + +if TYPE_CHECKING: + from chromadb.api.models.AttachedFunction import AttachedFunction +from chromadb.api.collection_configuration import ( + CreateCollectionConfiguration, + UpdateCollectionConfiguration, + create_collection_configuration_to_json_str, + update_collection_configuration_to_json_str, +) +from chromadb.auth import UserIdentity +from chromadb.config import DEFAULT_DATABASE, DEFAULT_TENANT, Settings, System +from chromadb.telemetry.product import ProductTelemetryClient +from chromadb.telemetry.product.events import ( + CollectionAddEvent, + CollectionDeleteEvent, + CollectionGetEvent, + CollectionUpdateEvent, + CollectionQueryEvent, + ClientCreateCollectionEvent, +) + +from chromadb.api.types import ( + DeleteResult, + IncludeMetadataDocuments, + IncludeMetadataDocumentsDistances, + IncludeMetadataDocumentsEmbeddings, + ReadLevel, + Schema, + SearchResult, +) + +# TODO(hammadb): Unify imports across types vs root __init__.py +from chromadb.types import Database, Tenant, Collection as CollectionModel +from chromadb.execution.expression.plan import Search +import chromadb_rust_bindings + + +from typing import Optional, Sequence, List, Dict, Any, Tuple +from overrides import override +from uuid import UUID +import json +import platform + +if platform.system() != "Windows": + import resource +elif platform.system() == "Windows": + import ctypes + + +# RustBindingsAPI is an implementation of ServerAPI which shims +# the Rust bindings to the Python API, providing a full implementation +# of the API. It could be that bindings was a direct implementation of +# ServerAPI, but in order to prevent propagating the bindings types +# into the Python API, we have to shim it here so we can convert into +# the legacy Python types. +# TODO(hammadb): Propagate the types from the bindings into the Python API +# and remove the python-level types entirely. +class RustBindingsAPI(ServerAPI): + bindings: chromadb_rust_bindings.Bindings + hnsw_cache_size: int + product_telemetry_client: ProductTelemetryClient + + def __init__(self, system: System): + super().__init__(system) + self.product_telemetry_client = self.require(ProductTelemetryClient) + + if platform.system() != "Windows": + max_file_handles = resource.getrlimit(resource.RLIMIT_NOFILE)[0] + else: + max_file_handles = ctypes.windll.msvcrt._getmaxstdio() # type: ignore + self.hnsw_cache_size = ( + max_file_handles + # This is integer division in Python 3, and not a comment. + # Each HNSW index has 4 data files and 1 metadata file + // 5 + ) + + @override + def start(self) -> None: + # Construct the SqliteConfig + # TOOD: We should add a "config converter" + if self._system.settings.require("is_persistent"): + persist_path = self._system.settings.require("persist_directory") + sqlite_persist_path = persist_path + "/chroma.sqlite3" + else: + persist_path = None + sqlite_persist_path = None + hash_type = self._system.settings.require("migrations_hash_algorithm") + hash_type_bindings = ( + chromadb_rust_bindings.MigrationHash.MD5 + if hash_type == "md5" + else chromadb_rust_bindings.MigrationHash.SHA256 + ) + migration_mode = self._system.settings.require("migrations") + migration_mode_bindings = ( + chromadb_rust_bindings.MigrationMode.Apply + if migration_mode == "apply" + else chromadb_rust_bindings.MigrationMode.Validate + ) + sqlite_config = chromadb_rust_bindings.SqliteDBConfig( + hash_type=hash_type_bindings, + migration_mode=migration_mode_bindings, + url=sqlite_persist_path, + ) + + self.bindings = chromadb_rust_bindings.Bindings( + allow_reset=self._system.settings.require("allow_reset"), + sqlite_db_config=sqlite_config, + persist_path=persist_path, + hnsw_cache_size=self.hnsw_cache_size, + ) + + @override + def stop(self) -> None: + del self.bindings + + # ////////////////////////////// Admin API ////////////////////////////// + + @override + def create_database(self, name: str, tenant: str = DEFAULT_TENANT) -> None: + return self.bindings.create_database(name, tenant) + + @override + def get_database(self, name: str, tenant: str = DEFAULT_TENANT) -> Database: + database = self.bindings.get_database(name, tenant) + return { + "id": database.id, + "name": database.name, + "tenant": database.tenant, + } + + @override + def delete_database(self, name: str, tenant: str = DEFAULT_TENANT) -> None: + return self.bindings.delete_database(name, tenant) + + @override + def list_databases( + self, + limit: Optional[int] = None, + offset: Optional[int] = None, + tenant: str = DEFAULT_TENANT, + ) -> Sequence[Database]: + databases = self.bindings.list_databases(limit, offset, tenant) + return [ + { + "id": database.id, + "name": database.name, + "tenant": database.tenant, + } + for database in databases + ] + + @override + def create_tenant(self, name: str) -> None: + return self.bindings.create_tenant(name) + + @override + def get_tenant(self, name: str) -> Tenant: + tenant = self.bindings.get_tenant(name) + return Tenant(name=tenant.name) + + # ////////////////////////////// Base API ////////////////////////////// + + @override + def heartbeat(self) -> int: + return self.bindings.heartbeat() + + @override + def count_collections( + self, tenant: str = DEFAULT_TENANT, database: str = DEFAULT_DATABASE + ) -> int: + return self.bindings.count_collections(tenant, database) + + @override + def list_collections( + self, + limit: Optional[int] = None, + offset: Optional[int] = None, + tenant: str = DEFAULT_TENANT, + database: str = DEFAULT_DATABASE, + ) -> Sequence[CollectionModel]: + collections = self.bindings.list_collections(limit, offset, tenant, database) + return [ + CollectionModel( + id=collection.id, + name=collection.name, + serialized_schema=collection.schema, + configuration_json=collection.configuration, + metadata=collection.metadata, + dimension=collection.dimension, + tenant=collection.tenant, + database=collection.database, + ) + for collection in collections + ] + + @override + def create_collection( + self, + name: str, + schema: Optional[Schema] = None, + configuration: Optional[CreateCollectionConfiguration] = None, + metadata: Optional[CollectionMetadata] = None, + get_or_create: bool = False, + tenant: str = DEFAULT_TENANT, + database: str = DEFAULT_DATABASE, + ) -> CollectionModel: + # TODO: This event doesn't capture the get_or_create case appropriately + # TODO: Re-enable embedding function tracking in create_collection + self.product_telemetry_client.capture( + ClientCreateCollectionEvent( + collection_uuid=str(id), + # embedding_function=embedding_function.__class__.__name__, + ) + ) + if configuration: + configuration_json_str = create_collection_configuration_to_json_str( + configuration, metadata + ) + else: + configuration_json_str = None + + if schema: + schema_str = json.dumps(schema.serialize_to_json()) + else: + schema_str = None + + collection = self.bindings.create_collection( + name, + configuration_json_str, + schema_str, + metadata, + get_or_create, + tenant, + database, + ) + collection_model = CollectionModel( + id=collection.id, + name=collection.name, + configuration_json=collection.configuration, + serialized_schema=collection.schema, + metadata=collection.metadata, + dimension=collection.dimension, + tenant=collection.tenant, + database=collection.database, + ) + return collection_model + + @override + def get_collection( + self, + name: str, + tenant: str = DEFAULT_TENANT, + database: str = DEFAULT_DATABASE, + ) -> CollectionModel: + collection = self.bindings.get_collection(name, tenant, database) + return CollectionModel( + id=collection.id, + name=collection.name, + configuration_json=collection.configuration, + serialized_schema=collection.schema, + metadata=collection.metadata, + dimension=collection.dimension, + tenant=collection.tenant, + database=collection.database, + ) + + @override + def get_collection_by_id( + self, + collection_id: UUID, + tenant: str = DEFAULT_TENANT, + database: str = DEFAULT_DATABASE, + ) -> CollectionModel: + collection = self.bindings.get_collection_by_id(str(collection_id), tenant, database) + return CollectionModel( + id=collection.id, + name=collection.name, + configuration_json=collection.configuration, + serialized_schema=collection.schema, + metadata=collection.metadata, + dimension=collection.dimension, + tenant=collection.tenant, + database=collection.database, + ) + + @override + def get_or_create_collection( + self, + name: str, + schema: Optional[Schema] = None, + configuration: Optional[CreateCollectionConfiguration] = None, + metadata: Optional[CollectionMetadata] = None, + tenant: str = DEFAULT_TENANT, + database: str = DEFAULT_DATABASE, + ) -> CollectionModel: + return self.create_collection( + name, schema, configuration, metadata, True, tenant, database + ) + + @override + def delete_collection( + self, + name: str, + tenant: str = DEFAULT_TENANT, + database: str = DEFAULT_DATABASE, + ) -> None: + self.bindings.delete_collection(name, tenant, database) + + @override + def _modify( + self, + id: UUID, + new_name: Optional[str] = None, + new_metadata: Optional[CollectionMetadata] = None, + new_configuration: Optional[UpdateCollectionConfiguration] = None, + tenant: str = DEFAULT_TENANT, + database: str = DEFAULT_DATABASE, + ) -> None: + if new_configuration: + new_configuration_json_str = update_collection_configuration_to_json_str( + new_configuration + ) + else: + new_configuration_json_str = None + self.bindings.update_collection( + str(id), new_name, new_metadata, new_configuration_json_str + ) + + @override + def _fork( + self, + collection_id: UUID, + new_name: str, + tenant: str = DEFAULT_TENANT, + database: str = DEFAULT_DATABASE, + ) -> CollectionModel: + raise NotImplementedError( + "Collection forking is not implemented for Local Chroma" + ) + + @override + def _fork_count( + self, + collection_id: UUID, + tenant: str = DEFAULT_TENANT, + database: str = DEFAULT_DATABASE, + ) -> int: + raise NotImplementedError( + "Fork count is not implemented for Local Chroma" + ) + + @override + def _get_indexing_status( + self, + collection_id: UUID, + tenant: str = DEFAULT_TENANT, + database: str = DEFAULT_DATABASE, + ) -> "IndexingStatus": + raise NotImplementedError("Indexing status is not implemented for Local Chroma") + + @override + def _search( + self, + collection_id: UUID, + searches: List[Search], + tenant: str = DEFAULT_TENANT, + database: str = DEFAULT_DATABASE, + read_level: ReadLevel = ReadLevel.INDEX_AND_WAL, + ) -> SearchResult: + raise NotImplementedError("Search is not implemented for Local Chroma") + + @override + def _count( + self, + collection_id: UUID, + tenant: str = DEFAULT_TENANT, + database: str = DEFAULT_DATABASE, + read_level: ReadLevel = ReadLevel.INDEX_AND_WAL, + ) -> int: + return self.bindings.count(str(collection_id), tenant, database) + + @override + def _peek( + self, + collection_id: UUID, + n: int = 10, + tenant: str = DEFAULT_TENANT, + database: str = DEFAULT_DATABASE, + ) -> GetResult: + return self._get( + collection_id, + limit=n, + tenant=tenant, + database=database, + include=IncludeMetadataDocumentsEmbeddings, + ) + + @override + def _get( + self, + collection_id: UUID, + ids: Optional[IDs] = None, + where: Optional[Where] = None, + limit: Optional[int] = None, + offset: Optional[int] = None, + where_document: Optional[WhereDocument] = None, + include: Include = IncludeMetadataDocuments, + tenant: str = DEFAULT_TENANT, + database: str = DEFAULT_DATABASE, + ) -> GetResult: + ids_amount = len(ids) if ids else 0 + self.product_telemetry_client.capture( + CollectionGetEvent( + collection_uuid=str(collection_id), + ids_count=ids_amount, + limit=limit if limit else 0, + include_metadata=ids_amount if "metadatas" in include else 0, + include_documents=ids_amount if "documents" in include else 0, + include_uris=ids_amount if "uris" in include else 0, + ) + ) + + rust_response = self.bindings.get( + str(collection_id), + ids, + json.dumps(where) if where else None, + limit, + offset or 0, + json.dumps(where_document) if where_document else None, + include, + tenant, + database, + ) + + return GetResult( + ids=rust_response.ids, + embeddings=rust_response.embeddings, + documents=rust_response.documents, + uris=rust_response.uris, + included=include, + data=None, + metadatas=rust_response.metadatas, + ) + + @override + def _add( + self, + ids: IDs, + collection_id: UUID, + embeddings: Embeddings, + metadatas: Optional[Metadatas] = None, + documents: Optional[Documents] = None, + uris: Optional[URIs] = None, + tenant: str = DEFAULT_TENANT, + database: str = DEFAULT_DATABASE, + ) -> bool: + self.product_telemetry_client.capture( + CollectionAddEvent( + collection_uuid=str(collection_id), + add_amount=len(ids), + with_metadata=len(ids) if metadatas is not None else 0, + with_documents=len(ids) if documents is not None else 0, + with_uris=len(ids) if uris is not None else 0, + ) + ) + + return self.bindings.add( + ids, + str(collection_id), + embeddings, + metadatas, + documents, + uris, + tenant, + database, + ) + + @override + def _update( + self, + collection_id: UUID, + ids: IDs, + embeddings: Optional[Embeddings] = None, + metadatas: Optional[Metadatas] = None, + documents: Optional[Documents] = None, + uris: Optional[URIs] = None, + tenant: str = DEFAULT_TENANT, + database: str = DEFAULT_DATABASE, + ) -> bool: + self.product_telemetry_client.capture( + CollectionUpdateEvent( + collection_uuid=str(collection_id), + update_amount=len(ids), + with_embeddings=len(embeddings) if embeddings else 0, + with_metadata=len(metadatas) if metadatas else 0, + with_documents=len(documents) if documents else 0, + with_uris=len(uris) if uris else 0, + ) + ) + + return self.bindings.update( + str(collection_id), + ids, + embeddings, + metadatas, + documents, + uris, + tenant, + database, + ) + + @override + def _upsert( + self, + collection_id: UUID, + ids: IDs, + embeddings: Embeddings, + metadatas: Optional[Metadatas] = None, + documents: Optional[Documents] = None, + uris: Optional[URIs] = None, + tenant: str = DEFAULT_TENANT, + database: str = DEFAULT_DATABASE, + ) -> bool: + return self.bindings.upsert( + str(collection_id), + ids, + embeddings, + metadatas, + documents, + uris, + tenant, + database, + ) + + @override + def _query( + self, + collection_id: UUID, + query_embeddings: Embeddings, + ids: Optional[IDs] = None, + n_results: int = 10, + where: Optional[Where] = None, + where_document: Optional[WhereDocument] = None, + include: Include = IncludeMetadataDocumentsDistances, + tenant: str = DEFAULT_TENANT, + database: str = DEFAULT_DATABASE, + ) -> QueryResult: + query_amount = len(query_embeddings) + filtered_ids_amount = len(ids) if ids else 0 + self.product_telemetry_client.capture( + CollectionQueryEvent( + collection_uuid=str(collection_id), + query_amount=query_amount, + filtered_ids_amount=filtered_ids_amount, + n_results=n_results, + with_metadata_filter=query_amount if where is not None else 0, + with_document_filter=query_amount if where_document is not None else 0, + include_metadatas=query_amount if "metadatas" in include else 0, + include_documents=query_amount if "documents" in include else 0, + include_uris=query_amount if "uris" in include else 0, + include_distances=query_amount if "distances" in include else 0, + ) + ) + + rust_response = self.bindings.query( + str(collection_id), + ids, + query_embeddings, + n_results, + json.dumps(where) if where else None, + json.dumps(where_document) if where_document else None, + include, + tenant, + database, + ) + + return QueryResult( + ids=rust_response.ids, + embeddings=rust_response.embeddings, + documents=rust_response.documents, + uris=rust_response.uris, + included=include, + data=None, + metadatas=rust_response.metadatas, + distances=rust_response.distances, + ) + + @override + def _delete( + self, + collection_id: UUID, + ids: Optional[IDs] = None, + where: Optional[Where] = None, + where_document: Optional[WhereDocument] = None, + limit: Optional[int] = None, + tenant: str = DEFAULT_TENANT, + database: str = DEFAULT_DATABASE, + ) -> DeleteResult: + deleted = self.bindings.delete( + str(collection_id), + ids, + json.dumps(where) if where else None, + json.dumps(where_document) if where_document else None, + limit, + tenant, + database, + ) + + self.product_telemetry_client.capture( + CollectionDeleteEvent( + collection_uuid=str(collection_id), + delete_amount=deleted, + ) + ) + + return DeleteResult(deleted=deleted) + + @override + def reset(self) -> bool: + return self.bindings.reset() + + @override + def get_version(self) -> str: + return self.bindings.get_version() + + @override + def get_settings(self) -> Settings: + return self._system.settings + + @override + def get_max_batch_size(self) -> int: + return self.bindings.get_max_batch_size() + + @override + def attach_function( + self, + function_id: str, + name: str, + input_collection_id: UUID, + output_collection: str, + params: Optional[Dict[str, Any]] = None, + tenant: str = DEFAULT_TENANT, + database: str = DEFAULT_DATABASE, + ) -> Tuple["AttachedFunction", bool]: + """Attached functions are not supported in the Rust bindings (local embedded mode).""" + raise NotImplementedError( + "Attached functions are only supported when connecting to a Chroma server via HttpClient. " + "The Rust bindings (embedded mode) do not support attached function operations." + ) + + @override + def get_attached_function( + self, + name: str, + input_collection_id: UUID, + tenant: str = DEFAULT_TENANT, + database: str = DEFAULT_DATABASE, + ) -> "AttachedFunction": + """Attached functions are not supported in the Rust bindings (local embedded mode).""" + raise NotImplementedError( + "Attached functions are only supported when connecting to a Chroma server via HttpClient. " + "The Rust bindings (embedded mode) do not support attached function operations." + ) + + @override + def detach_function( + self, + name: str, + input_collection_id: UUID, + delete_output: bool = False, + tenant: str = DEFAULT_TENANT, + database: str = DEFAULT_DATABASE, + ) -> bool: + """Attached functions are not supported in the Rust bindings (local embedded mode).""" + raise NotImplementedError( + "Attached functions are only supported when connecting to a Chroma server via HttpClient. " + "The Rust bindings (embedded mode) do not support attached function operations." + ) + + # TODO: Remove this if it's not planned to be used + @override + def get_user_identity(self) -> UserIdentity: + return UserIdentity( + user_id="", + tenant=DEFAULT_TENANT, + databases=[DEFAULT_DATABASE], + ) diff --git a/python/user_packages/Python313/site-packages/chromadb/api/segment.py b/python/user_packages/Python313/site-packages/chromadb/api/segment.py new file mode 100644 index 0000000000000000000000000000000000000000..85fe694b7a932c0effc3ff3d8e45783103835207 --- /dev/null +++ b/python/user_packages/Python313/site-packages/chromadb/api/segment.py @@ -0,0 +1,1127 @@ +from typing import TYPE_CHECKING + +from tenacity import retry, stop_after_attempt, retry_if_exception, wait_fixed +from chromadb.api import ServerAPI + +if TYPE_CHECKING: + from chromadb.api.models.AttachedFunction import AttachedFunction +from chromadb.api.collection_configuration import ( + CreateCollectionConfiguration, + UpdateCollectionConfiguration, + create_collection_configuration_to_json, +) +from chromadb.auth import UserIdentity +from chromadb.config import DEFAULT_DATABASE, DEFAULT_TENANT, Settings, System +from chromadb.db.system import SysDB +from chromadb.quota import QuotaEnforcer, Action +from chromadb.rate_limit import RateLimitEnforcer +from chromadb.segment import SegmentManager +from chromadb.execution.executor.abstract import Executor +from chromadb.execution.expression.operator import Scan, Filter, Limit, KNN, Projection +from chromadb.execution.expression.plan import CountPlan, GetPlan, KNNPlan +from chromadb.telemetry.opentelemetry import ( + add_attributes_to_current_span, + OpenTelemetryClient, + OpenTelemetryGranularity, + trace_method, +) +from chromadb.telemetry.product import ProductTelemetryClient +from chromadb.ingest import Producer +from chromadb.types import Collection as CollectionModel +from chromadb import __version__ +from chromadb.errors import ( + InvalidDimensionException, + NotFoundError, + VersionMismatchError, +) +from chromadb.api.types import ( + CollectionMetadata, + IDs, + Embeddings, + Metadatas, + Documents, + ReadLevel, + Schema, + URIs, + Where, + WhereDocument, + Include, + GetResult, + QueryResult, + SearchResult, + validate_metadata, + validate_update_metadata, + validate_where, + validate_where_document, + validate_batch, + IncludeMetadataDocuments, + IncludeMetadataDocumentsDistances, + DeleteResult, +) +from chromadb.telemetry.product.events import ( + CollectionAddEvent, + CollectionDeleteEvent, + CollectionGetEvent, + CollectionUpdateEvent, + CollectionQueryEvent, + ClientCreateCollectionEvent, +) + +import chromadb.types as t +from typing import ( + Optional, + Sequence, + Generator, + List, + Any, + Dict, + Callable, + TypeVar, + Tuple, +) +from overrides import override +from uuid import UUID, uuid4 +from functools import wraps +import time +import logging +import re +from chromadb.execution.expression.plan import Search + +T = TypeVar("T", bound=Callable[..., Any]) + +logger = logging.getLogger(__name__) + + +# mimics s3 bucket requirements for naming +def check_index_name(index_name: str) -> None: + msg = ( + "Expected collection name that " + "(1) contains 3-63 characters, " + "(2) starts and ends with an alphanumeric character, " + "(3) otherwise contains only alphanumeric characters, underscores or hyphens (-), " + "(4) contains no two consecutive periods (..) and " + "(5) is not a valid IPv4 address, " + f"got {index_name}" + ) + if len(index_name) < 3 or len(index_name) > 63: + raise ValueError(msg) + if not re.match("^[a-zA-Z0-9][a-zA-Z0-9._-]*[a-zA-Z0-9]$", index_name): + raise ValueError(msg) + if ".." in index_name: + raise ValueError(msg) + if re.match("^[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}$", index_name): + raise ValueError(msg) + + +def rate_limit(func: T) -> T: + @wraps(func) + def wrapper(*args: Any, **kwargs: Any) -> Any: + self = args[0] + return self._rate_limit_enforcer.rate_limit(func)(*args, **kwargs) + + return wrapper # type: ignore + + +class SegmentAPI(ServerAPI): + """API implementation utilizing the new segment-based internal architecture""" + + _settings: Settings + _sysdb: SysDB + _manager: SegmentManager + _executor: Executor + _producer: Producer + _product_telemetry_client: ProductTelemetryClient + _opentelemetry_client: OpenTelemetryClient + _tenant_id: str + _topic_ns: str + _rate_limit_enforcer: RateLimitEnforcer + + def __init__(self, system: System): + super().__init__(system) + self._settings = system.settings + self._sysdb = self.require(SysDB) + self._manager = self.require(SegmentManager) + self._executor = self.require(Executor) + self._quota_enforcer = self.require(QuotaEnforcer) + self._product_telemetry_client = self.require(ProductTelemetryClient) + self._opentelemetry_client = self.require(OpenTelemetryClient) + self._producer = self.require(Producer) + self._rate_limit_enforcer = self._system.require(RateLimitEnforcer) + + @override + def heartbeat(self) -> int: + return int(time.time_ns()) + + @trace_method("SegmentAPI.create_database", OpenTelemetryGranularity.OPERATION) + @override + def create_database(self, name: str, tenant: str = DEFAULT_TENANT) -> None: + if len(name) < 3: + raise ValueError("Database name must be at least 3 characters long") + + self._quota_enforcer.enforce( + action=Action.CREATE_DATABASE, + tenant=tenant, + name=name, + ) + + self._sysdb.create_database( + id=uuid4(), + name=name, + tenant=tenant, + ) + + @trace_method("SegmentAPI.get_database", OpenTelemetryGranularity.OPERATION) + @override + def get_database(self, name: str, tenant: str = DEFAULT_TENANT) -> t.Database: + return self._sysdb.get_database(name=name, tenant=tenant) + + @trace_method("SegmentAPI.delete_database", OpenTelemetryGranularity.OPERATION) + @override + def delete_database(self, name: str, tenant: str = DEFAULT_TENANT) -> None: + self._sysdb.delete_database(name=name, tenant=tenant) + + @trace_method("SegmentAPI.list_databases", OpenTelemetryGranularity.OPERATION) + @override + def list_databases( + self, + limit: Optional[int] = None, + offset: Optional[int] = None, + tenant: str = DEFAULT_TENANT, + ) -> Sequence[t.Database]: + return self._sysdb.list_databases(limit=limit, offset=offset, tenant=tenant) + + @trace_method("SegmentAPI.create_tenant", OpenTelemetryGranularity.OPERATION) + @override + def create_tenant(self, name: str) -> None: + if len(name) < 3: + raise ValueError("Tenant name must be at least 3 characters long") + + self._sysdb.create_tenant( + name=name, + ) + + @override + def get_user_identity(self) -> UserIdentity: + return UserIdentity( + user_id="", + tenant=DEFAULT_TENANT, + databases=[DEFAULT_DATABASE], + ) + + @trace_method("SegmentAPI.get_tenant", OpenTelemetryGranularity.OPERATION) + @override + def get_tenant(self, name: str) -> t.Tenant: + return self._sysdb.get_tenant(name=name) + + # TODO: Actually fix CollectionMetadata type to remove type: ignore flags. This is + # necessary because changing the value type from `Any` to`` `Union[str, int, float]` + # causes the system to somehow convert all values to strings. + @trace_method("SegmentAPI.create_collection", OpenTelemetryGranularity.OPERATION) + @override + @rate_limit + def create_collection( + self, + name: str, + schema: Optional[Schema] = None, + configuration: Optional[CreateCollectionConfiguration] = None, + metadata: Optional[CollectionMetadata] = None, + get_or_create: bool = False, + tenant: str = DEFAULT_TENANT, + database: str = DEFAULT_DATABASE, + ) -> CollectionModel: + if metadata is not None: + validate_metadata(metadata) + + # TODO: remove backwards compatibility in naming requirements + check_index_name(name) + + self._quota_enforcer.enforce( + action=Action.CREATE_COLLECTION, + tenant=tenant, + name=name, + metadata=metadata, + ) + + id = uuid4() + + model = CollectionModel( + id=id, + name=name, + metadata=metadata, + serialized_schema=None, + configuration_json=create_collection_configuration_to_json( + configuration or CreateCollectionConfiguration(), metadata + ), + tenant=tenant, + database=database, + dimension=None, + ) + + # TODO: Let sysdb create the collection directly from the model + coll, created = self._sysdb.create_collection( + id=model.id, + name=model.name, + schema=schema, + configuration=configuration or CreateCollectionConfiguration(), + segments=[], # Passing empty till backend changes are deployed. + metadata=model.metadata, + dimension=None, # This is lazily populated on the first add + get_or_create=get_or_create, + tenant=tenant, + database=database, + ) + + if created: + segments = self._manager.prepare_segments_for_new_collection(coll) + for segment in segments: + self._sysdb.create_segment(segment) + else: + logger.debug( + f"Collection {name} already exists, returning existing collection." + ) + + # TODO: This event doesn't capture the get_or_create case appropriately + # TODO: Re-enable embedding function tracking in create_collection + self._product_telemetry_client.capture( + ClientCreateCollectionEvent( + collection_uuid=str(id), + # embedding_function=embedding_function.__class__.__name__, + ) + ) + add_attributes_to_current_span({"collection_uuid": str(id)}) + + return coll + + @trace_method( + "SegmentAPI.get_or_create_collection", OpenTelemetryGranularity.OPERATION + ) + @override + @rate_limit + def get_or_create_collection( + self, + name: str, + schema: Optional[Schema] = None, + configuration: Optional[CreateCollectionConfiguration] = None, + metadata: Optional[CollectionMetadata] = None, + tenant: str = DEFAULT_TENANT, + database: str = DEFAULT_DATABASE, + ) -> CollectionModel: + return self.create_collection( + name=name, + schema=schema, + metadata=metadata, + configuration=configuration, + get_or_create=True, + tenant=tenant, + database=database, + ) + + # TODO: Actually fix CollectionMetadata type to remove type: ignore flags. This is + # necessary because changing the value type from `Any` to`` `Union[str, int, float]` + # causes the system to somehow convert all values to strings + @trace_method("SegmentAPI.get_collection", OpenTelemetryGranularity.OPERATION) + @override + @rate_limit + def get_collection( + self, + name: Optional[str] = None, + tenant: str = DEFAULT_TENANT, + database: str = DEFAULT_DATABASE, + ) -> CollectionModel: + existing = self._sysdb.get_collections( + name=name, tenant=tenant, database=database + ) + + if existing: + return existing[0] + else: + raise NotFoundError(f"Collection {name} does not exist.") + + @trace_method("SegmentAPI.get_collection_by_id", OpenTelemetryGranularity.OPERATION) + @override + @rate_limit + def get_collection_by_id( + self, + collection_id: UUID, + tenant: str = DEFAULT_TENANT, + database: str = DEFAULT_DATABASE, + ) -> CollectionModel: + existing = self._sysdb.get_collections( + id=collection_id, tenant=tenant, database=database + ) + + if existing: + return existing[0] + else: + raise NotFoundError(f"Collection {collection_id} does not exist.") + + @trace_method("SegmentAPI.list_collection", OpenTelemetryGranularity.OPERATION) + @override + @rate_limit + def list_collections( + self, + limit: Optional[int] = None, + offset: Optional[int] = None, + tenant: str = DEFAULT_TENANT, + database: str = DEFAULT_DATABASE, + ) -> Sequence[CollectionModel]: + self._quota_enforcer.enforce( + action=Action.LIST_COLLECTIONS, + tenant=tenant, + limit=limit, + ) + + return self._sysdb.get_collections( + limit=limit, offset=offset, tenant=tenant, database=database + ) + + @trace_method("SegmentAPI.count_collections", OpenTelemetryGranularity.OPERATION) + @override + @rate_limit + def count_collections( + self, + tenant: str = DEFAULT_TENANT, + database: str = DEFAULT_DATABASE, + ) -> int: + return self._sysdb.count_collections(tenant=tenant, database=database) + + @trace_method("SegmentAPI._modify", OpenTelemetryGranularity.OPERATION) + @override + @rate_limit + def _modify( + self, + id: UUID, + new_name: Optional[str] = None, + new_metadata: Optional[CollectionMetadata] = None, + new_configuration: Optional[UpdateCollectionConfiguration] = None, + tenant: str = DEFAULT_TENANT, + database: str = DEFAULT_DATABASE, + ) -> None: + if new_name: + # backwards compatibility in naming requirements (for now) + check_index_name(new_name) + + if new_metadata: + validate_update_metadata(new_metadata) + + # Ensure the collection exists + _ = self._get_collection(id) + + self._quota_enforcer.enforce( + action=Action.UPDATE_COLLECTION, + tenant=tenant, + name=new_name, + metadata=new_metadata, + ) + + # TODO eventually we'll want to use OptionalArgument and Unspecified in the + # signature of `_modify` but not changing the API right now. + if new_name and new_metadata and new_configuration: + self._sysdb.update_collection( + id, + name=new_name, + metadata=new_metadata, + configuration=new_configuration, + ) + elif new_name and new_metadata: + self._sysdb.update_collection(id, name=new_name, metadata=new_metadata) + elif new_name and new_configuration: + self._sysdb.update_collection( + id, name=new_name, configuration=new_configuration + ) + elif new_metadata and new_configuration: + self._sysdb.update_collection( + id, metadata=new_metadata, configuration=new_configuration + ) + elif new_name: + self._sysdb.update_collection(id, name=new_name) + elif new_metadata: + self._sysdb.update_collection(id, metadata=new_metadata) + elif new_configuration: + self._sysdb.update_collection(id, configuration=new_configuration) + + @override + def _fork( + self, + collection_id: UUID, + new_name: str, + tenant: str = DEFAULT_TENANT, + database: str = DEFAULT_DATABASE, + ) -> CollectionModel: + raise NotImplementedError( + "Collection forking is not implemented for SegmentAPI" + ) + + @override + def _fork_count( + self, + collection_id: UUID, + tenant: str = DEFAULT_TENANT, + database: str = DEFAULT_DATABASE, + ) -> int: + raise NotImplementedError( + "Fork count is not implemented for SegmentAPI" + ) + + @override + def _get_indexing_status( + self, + collection_id: UUID, + tenant: str = DEFAULT_TENANT, + database: str = DEFAULT_DATABASE, + ) -> "IndexingStatus": + raise NotImplementedError("Indexing status is not implemented for SegmentAPI") + + @override + def _search( + self, + collection_id: UUID, + searches: List[Search], + tenant: str = DEFAULT_TENANT, + database: str = DEFAULT_DATABASE, + read_level: ReadLevel = ReadLevel.INDEX_AND_WAL, + ) -> SearchResult: + raise NotImplementedError("Search is not implemented for SegmentAPI") + + @trace_method("SegmentAPI.delete_collection", OpenTelemetryGranularity.OPERATION) + @override + @rate_limit + def delete_collection( + self, + name: str, + tenant: str = DEFAULT_TENANT, + database: str = DEFAULT_DATABASE, + ) -> None: + existing = self._sysdb.get_collections( + name=name, tenant=tenant, database=database + ) + + if existing: + self._manager.delete_segments(existing[0].id) + self._sysdb.delete_collection( + existing[0].id, tenant=tenant, database=database + ) + else: + raise ValueError(f"Collection {name} does not exist.") + + @trace_method("SegmentAPI._add", OpenTelemetryGranularity.OPERATION) + @override + @rate_limit + def _add( + self, + ids: IDs, + collection_id: UUID, + embeddings: Embeddings, + metadatas: Optional[Metadatas] = None, + documents: Optional[Documents] = None, + uris: Optional[URIs] = None, + tenant: str = DEFAULT_TENANT, + database: str = DEFAULT_DATABASE, + ) -> bool: + coll = self._get_collection(collection_id) + self._manager.hint_use_collection(collection_id, t.Operation.ADD) + validate_batch( + (ids, embeddings, metadatas, documents, uris), + {"max_batch_size": self.get_max_batch_size()}, + ) + records_to_submit = list( + _records( + t.Operation.ADD, + ids=ids, + embeddings=embeddings, + metadatas=metadatas, + documents=documents, + uris=uris, + ) + ) + self._validate_embedding_record_set(coll, records_to_submit) + + self._quota_enforcer.enforce( + action=Action.ADD, + tenant=tenant, + ids=ids, + embeddings=embeddings, + metadatas=metadatas, + documents=documents, + uris=uris, + collection_id=collection_id, + ) + + self._producer.submit_embeddings(collection_id, records_to_submit) + + self._product_telemetry_client.capture( + CollectionAddEvent( + collection_uuid=str(collection_id), + add_amount=len(ids), + with_metadata=len(ids) if metadatas is not None else 0, + with_documents=len(ids) if documents is not None else 0, + with_uris=len(ids) if uris is not None else 0, + ) + ) + return True + + @trace_method("SegmentAPI._update", OpenTelemetryGranularity.OPERATION) + @override + @rate_limit + def _update( + self, + collection_id: UUID, + ids: IDs, + embeddings: Optional[Embeddings] = None, + metadatas: Optional[Metadatas] = None, + documents: Optional[Documents] = None, + uris: Optional[URIs] = None, + tenant: str = DEFAULT_TENANT, + database: str = DEFAULT_DATABASE, + ) -> bool: + coll = self._get_collection(collection_id) + self._manager.hint_use_collection(collection_id, t.Operation.UPDATE) + validate_batch( + (ids, embeddings, metadatas, documents, uris), + {"max_batch_size": self.get_max_batch_size()}, + ) + records_to_submit = list( + _records( + t.Operation.UPDATE, + ids=ids, + embeddings=embeddings, + metadatas=metadatas, + documents=documents, + uris=uris, + ) + ) + self._validate_embedding_record_set(coll, records_to_submit) + + self._quota_enforcer.enforce( + action=Action.UPDATE, + tenant=tenant, + ids=ids, + embeddings=embeddings, + metadatas=metadatas, + documents=documents, + uris=uris, + ) + + self._producer.submit_embeddings(collection_id, records_to_submit) + + self._product_telemetry_client.capture( + CollectionUpdateEvent( + collection_uuid=str(collection_id), + update_amount=len(ids), + with_embeddings=len(embeddings) if embeddings else 0, + with_metadata=len(metadatas) if metadatas else 0, + with_documents=len(documents) if documents else 0, + with_uris=len(uris) if uris else 0, + ) + ) + + return True + + @trace_method("SegmentAPI._upsert", OpenTelemetryGranularity.OPERATION) + @override + @rate_limit + def _upsert( + self, + collection_id: UUID, + ids: IDs, + embeddings: Embeddings, + metadatas: Optional[Metadatas] = None, + documents: Optional[Documents] = None, + uris: Optional[URIs] = None, + tenant: str = DEFAULT_TENANT, + database: str = DEFAULT_DATABASE, + ) -> bool: + coll = self._get_collection(collection_id) + self._manager.hint_use_collection(collection_id, t.Operation.UPSERT) + validate_batch( + (ids, embeddings, metadatas, documents, uris), + {"max_batch_size": self.get_max_batch_size()}, + ) + records_to_submit = list( + _records( + t.Operation.UPSERT, + ids=ids, + embeddings=embeddings, + metadatas=metadatas, + documents=documents, + uris=uris, + ) + ) + self._validate_embedding_record_set(coll, records_to_submit) + + self._quota_enforcer.enforce( + action=Action.UPSERT, + tenant=tenant, + ids=ids, + embeddings=embeddings, + metadatas=metadatas, + documents=documents, + uris=uris, + collection_id=collection_id, + ) + + self._producer.submit_embeddings(collection_id, records_to_submit) + + return True + + @trace_method("SegmentAPI._get", OpenTelemetryGranularity.OPERATION) + @retry( # type: ignore[misc] + retry=retry_if_exception(lambda e: isinstance(e, VersionMismatchError)), + wait=wait_fixed(2), + stop=stop_after_attempt(5), + reraise=True, + ) + @override + @rate_limit + def _get( + self, + collection_id: UUID, + ids: Optional[IDs] = None, + where: Optional[Where] = None, + limit: Optional[int] = None, + offset: Optional[int] = None, + where_document: Optional[WhereDocument] = None, + include: Include = IncludeMetadataDocuments, + tenant: str = DEFAULT_TENANT, + database: str = DEFAULT_DATABASE, + ) -> GetResult: + add_attributes_to_current_span( + { + "collection_id": str(collection_id), + "ids_count": len(ids) if ids else 0, + } + ) + + scan = self._scan(collection_id) + + # TODO: Replace with unified validation + if where is not None: + validate_where(where) + + if where_document is not None: + validate_where_document(where_document) + + self._quota_enforcer.enforce( + action=Action.GET, + tenant=tenant, + ids=ids, + where=where, + where_document=where_document, + limit=limit, + ) + + ids_amount = len(ids) if ids else 0 + self._product_telemetry_client.capture( + CollectionGetEvent( + collection_uuid=str(collection_id), + ids_count=ids_amount, + limit=limit if limit else 0, + include_metadata=ids_amount if "metadatas" in include else 0, + include_documents=ids_amount if "documents" in include else 0, + include_uris=ids_amount if "uris" in include else 0, + ) + ) + + return self._executor.get( + GetPlan( + scan, + Filter(ids, where, where_document), + Limit(offset or 0, limit), + Projection( + "documents" in include, + "embeddings" in include, + "metadatas" in include, + False, + "uris" in include, + ), + ) + ) + + @trace_method("SegmentAPI._delete", OpenTelemetryGranularity.OPERATION) + @override + @rate_limit + def _delete( + self, + collection_id: UUID, + ids: Optional[IDs] = None, + where: Optional[Where] = None, + where_document: Optional[WhereDocument] = None, + limit: Optional[int] = None, + tenant: str = DEFAULT_TENANT, + database: str = DEFAULT_DATABASE, + ) -> DeleteResult: + add_attributes_to_current_span( + { + "collection_id": str(collection_id), + "ids_count": len(ids) if ids else 0, + } + ) + + # TODO: Replace with unified validation + if where is not None: + validate_where(where) + + if where_document is not None: + validate_where_document(where_document) + + # You must have at least one of non-empty ids, where, or where_document. + if ( + (ids is None or (ids is not None and len(ids) == 0)) + and (where is None or (where is not None and len(where) == 0)) + and ( + where_document is None + or (where_document is not None and len(where_document) == 0) + ) + ): + raise ValueError( + """ + You must provide either ids, where, or where_document to delete. If + you want to delete all data in a collection you can delete the + collection itself using the delete_collection method. Or alternatively, + you can get() all the relevant ids and then delete them. + """ + ) + + scan = self._scan(collection_id) + + self._quota_enforcer.enforce( + action=Action.DELETE, + tenant=tenant, + ids=ids, + where=where, + where_document=where_document, + ) + + self._manager.hint_use_collection(collection_id, t.Operation.DELETE) + + if (where or where_document) or not ids: + ids_to_delete = self._executor.get( + GetPlan(scan, Filter(ids, where, where_document)) + )["ids"] + else: + ids_to_delete = ids + + # Apply limit if specified (validated upstream, but enforce defensively) + if limit is not None: + if not isinstance(limit, int) or isinstance(limit, bool) or limit < 0: + raise ValueError("limit must be a non-negative integer") + if where is None and where_document is None: + raise ValueError( + "limit can only be specified when a where or where_document clause is provided" + ) + ids_to_delete = ids_to_delete[:limit] + + if len(ids_to_delete) == 0: + return DeleteResult(deleted=0) + + records_to_submit = list( + _records(operation=t.Operation.DELETE, ids=ids_to_delete) + ) + self._validate_embedding_record_set(scan.collection, records_to_submit) + self._producer.submit_embeddings(collection_id, records_to_submit) + + deleted_count = len(ids_to_delete) + + self._product_telemetry_client.capture( + CollectionDeleteEvent( + collection_uuid=str(collection_id), delete_amount=deleted_count + ) + ) + + return DeleteResult(deleted=deleted_count) + + @trace_method("SegmentAPI._count", OpenTelemetryGranularity.OPERATION) + @retry( # type: ignore[misc] + retry=retry_if_exception(lambda e: isinstance(e, VersionMismatchError)), + wait=wait_fixed(2), + stop=stop_after_attempt(5), + reraise=True, + ) + @override + @rate_limit + def _count( + self, + collection_id: UUID, + tenant: str = DEFAULT_TENANT, + database: str = DEFAULT_DATABASE, + read_level: ReadLevel = ReadLevel.INDEX_AND_WAL, + ) -> int: + add_attributes_to_current_span({"collection_id": str(collection_id)}) + return self._executor.count(CountPlan(self._scan(collection_id))) + + @trace_method("SegmentAPI._query", OpenTelemetryGranularity.OPERATION) + # We retry on version mismatch errors because the version of the collection + # may have changed between the time we got the version and the time we + # actually query the collection on the FE. We are fine with fixed + # wait time because the version mismatch error is not a error due to + # network issues or other transient issues. It is a result of the + # collection being updated between the time we got the version and + # the time we actually query the collection on the FE. + @retry( # type: ignore[misc] + retry=retry_if_exception(lambda e: isinstance(e, VersionMismatchError)), + wait=wait_fixed(2), + stop=stop_after_attempt(5), + reraise=True, + ) + @override + @rate_limit + def _query( + self, + collection_id: UUID, + query_embeddings: Embeddings, + ids: Optional[IDs] = None, + n_results: int = 10, + where: Optional[Where] = None, + where_document: Optional[WhereDocument] = None, + include: Include = IncludeMetadataDocumentsDistances, + tenant: str = DEFAULT_TENANT, + database: str = DEFAULT_DATABASE, + ) -> QueryResult: + add_attributes_to_current_span( + { + "collection_id": str(collection_id), + "n_results": n_results, + "where": str(where), + } + ) + + query_amount = len(query_embeddings) + ids_amount = len(ids) if ids else 0 + self._product_telemetry_client.capture( + CollectionQueryEvent( + collection_uuid=str(collection_id), + query_amount=query_amount, + filtered_ids_amount=ids_amount, + n_results=n_results, + with_metadata_filter=query_amount if where is not None else 0, + with_document_filter=query_amount if where_document is not None else 0, + include_metadatas=query_amount if "metadatas" in include else 0, + include_documents=query_amount if "documents" in include else 0, + include_uris=query_amount if "uris" in include else 0, + include_distances=query_amount if "distances" in include else 0, + ) + ) + + # TODO: Replace with unified validation + if where is not None: + validate_where(where) + if where_document is not None: + validate_where_document(where_document) + + scan = self._scan(collection_id) + for embedding in query_embeddings: + self._validate_dimension(scan.collection, len(embedding), update=False) + + self._quota_enforcer.enforce( + action=Action.QUERY, + tenant=tenant, + where=where, + where_document=where_document, + query_embeddings=query_embeddings, + n_results=n_results, + ) + + return self._executor.knn( + KNNPlan( + scan, + KNN(query_embeddings, n_results), + Filter(None, where, where_document), + Projection( + "documents" in include, + "embeddings" in include, + "metadatas" in include, + "distances" in include, + "uris" in include, + ), + ) + ) + + @trace_method("SegmentAPI._peek", OpenTelemetryGranularity.OPERATION) + @override + @rate_limit + def _peek( + self, + collection_id: UUID, + n: int = 10, + tenant: str = DEFAULT_TENANT, + database: str = DEFAULT_DATABASE, + ) -> GetResult: + add_attributes_to_current_span({"collection_id": str(collection_id)}) + return self._get(collection_id, limit=n) # type: ignore + + @override + def get_version(self) -> str: + return __version__ + + @override + def reset_state(self) -> None: + pass + + @override + def reset(self) -> bool: + self._system.reset_state() + return True + + @override + def get_settings(self) -> Settings: + return self._settings + + @override + def get_max_batch_size(self) -> int: + return self._producer.max_batch_size + + @override + def attach_function( + self, + function_id: str, + name: str, + input_collection_id: UUID, + output_collection: str, + params: Optional[Dict[str, Any]] = None, + tenant: str = DEFAULT_TENANT, + database: str = DEFAULT_DATABASE, + ) -> Tuple["AttachedFunction", bool]: + """Attached functions are not supported in the Segment API (local embedded mode).""" + raise NotImplementedError( + "Attached functions are only supported when connecting to a Chroma server via HttpClient. " + "The Segment API (embedded mode) does not support attached function operations." + ) + + @override + def get_attached_function( + self, + name: str, + input_collection_id: UUID, + tenant: str = DEFAULT_TENANT, + database: str = DEFAULT_DATABASE, + ) -> "AttachedFunction": + """Attached functions are not supported in the Segment API (local embedded mode).""" + raise NotImplementedError( + "Attached functions are only supported when connecting to a Chroma server via HttpClient. " + "The Segment API (embedded mode) does not support attached function operations." + ) + + @override + def detach_function( + self, + name: str, + input_collection_id: UUID, + delete_output: bool = False, + tenant: str = DEFAULT_TENANT, + database: str = DEFAULT_DATABASE, + ) -> bool: + """Attached functions are not supported in the Segment API (local embedded mode).""" + raise NotImplementedError( + "Attached functions are only supported when connecting to a Chroma server via HttpClient. " + "The Segment API (embedded mode) does not support attached function operations." + ) + + # TODO: This could potentially cause race conditions in a distributed version of the + # system, since the cache is only local. + # TODO: promote collection -> topic to a base class method so that it can be + # used for channel assignment in the distributed version of the system. + @trace_method( + "SegmentAPI._validate_embedding_record_set", OpenTelemetryGranularity.ALL + ) + def _validate_embedding_record_set( + self, collection: t.Collection, records: List[t.OperationRecord] + ) -> None: + """Validate the dimension of an embedding record before submitting it to the system.""" + add_attributes_to_current_span({"collection_id": str(collection["id"])}) + for record in records: + if record["embedding"] is not None: + self._validate_dimension( + collection, len(record["embedding"]), update=True + ) + + # This method is intentionally left untraced because otherwise it can emit thousands of spans for requests containing many embeddings. + def _validate_dimension( + self, collection: t.Collection, dim: int, update: bool + ) -> None: + """Validate that a collection supports records of the given dimension. If update + is true, update the collection if the collection doesn't already have a + dimension.""" + if collection["dimension"] is None: + if update: + id = collection.id + self._sysdb.update_collection(id=id, dimension=dim) + collection["dimension"] = dim + elif collection["dimension"] != dim: + raise InvalidDimensionException( + f"Embedding dimension {dim} does not match collection dimensionality {collection['dimension']}" + ) + else: + return # all is well + + @trace_method("SegmentAPI._get_collection", OpenTelemetryGranularity.ALL) + def _get_collection(self, collection_id: UUID) -> t.Collection: + collections = self._sysdb.get_collections(id=collection_id) + if not collections or len(collections) == 0: + raise NotFoundError(f"Collection {collection_id} does not exist.") + return collections[0] + + @trace_method("SegmentAPI._scan", OpenTelemetryGranularity.OPERATION) + def _scan(self, collection_id: UUID) -> Scan: + collection_and_segments = self._sysdb.get_collection_with_segments( + collection_id + ) + # For now collection should have exactly one segment per scope: + # - Local scopes: vector, metadata + # - Distributed scopes: vector, metadata, record + scope_to_segment = { + segment["scope"]: segment for segment in collection_and_segments["segments"] + } + return Scan( + collection=collection_and_segments["collection"], + knn=scope_to_segment[t.SegmentScope.VECTOR], + metadata=scope_to_segment[t.SegmentScope.METADATA], + # Local chroma do not have record segment, and this is not used by the local executor + record=scope_to_segment.get(t.SegmentScope.RECORD, None), # type: ignore[arg-type] + ) + + +def _records( + operation: t.Operation, + ids: IDs, + embeddings: Optional[Embeddings] = None, + metadatas: Optional[Metadatas] = None, + documents: Optional[Documents] = None, + uris: Optional[URIs] = None, +) -> Generator[t.OperationRecord, None, None]: + """Convert parallel lists of embeddings, metadatas and documents to a sequence of + SubmitEmbeddingRecords""" + + # Presumes that callers were invoked via Collection model, which means + # that we know that the embeddings, metadatas and documents have already been + # normalized and are guaranteed to be consistently named lists. + + if embeddings == []: + embeddings = None + + for i, id in enumerate(ids): + metadata = None + if metadatas: + metadata = metadatas[i] + + if documents: + document = documents[i] + if metadata: + metadata = {**metadata, "chroma:document": document} + else: + metadata = {"chroma:document": document} + + if uris: + uri = uris[i] + if metadata: + metadata = {**metadata, "chroma:uri": uri} + else: + metadata = {"chroma:uri": uri} + + record = t.OperationRecord( + id=id, + embedding=embeddings[i] if embeddings is not None else None, + encoding=t.ScalarEncoding.FLOAT32, # Hardcode for now + metadata=metadata, + operation=operation, + ) + yield record diff --git a/python/user_packages/Python313/site-packages/chromadb/api/shared_system_client.py b/python/user_packages/Python313/site-packages/chromadb/api/shared_system_client.py new file mode 100644 index 0000000000000000000000000000000000000000..a5ddd4bed41d1c59af498dcbb0de4f5b2fe09abc --- /dev/null +++ b/python/user_packages/Python313/site-packages/chromadb/api/shared_system_client.py @@ -0,0 +1,193 @@ +from typing import ClassVar, Dict, Optional +import logging +import threading +import uuid +from chromadb.api import ServerAPI +from chromadb.api.base_http_client import BaseHTTPClient +from chromadb.config import Settings, System +from chromadb.telemetry.product import ProductTelemetryClient +from chromadb.telemetry.product.events import ClientStartEvent + +logger = logging.getLogger(__name__) + + +class SharedSystemClient: + _identifier_to_system: ClassVar[Dict[str, System]] = {} + _identifier_to_refcount: ClassVar[Dict[str, int]] = {} + _refcount_lock: ClassVar[threading.Lock] = threading.Lock() + _identifier: str + + def __init__( + self, + settings: Settings = Settings(), + ) -> None: + self._identifier = SharedSystemClient._get_identifier_from_settings(settings) + SharedSystemClient._create_system_if_not_exists(self._identifier, settings) + SharedSystemClient._increment_refcount(self._identifier) + + @classmethod + def _create_system_if_not_exists( + cls, identifier: str, settings: Settings + ) -> System: + if identifier not in cls._identifier_to_system: + new_system = System(settings) + cls._identifier_to_system[identifier] = new_system + + new_system.instance(ProductTelemetryClient) + new_system.instance(ServerAPI) + + new_system.start() + else: + previous_system = cls._identifier_to_system[identifier] + + # For now, the settings must match + if previous_system.settings != settings: + raise ValueError( + f"An instance of Chroma already exists for {identifier} with different settings" + ) + + return cls._identifier_to_system[identifier] + + @staticmethod + def _get_identifier_from_settings(settings: Settings) -> str: + identifier = "" + api_impl = settings.chroma_api_impl + + if api_impl is None: + raise ValueError("Chroma API implementation must be set in settings") + elif api_impl in [ + "chromadb.api.segment.SegmentAPI", + "chromadb.api.rust.RustBindingsAPI", + ]: + if settings.is_persistent: + identifier = settings.persist_directory + else: + identifier = ( + "ephemeral" # TODO: support pathing and multiple ephemeral clients + ) + elif api_impl in [ + "chromadb.api.fastapi.FastAPI", + "chromadb.api.async_fastapi.AsyncFastAPI", + ]: + # FastAPI clients can all use unique system identifiers since their configurations can be independent, e.g. different auth tokens + identifier = str(uuid.uuid4()) + else: + raise ValueError(f"Unsupported Chroma API implementation {api_impl}") + + return identifier + + @staticmethod + def _populate_data_from_system(system: System) -> str: + identifier = SharedSystemClient._get_identifier_from_settings(system.settings) + SharedSystemClient._identifier_to_system[identifier] = system + return identifier + + @classmethod + def from_system(cls, system: System) -> "SharedSystemClient": + """Create a client from an existing system. This is useful for testing and debugging.""" + + SharedSystemClient._populate_data_from_system(system) + instance = cls(system.settings) + return instance + + @classmethod + def _increment_refcount(cls, identifier: str) -> None: + """Increment the reference count for a system identifier.""" + with cls._refcount_lock: + if identifier not in cls._identifier_to_refcount: + cls._identifier_to_refcount[identifier] = 0 + cls._identifier_to_refcount[identifier] += 1 + + @classmethod + def _decrement_refcount(cls, identifier: str) -> int: + """Decrement the reference count for a system identifier and return the new count.""" + with cls._refcount_lock: + if identifier in cls._identifier_to_refcount: + cls._identifier_to_refcount[identifier] -= 1 + count = cls._identifier_to_refcount[identifier] + if count <= 0: + del cls._identifier_to_refcount[identifier] + return count + return 0 + + @classmethod + def _release_system(cls, identifier: str) -> None: + """Decrement refcount and stop the system if this was the last reference. + + This consolidates the "decrement + conditional stop" pattern used in + both Client.close() and the Client.__init__ exception handler. + """ + refcount = cls._decrement_refcount(identifier) + if refcount <= 0: + system = cls._identifier_to_system.pop(identifier, None) + if system is not None: + system.stop() + + @staticmethod + def clear_system_cache() -> None: + SharedSystemClient._identifier_to_system = {} + SharedSystemClient._identifier_to_refcount = {} + + @property + def _system(self) -> System: + return SharedSystemClient._identifier_to_system[self._identifier] + + def _submit_client_start_event(self) -> None: + telemetry_client = self._system.instance(ProductTelemetryClient) + telemetry_client.capture(ClientStartEvent()) + + @staticmethod + def get_chroma_cloud_api_key_from_clients() -> Optional[str]: + """ + Try to extract api key from existing client instances by checking httpx session headers. + + Requirements to pull api key: + - must be a BaseHTTPClient instance (ignore RustBindingsAPI and SegmentAPI) + - must have "api.trychroma.com" or "gcp.trychroma.com" in the _api_url (ignore local/self-hosted instances) + - must have "x-chroma-token" or "X-Chroma-Token" in the headers + + Returns: + The first api key found, or None if no client instances have api keys set. + """ + + api_keys: list[str] = [] + systems_snapshot = list(SharedSystemClient._identifier_to_system.values()) + for system in systems_snapshot: + try: + server_api = system.instance(ServerAPI) + + if not isinstance(server_api, BaseHTTPClient): + # RustBindingsAPI and SegmentAPI don't have HTTP headers + continue + + # Only pull api key if the url contains the chroma cloud url + api_url = server_api.get_api_url() + if ( + "api.trychroma.com" not in api_url + and "gcp.trychroma.com" not in api_url + ): + continue + + headers = server_api.get_request_headers() + api_key = None + for key, value in headers.items(): + if key.lower() == "x-chroma-token": + api_key = value + break + + if api_key: + api_keys.append(api_key) + except Exception: + # If we can't access the ServerAPI instance, continue to the next + continue + + if not api_keys: + return None + + # log if multiple viable api keys found + if len(api_keys) > 1: + logger.info( + f"Multiple Chroma Cloud clients found, using API key starting with {api_keys[0][:8]}..." + ) + + return api_keys[0] diff --git a/python/user_packages/Python313/site-packages/chromadb/api/types.py b/python/user_packages/Python313/site-packages/chromadb/api/types.py new file mode 100644 index 0000000000000000000000000000000000000000..9834ddd82f38497f2cddacfcb76ea7ab0cea05e3 --- /dev/null +++ b/python/user_packages/Python313/site-packages/chromadb/api/types.py @@ -0,0 +1,3028 @@ +from typing import ( + Optional, + Set, + Union, + TypeVar, + List, + Dict, + Any, + Tuple, + cast, + Literal, + get_args, + TYPE_CHECKING, + Final, + Type, +) +from copy import deepcopy +from typing_extensions import TypeAlias +from dataclasses import dataclass +from numpy.typing import NDArray +import numpy as np +import warnings +from typing_extensions import TypedDict, Protocol, runtime_checkable +from pydantic import BaseModel, field_validator, model_validator +from pydantic_core import PydanticCustomError + +import chromadb.errors as errors +from chromadb.base_types import ( + Metadata, + UpdateMetadata, + Vector, + PyVector, + LiteralValue, + LogicalOperator, + WhereOperator, + OperatorExpression, + Where, + WhereDocumentOperator, + WhereDocument, + SparseVector, +) + +if TYPE_CHECKING: + from chromadb.execution.expression.operator import Key + +try: + from chromadb.is_thin_client import is_thin_client +except ImportError: + is_thin_client = False +from inspect import signature +from tenacity import retry +from abc import abstractmethod +import pybase64 +from functools import lru_cache +import struct +import math +import re +from enum import Enum + +# Re-export types from chromadb.types +__all__ = [ + "Metadata", + "Where", + "WhereDocument", + "UpdateCollectionMetadata", + "UpdateMetadata", + "SearchResult", + "SearchResultRow", + "IndexingStatus", + "SparseVector", + # Index Configuration Types + "FtsIndexConfig", + "HnswIndexConfig", + "SpannIndexConfig", + "VectorIndexConfig", + "SparseVectorIndexConfig", + "StringInvertedIndexConfig", + "IntInvertedIndexConfig", + "FloatInvertedIndexConfig", + "BoolInvertedIndexConfig", + "IndexConfig", + # New Schema System (mirrors Rust Schema) + "Schema", + "ValueTypes", + "StringValueType", + "FloatListValueType", + "SparseVectorValueType", + "IntValueType", + "FloatValueType", + "BoolValueType", + # Index Type Classes + "FtsIndexType", + "VectorIndexType", + "SparseVectorIndexType", + "StringInvertedIndexType", + "IntInvertedIndexType", + "FloatInvertedIndexType", + "BoolInvertedIndexType", + # Value Type Constants + "STRING_VALUE_NAME", + "INT_VALUE_NAME", + "BOOL_VALUE_NAME", + "FLOAT_VALUE_NAME", + "FLOAT_LIST_VALUE_NAME", + "SPARSE_VECTOR_VALUE_NAME", + # Index Name Constants + "FTS_INDEX_NAME", + "VECTOR_INDEX_NAME", + "SPARSE_VECTOR_INDEX_NAME", + "STRING_INVERTED_INDEX_NAME", + "INT_INVERTED_INDEX_NAME", + "FLOAT_INVERTED_INDEX_NAME", + "BOOL_INVERTED_INDEX_NAME", + "HNSW_INDEX_NAME", + "SPANN_INDEX_NAME", + "DOCUMENT_KEY", + "EMBEDDING_KEY", + "TYPE_KEY", + "SPARSE_VECTOR_TYPE_VALUE", + # CMEK Support + "Cmek", + "CmekProvider", + # Space type + "Space", + # Embedding Functions + "EmbeddingFunction", + "SparseEmbeddingFunction", + "validate_embedding_function", + "validate_sparse_embedding_function", + # Sparse vectors + "SparseVector", + "SparseVectors", + "validate_sparse_vectors", +] +META_KEY_CHROMA_DOCUMENT = "chroma:document" +T = TypeVar("T") +OneOrMany = Union[T, List[T]] + + +def maybe_cast_one_to_many(target: Optional[OneOrMany[T]]) -> Optional[List[T]]: + if target is None: + return None + if isinstance(target, list): + return target + return [target] + + +# URIs +URI = str +URIs = List[URI] + +# IDs +ID = str +IDs = List[ID] + +# Embeddings +PyEmbedding = PyVector +PyEmbeddings = List[PyEmbedding] +Embedding = Vector +Embeddings = List[Embedding] +SparseVectors = List[SparseVector] + + +@lru_cache +def _get_struct(vector_length: int) -> struct.Struct: + return struct.Struct(f"<{vector_length}f") + + +def _to_f32(value: float) -> float: + F32_MAX = np.finfo(np.float32).max + F32_MIN = np.finfo(np.float32).min + if math.isnan(value): + return float("nan") + if value > F32_MAX: + return float("inf") + if value < F32_MIN: + return float("-inf") + return value + + +def pack_embedding_safely(embedding: Embedding) -> str: + try: + return pybase64.b64encode_as_string( + _get_struct(len(embedding)).pack(*embedding) + ) + except OverflowError: + return pybase64.b64encode_as_string( + _get_struct(len(embedding)).pack(*[_to_f32(value) for value in embedding]) + ) + + +# returns base64 encoded embeddings or None if the embedding is None +# currently, PyEmbeddings can't have None, but this is to future proof, we want to be able to handle None embeddings +def optional_embeddings_to_base64_strings( + embeddings: Optional[Embeddings], +) -> Optional[list[Union[str, None]]]: + if embeddings is None: + return None + return [ + pack_embedding_safely(embedding) if embedding is not None else None + for embedding in embeddings + ] + + +def optional_base64_strings_to_embeddings( + b64_strings: Optional[list[Union[str, None]]], +) -> Optional[PyEmbeddings]: + if b64_strings is None: + return None + + embeddings: PyEmbeddings = [] + for b64_string in b64_strings: + if b64_string is None: + embeddings.append(None) # type: ignore + else: + packed_data = pybase64.b64decode(b64_string) + vector_length = len(packed_data) // 4 + embedding_tuple = _get_struct(vector_length).unpack(packed_data) + embeddings.append(list(embedding_tuple)) + return embeddings + + +def normalize_embeddings( + target: Optional[Union[OneOrMany[Embedding], OneOrMany[PyEmbedding]]], +) -> Optional[Embeddings]: + if target is None: + return None + + if len(target) == 0: + raise ValueError( + f"Expected Embeddings to be non-empty list or numpy array, got {target}" + ) + + if isinstance(target, np.ndarray): + if target.ndim == 1: + return [target] + elif target.ndim == 2: + return [row for row in target] + elif isinstance(target, list): + # One PyEmbedding + if isinstance(target[0], (int, float)) and not isinstance(target[0], bool): + return [np.array(target, dtype=np.float32)] + elif isinstance(target[0], np.ndarray): + return cast(Embeddings, target) + elif isinstance(target[0], list): + if isinstance(target[0][0], (int, float)) and not isinstance( + target[0][0], bool + ): + return [np.array(row, dtype=np.float32) for row in target] + + raise ValueError( + f"Expected embeddings to be a list of floats or ints, a list of lists, a numpy array, or a list of numpy arrays, got {target}" + ) + + +# Metadatas +Metadatas = List[Metadata] + +CollectionMetadata = Dict[str, Any] +UpdateCollectionMetadata = UpdateMetadata + + +def normalize_metadata(metadata: Optional[Metadata]) -> Optional[Metadata]: + """ + Normalize metadata by converting dict-format sparse vectors to SparseVector instances. + + Accepts: + - SparseVector instances (pass through) + - Dict with #type='sparse_vector' (convert to SparseVector) + - Other primitive types (pass through) + + Returns: Metadata with all sparse vectors as SparseVector instances + + Note: This allows users to provide sparse vectors in dict format for convenience. + The dict format is automatically converted to SparseVector instances, which are + then validated by SparseVector.__post_init__. + """ + if metadata is None: + return metadata + + normalized = {} + for key, value in metadata.items(): + if isinstance(value, dict) and value.get(TYPE_KEY) == SPARSE_VECTOR_TYPE_VALUE: + # Convert dict format to SparseVector (validates via __post_init__) + normalized[key] = SparseVector.from_dict(value) + else: + # Pass through (including existing SparseVector instances) + normalized[key] = value + + return normalized + + +def normalize_metadatas( + metadatas: Optional[OneOrMany[Metadata]], +) -> Optional[List[Optional[Metadata]]]: + """ + Normalize metadatas list, converting dict-format sparse vectors to instances. + + Handles both single metadata dict and list of metadata dicts. + Converts any dict-format sparse vectors to SparseVector instances. + + Note: Individual items can be None (e.g., when embeddings are provided without metadata). + """ + unpacked = maybe_cast_one_to_many(metadatas) + if unpacked is None: + return None + + return [normalize_metadata(m) for m in unpacked] + + +# Documents +Document = str +Documents = List[Document] + + +def is_document(target: Any) -> bool: + if not isinstance(target, str): + return False + return True + + +# Images +ImageDType = Union[np.uint, np.int64, np.float64] +Image = NDArray[ImageDType] +Images = List[Image] + + +def is_image(target: Any) -> bool: + if not isinstance(target, np.ndarray): + return False + if len(target.shape) < 2: + return False + return True + + +class BaseRecordSet(TypedDict): + """ + The base record set includes 'data' fields which can be embedded, and embeddings. + """ + + embeddings: Optional[Embeddings] + documents: Optional[Documents] + images: Optional[Images] + uris: Optional[URIs] + + +def get_default_embeddable_record_set_fields() -> Set[str]: + """ + Returns the set of fields that can be embedded on a Record Set. + This is a way to avoid hardcoding the fields in multiple places, + and keeps them immutable. + """ + return {"documents", "images", "uris"} + + +class InsertRecordSet(BaseRecordSet): + """ + A set of records for inserting. + """ + + ids: IDs + metadatas: Optional[Metadatas] + + +def normalize_base_record_set( + embeddings: Optional[Union[OneOrMany[Embedding], OneOrMany[PyEmbedding]]] = None, + documents: Optional[OneOrMany[Document]] = None, + images: Optional[OneOrMany[Image]] = None, + uris: Optional[OneOrMany[URI]] = None, +) -> BaseRecordSet: + """ + Unpacks and normalizes the fields of a BaseRecordSet. + """ + + return BaseRecordSet( + embeddings=normalize_embeddings(embeddings), + documents=maybe_cast_one_to_many(documents), + images=maybe_cast_one_to_many(images), + uris=maybe_cast_one_to_many(uris), + ) + + +def normalize_insert_record_set( + ids: OneOrMany[ID], + embeddings: Optional[ + Union[ + OneOrMany[Embedding], + OneOrMany[PyEmbedding], + ] + ], + metadatas: Optional[OneOrMany[Metadata]] = None, + documents: Optional[OneOrMany[Document]] = None, + images: Optional[OneOrMany[Image]] = None, + uris: Optional[OneOrMany[URI]] = None, +) -> InsertRecordSet: + """ + Unpacks and normalizes the fields of an InsertRecordSet. + + Normalization includes: + - Converting various embedding formats to List[np.ndarray] + - Converting dict-format sparse vectors to SparseVector instances + - Converting single values to lists where appropriate + """ + base_record_set = normalize_base_record_set( + embeddings=embeddings, documents=documents, images=images, uris=uris + ) + + return InsertRecordSet( + ids=cast(IDs, maybe_cast_one_to_many(ids)), + metadatas=normalize_metadatas(metadatas), # type: ignore[typeddict-item] + embeddings=base_record_set["embeddings"], + documents=base_record_set["documents"], + images=base_record_set["images"], + uris=base_record_set["uris"], + ) + + +def validate_base_record_set(record_set: BaseRecordSet) -> None: + """ + Validates the RecordSet, ensuring that all fields are of the right type and length. + """ + _validate_record_set_length_consistency(record_set) + + if record_set["embeddings"] is not None: + validate_embeddings(embeddings=record_set["embeddings"]) + if record_set["documents"] is not None: + validate_documents( + documents=record_set["documents"], + # If embeddings are present, some documents can be None + nullable=(record_set["embeddings"] is not None), + ) + if record_set["images"] is not None: + validate_images(images=record_set["images"]) + + # TODO: Validate URIs + + +def validate_insert_record_set(record_set: InsertRecordSet) -> None: + """ + Validates the InsertRecordSet, ensuring that all fields are of the right type and length. + """ + _validate_record_set_length_consistency(record_set) + validate_base_record_set(record_set) + + validate_ids(record_set["ids"]) + if record_set["metadatas"] is not None: + validate_metadatas(record_set["metadatas"]) + + +def _validate_record_set_length_consistency(record_set: BaseRecordSet) -> None: + lengths = [len(lst) for lst in record_set.values() if lst is not None] # type: ignore[arg-type] + + if not lengths: + raise ValueError( + f"At least one of one of {', '.join(record_set.keys())} must be provided" + ) + + zero_lengths = [ + key + for key, lst in record_set.items() + if lst is not None and len(lst) == 0 # type: ignore[arg-type] + ] + + if zero_lengths: + raise ValueError(f"Non-empty lists are required for {zero_lengths}") + + if len(set(lengths)) > 1: + error_str = ", ".join( + f"{key}: {len(lst)}" + for key, lst in record_set.items() + if lst is not None # type: ignore[arg-type] + ) + raise ValueError(f"Unequal lengths for fields: {error_str}") + + +def validate_record_set_for_embedding( + record_set: BaseRecordSet, embeddable_fields: Optional[Set[str]] = None +) -> None: + """ + Validates that the Record is ready to be embedded, i.e. that it contains exactly one of the embeddable fields. + """ + if record_set["embeddings"] is not None: + raise ValueError("Attempting to embed a record that already has embeddings.") + if embeddable_fields is None: + embeddable_fields = get_default_embeddable_record_set_fields() + validate_record_set_contains_one(record_set, embeddable_fields) + + +def validate_record_set_contains_any( + record_set: BaseRecordSet, contains_any: Set[str] +) -> None: + """ + Validates that at least one of the fields in contains_any is not None. + """ + _validate_record_set_contains(record_set, contains_any) + + if not any(record_set[field] is not None for field in contains_any): # type: ignore[literal-required] + raise ValueError(f"At least one of {', '.join(contains_any)} must be provided") + + +def validate_record_set_contains_one( + record_set: BaseRecordSet, contains_one: Set[str] +) -> None: + """ + Validates that exactly one of the fields in contains_one is not None. + """ + _validate_record_set_contains(record_set, contains_one) + if sum(record_set[field] is not None for field in contains_one) != 1: # type: ignore[literal-required] + raise ValueError(f"Exactly one of {', '.join(contains_one)} must be provided") + + +def _validate_record_set_contains( + record_set: BaseRecordSet, contains: Set[str] +) -> None: + """ + Validates that all fields in contains are valid fields of the Record. + """ + if any(field not in record_set for field in contains): + raise ValueError( + f"Invalid field in contains: {', '.join(contains)}, available fields: {', '.join(record_set.keys())}" + ) + + +Parameter = TypeVar("Parameter", Document, Image, Embedding, Metadata, ID) + +Include = List[ + Literal["documents", "embeddings", "metadatas", "distances", "uris", "data"] +] +IncludeMetadataDocuments: Include = ["metadatas", "documents"] +IncludeMetadataDocumentsEmbeddings: Include = ["metadatas", "documents", "embeddings"] +IncludeMetadataDocumentsEmbeddingsDistances: Include = [ + "metadatas", + "documents", + "embeddings", + "distances", +] +IncludeMetadataDocumentsDistances: Include = ["metadatas", "documents", "distances"] + +# Re-export types from chromadb.types +LiteralValue = LiteralValue +LogicalOperator = LogicalOperator +WhereOperator = WhereOperator +OperatorExpression = OperatorExpression +Where = Where +WhereDocumentOperator = WhereDocumentOperator + + +class FilterSet(TypedDict): + where: Optional[Where] + where_document: Optional[WhereDocument] + + +def validate_filter_set(filter_set: FilterSet) -> None: + if filter_set["where"] is not None: + validate_where(filter_set["where"]) + if filter_set["where_document"] is not None: + validate_where_document(filter_set["where_document"]) + + +Embeddable = Union[Documents, Images] +D = TypeVar("D", bound=Embeddable, contravariant=True) + +Loadable = List[Optional[Image]] +L = TypeVar("L", covariant=True, bound=Loadable) + + +class AddRequest(TypedDict): + ids: IDs + embeddings: Embeddings + metadatas: Optional[Metadatas] + documents: Optional[Documents] + uris: Optional[URIs] + + +# Add result doesn't exist. + + +class GetRequest(TypedDict): + ids: Optional[IDs] + where: Optional[Where] + where_document: Optional[WhereDocument] + include: Include + + +class GetResult(TypedDict): + """Result payload for collection.get() operations. + + The returned records are in columnar form. Corresponding entries in each list correspond to the same record. + + >>> results = collection.get(ids=["id1", "id2", "id3"]) + >>> records = zip(results["ids"], results["documents"], results["metadatas"]) + >>> for id, document, metadata in records: + >>> print(id, document, metadata) + + GetResult will only include ids and the fields specified in the `include` param + when making the get() operation. + """ + + ids: List[ID] + embeddings: Optional[ + Union[Embeddings, PyEmbeddings, NDArray[Union[np.int32, np.float32]]] + ] + documents: Optional[List[Document]] + uris: Optional[URIs] + data: Optional[Loadable] + metadatas: Optional[List[Metadata]] + included: Include + + +class QueryRequest(TypedDict): + embeddings: Embeddings + ids: Optional[IDs] + where: Optional[Where] + where_document: Optional[WhereDocument] + include: Include + n_results: int + + +class QueryResult(TypedDict): + """Result payload for collection.query() operations. + + The returned records are batches of records in columnar form. + + >>> results = collection.query(query_embeddings=[batch_1, batch_2, ...]) + >>> batches = zip(results["ids"], results["documents"], results["metadatas"]) + + Each batch is a list of records in columnar form. + + >>> for batch in batches: + >>> records = zip(batch["ids"], batch["documents"], batch["metadatas"]) + >>> for id, document, metadata in records: + >>> print(id, document, metadata) + + QueryResult will only include ids and the fields specified in the `include` param + when making the query() operation. + """ + + ids: List[IDs] + embeddings: Optional[ + Union[ + List[Embeddings], + List[PyEmbeddings], + List[NDArray[Union[np.int32, np.float32]]], + ] + ] + documents: Optional[List[List[Document]]] + uris: Optional[List[List[URI]]] + data: Optional[List[Loadable]] + metadatas: Optional[List[List[Metadata]]] + distances: Optional[List[List[float]]] + included: Include + + +@dataclass +class IndexingStatus: + num_indexed_ops: int + num_unindexed_ops: int + total_ops: int + op_indexing_progress: float + + +class SearchResultRow(TypedDict, total=False): + """A single row from search results. + + Each SearchResultRow contains the fields present in the search response for a given record. + The 'id' field is always included; other fields are present if selected for in the search. + + `score` is the calculated value from the ranking function used during the search, if used. + """ + + id: str # Always present + document: Optional[str] + embedding: Optional[List[float]] + metadata: Optional[Dict[str, Any]] + score: Optional[float] + + +class SearchResult(dict): # type: ignore + """ + Column-major response from the search API. + + Searches are performed in batches. Each batch is a list of records in columnar form. + + >>> results = collection.search([search_1, search_2, ...]) + >>> payloads = zip(results["ids"], results["documents"], results["metadatas"]) + + Each payload contains a field grouped per search payload, in column-major form. + + >>> for payload in payloads: + >>> ids, docs, metas = payload + >>> for id, doc, meta in zip(ids, docs, metas): + >>> print(id, doc, meta) + """ + + # Type hints for IDE support and documentation + ids: List[List[str]] + documents: List[Optional[List[Optional[str]]]] + embeddings: List[Optional[List[Optional[List[float]]]]] + metadatas: List[Optional[List[Optional[Dict[str, Any]]]]] + scores: List[Optional[List[Optional[float]]]] + select: List[List[str]] + + def rows(self) -> List[List[SearchResultRow]]: + """Convert column-major format to row-major format. + + >>> results = collection.search([search_1, search_2, ...]) + >>> rows = results.rows() + >>> for payload in rows: + >>> for row in payload: + >>> print(row["id"], row["document"], row["metadata"], row["score"]) + + Returns: + List of per-payload rows as SearchResultRow dictionaries. + """ + result: List[List[SearchResultRow]] = [] + + # Get all field data with defaults + all_ids = self.get("ids", []) + n_payloads = len(all_ids) + all_docs = self.get("documents") or [None] * n_payloads + all_embs = self.get("embeddings") or [None] * n_payloads + all_metas = self.get("metadatas") or [None] * n_payloads + all_scores = self.get("scores") or [None] * n_payloads + + # Zip payload-level data together + for ids, docs, embs, metas, scores in zip( + all_ids, all_docs, all_embs, all_metas, all_scores + ): + payload_rows: List[SearchResultRow] = [] + + # Zip row-level data together (handle None payloads inline) + for id_val, doc, emb, meta, score in zip( + ids, + docs or [None] * len(ids), + embs or [None] * len(ids), + metas or [None] * len(ids), + scores or [None] * len(ids), + ): + row: SearchResultRow = {"id": id_val} + + # Add fields only if they have values + if doc is not None: + row["document"] = doc + if emb is not None: + row["embedding"] = emb + if meta is not None: + row["metadata"] = meta + if score is not None: + row["score"] = score + + payload_rows.append(row) + + result.append(payload_rows) + + return result + + +class UpdateRequest(TypedDict): + ids: IDs + embeddings: Optional[Embeddings] + metadatas: Optional[Metadatas] + documents: Optional[Documents] + uris: Optional[URIs] + + +# Update result doesn't exist. + + +class UpsertRequest(TypedDict): + ids: IDs + embeddings: Embeddings + metadatas: Optional[Metadatas] + documents: Optional[Documents] + uris: Optional[URIs] + + +# Upsert result doesn't exist. + + +class DeleteRequest(TypedDict): + ids: Optional[IDs] + where: Optional[Where] + where_document: Optional[WhereDocument] + limit: Optional[int] + + +class DeleteResult(TypedDict): + deleted: int + + +class IndexMetadata(TypedDict): + dimensionality: int + # The current number of elements in the index (total = additions - deletes) + curr_elements: int + # The auto-incrementing ID of the last inserted element, never decreases so + # can be used as a count of total historical size. Should increase by 1 every add. + # Assume cannot overflow + total_elements_added: int + time_created: float + + +Space = Literal["cosine", "l2", "ip"] + + +class ReadLevel(str, Enum): + """Controls whether search queries read from the write-ahead log (WAL). + + Attributes: + INDEX_AND_WAL: Read from both the compacted index and the WAL (default). + All committed writes will be visible. + INDEX_ONLY: Read only from the compacted index, skipping the WAL. + Faster, but recent writes that haven't been compacted may not be visible. + INDEX_AND_BOUNDED_WAL: Read from the index and up to a server-configured + number of WAL entries. Provides a consistent prefix of the WAL with + bounded query latency: recently committed writes beyond the limit + may not be visible. + """ + + INDEX_AND_WAL = "index_and_wal" + INDEX_ONLY = "index_only" + INDEX_AND_BOUNDED_WAL = "index_and_bounded_wal" + + +# TODO: make warnings prettier and add link to migration docs +@runtime_checkable +class EmbeddingFunction(Protocol[D]): + """Protocol for embedding functions. + + To implement a new embedding function, + you need to implement the following methods: + - __init__ + - __call__ + - name + - build_from_config + - get_config + + Additionally, you should register the embedding function so it will automatically + be used by the Chroma client. + + >>> @register_embedding_function + >>> class MyEmbeddingFunction(EmbeddingFunction[Documents]): + >>> ... + """ + + @abstractmethod + def __call__(self, input: D) -> Embeddings: ... + + def embed_query(self, input: D) -> Embeddings: + """Embed a query input. + + Use this to create embeddings for documents and embeddings for queries/searches differently. + Some embedding models are trained to produce different embeddings for documents and queries/searches + for better performance. + + If not overridden, this calls ``__call__``. + """ + return self.__call__(input) + + def __init_subclass__(cls) -> None: + super().__init_subclass__() + # Raise an exception if __call__ is not defined since it is expected to be defined + call = getattr(cls, "__call__") + + def __call__(self: EmbeddingFunction[D], input: D) -> Embeddings: + result = call(self, input) + assert result is not None + return validate_embeddings(cast(Embeddings, normalize_embeddings(result))) + + setattr(cls, "__call__", __call__) + + def embed_with_retries( + self, input: D, **retry_kwargs: Dict[str, Any] + ) -> Embeddings: + return cast(Embeddings, retry(**retry_kwargs)(self.__call__)(input)) # type: ignore[call-overload] + + def __init__(self, *args: Any, **kwargs: Any) -> None: + """Initialize the embedding function. This method should be overriden.""" + + warnings.warn( + f"The class {self.__class__.__name__} does not implement __init__. " + "This will be required in a future version.", + DeprecationWarning, + stacklevel=2, + ) + + @staticmethod + def name() -> str: + """Return the embedding function name. This method should be overriden.""" + + warnings.warn( + "The EmbeddingFunction class does not implement name(). " + "This will be required in a future version.", + DeprecationWarning, + stacklevel=2, + ) + return NotImplemented + + def default_space(self) -> Space: + """Return the default space for the embedding function.""" + return "l2" + + def supported_spaces(self) -> List[Space]: + """Return the supported spaces for the embedding function.""" + return ["cosine", "l2", "ip"] + + @staticmethod + def build_from_config(config: Dict[str, Any]) -> "EmbeddingFunction[D]": + """Build an embedding function from a serialized config. This method should be overriden.""" + + warnings.warn( + "The EmbeddingFunction class does not implement build_from_config(). " + "This will be required in a future version.", + DeprecationWarning, + stacklevel=2, + ) + return NotImplemented + + def get_config(self) -> Dict[str, Any]: + """Return a serializable configuration for the embedding function. + This method should be overriden. + """ + + warnings.warn( + f"The class {self.__class__.__name__} does not implement get_config(). " + "This will be required in a future version.", + DeprecationWarning, + stacklevel=2, + ) + return NotImplemented + + def validate_config_update( + self, old_config: Dict[str, Any], new_config: Dict[str, Any] + ) -> None: + """Validate a config update.""" + return + + @staticmethod + def validate_config(config: Dict[str, Any]) -> None: + """Validate a config.""" + return + + def is_legacy(self) -> bool: + if ( + self.name() is NotImplemented + or self.get_config() is NotImplemented + or self.build_from_config(self.get_config()) is NotImplemented + ): + return True + return False + + +class DefaultEmbeddingFunction(EmbeddingFunction[Documents]): + """Default embedding function that delegates to ONNXMiniLM_L6_V2.""" + + def __init__(self) -> None: + if is_thin_client: + return + + def __call__(self, input: Documents) -> Embeddings: + # Import here to avoid circular imports + from chromadb.utils.embedding_functions.onnx_mini_lm_l6_v2 import ( + ONNXMiniLM_L6_V2, + ) + + return ONNXMiniLM_L6_V2()(input) + + @staticmethod + def build_from_config(config: Dict[str, Any]) -> "DefaultEmbeddingFunction": + DefaultEmbeddingFunction.validate_config(config) + return DefaultEmbeddingFunction() + + @staticmethod + def name() -> str: + return "default" + + def get_config(self) -> Dict[str, Any]: + return {} + + def max_tokens(self) -> int: + return 256 + + @staticmethod + def validate_config(config: Dict[str, Any]) -> None: + return + + +def validate_embedding_function( + embedding_function: EmbeddingFunction[Embeddable], +) -> None: + function_signature = signature( + embedding_function.__class__.__call__ + ).parameters.keys() + protocol_signature = signature(EmbeddingFunction.__call__).parameters.keys() + + if not function_signature == protocol_signature: + raise ValueError( + f"Expected EmbeddingFunction.__call__ to have the following signature: {protocol_signature}, got {function_signature}\n" + "Please see https://docs.trychroma.com/guides/embeddings for details of the EmbeddingFunction interface.\n" + "Please note the recent change to the EmbeddingFunction interface: https://docs.trychroma.com/deployment/migration#migration-to-0.4.16---november-7,-2023 \n" + ) + + +class DataLoader(Protocol[L]): + def __call__(self, uris: URIs) -> L: ... + + +def validate_ids(ids: IDs) -> IDs: + """Validates ids to ensure it is a list of strings""" + if not isinstance(ids, list): + raise ValueError(f"Expected IDs to be a list, got {type(ids).__name__} as IDs") + if len(ids) == 0: + raise ValueError(f"Expected IDs to be a non-empty list, got {len(ids)} IDs") + seen = set() + dups = set() + for id_ in ids: + if not isinstance(id_, str): + raise ValueError(f"Expected ID to be a str, got {id_}") + if id_ in seen: + dups.add(id_) + else: + seen.add(id_) + if dups: + n_dups = len(dups) + if n_dups < 10: + example_string = ", ".join(dups) + message = ( + f"Expected IDs to be unique, found duplicates of: {example_string}" + ) + else: + examples = [] + for idx, dup in enumerate(dups): + examples.append(dup) + if idx == 10: + break + example_string = ( + f"{', '.join(examples[:5])}, ..., {', '.join(examples[-5:])}" + ) + message = f"Expected IDs to be unique, found {n_dups} duplicated IDs: {example_string}" + raise errors.DuplicateIDError(message) + return ids + + +def _validate_metadata_list_value(key: str, value: list) -> None: + """Validates a list metadata value: must be non-empty and homogeneously typed.""" + if len(value) == 0: + raise ValueError( + f"Expected metadata list value for key '{key}' to be non-empty" + ) + first_type = type(value[0]) + # Normalize: bool must be checked before int since isinstance(True, int) is True + if isinstance(value[0], bool): + first_type = bool + for item in value: + item_type = bool if isinstance(item, bool) else type(item) + if item_type is not first_type or item_type not in (str, int, float, bool): + raise ValueError( + f"Expected metadata list value for key '{key}' to contain only str, int, float, or bool " + f"and all elements must be the same type, got {value}" + ) + + +def validate_metadata(metadata: Metadata) -> Metadata: + """Validates metadata to ensure it is a dictionary of strings to strings, ints, floats, bools, SparseVectors, or lists thereof""" + if not isinstance(metadata, dict) and metadata is not None: + raise ValueError( + f"Expected metadata to be a dict or None, got {type(metadata).__name__} as metadata" + ) + if metadata is None: + return metadata + if len(metadata) == 0: + raise ValueError( + f"Expected metadata to be a non-empty dict, got {len(metadata)} metadata attributes" + ) + for key, value in metadata.items(): + if key == META_KEY_CHROMA_DOCUMENT: + raise ValueError( + f"Expected metadata to not contain the reserved key {META_KEY_CHROMA_DOCUMENT}" + ) + if not isinstance(key, str): + raise TypeError( + f"Expected metadata key to be a str, got {key} which is a {type(key).__name__}" + ) + # Check if value is a SparseVector (validation happens in __post_init__) + if isinstance(value, SparseVector): + pass # Already validated in SparseVector.__post_init__ + elif isinstance(value, list): + _validate_metadata_list_value(key, value) + # isinstance(True, int) evaluates to True, so we need to check for bools separately + elif not isinstance(value, bool) and not isinstance( + value, (str, int, float, type(None)) + ): + raise ValueError( + f"Expected metadata value to be a str, int, float, bool, SparseVector, list, or None, got {value} which is a {type(value).__name__}" + ) + return metadata + + +def validate_update_metadata(metadata: UpdateMetadata) -> UpdateMetadata: + """Validates metadata to ensure it is a dictionary of strings to strings, ints, floats, bools, SparseVectors, or lists thereof""" + if not isinstance(metadata, dict) and metadata is not None: + raise ValueError( + f"Expected metadata to be a dict or None, got {type(metadata)}" + ) + if metadata is None: + return metadata + if len(metadata) == 0: + raise ValueError(f"Expected metadata to be a non-empty dict, got {metadata}") + for key, value in metadata.items(): + if not isinstance(key, str): + raise ValueError(f"Expected metadata key to be a str, got {key}") + # Check if value is a SparseVector (validation happens in __post_init__) + if isinstance(value, SparseVector): + pass # Already validated in SparseVector.__post_init__ + elif isinstance(value, list): + _validate_metadata_list_value(key, value) + # isinstance(True, int) evaluates to True, so we need to check for bools separately + elif not isinstance(value, bool) and not isinstance( + value, (str, int, float, type(None)) + ): + raise ValueError( + f"Expected metadata value to be a str, int, float, bool, SparseVector, list, or None, got {value}" + ) + return metadata + + +def serialize_metadata(metadata: Optional[Metadata]) -> Optional[Dict[str, Any]]: + """Serialize metadata for transport, converting SparseVector dataclass instances to dicts. + + Args: + metadata: Metadata dictionary that may contain SparseVector instances + + Returns: + Metadata dictionary with SparseVector instances converted to transport format + """ + if metadata is None: + return None + + result: Dict[str, Any] = {} + for key, value in metadata.items(): + if isinstance(value, SparseVector): + result[key] = value.to_dict() + else: + result[key] = value + return result + + +def deserialize_metadata( + metadata: Optional[Dict[str, Any]], +) -> Optional[Dict[str, Any]]: + """Deserialize metadata from transport, converting dicts with #type=sparse_vector to dataclass instances. + + Args: + metadata: Metadata dictionary from transport that may contain serialized SparseVectors + + Returns: + Metadata dictionary with serialized SparseVectors converted to dataclass instances + """ + if metadata is None: + return None + + result: Dict[str, Any] = {} + for key, value in metadata.items(): + if isinstance(value, dict) and value.get(TYPE_KEY) == SPARSE_VECTOR_TYPE_VALUE: + result[key] = SparseVector.from_dict(value) + else: + result[key] = value + return result + + +def validate_metadatas(metadatas: Metadatas) -> Metadatas: + """Validates metadatas to ensure it is a list of dictionaries of strings to strings, ints, floats or bools""" + if not isinstance(metadatas, list): + raise ValueError(f"Expected metadatas to be a list, got {metadatas}") + for metadata in metadatas: + validate_metadata(metadata) + return metadatas + + +def validate_where(where: Where) -> None: + """ + Validates where to ensure it is a dictionary of strings to strings, ints, floats or operator expressions, + or in the case of $and and $or, a list of where expressions + """ + if not isinstance(where, dict): + raise ValueError(f"Expected where to be a dict, got {where}") + if len(where) != 1: + raise ValueError(f"Expected where to have exactly one operator, got {where}") + for key, value in where.items(): + if not isinstance(key, str): + raise ValueError(f"Expected where key to be a str, got {key}") + # $contains and $not_contains are only valid as operators within a + # field expression (e.g. {"field": {"$contains": val}}), not as + # top-level where keys. + if key in ("$contains", "$not_contains"): + raise ValueError( + f"Expected where key to be a metadata field name or a logical " + f"operator ($and, $or), got {key}" + ) + if ( + key != "$and" + and key != "$or" + and key != "$in" + and key != "$nin" + and not isinstance(value, (str, int, float, dict)) + ): + raise ValueError( + f"Expected where value to be a str, int, float, or operator expression, got {value}" + ) + if key == "$and" or key == "$or": + if not isinstance(value, list): + raise ValueError( + f"Expected where value for $and or $or to be a list of where expressions, got {value}" + ) + if len(value) <= 1: + raise ValueError( + f"Expected where value for $and or $or to be a list with at least two where expressions, got {value}" + ) + for where_expression in value: + validate_where(where_expression) + # Value is a operator expression + if isinstance(value, dict): + # Ensure there is only one operator + if len(value) != 1: + raise ValueError( + f"Expected operator expression to have exactly one operator, got {value}" + ) + + for operator, operand in value.items(): + # Only numbers can be compared with gt, gte, lt, lte + if operator in ["$gt", "$gte", "$lt", "$lte"]: + if not isinstance(operand, (int, float)): + raise ValueError( + f"Expected operand value to be an int or a float for operator {operator}, got {operand}" + ) + if operator in ["$in", "$nin"]: + if not isinstance(operand, list): + raise ValueError( + f"Expected operand value to be an list for operator {operator}, got {operand}" + ) + # $contains/$not_contains: scalar operand (checks if array field contains value) + if operator in ["$contains", "$not_contains"]: + if key == "#document" and not isinstance(operand, str): + raise ValueError( + f"Expected operand value to be a str for operator {operator} on #document, got {operand}" + ) + if not isinstance(operand, (str, int, float, bool)): + raise ValueError( + f"Expected operand value to be a str, int, float, or bool for operator {operator}, got {operand}" + ) + if operator not in [ + "$gt", + "$gte", + "$lt", + "$lte", + "$ne", + "$eq", + "$in", + "$nin", + "$contains", + "$not_contains", + ]: + raise ValueError( + f"Expected where operator to be one of $gt, $gte, $lt, $lte, $ne, $eq, $in, $nin, " + f"$contains, $not_contains, got {operator}" + ) + + if not isinstance(operand, (str, int, float, bool, list)): + raise ValueError( + f"Expected where operand value to be a str, int, float, bool, or list of those type, got {operand}" + ) + if isinstance(operand, list) and ( + len(operand) == 0 + or not all(isinstance(x, type(operand[0])) for x in operand) + ): + raise ValueError( + f"Expected where operand value to be a non-empty list, and all values to be of the same type " + f"got {operand}" + ) + + +def validate_where_document(where_document: WhereDocument) -> None: + """ + Validates where_document to ensure it is a dictionary of WhereDocumentOperator to strings, or in the case of $and and $or, + a list of where_document expressions + """ + if not isinstance(where_document, dict): + raise ValueError( + f"Expected where document to be a dictionary, got {where_document}" + ) + if len(where_document) != 1: + raise ValueError( + f"Expected where document to have exactly one operator, got {where_document}" + ) + for operator, operand in where_document.items(): + if operator not in [ + "$contains", + "$not_contains", + "$regex", + "$not_regex", + "$and", + "$or", + ]: + raise ValueError( + f"Expected where document operator to be one of $contains, $not_contains, $regex, $not_regex, $and, $or, got {operator}" + ) + if operator == "$and" or operator == "$or": + if not isinstance(operand, list): + raise ValueError( + f"Expected document value for $and or $or to be a list of where document expressions, got {operand}" + ) + if len(operand) <= 1: + raise ValueError( + f"Expected document value for $and or $or to be a list with at least two where document expressions, got {operand}" + ) + for where_document_expression in operand: + validate_where_document(where_document_expression) + # Value is $contains/$not_contains/$regex/$not_regex operator + elif not isinstance(operand, str): + raise ValueError( + f"Expected where document operand value for operator {operator} to be a str, got {operand}" + ) + elif len(operand) == 0: + raise ValueError( + f"Expected where document operand value for operator {operator} to be a non-empty str" + ) + + +def validate_include(include: Include, dissalowed: Optional[Include] = None) -> None: + """Validates include to ensure it is a list of strings. Since get does not allow distances, allow_distances is used + to control if distances is allowed""" + + if not isinstance(include, list): + raise ValueError(f"Expected include to be a list, got {include}") + for item in include: + if not isinstance(item, str): + raise ValueError(f"Expected include item to be a str, got {item}") + + # Get the valid items from the Literal type inside the List + valid_items = get_args(get_args(Include)[0]) + if item not in valid_items: + raise ValueError( + f"Expected include item to be one of {', '.join(valid_items)}, got {item}" + ) + + if dissalowed is not None and any(item == e for e in dissalowed): + raise ValueError( + f"Include item cannot be one of {', '.join(dissalowed)}, got {item}" + ) + + +def validate_n_results(n_results: int) -> int: + """Validates n_results to ensure it is a positive Integer. Since hnswlib does not allow n_results to be negative.""" + # Check Number of requested results + if not isinstance(n_results, int): + raise ValueError( + f"Expected requested number of results to be a int, got {n_results}" + ) + if n_results <= 0: + raise TypeError( + f"Number of requested results {n_results}, cannot be negative, or zero." + ) + return n_results + + +def validate_embeddings(embeddings: Embeddings) -> Embeddings: + """Validates embeddings to ensure it is a list of numpy arrays of ints, or floats""" + if not isinstance(embeddings, (list, np.ndarray)): + raise ValueError( + f"Expected embeddings to be a list, got {type(embeddings).__name__}" + ) + if len(embeddings) == 0: + raise ValueError( + f"Expected embeddings to be a list with at least one item, got {len(embeddings)} embeddings" + ) + if not all([isinstance(e, np.ndarray) for e in embeddings]): + raise ValueError( + "Expected each embedding in the embeddings to be a numpy array, got " + f"{list(set([type(e).__name__ for e in embeddings]))}" + ) + for i, embedding in enumerate(embeddings): + if embedding.ndim == 0: + raise ValueError( + f"Expected a 1-dimensional array, got a 0-dimensional array {embedding}" + ) + if embedding.size == 0: + raise ValueError( + f"Expected each embedding in the embeddings to be a 1-dimensional numpy array with at least 1 int/float value. Got a 1-dimensional numpy array with no values at pos {i}" + ) + + if embedding.dtype not in [ + np.float16, + np.float32, + np.float64, + np.int32, + np.int64, + ]: + raise ValueError( + "Expected each value in the embedding to be a int or float, got an embedding with " + f"{embedding.dtype} - {embedding}" + ) + return embeddings + + +def validate_sparse_vectors(vectors: SparseVectors) -> SparseVectors: + """Validates sparse vectors to ensure it is a non-empty list of SparseVector instances. + + This function validates the structure and types of sparse vectors returned by + SparseEmbeddingFunction implementations. It ensures: + - Vectors is a list + - List is non-empty + - All items are SparseVector instances + + Note: Individual SparseVector validation (sorted indices, non-negative values, etc.) + happens automatically in SparseVector.__post_init__ when each instance is created. + This function only validates the list structure and instance types. + """ + if not isinstance(vectors, list): + raise ValueError( + f"Expected sparse vectors to be a list, got {type(vectors).__name__}" + ) + if len(vectors) == 0: + raise ValueError( + f"Expected sparse vectors to be a non-empty list, got {len(vectors)} sparse vectors" + ) + for i, vector in enumerate(vectors): + if not isinstance(vector, SparseVector): + raise ValueError( + f"Expected SparseVector instance at position {i}, got {type(vector).__name__}" + ) + return vectors + + +def validate_documents(documents: Documents, nullable: bool = False) -> None: + """Validates documents to ensure it is a list of strings""" + if not isinstance(documents, list): + raise ValueError( + f"Expected documents to be a list, got {type(documents).__name__}" + ) + if len(documents) == 0: + raise ValueError( + f"Expected documents to be a non-empty list, got {len(documents)} documents" + ) + for document in documents: + # If embeddings are present, some documents can be None + if document is None and nullable: + continue + if not is_document(document): + raise ValueError(f"Expected document to be a str, got {document}") + + +def validate_images(images: Images) -> None: + """Validates images to ensure it is a list of numpy arrays""" + if not isinstance(images, list): + raise ValueError(f"Expected images to be a list, got {type(images).__name__}") + if len(images) == 0: + raise ValueError( + f"Expected images to be a non-empty list, got {len(images)} images" + ) + for image in images: + if not is_image(image): + raise ValueError(f"Expected image to be a numpy array, got {image}") + + +def validate_batch( + batch: Tuple[ + IDs, + Optional[Union[Embeddings, PyEmbeddings]], + Optional[Metadatas], + Optional[Documents], + Optional[URIs], + ], + limits: Dict[str, Any], +) -> None: + if len(batch[0]) > limits["max_batch_size"]: + raise ValueError( + f"Batch size {len(batch[0])} exceeds maximum batch size {limits['max_batch_size']}" + ) + + +def convert_np_embeddings_to_list(embeddings: Embeddings) -> PyEmbeddings: + # Cast the result to PyEmbeddings to ensure type compatibility + return cast(PyEmbeddings, [embedding.tolist() for embedding in embeddings]) + + +def convert_list_embeddings_to_np(embeddings: PyEmbeddings) -> Embeddings: + return [np.array(embedding) for embedding in embeddings] + + +@runtime_checkable +class SparseEmbeddingFunction(Protocol[D]): + """Protocol for sparse embedding functions. + + To implement a new sparse embedding function, you need to implement the following methods: + - __call__ + - __init__ + - name + - build_from_config + - get_config + """ + + @abstractmethod + def __call__(self, input: D) -> SparseVectors: ... + + def embed_query(self, input: D) -> SparseVectors: + """Embed a query input. + + If not overridden, this calls ``__call__``. + """ + return self.__call__(input) + + def __init_subclass__(cls) -> None: + super().__init_subclass__() + # Raise an exception if __call__ is not defined since it is expected to be defined + call = getattr(cls, "__call__") + + def __call__(self: SparseEmbeddingFunction[D], input: D) -> SparseVectors: + result = call(self, input) + assert result is not None + return validate_sparse_vectors(cast(SparseVectors, result)) + + setattr(cls, "__call__", __call__) + + def embed_with_retries( + self, input: D, **retry_kwargs: Dict[str, Any] + ) -> SparseVectors: + return cast(SparseVectors, retry(**retry_kwargs)(self.__call__)(input)) # type: ignore[call-overload] + + @abstractmethod + def __init__(self, *args: Any, **kwargs: Any) -> None: + """Initialize the embedding function.""" + ... + + @staticmethod + @abstractmethod + def name() -> str: + """Return the embedding function name.""" + ... + + @staticmethod + @abstractmethod + def build_from_config(config: Dict[str, Any]) -> "SparseEmbeddingFunction[D]": + """Build an embedding function from a serialized config.""" + ... + + @abstractmethod + def get_config(self) -> Dict[str, Any]: + """Return a serializable configuration for the embedding function.""" + ... + + def validate_config_update( + self, old_config: Dict[str, Any], new_config: Dict[str, Any] + ) -> None: + """Validate a config update.""" + return + + @staticmethod + def validate_config(config: Dict[str, Any]) -> None: + """Validate a config.""" + return + + +def validate_sparse_embedding_function( + sparse_vector_function: SparseEmbeddingFunction[Embeddable], +) -> None: + """Validate that a sparse vector function conforms to the SparseEmbeddingFunction protocol.""" + function_signature = signature( + sparse_vector_function.__class__.__call__ + ).parameters.keys() + protocol_signature = signature(SparseEmbeddingFunction.__call__).parameters.keys() + + if not function_signature == protocol_signature: + raise ValueError( + f"Expected SparseEmbeddingFunction.__call__ to have the following signature: {protocol_signature}, got {function_signature}\n" + "Please see https://docs.trychroma.com/guides/embeddings for details of the SparseEmbeddingFunction interface.\n" + ) + + +# Index Configuration Types for Collection Schema +def _create_extra_fields_validator(valid_fields: list[str]) -> Any: + """Create a model validator that provides helpful error messages for invalid fields.""" + + @model_validator(mode="before") + def validate_extra_fields(cls: Type[BaseModel], data: Any) -> Any: + if isinstance(data, dict): + invalid_fields = [k for k in data.keys() if k not in valid_fields] + if invalid_fields: + invalid_fields_str = ", ".join(f"'{f}'" for f in invalid_fields) + class_name = cls.__name__ + # Create a clear, actionable error message + if len(invalid_fields) == 1: + msg = ( + f"'{invalid_fields[0]}' is not a valid field for {class_name}. " + ) + else: + msg = f"Invalid fields for {class_name}: {invalid_fields_str}. " + + raise PydanticCustomError( + "invalid_field", + msg, + {"invalid_fields": invalid_fields}, + ) + return data + + return validate_extra_fields + + +class FtsIndexConfig(BaseModel): + """Configuration for Full-Text Search index. No parameters required.""" + + model_config = {"extra": "forbid"} + + pass + + +class HnswIndexConfig(BaseModel): + """Configuration for HNSW vector index.""" + + _validate_extra_fields = _create_extra_fields_validator( + [ + "ef_construction", + "max_neighbors", + "ef_search", + "num_threads", + "batch_size", + "sync_threshold", + "resize_factor", + ] + ) + + ef_construction: Optional[int] = None + max_neighbors: Optional[int] = None + ef_search: Optional[int] = None + num_threads: Optional[int] = None + batch_size: Optional[int] = None + sync_threshold: Optional[int] = None + resize_factor: Optional[float] = None + + +class SpannIndexConfig(BaseModel): + """Configuration for SPANN vector index.""" + + _validate_extra_fields = _create_extra_fields_validator( + [ + "search_nprobe", + "search_rng_factor", + "search_rng_epsilon", + "nreplica_count", + "write_nprobe", + "write_rng_factor", + "write_rng_epsilon", + "split_threshold", + "num_samples_kmeans", + "initial_lambda", + "reassign_neighbor_count", + "merge_threshold", + "num_centers_to_merge_to", + "ef_construction", + "ef_search", + "max_neighbors", + "center_drift_threshold", + "quantize", + ] + ) + + search_nprobe: Optional[int] = None + write_nprobe: Optional[int] = None + ef_construction: Optional[int] = None + ef_search: Optional[int] = None + max_neighbors: Optional[int] = None + reassign_neighbor_count: Optional[int] = None + split_threshold: Optional[int] = None + merge_threshold: Optional[int] = None + + +class VectorIndexConfig(BaseModel): + """Configuration for vector index with space, embedding function, and algorithm config.""" + + model_config = {"arbitrary_types_allowed": True, "extra": "forbid"} + + space: Optional[Space] = None + embedding_function: Optional[Any] = DefaultEmbeddingFunction() + source_key: Optional[str] = ( + None # key to source the vector from (accepts str or Key) + ) + hnsw: Optional[HnswIndexConfig] = None + spann: Optional[SpannIndexConfig] = None + + @field_validator("source_key", mode="before") + @classmethod + def validate_source_key_field(cls, v: Any) -> Optional[str]: + """Convert Key objects to strings automatically. Accepts both str and Key types.""" + if v is None: + return None + # Import Key at runtime to avoid circular import + from chromadb.execution.expression.operator import Key as KeyType + + if isinstance(v, KeyType): + v = v.name # Extract string from Key + elif isinstance(v, str): + pass # Already a string + else: + raise ValueError(f"source_key must be str or Key, got {type(v).__name__}") + + # Validate: only #document is allowed if key starts with # + if v.startswith("#") and v != "#document": + raise ValueError( + "source_key cannot begin with '#'. " + "The only valid key starting with '#' is Key.DOCUMENT or '#document'." + ) + + return v # type: ignore[no-any-return] + + @field_validator("embedding_function", mode="before") + @classmethod + def validate_embedding_function_field(cls, v: Any) -> Any: + # Use the existing validate_embedding_function for proper validation + if v is None: + return v + if callable(v): + # Use the existing validation function + validate_embedding_function(v) + return v + raise ValueError("embedding_function must be callable or None") + + +class SparseVectorIndexConfig(BaseModel): + """Configuration for sparse vector index.""" + + model_config = {"arbitrary_types_allowed": True} + + _validate_extra_fields = _create_extra_fields_validator( + [ + "embedding_function", + "source_key", + "bm25", + "algorithm", + ] + ) + + # TODO(Sanket): Change this to the appropriate sparse ef and use a default here. + embedding_function: Optional[Any] = None + source_key: Optional[str] = ( + None # key to source the sparse vector from (accepts str or Key) + ) + bm25: Optional[bool] = None + + @field_validator("source_key", mode="before") + @classmethod + def validate_source_key_field(cls, v: Any) -> Optional[str]: + """Convert Key objects to strings automatically. Accepts both str and Key types.""" + if v is None: + return None + # Import Key at runtime to avoid circular import + from chromadb.execution.expression.operator import Key as KeyType + + if isinstance(v, KeyType): + v = v.name # Extract string from Key + elif isinstance(v, str): + pass # Already a string + else: + raise ValueError(f"source_key must be str or Key, got {type(v).__name__}") + + # Validate: only #document is allowed if key starts with # + if v.startswith("#") and v != "#document": + raise ValueError( + "source_key cannot begin with '#'. " + "The only valid key starting with '#' is Key.DOCUMENT or '#document'." + ) + + return v # type: ignore[no-any-return] + + @field_validator("embedding_function", mode="before") + @classmethod + def validate_embedding_function_field(cls, v: Any) -> Any: + # Validate sparse vector function for sparse vector index + if v is None: + return v + if callable(v): + # Use the sparse vector function validation + validate_sparse_embedding_function(v) + return v + raise ValueError( + "embedding_function must be a callable SparseEmbeddingFunction or None" + ) + + +class StringInvertedIndexConfig(BaseModel): + """Configuration for string inverted index.""" + + model_config = {"extra": "forbid"} + + pass + + +class IntInvertedIndexConfig(BaseModel): + """Configuration for integer inverted index.""" + + model_config = {"extra": "forbid"} + + pass + + +class FloatInvertedIndexConfig(BaseModel): + """Configuration for float inverted index.""" + + model_config = {"extra": "forbid"} + + pass + + +class BoolInvertedIndexConfig(BaseModel): + """Configuration for boolean inverted index.""" + + model_config = {"extra": "forbid"} + + pass + + +# Union type for all index configurations (used by new Schema class) +IndexConfig: TypeAlias = Union[ + FtsIndexConfig, + VectorIndexConfig, + SparseVectorIndexConfig, + StringInvertedIndexConfig, + IntInvertedIndexConfig, + FloatInvertedIndexConfig, + BoolInvertedIndexConfig, +] + + +# Value type constants +STRING_VALUE_NAME: Final[str] = "string" +INT_VALUE_NAME: Final[str] = "int" +BOOL_VALUE_NAME: Final[str] = "bool" +FLOAT_VALUE_NAME: Final[str] = "float" +FLOAT_LIST_VALUE_NAME: Final[str] = "float_list" +SPARSE_VECTOR_VALUE_NAME: Final[str] = "sparse_vector" + +# Index type name constants +FTS_INDEX_NAME: Final[str] = "fts_index" +VECTOR_INDEX_NAME: Final[str] = "vector_index" +SPARSE_VECTOR_INDEX_NAME: Final[str] = "sparse_vector_index" +STRING_INVERTED_INDEX_NAME: Final[str] = "string_inverted_index" +INT_INVERTED_INDEX_NAME: Final[str] = "int_inverted_index" +FLOAT_INVERTED_INDEX_NAME: Final[str] = "float_inverted_index" +BOOL_INVERTED_INDEX_NAME: Final[str] = "bool_inverted_index" +HNSW_INDEX_NAME: Final[str] = "hnsw_index" +SPANN_INDEX_NAME: Final[str] = "spann_index" + +# Special key constants +DOCUMENT_KEY: Final[str] = "#document" +EMBEDDING_KEY: Final[str] = "#embedding" +TYPE_KEY: Final[str] = "#type" + +# Type value constants +SPARSE_VECTOR_TYPE_VALUE: Final[str] = "sparse_vector" + + +# ============================================================================ +# CMEK (Customer-Managed Encryption Key) Support +# ============================================================================ + + +class CmekProvider(str, Enum): + """Supported cloud providers for customer-managed encryption keys. + + Currently only Google Cloud Platform (GCP) is supported. + """ + + GCP = "gcp" + + +# Regex pattern for validating GCP KMS resource names +_CMEK_GCP_PATTERN = re.compile(r"^projects/.+/locations/.+/keyRings/.+/cryptoKeys/.+$") + + +@dataclass +class Cmek: + """Customer-managed encryption key (CMEK) for collection data encryption. + + CMEK allows you to use your own encryption keys managed by cloud providers' + key management services (KMS) instead of default provider-managed keys. This + gives you greater control over key lifecycle, access policies, and audit logging. + + Attributes: + provider: The cloud provider (currently only 'gcp' supported) + resource: The provider-specific resource identifier for the encryption key + + Example: + >>> # Create a CMEK for GCP + >>> cmek = Cmek.gcp( + ... "projects/my-project/locations/us-central1/" + ... "keyRings/my-ring/cryptoKeys/my-key" + ... ) + >>> + >>> # Validate the resource name format + >>> if cmek.validate_pattern(): + ... print("Valid CMEK format") + + Note: + Pattern validation only checks format correctness. It does not verify + that the key exists or is accessible. Key permissions and access control + must be configured separately in your cloud provider's console. + """ + + provider: CmekProvider + resource: str + + @classmethod + def gcp(cls, resource: str) -> "Cmek": + """Create a CMEK instance for Google Cloud Platform. + + Args: + resource: GCP Cloud KMS resource name in the format: + projects/{project-id}/locations/{location}/keyRings/{key-ring}/cryptoKeys/{key-name} + + Example: "projects/my-project/locations/us-central1/keyRings/my-ring/cryptoKeys/my-key" + + Returns: + Cmek: A new CMEK instance configured for GCP + + Raises: + ValueError: If the resource format is invalid (when validate_pattern() is called) + + Example: + >>> cmek = Cmek.gcp( + ... "projects/my-project/locations/us-central1/" + ... "keyRings/my-ring/cryptoKeys/my-key" + ... ) + """ + return cls(provider=CmekProvider.GCP, resource=resource) + + def validate_pattern(self) -> bool: + """Validate the CMEK resource name format. + + Validates that the resource name matches the expected pattern for the + provider. This is a format check only and does not verify that the key + exists or that you have access to it. + + For GCP, the expected format is: + projects/{project}/locations/{location}/keyRings/{keyRing}/cryptoKeys/{cryptoKey} + + Returns: + bool: True if the resource name format is valid, False otherwise + + Example: + >>> cmek = Cmek.gcp("projects/p/locations/l/keyRings/r/cryptoKeys/k") + >>> cmek.validate_pattern() # Returns True + >>> + >>> bad_cmek = Cmek.gcp("invalid-format") + >>> bad_cmek.validate_pattern() # Returns False + """ + if self.provider == CmekProvider.GCP: + return _CMEK_GCP_PATTERN.match(self.resource) is not None + return False + + def to_dict(self) -> Dict[str, Any]: + """Serialize CMEK to dictionary format for API transport. + + Returns: + Dict containing the provider variant and resource identifier. + + Example: + >>> cmek = Cmek.gcp("projects/p/locations/l/keyRings/r/cryptoKeys/k") + >>> cmek.to_dict() + {'gcp': 'projects/p/locations/l/keyRings/r/cryptoKeys/k'} + """ + if self.provider == CmekProvider.GCP: + return {"gcp": self.resource} + # Unreachable with current providers, but future-proof + raise ValueError(f"Unknown CMEK provider: {self.provider}") + + @classmethod + def from_dict(cls, data: Dict[str, Any]) -> "Cmek": + """Deserialize CMEK from dictionary format. + + Args: + data: Dictionary containing provider variant and resource. + Format matches Rust serde enum serialization with snake_case. + + Returns: + Cmek: Deserialized CMEK instance + + Raises: + ValueError: If the provider is unsupported or data is malformed + + Example: + >>> data = {'gcp': 'projects/p/locations/l/keyRings/r/cryptoKeys/k'} + >>> cmek = Cmek.from_dict(data) + """ + if "gcp" in data: + resource = data["gcp"] + if not isinstance(resource, str): + raise ValueError( + f"CMEK gcp resource must be a string, got: {type(resource)}" + ) + return cls.gcp(resource) + raise ValueError(f"Unsupported or missing CMEK provider in data: {data}") + + +# Index Type Classes + + +@dataclass +class FtsIndexType: + enabled: bool + config: FtsIndexConfig + + +@dataclass +class VectorIndexType: + enabled: bool + config: VectorIndexConfig + + +@dataclass +class SparseVectorIndexType: + enabled: bool + config: SparseVectorIndexConfig + + +@dataclass +class StringInvertedIndexType: + enabled: bool + config: StringInvertedIndexConfig + + +@dataclass +class IntInvertedIndexType: + enabled: bool + config: IntInvertedIndexConfig + + +@dataclass +class FloatInvertedIndexType: + enabled: bool + config: FloatInvertedIndexConfig + + +@dataclass +class BoolInvertedIndexType: + enabled: bool + config: BoolInvertedIndexConfig + + +# Individual Value Type Classes + + +@dataclass +class StringValueType: + fts_index: Optional[FtsIndexType] = None + string_inverted_index: Optional[StringInvertedIndexType] = None + + +@dataclass +class FloatListValueType: + vector_index: Optional[VectorIndexType] = None + + +@dataclass +class SparseVectorValueType: + sparse_vector_index: Optional[SparseVectorIndexType] = None + + +@dataclass +class IntValueType: + int_inverted_index: Optional[IntInvertedIndexType] = None + + +@dataclass +class FloatValueType: + float_inverted_index: Optional[FloatInvertedIndexType] = None + + +@dataclass +class BoolValueType: + bool_inverted_index: Optional[BoolInvertedIndexType] = None + + +@dataclass +class ValueTypes: + string: Optional[StringValueType] = None + float_list: Optional[FloatListValueType] = None + sparse_vector: Optional[SparseVectorValueType] = None + int_value: Optional[IntValueType] = None + float_value: Optional[FloatValueType] = None + boolean: Optional[BoolValueType] = None + + +@dataclass +class Schema: + """Collection schema for indexing and encryption configuration. + + Attributes: + defaults: Default index configurations for each value type. + keys: Key-specific index overrides. + cmek: Optional customer-managed encryption key for collection data. + """ + + defaults: ValueTypes + keys: Dict[str, ValueTypes] + cmek: Optional[Cmek] = None + + def __init__(self) -> None: + # Initialize the dataclass fields first + self.defaults = ValueTypes() + self.keys: Dict[str, ValueTypes] = {} + self.cmek: Optional[Cmek] = None + + # Populate with sensible defaults automatically + self._initialize_defaults() + self._initialize_keys() + + def create_index( + self, + config: Optional[IndexConfig] = None, + key: Optional[Union[str, "Key"]] = None, + ) -> "Schema": + """Create an index configuration.""" + # Convert Key to string if provided + from chromadb.execution.expression.operator import Key as KeyType + + if key is not None and isinstance(key, KeyType): + key = key.name + + # Disallow config=None and key=None - too dangerous + if config is None and key is None: + raise ValueError( + "Cannot enable all index types globally. Must specify either config or key." + ) + + # Disallow using special internal key #embedding + if key is not None and key == EMBEDDING_KEY: + raise ValueError( + f"Cannot create index on special key '{key}'. This key is managed automatically by the system. Invoke create_index(VectorIndexConfig(...)) without specifying a key to configure the vector index globally." + ) + + # Only allow #document with FtsIndexConfig + if key == DOCUMENT_KEY and not isinstance(config, FtsIndexConfig): + raise ValueError( + f"Cannot create index on special key '{key}' with this config. " + "Only FtsIndexConfig is allowed for #document." + ) + + # Disallow any key starting with # (except #document which allows FTS) + if key is not None and key.startswith("#") and key != DOCUMENT_KEY: + raise ValueError( + "key cannot begin with '#'. " + "Keys starting with '#' are reserved for system use." + ) + + # Special handling for vector index + if isinstance(config, VectorIndexConfig): + if key is None: + # Allow setting vector config globally - it applies to defaults and #embedding + # but doesn't change enabled state (vector index is always enabled on #embedding) + self._set_vector_index_config(config) + return self + else: + # Disallow vector index on any custom key + raise ValueError( + "Vector index cannot be enabled on specific keys. Use create_index(config=VectorIndexConfig(...)) without specifying a key to configure the vector index globally." + ) + + # FTS index is only allowed on #document key + if isinstance(config, FtsIndexConfig) and key != DOCUMENT_KEY: + raise ValueError( + "FTS index can only be enabled on #document key. " + "Use create_index(config=FtsIndexConfig(), key='#document')" + ) + + # Disallow sparse vector index without a specific key + if isinstance(config, SparseVectorIndexConfig) and key is None: + raise ValueError( + "Sparse vector index must be created on a specific key. " + "Please specify a key using: create_index(config=SparseVectorIndexConfig(...), key='your_key')" + ) + + # TODO: Consider removing this check in the future to allow enabling all indexes for a key + # Disallow enabling all index types for a key (config=None, key="some_key") + if config is None and key is not None: + raise ValueError( + f"Cannot enable all index types for key '{key}'. Please specify a specific index configuration." + ) + + # Case 1: config is not None and key is None - enable specific index type globally + if config is not None and key is None: + self._set_index_in_defaults(config, enabled=True) + + # Case 2: config is None and key is not None - enable all index types for that key + elif config is None and key is not None: + self._enable_all_indexes_for_key(key) + + # Case 3: config is not None and key is not None - enable specific index type for that key + elif config is not None and key is not None: + self._set_index_for_key(key, config, enabled=True) + + return self + + def delete_index( + self, + config: Optional[IndexConfig] = None, + key: Optional[Union[str, "Key"]] = None, + ) -> "Schema": + """Disable an index configuration (set enabled=False).""" + # Convert Key to string if provided + from chromadb.execution.expression.operator import Key as KeyType + + if key is not None and isinstance(key, KeyType): + key = key.name + + # Case 1: Both config and key are None - fail the request + if config is None and key is None: + raise ValueError( + "Cannot disable all indexes. Must specify either config or key." + ) + + # Disallow using special internal key #embedding + if key is not None and key == EMBEDDING_KEY: + raise ValueError("Cannot modify #embedding. Currently not supported") + + # Only allow #document with FtsIndexConfig (to disable FTS) + if key == DOCUMENT_KEY and not isinstance(config, FtsIndexConfig): + raise ValueError( + f"Cannot delete index on special key '{key}' with this config. " + "Only FtsIndexConfig is allowed for #document." + ) + + # Disallow any key starting with # (except #document which allows FTS deletion) + if key is not None and key.startswith("#") and key != DOCUMENT_KEY: + raise ValueError( + "key cannot begin with '#'. " + "Keys starting with '#' are reserved for system use." + ) + + # TODO: Consider removing these checks in the future to allow disabling vector and sparse vector indexes + # Temporarily disallow deleting vector index (both globally and per-key) + if isinstance(config, VectorIndexConfig): + raise ValueError("Deleting vector index is not currently supported.") + + # Temporarily disallow deleting sparse vector index (both globally and per-key) + if isinstance(config, SparseVectorIndexConfig): + raise ValueError("Deleting sparse vector index is not currently supported.") + + # FTS deletion is only allowed on #document key + if isinstance(config, FtsIndexConfig) and key != DOCUMENT_KEY: + raise ValueError("Deleting FTS index is only supported on #document key.") + + # TODO: Consider removing this check in the future to allow disabling all indexes for a key + # Disallow disabling all index types for a key (config=None, key="some_key") + if key is not None and config is None: + raise ValueError( + f"Cannot disable all index types for key '{key}'. Please specify a specific index configuration." + ) + + # Case 2: key is not None and config is None - disable all possible index types for that key + if key is not None and config is None: + self._disable_all_indexes_for_key(key) + + # Case 3: key is not None and config is not None - disable specific index for that key + elif key is not None and config is not None: + self._set_index_for_key(key, config, enabled=False) + + # Case 4: key is None and config is not None - disable specific index globally + elif key is None and config is not None: + self._set_index_in_defaults(config, enabled=False) + + return self + + def set_cmek(self, cmek: Optional[Cmek]) -> "Schema": + """Set customer-managed encryption key for the collection (fluent interface). + + Args: + cmek: Customer-managed encryption key configuration, or None to remove CMEK + + Returns: + Self for method chaining + + Example: + >>> schema = Schema().set_cmek( + ... Cmek.gcp("projects/my-project/locations/us/keyRings/my-ring/cryptoKeys/my-key") + ... ) + """ + self.cmek = cmek + return self + + def _get_config_class_name(self, config: IndexConfig) -> str: + """Get the class name for a config.""" + return config.__class__.__name__ + + def _set_vector_index_config(self, config: VectorIndexConfig) -> None: + """ + Set vector index config globally and on #embedding key. + This updates the config but preserves the enabled state. + Vector index is always enabled on #embedding, disabled in defaults. + Note: source_key on #embedding is always preserved as "#document". + """ + # Update the config in defaults (preserve enabled=False) + current_enabled = self.defaults.float_list.vector_index.enabled # type: ignore[union-attr] + self.defaults.float_list.vector_index = VectorIndexType( + enabled=current_enabled, config=config + ) # type: ignore[union-attr] + + # Update the config on #embedding key (preserve enabled=True and source_key="#document") + current_enabled = self.keys[EMBEDDING_KEY].float_list.vector_index.enabled # type: ignore[union-attr] + current_source_key = self.keys[ + EMBEDDING_KEY + ].float_list.vector_index.config.source_key # type: ignore[union-attr] + + # Create a new config with user settings but preserve the original source_key + embedding_config = VectorIndexConfig( + space=config.space, + embedding_function=config.embedding_function, + hnsw=config.hnsw, + spann=config.spann, + source_key=current_source_key, # Preserve original source_key (should be "#document") + ) + self.keys[EMBEDDING_KEY].float_list.vector_index = VectorIndexType( + enabled=current_enabled, config=embedding_config + ) # type: ignore[union-attr] + + def _set_index_in_defaults(self, config: IndexConfig, enabled: bool) -> None: + """Set an index configuration in the defaults.""" + config_name = self._get_config_class_name(config) + + if config_name == "FtsIndexConfig": + if self.defaults.string is None: + self.defaults.string = StringValueType() + self.defaults.string.fts_index = FtsIndexType( + enabled=enabled, config=cast(FtsIndexConfig, config) + ) + + elif config_name == "StringInvertedIndexConfig": + if self.defaults.string is None: + self.defaults.string = StringValueType() + self.defaults.string.string_inverted_index = StringInvertedIndexType( + enabled=enabled, config=cast(StringInvertedIndexConfig, config) + ) + + elif config_name == "VectorIndexConfig": + if self.defaults.float_list is None: + self.defaults.float_list = FloatListValueType() + self.defaults.float_list.vector_index = VectorIndexType( + enabled=enabled, config=cast(VectorIndexConfig, config) + ) + + elif config_name == "SparseVectorIndexConfig": + if self.defaults.sparse_vector is None: + self.defaults.sparse_vector = SparseVectorValueType() + self.defaults.sparse_vector.sparse_vector_index = SparseVectorIndexType( + enabled=enabled, config=cast(SparseVectorIndexConfig, config) + ) + + elif config_name == "IntInvertedIndexConfig": + if self.defaults.int_value is None: + self.defaults.int_value = IntValueType() + self.defaults.int_value.int_inverted_index = IntInvertedIndexType( + enabled=enabled, config=cast(IntInvertedIndexConfig, config) + ) + + elif config_name == "FloatInvertedIndexConfig": + if self.defaults.float_value is None: + self.defaults.float_value = FloatValueType() + self.defaults.float_value.float_inverted_index = FloatInvertedIndexType( + enabled=enabled, config=cast(FloatInvertedIndexConfig, config) + ) + + elif config_name == "BoolInvertedIndexConfig": + if self.defaults.boolean is None: + self.defaults.boolean = BoolValueType() + self.defaults.boolean.bool_inverted_index = BoolInvertedIndexType( + enabled=enabled, config=cast(BoolInvertedIndexConfig, config) + ) + + def _validate_single_sparse_vector_index(self, key: str) -> None: + """ + Validate that only one sparse vector index is enabled per collection. + + Raises ValueError if another key already has a sparse vector index enabled. + """ + for existing_key, value_types in self.keys.items(): + if existing_key == key: + continue # Skip the current key being updated + if value_types.sparse_vector is not None: + if value_types.sparse_vector.sparse_vector_index is not None: + if value_types.sparse_vector.sparse_vector_index.enabled: + raise ValueError( + f"Cannot enable sparse vector index on key '{key}'. " + f"A sparse vector index is already enabled on key '{existing_key}'. " + f"Only one sparse vector index is allowed per collection." + ) + + def _validate_sparse_vector_config(self, config: SparseVectorIndexConfig) -> None: + """ + Validate that if source_key is provided then embedding_function is also provided + since there is no default embedding function. Raises ValueError otherwise. + """ + if config.source_key is not None and config.embedding_function is None: + raise ValueError( + f"If source_key is provided then embedding_function must also be provided " + f"since there is no default embedding function. Config: {config}" + ) + + def _set_index_for_key(self, key: str, config: IndexConfig, enabled: bool) -> None: + """Set an index configuration for a specific key.""" + config_name = self._get_config_class_name(config) + + # Validate sparse vector index - only one is allowed per collection + # Do this BEFORE creating the key entry + if config_name == "SparseVectorIndexConfig" and enabled: + self._validate_single_sparse_vector_index(key) + self._validate_sparse_vector_config(cast(SparseVectorIndexConfig, config)) + + if key not in self.keys: + self.keys[key] = ValueTypes() + + if config_name == "FtsIndexConfig": + if self.keys[key].string is None: + self.keys[key].string = StringValueType() + self.keys[key].string.fts_index = FtsIndexType( + enabled=enabled, config=cast(FtsIndexConfig, config) + ) # type: ignore[union-attr] + + elif config_name == "StringInvertedIndexConfig": + if self.keys[key].string is None: + self.keys[key].string = StringValueType() + self.keys[key].string.string_inverted_index = StringInvertedIndexType( + enabled=enabled, config=cast(StringInvertedIndexConfig, config) + ) # type: ignore[union-attr] + + elif config_name == "VectorIndexConfig": + if self.keys[key].float_list is None: + self.keys[key].float_list = FloatListValueType() + self.keys[key].float_list.vector_index = VectorIndexType( + enabled=enabled, config=cast(VectorIndexConfig, config) + ) # type: ignore[union-attr] + + elif config_name == "SparseVectorIndexConfig": + if self.keys[key].sparse_vector is None: + self.keys[key].sparse_vector = SparseVectorValueType() + self.keys[key].sparse_vector.sparse_vector_index = SparseVectorIndexType( + enabled=enabled, config=cast(SparseVectorIndexConfig, config) + ) # type: ignore[union-attr] + + elif config_name == "IntInvertedIndexConfig": + if self.keys[key].int_value is None: + self.keys[key].int_value = IntValueType() + self.keys[key].int_value.int_inverted_index = IntInvertedIndexType( + enabled=enabled, config=cast(IntInvertedIndexConfig, config) + ) # type: ignore[union-attr] + + elif config_name == "FloatInvertedIndexConfig": + if self.keys[key].float_value is None: + self.keys[key].float_value = FloatValueType() + self.keys[key].float_value.float_inverted_index = FloatInvertedIndexType( + enabled=enabled, config=cast(FloatInvertedIndexConfig, config) + ) # type: ignore[union-attr] + + elif config_name == "BoolInvertedIndexConfig": + if self.keys[key].boolean is None: + self.keys[key].boolean = BoolValueType() + self.keys[key].boolean.bool_inverted_index = BoolInvertedIndexType( + enabled=enabled, config=cast(BoolInvertedIndexConfig, config) + ) # type: ignore[union-attr] + + def _enable_all_indexes_for_key(self, key: str) -> None: + """Enable all possible index types for a specific key.""" + if key not in self.keys: + self.keys[key] = ValueTypes() + + self._validate_single_sparse_vector_index(key) + + # Enable all index types with default configs + self.keys[key].string = StringValueType( + fts_index=FtsIndexType(enabled=True, config=FtsIndexConfig()), + string_inverted_index=StringInvertedIndexType( + enabled=True, config=StringInvertedIndexConfig() + ), + ) + self.keys[key].float_list = FloatListValueType( + vector_index=VectorIndexType(enabled=True, config=VectorIndexConfig()) + ) + self.keys[key].sparse_vector = SparseVectorValueType( + sparse_vector_index=SparseVectorIndexType( + enabled=True, config=SparseVectorIndexConfig() + ) + ) + self.keys[key].int_value = IntValueType( + int_inverted_index=IntInvertedIndexType( + enabled=True, config=IntInvertedIndexConfig() + ) + ) + self.keys[key].float_value = FloatValueType( + float_inverted_index=FloatInvertedIndexType( + enabled=True, config=FloatInvertedIndexConfig() + ) + ) + self.keys[key].boolean = BoolValueType( + bool_inverted_index=BoolInvertedIndexType( + enabled=True, config=BoolInvertedIndexConfig() + ) + ) + + def _disable_all_indexes_for_key(self, key: str) -> None: + """Disable all possible index types for a specific key.""" + if key not in self.keys: + self.keys[key] = ValueTypes() + + # Disable all index types with default configs + self.keys[key].string = StringValueType( + fts_index=FtsIndexType(enabled=False, config=FtsIndexConfig()), + string_inverted_index=StringInvertedIndexType( + enabled=False, config=StringInvertedIndexConfig() + ), + ) + self.keys[key].float_list = FloatListValueType( + vector_index=VectorIndexType(enabled=False, config=VectorIndexConfig()) + ) + self.keys[key].sparse_vector = SparseVectorValueType( + sparse_vector_index=SparseVectorIndexType( + enabled=False, config=SparseVectorIndexConfig() + ) + ) + self.keys[key].int_value = IntValueType( + int_inverted_index=IntInvertedIndexType( + enabled=False, config=IntInvertedIndexConfig() + ) + ) + self.keys[key].float_value = FloatValueType( + float_inverted_index=FloatInvertedIndexType( + enabled=False, config=FloatInvertedIndexConfig() + ) + ) + self.keys[key].boolean = BoolValueType( + bool_inverted_index=BoolInvertedIndexType( + enabled=False, config=BoolInvertedIndexConfig() + ) + ) + + def _initialize_defaults(self) -> None: + """Initialize defaults with base structure and standard configuration.""" + # Initialize all value types with default configurations + self.defaults.string = StringValueType( + fts_index=FtsIndexType( + enabled=False, config=FtsIndexConfig() + ), # Disabled for performance + string_inverted_index=StringInvertedIndexType( + enabled=True, config=StringInvertedIndexConfig() + ), + ) + + self.defaults.float_list = FloatListValueType( + vector_index=VectorIndexType( + enabled=False, config=VectorIndexConfig() + ) # Disabled by default + ) + + self.defaults.sparse_vector = SparseVectorValueType( + sparse_vector_index=SparseVectorIndexType( + enabled=False, config=SparseVectorIndexConfig() + ) # Disabled for performance + ) + + self.defaults.int_value = IntValueType( + int_inverted_index=IntInvertedIndexType( + enabled=True, config=IntInvertedIndexConfig() + ) + ) + + self.defaults.float_value = FloatValueType( + float_inverted_index=FloatInvertedIndexType( + enabled=True, config=FloatInvertedIndexConfig() + ) + ) + + self.defaults.boolean = BoolValueType( + bool_inverted_index=BoolInvertedIndexType( + enabled=True, config=BoolInvertedIndexConfig() + ) + ) + + def _initialize_keys(self) -> None: + """Initialize key-specific index overrides.""" + # Enable full-text search for document content + self.keys[DOCUMENT_KEY] = ValueTypes( + string=StringValueType( + fts_index=FtsIndexType(enabled=True, config=FtsIndexConfig()), + string_inverted_index=StringInvertedIndexType( + enabled=False, config=StringInvertedIndexConfig() + ), + ) + ) + + # Enable vector index for embeddings with document source reference + vector_config = VectorIndexConfig(source_key=DOCUMENT_KEY) + self.keys[EMBEDDING_KEY] = ValueTypes( + float_list=FloatListValueType( + vector_index=VectorIndexType(enabled=True, config=vector_config) + ) + ) + + def serialize_to_json(self) -> Dict[str, Any]: + """Convert Schema to a JSON-serializable dict for transmission over the wire.""" + # Convert defaults to JSON format + defaults_json = self._serialize_value_types(self.defaults) + + # Convert key overrides to JSON format + keys_json: Dict[str, Dict[str, Any]] = {} + for key, value_types in self.keys.items(): + keys_json[key] = self._serialize_value_types(value_types) + + result: Dict[str, Any] = {"defaults": defaults_json, "keys": keys_json} + + # Add CMEK if present + if self.cmek is not None: + result["cmek"] = self.cmek.to_dict() + + return result + + @classmethod + def deserialize_from_json(cls, json_data: Dict[str, Any]) -> "Schema": + """Create Schema from JSON-serialized data.""" + # Create empty instance + instance = cls.__new__(cls) + + # Deserialize and set the components + instance.defaults = cls._deserialize_value_types(json_data.get("defaults", {})) + instance.keys = {} + for key, value_types_json in json_data.get("keys", {}).items(): + instance.keys[key] = cls._deserialize_value_types(value_types_json) + + # Deserialize CMEK if present + instance.cmek = None + if "cmek" in json_data and json_data["cmek"] is not None: + instance.cmek = Cmek.from_dict(json_data["cmek"]) + + return instance + + def _serialize_value_types(self, value_types: ValueTypes) -> Dict[str, Any]: + """Convert a ValueTypes object to JSON-serializable format.""" + result: Dict[str, Any] = {} + + # Serialize each value type if it exists + if value_types.string is not None: + result[STRING_VALUE_NAME] = self._serialize_string_value_type( + value_types.string + ) + + if value_types.float_list is not None: + result[FLOAT_LIST_VALUE_NAME] = self._serialize_float_list_value_type( + value_types.float_list + ) + + if value_types.sparse_vector is not None: + result[SPARSE_VECTOR_VALUE_NAME] = self._serialize_sparse_vector_value_type( + value_types.sparse_vector + ) + + if value_types.int_value is not None: + result[INT_VALUE_NAME] = self._serialize_int_value_type( + value_types.int_value + ) + + if value_types.float_value is not None: + result[FLOAT_VALUE_NAME] = self._serialize_float_value_type( + value_types.float_value + ) + + if value_types.boolean is not None: + result[BOOL_VALUE_NAME] = self._serialize_bool_value_type( + value_types.boolean + ) + + return result + + def _serialize_string_value_type( + self, string_type: StringValueType + ) -> Dict[str, Any]: + """Serialize StringValueType to JSON format.""" + result: Dict[str, Any] = {} + + if string_type.fts_index is not None: + result[FTS_INDEX_NAME] = { + "enabled": string_type.fts_index.enabled, + "config": self._serialize_config(string_type.fts_index.config), + } + + if string_type.string_inverted_index is not None: + result[STRING_INVERTED_INDEX_NAME] = { + "enabled": string_type.string_inverted_index.enabled, + "config": self._serialize_config( + string_type.string_inverted_index.config + ), + } + + return result + + def _serialize_float_list_value_type( + self, float_list_type: FloatListValueType + ) -> Dict[str, Any]: + """Serialize FloatListValueType to JSON format.""" + result: Dict[str, Any] = {} + + if float_list_type.vector_index is not None: + result[VECTOR_INDEX_NAME] = { + "enabled": float_list_type.vector_index.enabled, + "config": self._serialize_config(float_list_type.vector_index.config), + } + + return result + + def _serialize_sparse_vector_value_type( + self, sparse_vector_type: SparseVectorValueType + ) -> Dict[str, Any]: + """Serialize SparseVectorValueType to JSON format.""" + result: Dict[str, Any] = {} + + if sparse_vector_type.sparse_vector_index is not None: + result[SPARSE_VECTOR_INDEX_NAME] = { + "enabled": sparse_vector_type.sparse_vector_index.enabled, + "config": self._serialize_config( + sparse_vector_type.sparse_vector_index.config + ), + } + + return result + + def _serialize_int_value_type(self, int_type: IntValueType) -> Dict[str, Any]: + """Serialize IntValueType to JSON format.""" + result: Dict[str, Any] = {} + + if int_type.int_inverted_index is not None: + result[INT_INVERTED_INDEX_NAME] = { + "enabled": int_type.int_inverted_index.enabled, + "config": self._serialize_config(int_type.int_inverted_index.config), + } + + return result + + def _serialize_float_value_type(self, float_type: FloatValueType) -> Dict[str, Any]: + """Serialize FloatValueType to JSON format.""" + result: Dict[str, Any] = {} + + if float_type.float_inverted_index is not None: + result[FLOAT_INVERTED_INDEX_NAME] = { + "enabled": float_type.float_inverted_index.enabled, + "config": self._serialize_config( + float_type.float_inverted_index.config + ), + } + + return result + + def _serialize_bool_value_type(self, bool_type: BoolValueType) -> Dict[str, Any]: + """Serialize BoolValueType to JSON format.""" + result: Dict[str, Any] = {} + + if bool_type.bool_inverted_index is not None: + result[BOOL_INVERTED_INDEX_NAME] = { + "enabled": bool_type.bool_inverted_index.enabled, + "config": self._serialize_config(bool_type.bool_inverted_index.config), + } + + return result + + def _serialize_config(self, config: IndexConfig) -> Dict[str, Any]: + """Serialize config object to JSON-serializable dictionary.""" + # All IndexConfig types are Pydantic models, so use model_dump + config_dict = config.model_dump(exclude_none=True) + + # Handle embedding function serialization for vector configs + if isinstance(config, VectorIndexConfig): + if hasattr(config, "embedding_function"): + embedding_func = getattr(config, "embedding_function", None) + if embedding_func is None: + config_dict["embedding_function"] = {"type": "legacy"} + else: + try: + # Cast to EmbeddingFunction type to access methods + embedding_func = cast(EmbeddingFunction, embedding_func) # type: ignore + if embedding_func.is_legacy(): + config_dict["embedding_function"] = {"type": "legacy"} + else: + if hasattr(embedding_func, "validate_config"): + embedding_func.validate_config( + embedding_func.get_config() + ) + config_dict["embedding_function"] = { + "name": embedding_func.name(), + "type": "known", + "config": embedding_func.get_config(), + } + + # Handle space resolution from embedding function + if hasattr(config, "space") and config.space is None: + config_dict["space"] = embedding_func.default_space() + elif hasattr(config, "space") and config.space is not None: + if ( + config.space + not in embedding_func.supported_spaces() + ): + warnings.warn( + f"space {config.space} is not supported by {embedding_func.name()}. Supported spaces: {embedding_func.supported_spaces()}", + UserWarning, + stacklevel=2, + ) + except Exception: + config_dict["embedding_function"] = {"type": "legacy"} + + elif isinstance(config, SparseVectorIndexConfig): + if hasattr(config, "embedding_function"): + embedding_func = getattr(config, "embedding_function", None) + if embedding_func is None: + config_dict["embedding_function"] = {"type": "unknown"} + else: + embedding_func = cast(SparseEmbeddingFunction, embedding_func) # type: ignore + if hasattr(embedding_func, "validate_config"): + embedding_func.validate_config(embedding_func.get_config()) + config_dict["embedding_function"] = { + "name": embedding_func.name(), + "type": "known", + "config": embedding_func.get_config(), + } + + return config_dict + + @classmethod + def _deserialize_value_types(cls, value_types_json: Dict[str, Any]) -> ValueTypes: + """Deserialize ValueTypes from JSON format.""" + result = ValueTypes() + + # Deserialize each value type if present + if STRING_VALUE_NAME in value_types_json: + result.string = cls._deserialize_string_value_type( + value_types_json[STRING_VALUE_NAME] + ) + + if FLOAT_LIST_VALUE_NAME in value_types_json: + result.float_list = cls._deserialize_float_list_value_type( + value_types_json[FLOAT_LIST_VALUE_NAME] + ) + + if SPARSE_VECTOR_VALUE_NAME in value_types_json: + result.sparse_vector = cls._deserialize_sparse_vector_value_type( + value_types_json[SPARSE_VECTOR_VALUE_NAME] + ) + + if INT_VALUE_NAME in value_types_json: + result.int_value = cls._deserialize_int_value_type( + value_types_json[INT_VALUE_NAME] + ) + + if FLOAT_VALUE_NAME in value_types_json: + result.float_value = cls._deserialize_float_value_type( + value_types_json[FLOAT_VALUE_NAME] + ) + + if BOOL_VALUE_NAME in value_types_json: + result.boolean = cls._deserialize_bool_value_type( + value_types_json[BOOL_VALUE_NAME] + ) + + return result + + @classmethod + def _deserialize_string_value_type( + cls, string_json: Dict[str, Any] + ) -> StringValueType: + """Deserialize StringValueType from JSON format.""" + fts_index = None + string_inverted_index = None + + if FTS_INDEX_NAME in string_json: + fts_index_data = string_json[FTS_INDEX_NAME] + fts_enabled = fts_index_data.get("enabled", True) + fts_config_data = fts_index_data.get("config", {}) + fts_config = FtsIndexConfig(**fts_config_data) + fts_index = FtsIndexType(enabled=fts_enabled, config=fts_config) + + if STRING_INVERTED_INDEX_NAME in string_json: + string_index_data = string_json[STRING_INVERTED_INDEX_NAME] + string_enabled = string_index_data.get("enabled", True) + string_config_data = string_index_data.get("config", {}) + string_config = StringInvertedIndexConfig(**string_config_data) + string_inverted_index = StringInvertedIndexType( + enabled=string_enabled, config=string_config + ) + + return StringValueType( + fts_index=fts_index, string_inverted_index=string_inverted_index + ) + + @classmethod + def _deserialize_float_list_value_type( + cls, float_list_json: Dict[str, Any] + ) -> FloatListValueType: + """Deserialize FloatListValueType from JSON format.""" + vector_index = None + + if VECTOR_INDEX_NAME in float_list_json: + index_data = float_list_json[VECTOR_INDEX_NAME] + enabled = index_data.get("enabled", True) + config_data = deepcopy(index_data.get("config", {})) + + # Handle embedding function deserialization + if "embedding_function" in config_data: + ef_config = config_data["embedding_function"] + if ef_config.get("type") == "legacy": + config_data["embedding_function"] = None + else: + try: + from chromadb.utils.embedding_functions import ( + known_embedding_functions, + ) + + ef_name = ef_config["name"] + ef = known_embedding_functions[ef_name] + config_data["embedding_function"] = ef.build_from_config( + ef_config["config"] + ) + + # Handle space deserialization + if "space" not in config_data or config_data["space"] is None: + config_data["space"] = config_data[ + "embedding_function" + ].default_space() + except Exception as e: + warnings.warn( + f"Could not reconstruct embedding function {ef_config.get('name', 'unknown')}: {e}. Setting to None.", + UserWarning, + stacklevel=2, + ) + config_data["embedding_function"] = None + + config = VectorIndexConfig(**config_data) + vector_index = VectorIndexType(enabled=enabled, config=config) + + return FloatListValueType(vector_index=vector_index) + + @classmethod + def _deserialize_sparse_vector_value_type( + cls, sparse_vector_json: Dict[str, Any] + ) -> SparseVectorValueType: + """Deserialize SparseVectorValueType from JSON format.""" + sparse_vector_index = None + + if SPARSE_VECTOR_INDEX_NAME in sparse_vector_json: + index_data = sparse_vector_json[SPARSE_VECTOR_INDEX_NAME] + enabled = index_data.get("enabled", True) + config_data = deepcopy(index_data.get("config", {})) + + # Handle embedding function deserialization + if "embedding_function" in config_data: + ef_config = config_data["embedding_function"] + if ( + ef_config.get("type") == "unknown" + or ef_config.get("type") == "legacy" + ): + config_data["embedding_function"] = None + else: + try: + from chromadb.utils.embedding_functions import ( + sparse_known_embedding_functions, + ) + + ef_name = ef_config["name"] + ef = sparse_known_embedding_functions[ef_name] + config_data["embedding_function"] = ef.build_from_config( + ef_config["config"] + ) + except Exception as e: + warnings.warn( + f"Could not reconstruct sparse embedding function {ef_config.get('name', 'unknown')}: {e}. Setting to None.", + UserWarning, + stacklevel=2, + ) + config_data["embedding_function"] = None + + config = SparseVectorIndexConfig(**config_data) + sparse_vector_index = SparseVectorIndexType(enabled=enabled, config=config) + + return SparseVectorValueType(sparse_vector_index=sparse_vector_index) + + @classmethod + def _deserialize_int_value_type(cls, int_json: Dict[str, Any]) -> IntValueType: + """Deserialize IntValueType from JSON format.""" + int_inverted_index = None + + if INT_INVERTED_INDEX_NAME in int_json: + index_data = int_json[INT_INVERTED_INDEX_NAME] + enabled = index_data.get("enabled", True) + config_data = index_data.get("config", {}) + config = IntInvertedIndexConfig(**config_data) + int_inverted_index = IntInvertedIndexType(enabled=enabled, config=config) + + return IntValueType(int_inverted_index=int_inverted_index) + + @classmethod + def _deserialize_float_value_type( + cls, float_json: Dict[str, Any] + ) -> FloatValueType: + """Deserialize FloatValueType from JSON format.""" + float_inverted_index = None + + if FLOAT_INVERTED_INDEX_NAME in float_json: + index_data = float_json[FLOAT_INVERTED_INDEX_NAME] + enabled = index_data.get("enabled", True) + config_data = index_data.get("config", {}) + config = FloatInvertedIndexConfig(**config_data) + float_inverted_index = FloatInvertedIndexType( + enabled=enabled, config=config + ) + + return FloatValueType(float_inverted_index=float_inverted_index) + + @classmethod + def _deserialize_bool_value_type(cls, bool_json: Dict[str, Any]) -> BoolValueType: + """Deserialize BoolValueType from JSON format.""" + bool_inverted_index = None + + if BOOL_INVERTED_INDEX_NAME in bool_json: + index_data = bool_json[BOOL_INVERTED_INDEX_NAME] + enabled = index_data.get("enabled", True) + config_data = index_data.get("config", {}) + config = BoolInvertedIndexConfig(**config_data) + bool_inverted_index = BoolInvertedIndexType(enabled=enabled, config=config) + + return BoolValueType(bool_inverted_index=bool_inverted_index) diff --git a/python/user_packages/Python313/site-packages/chromadb/auth/__init__.py b/python/user_packages/Python313/site-packages/chromadb/auth/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..72c71e7454ea538fe763faec2fe5bc29f33d37d6 --- /dev/null +++ b/python/user_packages/Python313/site-packages/chromadb/auth/__init__.py @@ -0,0 +1,237 @@ +from __future__ import annotations + +from abc import abstractmethod +from enum import Enum +from typing import ( + Any, + List, + Optional, + Dict, + Tuple, + TypeVar, +) +from dataclasses import dataclass + +from pydantic import SecretStr + +from chromadb.config import ( + Component, + System, +) + +T = TypeVar("T") +S = TypeVar("S") + + +class AuthError(Exception): + pass + + +ClientAuthHeaders = Dict[str, SecretStr] + + +class ClientAuthProvider(Component): + """ + ClientAuthProvider is responsible for providing authentication headers for + client requests. Client implementations (in our case, just the FastAPI + client) must inject these headers into their requests. + """ + + def __init__(self, system: System) -> None: + super().__init__(system) + + @abstractmethod + def authenticate(self) -> ClientAuthHeaders: + pass + + +@dataclass +class UserIdentity: + """ + UserIdentity represents the identity of a user. In general, not all fields + will be populated, and the fields that are populated will depend on the + authentication provider. + + The idea is that the AuthenticationProvider is responsible for populating + _all_ information known about the user, and the AuthorizationProvider is + responsible for making decisions based on that information. + """ + + user_id: str + tenant: Optional[str] = None + databases: Optional[List[str]] = None + # This can be used for any additional auth context which needs to be + # propagated from the authentication provider to the authorization + # provider. + attributes: Optional[Dict[str, Any]] = None + + +class ServerAuthenticationProvider(Component): + """ + ServerAuthenticationProvider is responsible for authenticating requests. If + a ServerAuthenticationProvider is configured, it will be called by the + server to authenticate requests. If no ServerAuthenticationProvider is + configured, all requests will be authenticated. + + The ServerAuthenticationProvider should return a UserIdentity object if the + request is authenticated for use by the ServerAuthorizationProvider. + """ + + def __init__(self, system: System) -> None: + super().__init__(system) + self._ignore_auth_paths: Dict[ + str, List[str] + ] = system.settings.chroma_server_auth_ignore_paths + self.overwrite_singleton_tenant_database_access_from_auth = ( + system.settings.chroma_overwrite_singleton_tenant_database_access_from_auth + ) + + @abstractmethod + def authenticate_or_raise(self, headers: Dict[str, str]) -> UserIdentity: + pass + + def ignore_operation(self, verb: str, path: str) -> bool: + if ( + path in self._ignore_auth_paths.keys() + and verb.upper() in self._ignore_auth_paths[path] + ): + return True + return False + + def read_creds_or_creds_file(self) -> List[str]: + _creds_file = None + _creds = None + + if self._system.settings.chroma_server_authn_credentials_file: + _creds_file = str( + self._system.settings["chroma_server_authn_credentials_file"] + ) + if self._system.settings.chroma_server_authn_credentials: + _creds = str(self._system.settings["chroma_server_authn_credentials"]) + if not _creds_file and not _creds: + raise ValueError( + "No credentials file or credentials found in " + "[chroma_server_authn_credentials]." + ) + if _creds_file and _creds: + raise ValueError( + "Both credentials file and credentials found." + "Please provide only one." + ) + if _creds: + return [c for c in _creds.split("\n") if c] + elif _creds_file: + with open(_creds_file, "r") as f: + return f.readlines() + raise ValueError("Should never happen") + + def singleton_tenant_database_if_applicable( + self, user: Optional[UserIdentity] + ) -> Tuple[Optional[str], Optional[str]]: + """ + If settings.chroma_overwrite_singleton_tenant_database_access_from_auth + is False, this function always returns (None, None). + + If settings.chroma_overwrite_singleton_tenant_database_access_from_auth + is True, follows the following logic: + - If the user only has access to a single tenant, this function will + return that tenant as its first return value. + - If the user only has access to a single database, this function will + return that database as its second return value. If the user has + access to multiple tenants and/or databases, including "*", this + function will return None for the corresponding value(s). + - If the user has access to multiple tenants and/or databases this + function will return None for the corresponding value(s). + """ + if not self.overwrite_singleton_tenant_database_access_from_auth or not user: + return None, None + tenant = None + database = None + if user.tenant and user.tenant != "*": + tenant = user.tenant + if user.databases and len(user.databases) == 1 and user.databases[0] != "*": + database = user.databases[0] + return tenant, database + + +class AuthzAction(str, Enum): + """ + The set of actions that can be authorized by the authorization provider. + """ + + RESET = "system:reset" + CREATE_TENANT = "tenant:create_tenant" + GET_TENANT = "tenant:get_tenant" + CREATE_DATABASE = "db:create_database" + GET_DATABASE = "db:get_database" + DELETE_DATABASE = "db:delete_database" + LIST_DATABASES = "db:list_databases" + LIST_COLLECTIONS = "db:list_collections" + COUNT_COLLECTIONS = "db:count_collections" + CREATE_COLLECTION = "db:create_collection" + GET_OR_CREATE_COLLECTION = "db:get_or_create_collection" + GET_COLLECTION = "collection:get_collection" + DELETE_COLLECTION = "collection:delete_collection" + UPDATE_COLLECTION = "collection:update_collection" + ADD = "collection:add" + DELETE = "collection:delete" + GET = "collection:get" + QUERY = "collection:query" + COUNT = "collection:count" + UPDATE = "collection:update" + UPSERT = "collection:upsert" + + +@dataclass +class AuthzResource: + """ + The resource being accessed in an authorization request. + """ + + tenant: Optional[str] + database: Optional[str] + collection: Optional[str] + + +class ServerAuthorizationProvider(Component): + """ + ServerAuthorizationProvider is responsible for authorizing requests. If a + ServerAuthorizationProvider is configured, it will be called by the server + to authorize requests. If no ServerAuthorizationProvider is configured, all + requests will be authorized. + + ServerAuthorizationProvider should raise an exception if the request is not + authorized. + """ + + def __init__(self, system: System) -> None: + super().__init__(system) + + @abstractmethod + def authorize_or_raise( + self, user: UserIdentity, action: AuthzAction, resource: AuthzResource + ) -> None: + pass + + def read_config_or_config_file(self) -> List[str]: + _config_file = None + _config = None + if self._system.settings.chroma_server_authz_config_file: + _config_file = self._system.settings["chroma_server_authz_config_file"] + if self._system.settings.chroma_server_authz_config: + _config = str(self._system.settings["chroma_server_authz_config"]) + if not _config_file and not _config: + raise ValueError( + "No authz configuration file or authz configuration found." + ) + if _config_file and _config: + raise ValueError( + "Both authz configuration file and authz configuration found." + "Please provide only one." + ) + if _config: + return [c for c in _config.split("\n") if c] + elif _config_file: + with open(_config_file, "r") as f: + return f.readlines() + raise ValueError("Should never happen") diff --git a/python/user_packages/Python313/site-packages/chromadb/cli/__init__.py b/python/user_packages/Python313/site-packages/chromadb/cli/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/python/user_packages/Python313/site-packages/chromadb/cli/cli.py b/python/user_packages/Python313/site-packages/chromadb/cli/cli.py new file mode 100644 index 0000000000000000000000000000000000000000..9ec33d4d330d303e39b8403a1802bb3f31240a65 --- /dev/null +++ b/python/user_packages/Python313/site-packages/chromadb/cli/cli.py @@ -0,0 +1,56 @@ +import re +import sys + +import chromadb_rust_bindings +import requests +from packaging.version import parse + +import chromadb + + +def build_cli_args(**kwargs): + args = [] + for key, value in kwargs.items(): + if isinstance(value, bool): + if value: + args.append(f"--{key}") + elif value is not None: + args.extend([f"--{key}", str(value)]) + return args + + +def update(): + try: + url = f"https://api.github.com/repos/chroma-core/chroma/releases" + response = requests.get(url) + response.raise_for_status() + releases = response.json() + + version_pattern = re.compile(r'^\d+\.\d+\.\d+$') + numeric_releases = [r["tag_name"] for r in releases if version_pattern.fullmatch(r["tag_name"])] + + if not numeric_releases: + print("Couldn't fetch the latest Chroma version") + return + + latest = max(numeric_releases, key=parse) + if latest == chromadb.__version__: + print("Your Chroma version is up-to-date") + return + + print( + f"A new version of Chroma is available!\nIf you're using pip, run 'pip install --upgrade chromadb' to upgrade to version {latest}") + + except Exception as e: + print("Couldn't fetch the latest Chroma version") + + +def app(): + args = sys.argv + if ["chroma", "update"] in args: + update() + return + try: + chromadb_rust_bindings.cli(args) + except KeyboardInterrupt: + pass \ No newline at end of file diff --git a/python/user_packages/Python313/site-packages/chromadb/cli/utils.py b/python/user_packages/Python313/site-packages/chromadb/cli/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..41acfa0af13661b878617b84600095bf540c082e --- /dev/null +++ b/python/user_packages/Python313/site-packages/chromadb/cli/utils.py @@ -0,0 +1,40 @@ +from typing import Any, Dict + +import os +import yaml + + +def set_log_file_path( + log_config_path: str, new_filename: str = "chroma.log" +) -> Dict[str, Any]: + """This works with the standard log_config.yml file. + It will not work with custom log configs that may use different handlers""" + with open(f"{log_config_path}", "r") as file: + log_config = yaml.safe_load(file) + for handler in log_config["handlers"].values(): + if handler.get("class") == "logging.handlers.RotatingFileHandler": + handler["filename"] = new_filename + + return log_config + + +def get_directory_size(directory: str) -> int: + """Get the size of a directory in bytes""" + total = 0 + with os.scandir(directory) as it: + for entry in it: + if entry.is_file(): + total += entry.stat().st_size + elif entry.is_dir(): + total += get_directory_size(entry.path) + return total + + +# https://stackoverflow.com/a/1094933 +def sizeof_fmt(num: int, suffix: str = "B") -> str: + n: float = float(num) + for unit in ("", "Ki", "Mi", "Gi", "Ti", "Pi", "Ei", "Zi"): + if abs(n) < 1024.0: + return f"{n:3.1f}{unit}{suffix}" + n /= 1024.0 + return f"{n:.1f}Yi{suffix}" diff --git a/python/user_packages/Python313/site-packages/chromadb/db/__init__.py b/python/user_packages/Python313/site-packages/chromadb/db/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..f6d87beb49df2fdb5272133136346f1e3eec5220 --- /dev/null +++ b/python/user_packages/Python313/site-packages/chromadb/db/__init__.py @@ -0,0 +1,122 @@ +from abc import abstractmethod +from typing import List, Sequence, Optional, Tuple +from uuid import UUID +from chromadb.api.types import ( + Embeddings, + Documents, + IDs, + Metadatas, + Metadata, + Where, + WhereDocument, +) +from chromadb.config import Component + + +class DB(Component): + @abstractmethod + def create_collection( + self, + name: str, + metadata: Optional[Metadata] = None, + get_or_create: bool = False, + ) -> Sequence: # type: ignore + pass + + @abstractmethod + def get_collection(self, name: str) -> Sequence: # type: ignore + pass + + @abstractmethod + def list_collections( + self, limit: Optional[int] = None, offset: Optional[int] = None + ) -> Sequence: # type: ignore + pass + + @abstractmethod + def count_collections(self) -> int: + pass + + @abstractmethod + def update_collection( + self, + id: UUID, + new_name: Optional[str] = None, + new_metadata: Optional[Metadata] = None, + ) -> None: + pass + + @abstractmethod + def delete_collection(self, name: str) -> None: + pass + + @abstractmethod + def get_collection_uuid_from_name(self, collection_name: str) -> UUID: + pass + + @abstractmethod + def add( + self, + collection_uuid: UUID, + embeddings: Embeddings, + metadatas: Optional[Metadatas], + documents: Optional[Documents], + ids: List[str], + ) -> List[UUID]: + pass + + @abstractmethod + def get( + self, + where: Optional[Where] = None, + collection_name: Optional[str] = None, + collection_uuid: Optional[UUID] = None, + ids: Optional[IDs] = None, + limit: Optional[int] = None, + offset: Optional[int] = None, + where_document: Optional[WhereDocument] = None, + columns: Optional[List[str]] = None, + ) -> Sequence: # type: ignore + pass + + @abstractmethod + def update( + self, + collection_uuid: UUID, + ids: IDs, + embeddings: Optional[Embeddings] = None, + metadatas: Optional[Metadatas] = None, + documents: Optional[Documents] = None, + ) -> bool: + pass + + @abstractmethod + def count(self, collection_id: UUID) -> int: + pass + + @abstractmethod + def delete( + self, + where: Optional[Where] = None, + collection_uuid: Optional[UUID] = None, + ids: Optional[IDs] = None, + where_document: Optional[WhereDocument] = None, + ) -> None: + pass + + @abstractmethod + def get_nearest_neighbors( + self, + collection_uuid: UUID, + where: Optional[Where] = None, + embeddings: Optional[Embeddings] = None, + n_results: int = 10, + where_document: Optional[WhereDocument] = None, + ) -> Tuple[List[List[UUID]], List[List[float]]]: + pass + + @abstractmethod + def get_by_ids( + self, uuids: List[UUID], columns: Optional[List[str]] = None + ) -> Sequence: # type: ignore + pass diff --git a/python/user_packages/Python313/site-packages/chromadb/db/base.py b/python/user_packages/Python313/site-packages/chromadb/db/base.py new file mode 100644 index 0000000000000000000000000000000000000000..89866ccc14d97ef1012386f0f9517d377669635f --- /dev/null +++ b/python/user_packages/Python313/site-packages/chromadb/db/base.py @@ -0,0 +1,180 @@ +from typing import Any, Optional, Sequence, Tuple, Type +from types import TracebackType +from typing_extensions import Protocol, Self, Literal +from abc import ABC, abstractmethod +from threading import local +from overrides import override, EnforceOverrides +import pypika +import pypika.queries +from chromadb.config import System, Component +from uuid import UUID +from itertools import islice, count + + +class Cursor(Protocol): + """Reifies methods we use from a DBAPI2 Cursor since DBAPI2 is not typed.""" + + def execute(self, sql: str, params: Optional[Tuple[Any, ...]] = None) -> Self: + ... + + def executescript(self, script: str) -> Self: + ... + + def executemany( + self, sql: str, params: Optional[Sequence[Tuple[Any, ...]]] = None + ) -> Self: + ... + + def fetchone(self) -> Tuple[Any, ...]: + ... + + def fetchall(self) -> Sequence[Tuple[Any, ...]]: + ... + + +class TxWrapper(ABC, EnforceOverrides): + """Wrapper class for DBAPI 2.0 Connection objects, with which clients can implement transactions. + Makes two guarantees that basic DBAPI 2.0 connections do not: + + - __enter__ returns a Cursor object consistently (instead of a Connection like some do) + - Always re-raises an exception if one was thrown from the body + """ + + @abstractmethod + def __enter__(self) -> Cursor: + pass + + @abstractmethod + def __exit__( + self, + exc_type: Optional[Type[BaseException]], + exc_value: Optional[BaseException], + traceback: Optional[TracebackType], + ) -> Literal[False]: + pass + + +class SqlDB(Component): + """DBAPI 2.0 interface wrapper to ensure consistent behavior between implementations""" + + def __init__(self, system: System): + super().__init__(system) + + @abstractmethod + def tx(self) -> TxWrapper: + """Return a transaction wrapper""" + pass + + @staticmethod + @abstractmethod + def querybuilder() -> Type[pypika.Query]: + """Return a PyPika Query builder of an appropriate subtype for this database + implementation (see + https://pypika.readthedocs.io/en/latest/3_advanced.html#handling-different-database-platforms) + """ + pass + + @staticmethod + @abstractmethod + def parameter_format() -> str: + """Return the appropriate parameter format for this database implementation. + Will be called with str.format(i) where i is the numeric index of the parameter. + """ + pass + + @staticmethod + @abstractmethod + def uuid_to_db(uuid: Optional[UUID]) -> Optional[Any]: + """Convert a UUID to a value that can be passed to the DB driver""" + pass + + @staticmethod + @abstractmethod + def uuid_from_db(value: Optional[Any]) -> Optional[UUID]: + """Convert a value from the DB driver to a UUID""" + pass + + @staticmethod + @abstractmethod + def unique_constraint_error() -> Type[BaseException]: + """Return the exception type that the DB raises when a unique constraint is + violated""" + pass + + def param(self, idx: int) -> pypika.Parameter: + """Return a PyPika Parameter object for the given index""" + return pypika.Parameter(self.parameter_format().format(idx)) + + +_context = local() + + +class ParameterValue(pypika.Parameter): # type: ignore + """ + Wrapper class for PyPika paramters that allows the values for Parameters + to be expressed inline while building a query. See get_sql() for + detailed usage information. + """ + + def __init__(self, value: Any): + self.value = value + + @override + def get_sql(self, **kwargs: Any) -> str: + if isinstance(self.value, (list, tuple)): + _context.values.extend(self.value) + indexes = islice(_context.generator, len(self.value)) + placeholders = ", ".join(_context.formatstr.format(i) for i in indexes) + val = f"({placeholders})" + else: + _context.values.append(self.value) + val = _context.formatstr.format(next(_context.generator)) + + return str(val) + + +def get_sql( + query: pypika.queries.QueryBuilder, formatstr: str = "?" +) -> Tuple[str, Tuple[Any, ...]]: + """ + Wrapper for pypika's get_sql method that allows the values for Parameters + to be expressed inline while building a query, and that returns a tuple of the + SQL string and parameters. This makes it easier to construct complex queries + programmatically and automatically matches up the generated SQL with the required + parameter vector. + + Doing so requires using the ParameterValue class defined in this module instead + of the base pypika.Parameter class. + + Usage Example: + + q = ( + pypika.Query().from_("table") + .select("col1") + .where("col2"==ParameterValue("foo")) + .where("col3"==ParameterValue("bar")) + ) + + sql, params = get_sql(q) + + cursor.execute(sql, params) + + Note how it is not necessary to construct the parameter vector manually... it + will always be generated with the parameter values in the same order as emitted + SQL string. + + The format string should match the parameter format for the database being used. + It will be called with str.format(i) where i is the numeric index of the parameter. + For example, Postgres requires parameters like `:1`, `:2`, etc. so the format string + should be `":{}"`. + + See https://pypika.readthedocs.io/en/latest/2_tutorial.html#parametrized-queries for more + information on parameterized queries in PyPika. + """ + + _context.values = [] + _context.generator = count(1) + _context.formatstr = formatstr + sql = query.get_sql() + params = tuple(_context.values) + return sql, params diff --git a/python/user_packages/Python313/site-packages/chromadb/db/migrations.py b/python/user_packages/Python313/site-packages/chromadb/db/migrations.py new file mode 100644 index 0000000000000000000000000000000000000000..bac9beb6a61a969e26b988d59ef4eae156ba0a2e --- /dev/null +++ b/python/user_packages/Python313/site-packages/chromadb/db/migrations.py @@ -0,0 +1,276 @@ +import sys +from typing import Sequence +from typing_extensions import TypedDict, NotRequired +from importlib_resources.abc import Traversable +import re +import hashlib +from chromadb.db.base import SqlDB, Cursor +from abc import abstractmethod +from chromadb.config import System, Settings +from chromadb.telemetry.opentelemetry import ( + OpenTelemetryClient, + OpenTelemetryGranularity, + trace_method, +) + + +class MigrationFile(TypedDict): + path: NotRequired[Traversable] + dir: str + filename: str + version: int + scope: str + + +class Migration(MigrationFile): + hash: str + sql: str + + +class UninitializedMigrationsError(Exception): + def __init__(self) -> None: + super().__init__("Migrations have not been initialized") + + +class UnappliedMigrationsError(Exception): + def __init__(self, dir: str, version: int): + self.dir = dir + self.version = version + super().__init__( + f"Unapplied migrations in {dir}, starting with version {version}" + ) + + +class InconsistentVersionError(Exception): + def __init__(self, dir: str, db_version: int, source_version: int): + super().__init__( + f"Inconsistent migration versions in {dir}:" + + f"db version was {db_version}, source version was {source_version}." + + " Has the migration sequence been modified since being applied to the DB?" + ) + + +class InconsistentHashError(Exception): + def __init__(self, path: str, db_hash: str, source_hash: str): + super().__init__( + f"Inconsistent hashes in {path}:" + + f"db hash was {db_hash}, source has was {source_hash}." + + " Was the migration file modified after being applied to the DB?" + ) + + +class InvalidHashError(Exception): + def __init__(self, alg: str): + super().__init__(f"Invalid hash algorithm specified: {alg}") + + +class InvalidMigrationFilename(Exception): + pass + + +class MigratableDB(SqlDB): + """Simple base class for databases which support basic migrations. + + Migrations are SQL files stored as package resources and accessed via + importlib_resources. + + All migrations in the same directory are assumed to be dependent on previous + migrations in the same directory, where "previous" is defined on lexographical + ordering of filenames. + + Migrations have a ascending numeric version number and a hash of the file contents. + When migrations are applied, the hashes of previous migrations are checked to ensure + that the database is consistent with the source repository. If they are not, an + error is thrown and no migrations will be applied. + + Migration files must follow the naming convention: + ...sql, where is a 5-digit zero-padded + integer, is a short textual description, and is a short string + identifying the database implementation. + """ + + _settings: Settings + + def __init__(self, system: System) -> None: + self._settings = system.settings + self._opentelemetry_client = system.require(OpenTelemetryClient) + super().__init__(system) + + @staticmethod + @abstractmethod + def migration_scope() -> str: + """The database implementation to use for migrations (e.g, sqlite, pgsql)""" + pass + + @abstractmethod + def migration_dirs(self) -> Sequence[Traversable]: + """Directories containing the migration sequences that should be applied to this + DB.""" + pass + + @abstractmethod + def setup_migrations(self) -> None: + """Idempotently creates the migrations table""" + pass + + @abstractmethod + def migrations_initialized(self) -> bool: + """Return true if the migrations table exists""" + pass + + @abstractmethod + def db_migrations(self, dir: Traversable) -> Sequence[Migration]: + """Return a list of all migrations already applied to this database, from the + given source directory, in ascending order.""" + pass + + @abstractmethod + def apply_migration(self, cur: Cursor, migration: Migration) -> None: + """Apply a single migration to the database""" + pass + + def initialize_migrations(self) -> None: + """Initialize migrations for this DB""" + migrate = self._settings.require("migrations") + + if migrate == "validate": + self.validate_migrations() + + if migrate == "apply": + self.apply_migrations() + + @trace_method("MigratableDB.validate_migrations", OpenTelemetryGranularity.ALL) + def validate_migrations(self) -> None: + """Validate all migrations and throw an exception if there are any unapplied + migrations in the source repo.""" + if not self.migrations_initialized(): + raise UninitializedMigrationsError() + for dir in self.migration_dirs(): + db_migrations = self.db_migrations(dir) + source_migrations = find_migrations( + dir, + self.migration_scope(), + self._settings.require("migrations_hash_algorithm"), + ) + unapplied_migrations = verify_migration_sequence( + db_migrations, source_migrations + ) + if len(unapplied_migrations) > 0: + version = unapplied_migrations[0]["version"] + raise UnappliedMigrationsError(dir=dir.name, version=version) + + @trace_method("MigratableDB.apply_migrations", OpenTelemetryGranularity.ALL) + def apply_migrations(self) -> None: + """Validate existing migrations, and apply all new ones.""" + self.setup_migrations() + for dir in self.migration_dirs(): + db_migrations = self.db_migrations(dir) + source_migrations = find_migrations( + dir, + self.migration_scope(), + self._settings.require("migrations_hash_algorithm"), + ) + unapplied_migrations = verify_migration_sequence( + db_migrations, source_migrations + ) + with self.tx() as cur: + for migration in unapplied_migrations: + self.apply_migration(cur, migration) + + +# Format is -..sql +# e.g, 00001-users.sqlite.sql +filename_regex = re.compile(r"(\d+)-(.+)\.(.+)\.sql") + + +def _parse_migration_filename( + dir: str, filename: str, path: Traversable +) -> MigrationFile: + """Parse a migration filename into a MigrationFile object""" + match = filename_regex.match(filename) + if match is None: + raise InvalidMigrationFilename("Invalid migration filename: " + filename) + version, _, scope = match.groups() + return { + "path": path, + "dir": dir, + "filename": filename, + "version": int(version), + "scope": scope, + } + + +def verify_migration_sequence( + db_migrations: Sequence[Migration], + source_migrations: Sequence[Migration], +) -> Sequence[Migration]: + """Given a list of migrations already applied to a database, and a list of + migrations from the source code, validate that the applied migrations are correct + and match the expected migrations. + + Throws an exception if any migrations are missing, out of order, or if the source + hash does not match. + + Returns a list of all unapplied migrations, or an empty list if all migrations are + applied and the database is up to date.""" + + for db_migration, source_migration in zip(db_migrations, source_migrations): + if db_migration["version"] != source_migration["version"]: + raise InconsistentVersionError( + dir=db_migration["dir"], + db_version=db_migration["version"], + source_version=source_migration["version"], + ) + + if db_migration["hash"] != source_migration["hash"]: + raise InconsistentHashError( + path=db_migration["dir"] + "/" + db_migration["filename"], + db_hash=db_migration["hash"], + source_hash=source_migration["hash"], + ) + + return source_migrations[len(db_migrations) :] + + +def find_migrations( + dir: Traversable, scope: str, hash_alg: str = "md5" +) -> Sequence[Migration]: + """Return a list of all migration present in the given directory, in ascending + order. Filter by scope.""" + files = [ + _parse_migration_filename(dir.name, t.name, t) + for t in dir.iterdir() + if t.name.endswith(".sql") + ] + files = list(filter(lambda f: f["scope"] == scope, files)) + files = sorted(files, key=lambda f: f["version"]) + return [_read_migration_file(f, hash_alg) for f in files] + + +def _read_migration_file(file: MigrationFile, hash_alg: str) -> Migration: + """Read a migration file""" + if "path" not in file or not file["path"].is_file(): + raise FileNotFoundError( + f"No migration file found for dir {file['dir']} with filename {file['filename']} and scope {file['scope']} at version {file['version']}" + ) + sql = file["path"].read_text() + + if hash_alg == "md5": + hash = ( + hashlib.md5(sql.encode("utf-8"), usedforsecurity=False).hexdigest() + if sys.version_info >= (3, 9) + else hashlib.md5(sql.encode("utf-8")).hexdigest() + ) + elif hash_alg == "sha256": + hash = hashlib.sha256(sql.encode("utf-8")).hexdigest() + else: + raise InvalidHashError(alg=hash_alg) + + return { + "hash": hash, + "sql": sql, + "dir": file["dir"], + "filename": file["filename"], + "version": file["version"], + "scope": file["scope"], + } diff --git a/python/user_packages/Python313/site-packages/chromadb/db/system.py b/python/user_packages/Python313/site-packages/chromadb/db/system.py new file mode 100644 index 0000000000000000000000000000000000000000..638c1aecddb965f155f119cf19fe0a6f0bb67ac9 --- /dev/null +++ b/python/user_packages/Python313/site-packages/chromadb/db/system.py @@ -0,0 +1,189 @@ +from abc import abstractmethod +from typing import Optional, Sequence, Tuple +from uuid import UUID +from chromadb.api.collection_configuration import ( + CreateCollectionConfiguration, + UpdateCollectionConfiguration, +) +from chromadb.api.types import Schema +from chromadb.types import ( + Collection, + CollectionAndSegments, + Database, + Tenant, + Metadata, + Segment, + SegmentScope, + OptionalArgument, + Unspecified, + UpdateMetadata, +) +from chromadb.config import DEFAULT_DATABASE, DEFAULT_TENANT, Component + + +class SysDB(Component): + """Data interface for Chroma's System database""" + + @abstractmethod + def create_database( + self, id: UUID, name: str, tenant: str = DEFAULT_TENANT + ) -> None: + """Create a new database in the System database. Raises an Error if the Database + already exists.""" + pass + + @abstractmethod + def get_database(self, name: str, tenant: str = DEFAULT_TENANT) -> Database: + """Get a database by name and tenant. Raises an Error if the Database does not + exist.""" + pass + + @abstractmethod + def delete_database(self, name: str, tenant: str = DEFAULT_TENANT) -> None: + """Delete a database.""" + pass + + @abstractmethod + def list_databases( + self, + limit: Optional[int] = None, + offset: Optional[int] = None, + tenant: str = DEFAULT_TENANT, + ) -> Sequence[Database]: + """List all databases for a tenant.""" + pass + + @abstractmethod + def create_tenant(self, name: str) -> None: + """Create a new tenant in the System database. The name must be unique. + Raises an Error if the Tenant already exists.""" + pass + + @abstractmethod + def get_tenant(self, name: str) -> Tenant: + """Get a tenant by name. Raises an Error if the Tenant does not exist.""" + pass + + # TODO: Investigate and remove this method, as segment creation is done as + # part of collection creation. + @abstractmethod + def create_segment(self, segment: Segment) -> None: + """Create a new segment in the System database. Raises an Error if the ID + already exists.""" + pass + + @abstractmethod + def delete_segment(self, collection: UUID, id: UUID) -> None: + """Delete a segment from the System database.""" + pass + + @abstractmethod + def get_segments( + self, + collection: UUID, + id: Optional[UUID] = None, + type: Optional[str] = None, + scope: Optional[SegmentScope] = None, + ) -> Sequence[Segment]: + """Find segments by id, type, scope or collection.""" + pass + + @abstractmethod + def update_segment( + self, + collection: UUID, + id: UUID, + metadata: OptionalArgument[Optional[UpdateMetadata]] = Unspecified(), + ) -> None: + """Update a segment. Unspecified fields will be left unchanged. For the + metadata, keys with None values will be removed and keys not present in the + UpdateMetadata dict will be left unchanged.""" + pass + + @abstractmethod + def create_collection( + self, + id: UUID, + name: str, + schema: Optional[Schema], + configuration: CreateCollectionConfiguration, + segments: Sequence[Segment], + metadata: Optional[Metadata] = None, + dimension: Optional[int] = None, + get_or_create: bool = False, + tenant: str = DEFAULT_TENANT, + database: str = DEFAULT_DATABASE, + ) -> Tuple[Collection, bool]: + """Create a new collection and associated resources + in the SysDB. If get_or_create is True, the + collection will be created if one with the same name does not exist. + The metadata will be updated using the same protocol as update_collection. If get_or_create + is False and the collection already exists, an error will be raised. + + Returns a tuple of the created collection and a boolean indicating whether the + collection was created or not. + """ + pass + + @abstractmethod + def delete_collection( + self, + id: UUID, + tenant: str = DEFAULT_TENANT, + database: str = DEFAULT_DATABASE, + ) -> None: + """Delete a collection, all associated segments and any associate resources (log stream) + from the SysDB and the system at large.""" + pass + + @abstractmethod + def get_collections( + self, + id: Optional[UUID] = None, + name: Optional[str] = None, + tenant: str = DEFAULT_TENANT, + database: str = DEFAULT_DATABASE, + limit: Optional[int] = None, + offset: Optional[int] = None, + ) -> Sequence[Collection]: + """Find collections by id or name. If name is provided, tenant and database must also be provided.""" + pass + + @abstractmethod + def count_collections( + self, + tenant: str = DEFAULT_TENANT, + database: Optional[str] = None, + ) -> int: + """Gets the number of collections for the (tenant, database) combination.""" + pass + + @abstractmethod + def get_collection_with_segments( + self, collection_id: UUID + ) -> CollectionAndSegments: + """Get a consistent snapshot of a collection by id. This will return a collection with segment + information that matches the collection version and log position. + """ + pass + + @abstractmethod + def update_collection( + self, + id: UUID, + name: OptionalArgument[str] = Unspecified(), + dimension: OptionalArgument[Optional[int]] = Unspecified(), + metadata: OptionalArgument[Optional[UpdateMetadata]] = Unspecified(), + configuration: OptionalArgument[ + Optional[UpdateCollectionConfiguration] + ] = Unspecified(), + ) -> None: + """Update a collection. Unspecified fields will be left unchanged. For metadata, + keys with None values will be removed and keys not present in the UpdateMetadata + dict will be left unchanged.""" + pass + + @abstractmethod + def get_collection_size(self, id: UUID) -> int: + """Returns the number of records in a collection.""" + pass diff --git a/python/user_packages/Python313/site-packages/chromadb/execution/__init__.py b/python/user_packages/Python313/site-packages/chromadb/execution/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/python/user_packages/Python313/site-packages/chromadb/experimental/density_relevance.ipynb b/python/user_packages/Python313/site-packages/chromadb/experimental/density_relevance.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..ff32598dead5d97bf43d353e3b3923906e87200c --- /dev/null +++ b/python/user_packages/Python313/site-packages/chromadb/experimental/density_relevance.ipynb @@ -0,0 +1,542 @@ +{ + "cells": [ + { + "attachments": {}, + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Density based retrieval relevance\n", + "\n", + "An important aspect of using embeddings-based retreival systems like Chroma is knowing whether there are relevant results to a given query in the existing dataset. As application developers, we would like to know when the system doesn't have enough information to complete a given query or task - we want to know what we don't know. \n", + "\n", + "This is particularly important in the case of retrieval-augmented generation, since it's [often been observed](https://arxiv.org/abs/2302.00093) that supplying irrelevant context serves to confuse the generative model, leading to the degredation of application performance in ways that are difficult to detect. \n", + "\n", + "Unlike a relational database which will not return results if none match the query, a vector search based retrieval system will return the $k$ nearest neighbors to any given query, whether they are relevant or not. \n", + "\n", + "One possible approach one might take is to tune a distance threshold, and reject any results which fall further away from the query. This might be suitable for certain kind of fixed datasets, but in practice such thresholds tend to be very brittle, and often serve to exclude many relevant results while not always excluding irrelevant ones. Additionally, the threshold will need to be continously adapted as the data changes. Additionally, such distance thresholds are not comparable across embedding models for a given dataset, nor across datasets for a given embedding model. \n", + "\n", + "We would prefer to find a data driven approach which can:\n", + "- produce a uniform and comparable measure of relevance for any dataset \n", + "- automatically adapt as the underlying data changes \n", + "- is relatively inexpensive to compute\n", + "\n", + "This notebook demonstrates one possible such approach, which relies on the distribution of distances (pseudo 'density') between points in a given dataset. For a given result, we use compute the percentile the result's distance to the query falls into with respect to the overall distribution of distances in the dataset. This approach produces a uniform measure of relevance for any dataset, and is relatively cheap to compute, and can be computed online as data mutates. \n", + "\n", + "This approach is still very preliminary, and we welcome contributions and alternative approaches - some ideas are listed at the end of this notebook." + ] + }, + { + "attachments": {}, + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Preliminaries" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "# Install required packages\n", + "\n", + "import sys\n", + "!{sys.executable} -m pip install chromadb numpy umap-learn[plot] matplotlib tqdm datasets" + ] + }, + { + "attachments": {}, + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Dataset\n", + "\n", + "As a demonstration we use the [SciQ dataset](https://arxiv.org/abs/1707.06209), available from [HuggingFace](https://huggingface.co/datasets/sciq). \n", + "\n", + "Dataset description, from HuggingFace:\n", + "\n", + "> The SciQ dataset contains 13,679 crowdsourced science exam questions about Physics, Chemistry and Biology, among others. The questions are in multiple-choice format with 4 answer options each. For the majority of the questions, an additional paragraph with supporting evidence for the correct answer is provided." + ] + }, + { + "cell_type": "code", + "execution_count": 4, + "metadata": {}, + "outputs": [ + { + "name": "stderr", + "output_type": "stream", + "text": [ + "Found cached dataset sciq (/Users/antontroynikov/.cache/huggingface/datasets/sciq/default/0.1.0/50e5c6e3795b55463819d399ec417bfd4c3c621105e00295ddb5f3633d708493)\n", + "Loading cached processed dataset at /Users/antontroynikov/.cache/huggingface/datasets/sciq/default/0.1.0/50e5c6e3795b55463819d399ec417bfd4c3c621105e00295ddb5f3633d708493/cache-9181e6e3516ba4ed.arrow\n" + ] + }, + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Number of questions with support: 10481\n" + ] + } + ], + "source": [ + "# Get the SciQ dataset from HuggingFace\n", + "from datasets import load_dataset\n", + "\n", + "dataset = load_dataset(\"sciq\", split=\"train\")\n", + "\n", + "# Filter the dataset to only include questions with a support\n", + "dataset = dataset.filter(lambda x: x['support'] != '')\n", + "\n", + "print(\"Number of questions with support: \", len(dataset))" + ] + }, + { + "attachments": {}, + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Data loading \n", + "\n", + "We load the dataset into a local persistent instance of Chroma, into a collection called `sciq`. We use Chroma's [default embedding function](https://docs.trychroma.com/embeddings#default-all-minilm-l6-v2), all-MiniLM-L6-v2 from [sentence tranformers](https://www.sbert.net/)." + ] + }, + { + "cell_type": "code", + "execution_count": 5, + "metadata": {}, + "outputs": [], + "source": [ + "import chromadb\n", + "from chromadb.config import Settings\n", + "\n", + "chroma_client = chromadb.PersistentClient(path=\"./chroma)\")\n", + "\n", + "collection = chroma_client.get_or_create_collection(name=\"sciq\")" + ] + }, + { + "attachments": {}, + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Load the data into Chroma and persist, if it hasn't already been loaded and previously. " + ] + }, + { + "cell_type": "code", + "execution_count": 28, + "metadata": {}, + "outputs": [ + { + "data": { + "application/vnd.jupyter.widget-view+json": { + "model_id": "0df53f502e3a450783f7cbc3b3c658ea", + "version_major": 2, + "version_minor": 0 + }, + "text/plain": [ + " 0%| | 0/11 [00:00" + ] + }, + "execution_count": 49, + "metadata": {}, + "output_type": "execute_result" + }, + { + "data": { + "image/png": "iVBORw0KGgoAAAANSUhEUgAAAoQAAAKACAYAAAAFJmlZAAAAOXRFWHRTb2Z0d2FyZQBNYXRwbG90bGliIHZlcnNpb24zLjUuMiwgaHR0cHM6Ly9tYXRwbG90bGliLm9yZy8qNh9FAAAACXBIWXMAAA9hAAAPYQGoP6dpAAEAAElEQVR4nOzddZzd133n/9f5wmUaZkkzGjFbtmXGmOIkDlPbQNNs02zatNtu++tuu6Utw7bbNltIkzhuYsexY2YmgSVZzBpmvIxfOL8/riywWBrPyNJ5Ph5+aDz3+/3ec+/MvfO+Bz5HSCkliqIoiqIoyiVLm+kGKIqiKIqiKDNLBUJFURRFUZRLnAqEiqIoiqIolzgVCBVFURRFUS5xKhAqiqIoiqJc4lQgVBRFURRFucSpQKgoiqIoinKJM871RNd1GRwcJBwOI4SYyjYpiqIoiqIoU0BKSTqdprGxEU07eT/gOQfCwcFBWlpazvV0RVEURVEUZZr09fXR3Nx80tvPecg4HA6f66mKoiiKoijKNDpdbjvnQKiGiRVFURRFUT4YTpfb1KISRVEURVGUS5wKhIqiKIqiKJc4FQgVRVEURVEucSoQKoqiKIqiXOJUIFQURVEURbnEqUCoKIq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EREROTnmBASERER+TkmhERERER+jgkhERERkZ9jQkhERETk55gQEhEREfm5/wP6o65pjkQApQAAAABJRU5ErkJggg==", + "text/plain": [ + "
" + ] + }, + "metadata": {}, + "output_type": "display_data" + } + ], + "source": [ + "from umap.umap_ import UMAP\n", + "import umap.plot as umap_plot\n", + "import numpy as np\n", + "\n", + "mapper = UMAP().fit(support_embeddings)\n", + "umap_plot.points(mapper, values=np.array(flat_dists), show_legend=False, theme='inferno')" + ] + }, + { + "attachments": {}, + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Computing the density function over distances \n", + "\n", + "Using the returned distances, we compute the density function using `numpy`. " + ] + }, + { + "cell_type": "code", + "execution_count": 33, + "metadata": {}, + "outputs": [], + "source": [ + "# Compute a density function over the distances\n", + "import numpy as np\n", + "hist, bin_edges = np.histogram(flat_dists, bins=100, density=True)\n", + "cumulative_density = np.cumsum(hist) / np.sum(hist)" + ] + }, + { + "cell_type": "code", + "execution_count": 34, + "metadata": {}, + "outputs": [ + { + "data": { + "image/png": "iVBORw0KGgoAAAANSUhEUgAAAiMAAAGwCAYAAAB7MGXBAAAAOXRFWHRTb2Z0d2FyZQBNYXRwbG90bGliIHZlcnNpb24zLjUuMiwgaHR0cHM6Ly9tYXRwbG90bGliLm9yZy8qNh9FAAAACXBIWXMAAA9hAAAPYQGoP6dpAAB0n0lEQVR4nO3dd3iUVfrG8e/MpHdCKhASOkgvUqWKoCIruiqiK6Kiq2Jff7a1N1zLWrEruAXFjitFKSJVlA4CoQVCSSFAep95f39MSUISTEKSSbk/15UrzMw7M+cNkNw55znPazIMw0BERETETczuHoCIiIg0bwojIiIi4lYKIyIiIuJWCiMiIiLiVgojIiIi4lYKIyIiIuJWCiMiIiLiVh7uHkBV2Gw2jh07RmBgICaTyd3DERERkSowDIOsrCxatWqF2Vz5/EejCCPHjh0jJibG3cMQERGRGjh8+DBt2rSp9PFGEUYCAwMB+8kEBQW5eTQiIiJSFZmZmcTExLh+jlemUYQR59JMUFCQwoiI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HiqHbyIiIjbNeswYtHWXhEREbdr1mHEQ8s0IiIibte8w4hFBawiIiLu1rzDiFk1IyIijZHJZOLbb79tMK/TWMTFxfHaa6+5exjlNOsw4qwZUdMzEZGykpOTufPOO2nfvj3e3t7ExMQwceJEli1b5u6h1ciTTz5Jnz59yt2flJRUafv52hIXF4fJZMJkMuHr60tcXBxXXXUVy5cvr9P3rchvv/3GLbfc4rrdUMJYsw4jJbtpVDMiIuJ08OBB+vfvz/Lly3nppZfYvn07ixcvZvTo0cyYMcPdw6tVUVFReHt71/n7PP300yQlJREfH8+//vUvQkJCGDt2LM8991ydv3dp4eHh+Pn51et7VkWzDiMWNT0TESnn9ttvx2Qy8euvv/LnP/+Zzp070717d+677z5++eUXwB5YTCYTW7ZscT0vPT0dk8nEihUrAFixYgUmk4kffviBvn374uvry5gxY0hNTWXRokV069aNoKAgrrnmGnJzc12vU9FSQp8+fXjyyScrHfODDz5I586d8fPzo3379jz22GMUFRUBMGfOHJ566im2bt3qmqGYM2cOUHZmYOjQoTz44INlXvf48eN4enqycuVKwN5+/v7776d169b4+/szaNAg1/meSWBgIFFRUbRt25YRI0bw/vvv89hjj/H4448THx/vOm7Hjh1cdNFFBAQEEBkZyXXXXUdaWprr8VGjRnHXXXfxwAMPEBoaSlRUVJmvi2EYPPnkk7Rt2xZvb29atWrFXXfdVeHXNi4uDoDLLrsMk8lEXFwcBw8exGw2s2HDhjLjf+2114iNjcVWR7+8N+swUrKbRmFEROqBYUBhjns+qnhN1JMnT7J48WJmzJiBv79/ucdDQkKqfdpPPvkkb731FmvXruXw4cNcddVVvPbaa8ydO5cFCxbw448/8uabb1b7dUsLDAxkzpw57Ny5k9dff50PPviAV199FYDJkyfzt7/9je7du5OUlERSUhKTJ08u9xrXXnstn332GaWvHztv3jxatWrF8OHDAbjjjjtYt24dn332Gdu2bePKK6/kwgsvZO/evdUe8913341hGMyfPx+wh7kxY8bQt29fNmzYwOLFi0lJSeGqq64q87xPPvkEf39/1q9fz4svvsjTTz/NkiVLAPjqq6949dVXee+999i7dy/ffvstPXv2rPD9f/vtNwBmz55NUlISv/32G3FxcYwdO5bZs2eXOXb27NlMmzYNs7luYkOzvlCe89o0mhkRkXpRlAvPt3LPez9yDLzKh4vT7du3D8Mw6Nq1a6299bPPPsuwYcMAuOmmm3j44YfZv38/7du3B+CKK67gp59+KjcrUR2PPvqo689xcXHcf//9fPbZZzzwwAP4+voSEBCAh4cHUVFRlb7GVVddxT333MPq1atd4WPu3LlMmTIFk8lEYmIis2fPJjExkVat7H+P999/P4sXL2b27Nk8//zz1RpzaGgoERERHDx4EIC33nqLvn37lnmdjz/+mJiYGPbs2UPnzp0B6NWrF0888QQAnTp14q233mLZsmVccMEFJCYmEhUVxdixY/H09KRt27YMHDiwwvcPDw8H7AGz9Ndl+vTp3Hrrrfzzn//E29ubTZs2sX37dldoqgvNembEYlbNiIhIaUYVZ1Cqo1evXq4/R0ZGupZSSt+Xmpp6Vu8xb948hg0bRlRUFAEBATz66KMkJiZW6zXCw8MZN24c//3vfwFISEhg3bp1XHvttQBs374dq9VK586dCQgIcH38/PPP7N+/v0bjNgwDk8n+s2jr1q389NNPZV7bGQpLv37prydAdHS06+t35ZVXkpeXR/v27bn55pv55ptvKC4urtaYJk2ahMVi4ZtvvgHsy1yjR492LevUheY9M6KaERGpT55+9hkKd713FXTq1AmTycTu3bvPeJxzur50eHHWaJR7a09P159NJlOZ2877StcimM3mcqGostcGXIHhqaeeYvz48QQHB/PZZ5/xyiuvnPEcKnLttddy11138eabbzJ37lx69uzpWubIzs7GYrGwceNGLBZLmecFBARU+71OnDjB8ePHadeunev1J06cyD/+8Y9yx0ZHR7v+fKavX0xMDPHx8SxdupQlS5Zw++2389JLL/Hzzz+Xe15lvLy8mDp1KrNnz+byyy9n7ty5vP7669U+v+po3mHEuUyjmhERqQ8mU5WWStwpNDSU8ePHM2vWLO66665ydSPp6emEhIS4pviTkpLo27cvQJli1rMRHh5OUlKS63ZmZiYJCQmVHr927VpiY2P5+9//7rrv0KFDZY7x8vLCarX+4Xtfeuml3HLLLSxevJi5c+cydepU12N9+/bFarWSmprqWsY5G6+//jpms5lJkyYB0K9fP7766ivi4uLw8Kj5j2dfX18mTpzIxIkTmTFjBl27dmX79u3069ev3LGenp4Vfl2mT59Ojx49ePvttykuLubyyy+v8Xiqolkv06jpmYhIebNmzcJqtTJw4EC++uor9u7dy65du3jjjTcYMmQIYP+BN3jwYF544QV27drFzz//XKZu42yMGTOGf//736xatYrt27dz/fXXl5uJKK1Tp04kJiby2WefsX//ft544w3XEoNTXFwcCQkJbNmyhbS0NAoKCip8LX9/fyZNmsRjjz3Grl27mDJliuuxzp07c+211zJ16lS+/vprEhIS+PXXX5k5cyYLFiw44zllZWWRnJzM4cOHWblyJbfccgvPPvsszz33HB07dgRgxowZnDx5kilTpvDbb7+xf/9+fvjhB2644YYqBSmwL6l89NFH7NixgwMHDvCf//wHX19fYmNjKzw+Li6OZcuWkZyczKlTp1z3d+vWjcGDB/Pggw8yZcoUfH19q/T+NdWsw4izZqRINSMiIi7t27dn06ZNjB49mr/97W/06NGDCy64gGXLlvHOO++4jvv4448pLi6mf//+3HPPPTz77LO18v4PP/wwI0eO5JJLLmHChAlMmjSJDh06VHr8n/70J+69917uuOMO+vTpw9q1a3nsscfKHPPnP/+ZCy+8kNGjRxMeHs6nn35a6etde+21bN26leHDh9O2bdsyj82ePZupU6fyt7/9jS5dujBp0iR+++23csed7vHHHyc6OpqOHTty3XXXkZGRwbJly8oU7bZq1Yo1a9ZgtVoZN24cPXv25J577iEkJKTKu1hCQkL44IMPGDZsGL169WLp0qX873//o2XLlhUe/8orr7BkyRJiYmJcM1xON910E4WFhdx4441Veu+zYTLqolqplmVmZhIcHExGRgZBQUG19rrLd6dw45wN9GoTzHd3nFdrrysikp+fT0JCAu3atcPHx8fdwxGptmeeeYYvvviCbdu2nfG4M/1br+rP72Y+M6KaERERkdKys7PZsWMHb731FnfeeWe9vGe1wsjMmTM599xzCQwMJCIigkmTJpXpHFeROX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+RdXMNNTmsVson+sfYzju0fRogG07m+Q20Yefvhh7rvvPtdt58yIiIiIk7+3B8M7hTO8U3iVjvdy7N65dlDsGY+zmE3lAkppHSMCuXtsIHeP7VTlsXpYzK6xzry8yk+rkgvOifzjgxq4aoWRsLAwLBYLKSkpZe5PSUkhKqridaaoqKhqHQ/g7e2Nt7cuby0iItIcVKus18vLi/79+7Ns2TLXfTabjWXLljFkyJAKnzNkyJAyxwMsWbKk0uNFRESkean2Ms19993H9ddfz4ABAxg4cCCvvfYaOTk53HDDDQBMnTqV1q1bM3PmTADuvvtuRo4cySuvvMKECRP47LPP2LBhA++//37tnomIiIg0StUOI5MnT+b48eM8/vjjJCcn06dPHxYvXuwqUk1MTMRcap/T0KFDmTt3Lo8++iiPPPIInTp14ttvv61yjxERERFp2pp3O3gRERGpM1X9+d2wWsGJiIhIs6MwIiIiIm6lMCIiIiJupTAiIiIibqUwIiIiIm6lMCIiIiJupTAiIiIibqUwIiIiIm6lMCIiIiJuVe128O7gbBKbmZnp5pGIiIhIVTl/bv9Rs/dGEUaysrIAiImJcfNIREREpLqysrIIDg6u9PFGcW0am83GsWPHCAwMxGQy1fh1MjMziYmJ4fDhw83iGjc636avuZ2zzrfpa27n3NTP1zAMsrKyaNWqVZmL6J6uUcyMmM1m2rRpU2uvFxQU1CT/0iuj8236mts563ybvuZ2zk35fM80I+KkAlYRERFxK4URERERcatmFUa8vb154okn8Pb2dvdQ6oXOt+lrbues8236mts5N7fzrUyjKGAVERGRpqtZzYyIiIhIw6MwIiIiIm6lMCIiIiJupTAiIiIibtXkwsisWbOIi4vDx8eHQYMG8euvv57x+C+++IKuXbvi4+NDz549WbhwYT2NtHZU53w/+OADhg8fTosWLWjRogVjx479w69PQ1Pdv1+nzz77DJPJxKRJk+p2gHWguuecnp7OjBkziI6Oxtvbm86dOzeqf9fVPd/XXnuNLl264OvrS0xMDPfeey/5+fn1NNqzs3LlSiZOnEirVq0wmUx8++23f/icFStW0K9fP7y9venYsSNz5syp83H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bodGxtr/OUvf3HdttlsRkREhPHOO+8YhmEY7733nhEYGGicOHGiwtc7//zzjeeff77Mff/+97+N6OjoPxyLiNQfD3eHIRFpPAzDwGQylbt/2rRpXHDBBXTp0oULL7yQSy65hHHjxp3xtbKzs3nyySdZsGABSUlJFBcXk5eXV25mpFevXq4/m0wmoqKiSE1NBWDLli307duX0NDQCt9j69atrFmzpsxMiNVqJT8/n9zcXPz8/Kp87iJSdxRGRKTKdu3aRbt27crd369fPxISEli0aBFLly7lqquuYuzYsXz55ZeVvtb999/PkiVLePnll+nYsSO+vr5cccUVFBYWljnO09OzzG2TyeRahvH19T3jeLOzs3nqqae4/PLLyz3m4+NzxueKSP1RGBGRKlm+fDnbt2/n3nvvrfDxoKAgJk+ezOTJk7niiiu48MILOXnyJKGhoXh6emK1Wsscv2bNGqZNm8Zll10G2IPDwYMHqzWmXr168eGHH7re53T9+vUjPj6ejh07Vut1RaR+KYyISDkFBQUkJydjtVpJSUlh8eLFzJw5k0suuYSpU6eWO/6f//wn0dHR9O3bF7PZzBdffEFUVBQhISGAfVfMsmXLGDZsGN7e3rRo0YJOnTrx9ddfM3HiREwmE4899liZPiZVMWXKFJ5//nkmTZrEzJkziY6OZvPmzbRq1YohQ4bw+OOPc8kll9C2bVuuuOIKzGYzW7duZceOHTz77LO18aUSkVqg3TQiUs7ixYuJjo4mLi6OCy+8kJ9++ok33niD+fPnY7FYyh0fGBjIiy++yIABAzj33HM5ePAgCxcuxGy2f4t55ZVXWLJkCTExMfTt2xewB5gWLVowdOhQJk6cyPjx4+nXr1+1xunl5cWPP/5IREQEF198MT179uSFF15wjXH8+PF8//33/Pjjj5x77rkMHjyYV199ldjY2LP8ColIbTIZhmG4exAiIiLSfGlmRERERNxKYURERETcSmFERERE3EphRERERNxKYURERETcSmFERERE3EphRERERNxKYURERETcSmFERERE3EphRERERNxKYURERETc6v8Bby5t8VgCpY0AAAAASUVORK5CYII=", + "text/plain": [ + "
" + ] + }, + "metadata": {}, + "output_type": "display_data" + } + ], + "source": [ + "# Plot the density function\n", + "import matplotlib.pyplot as plt\n", + "plt.plot(bin_edges[1:], hist, label=\"Density\")\n", + "plt.plot(bin_edges[1:], cumulative_density, label=\"Cumulative Density\")\n", + "plt.legend(loc=\"upper right\")\n", + "plt.xlabel(\"Distance\")\n", + "plt.show()\n" + ] + }, + { + "attachments": {}, + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Computing relevance using the density function\n", + "\n", + "We use the percentile a given query falls into with respect to the overall distribution of distances between elements of the dataset, to estimate its relevance. Intuitively, results which are less relevant to the query, should be in higher percentiles than those which are more relevant. \n", + "\n", + "By using the distribution of distances in this way, we eliminate the need to tune an explicit distance threshold, and can instead reason in terms of likelihoods. We could either apply a threshold to the percentile-based relevance directly, or else feed this information into a re-ranking model, or take a sampling approach. " + ] + }, + { + "cell_type": "code", + "execution_count": 35, + "metadata": {}, + "outputs": [], + "source": [ + "def compute_percentile(dist):\n", + " index = np.searchsorted(bin_edges[1:], dist, side='right')\n", + " return cumulative_density[index - 1]" + ] + }, + { + "attachments": {}, + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Evaluation\n", + "\n", + "We evaluate the percentile based relevance score using the SciQ dataset. \n", + "\n", + "1. We query the collection of supporting sentences using the questions from the dataset, returning the 10 nearest results, along with their distances.\n", + "2. We check the results for whether the supporting sentence is present or absent. If it's present in the results, we record the percentile that the support falls into, otherwise we record the percentile of the nearest result. " + ] + }, + { + "cell_type": "code", + "execution_count": 36, + "metadata": {}, + "outputs": [], + "source": [ + "question_results = collection.query(query_texts=dataset['question'], n_results=10, include=['documents', 'distances'])" + ] + }, + { + "cell_type": "code", + "execution_count": 37, + "metadata": {}, + "outputs": [], + "source": [ + "support_percentiles = []\n", + "missing_support_percentiles = []\n", + "for i, q in enumerate(dataset['question']):\n", + " support = dataset['support'][i]\n", + " if support in question_results['documents'][i]:\n", + " support_index = question_results['documents'][i].index(support)\n", + " percentile = compute_percentile(question_results['distances'][i][support_index])\n", + " support_percentiles.append(percentile)\n", + " else:\n", + " missing_support_percentiles.append(compute_percentile(question_results['distances'][i][0]))" + ] + }, + { + "attachments": {}, + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Visualization\n", + "\n", + "We plot histograms of the percentiles for the cases where the support was found, and the case where it wasn't. A lower percentile is more relevant. " + ] + }, + { + "cell_type": "code", + "execution_count": 40, + "metadata": {}, + "outputs": [ + { + "data": { + "image/png": "iVBORw0KGgoAAAANSUhEUgAAAiMAAAGdCAYAAADAAnMpAAAAOXRFWHRTb2Z0d2FyZQBNYXRwbG90bGliIHZlcnNpb24zLjUuMiwgaHR0cHM6Ly9tYXRwbG90bGliLm9yZy8qNh9FAAAACXBIWXMAAA9hAAAPYQGoP6dpAAArl0lEQVR4nO3de3RU1d3G8WcIZBIkF265ABG5hjuBIBBQgRabAkVifZGKr1wE1BoqGMUaFMKlGhARrCKICKFWGkUlKFA0jUZeIaggqYAIIkiwJgEsJBgggeS8f1imjiSBGTLZuXw/a81anTP77PObHZbzdJ99zrFZlmUJAADAkDqmCwAAALUbYQQAABhFGAEAAEYRRgAAgFGEEQAAYBRhBAAAGEUYAQAARhFGAACAUXVNF3AlSkpK9N1338nPz082m810OQAA4ApYlqXTp0+rWbNmqlOn7PmPahFGvvvuO4WFhZkuAwAAuOHo0aNq0aJFmZ9XizDi5+cn6ccv4+/vb7gaAABwJfLz8xUWFub4HS9LtQgjF0/N+Pv7E0YAAKhmLrfEggWsAADAKJfCyNKlS9WtWzfHDEVUVJT+/ve/l7vP2rVr1aFDB/n4+Khr167atGnTVRUMAABqFpfCSIsWLTRv3jzt3LlTO3bs0C9+8QuNGDFCe/fuLbX9tm3bdMcdd2jChAnatWuXYmJiFBMToz179lRI8QAAoPqzWZZlXU0HjRo10oIFCzRhwoRLPhs1apQKCgq0YcMGx7a+ffsqIiJCy5Ytu+Jj5OfnKyAgQHl5eawZAYAqzLIsXbhwQcXFxaZLQSXw8vJS3bp1y1wTcqW/324vYC0uLtbatWtVUFCgqKioU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lqfgbOHlGwEAUIk88fv6034tyyq3nUth5MSJEyouLlZwcLDT9uDgYH355Zel7pOTk1Nq+5ycnDKPk5iYqNmzZ1+yPSwszJVyAQDAlfiDZ89WnD59WgEBAWV+XiVvBx8fH+80m1JSUqJ///vfaty4sU6fPq2wsDAdPXpU/v7+BqusXfLz8xl3Axh3Mxh3Mxh3Mzw57pZl6fTp02rWrFm57VwKI02aNJGXl5dyc3Odtufm5iokJKTUfUJCQlxqL0l2u112u91pW2BgoCTJZrNJkvz9/fnHagDjbgbjbgbjbgbjboanxr28GZGLXFrA6u3trcjISKWlpTm2lZSUKC0tTVFRUaXuExUV5dReklJTU8tsDwAAaheXT9PExcVp7Nix6tWrl3r37q3FixeroKBA48ePlySNGTNGzZs3V2JioiRpypQpGjBggBYuXKhhw4YpOTlZO3bs0PLl3G8DAAC4EUZGjRql48ePa+bMmcrJyVFERIQ2b97sWKSalZWlOnX+O+HSr18/rVmzRo8//rimT5+udu3aKSUlRV26dHGrYLvdroSEhEtO48CzGHczGHczGHczGHczqsK426zLXW8DAADgQTybBgAAGEUYAQAARhFGAACAUYQRAABgVJULI0uWLNF1110nHx8f9enTR5988km57deuXasOHTrIx8dHXbt21aZNmyqp0prHlbF/6aWXdOONN6phw4Zq2LChBg8efNm/FUrn6r/5i5KTk2Wz2RQTE+PZAmsoV8f91KlTio2NVWhoqOx2u9q3b89/b9zg6rgvXrxY4eHh8vX1VVhYmB588EGdO3eukqqtGbZs2aLhw4erWbNmstls5T4b7qL09HT17NlTdrtdbdu2VVJSkmeLtKqQ5ORky9vb21q5cqW1d+9ea9KkSVZgYKCVm5tbavutW7daXl5e1lNPPWV98cUX1uOPP27Vq1fP2r17dyVXXv25OvajR4+2lixZYu3atcvat2+fNW7cOCsgIMD69ttvK7ny6s3Vcb/o8OHDVvPmza0bb7zRGjFiROUUW4O4Ou6FhYVWr169rKFDh1offfSRdfjwYSs9Pd3KzMys5MqrN1fH/dVXX7Xsdrv16quvWocPH7beffddKzQ01HrwwQcrufLqbdOmTdZjjz1mvfXWW5Yka926deW2P3TokFW/fn0rLi7O+uKLL6znnnvO8vLysjZv3uyxGqtUGOndu7cVGxvreF9cXGw1a9bMSkxMLLX97bffbg0bNsxpW58+fax7773Xo3XWRK6O/c9duHDB8vPzs1avXu2pEmskd8b9woULVr9+/awVK1ZYY8eOJYy4wdVxX7p0qdW6dWurqKioskqskVwd99jYWOsXv/iF07a4uDirf//+Hq2zJruSMPLII49YnTt3dto2atQoKzo62mN1VZnTNEVFRdq5c6cGDx7s2FanTh0NHjxYGRkZpe6TkZHh1F6SoqOjy2yP0rkz9j935swZnT9/Xo0aNfJUmTWOu+M+Z84cBQUFacKECZVRZo3jzri//fbbioqKUmxsrIKDg9WlSxc9+eSTKi4urqyyqz13xr1fv37auXOn41TOoUOHtGnTJg0dOrRSaq6tTPy2Vpmn9p44cULFxcWOO7leFBwcrC+//LLUfXJyckptn5OT47E6ayJ3xv7n/vjHP6pZs2aX/ANG2dwZ948++kgvv/yyMjMzK6HCmsmdcT906JDef/993Xnnndq0aZMOHjyo+++/X+fPn1dCQkJllF3tuTPuo0eP1okTJ3TDDTfIsixduHBB9913n6ZPn14ZJddaZf225ufn6+zZs/L19a3wY1aZmRFUX/PmzVNycrLWrVsnHx8f0+XUWKdPn9Zdd92ll156SU2aNDFdTq1SUlKioKAgLV++XJGRkRo1apQee+wxLVu2zHRpNVp6erqefPJJvfDCC/rss8/01ltvaePGjZo7d67p0lDBqszMSJMmTeTl5aXc3Fyn7bm5uQoJCSl1n5CQEJfao3TujP1FTz/9tObNm6d//OMf6tatmyfLrHFcHfevv/5a33zzjYYPH+7YVlJSIkmqW7eu9u/frzZt2ni26BrAnX/voaGhqlevnry8vBzbOnbsqJycHBUVFcnb29ujNdcE7oz7jBkzdNddd2nixImSpK5du6qgoED33HOPHnvsMafnoKHilPXb6u/v75FZEakKzYx4e3srMjJSaWlpjm0lJSVKS0tTVFRUqftERUU5tZek1NTUMtujdO6MvSQ99dRTmjt3rjZv3qxevXpVRqk1iqvj3qFDB+3evVuZmZmO1y233KJBgwYpMzNTYWFhlVl+teXOv/f+/fvr4MGDjvAnSQcOHFBoaChB5Aq5M+5nzpy5JHBcDIQWj1XzGCO/rR5bGuuG5ORky263W0lJSdYXX3xh3XPPPVZgYKCVk5NjWZZl3XXXXdajjz7qaL9161arbt261tNPP23t27fPSkhI4NJeN7k69vPmzbO8vb2tN954w8rOzna8Tp8+beorVEuujvvPcTWNe1wd96ysLMvPz8+aPHmytX//fmvDhg1WUFCQ9ac//cnUV6iWXB33hIQEy8/Pz/rb3/5mHTp0yHrvvfesNm3aWLfffrupr1AtnT592tq1a5e1a9cuS5L1zDPPWLt27bKOHDliWZZlPfroo9Zdd93laH/x0t5p06ZZ+/bts5YsWVK7Lu21LMt67rnnrGuvvdby9va2evfubW3fvt3x2YABA6yxY8c6tX/99det9u3bW97e3lbnzp2tjRs3VnLFNYcrY9+yZUtL0iWvhISEyi+8mnP13/xPEUbc5+q4b9u2zerTp49lt9ut1q1bW0888YR14cKFSq66+nNl3M+fP2/NmjXLatOmjeXj42OFhYVZ999/v3Xy5MnKL7wa++CDD0r97/XFsR47dqw1YMCAS/aJiIiwvL29rdatW1urVq3yaI02y2KuCwAAmFNl1owAAIDaiTACAACMIowAAACjCCMAAMAowggAADCKMAIAAIwijAAAAKMIIwAAwCjCCAAAMIowAgAAjCKMAAAAowgjAADAqP8HTt6+4hHjJtgAAAAASUVORK5CYII=", + "text/plain": [ + "
" + ] + }, + "metadata": {}, + "output_type": "display_data" + } + ], + "source": [ + "# Plot normalized histograms of the percentiles\n", + "plt.hist(support_percentiles, bins=20, density=True, alpha=0.5, label='Support')\n", + "plt.hist(missing_support_percentiles, bins=20, density=True, alpha=0.5, label='No support')\n", + "plt.legend(loc='upper right')\n", + "plt.show()" + ] + }, + { + "attachments": {}, + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Preliminary results\n", + "\n", + "While we don't observe a clear separation of the two classes, we do note that in general, supports tend to be in lower percentiles, and hence more relevant, than results which aren't the support. \n", + "\n", + "One possible confounding factor is that in some cases, the result does contain the answer to the query question, but is not itself the support for that question. " + ] + }, + { + "cell_type": "code", + "execution_count": 41, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Question: What type of organism is commonly used in preparation of foods such as cheese and yogurt? \n", + "Support: Mesophiles grow best in moderate temperature, typically between 25°C and 40°C (77°F and 104°F). Mesophiles are often found living in or on the bodies of humans or other animals. The optimal growth temperature of many pathogenic mesophiles is 37°C (98°F), the normal human body temperature. Mesophilic organisms have important uses in food preparation, including cheese, yogurt, beer and wine. \n", + "Top result: Bacteria can be used to make cheese from milk. The bacteria turn the milk sugars into lactic acid. The acid is what causes the milk to curdle to form cheese. Bacteria are also involved in producing other foods. Yogurt is made by using bacteria to ferment milk ( Figure below ). Fermenting cabbage with bacteria produces sauerkraut.\n", + "\n", + "Question: Changes from a less-ordered state to a more-ordered state (such as a liquid to a solid) are always what? \n", + "Support: Summary Changes of state are examples of phase changes, or phase transitions. All phase changes are accompanied by changes in the energy of a system. Changes from a more-ordered state to a less-ordered state (such as a liquid to a gas) areendothermic. Changes from a less-ordered state to a more-ordered state (such as a liquid to a solid) are always exothermic. The conversion of a solid to a liquid is called fusion (or melting). The energy required to melt 1 mol of a substance is its enthalpy of fusion (ΔHfus). The energy change required to vaporize 1 mol of a substance is the enthalpy of vaporization (ΔHvap). The direct conversion of a solid to a gas is sublimation. The amount of energy needed to sublime 1 mol of a substance is its enthalpy of sublimation (ΔHsub) and is the sum of the enthalpies of fusion and vaporization. Plots of the temperature of a substance versus heat added or versus heating time at a constant rate of heating are calledheating curves. Heating curves relate temperature changes to phase transitions. A superheated liquid, a liquid at a temperature and pressure at which it should be a gas, is not stable. A cooling curve is not exactly the reverse of the heating curve because many liquids do not freeze at the expected temperature. Instead, they form a supercooled liquid, a metastable liquid phase that exists below the normal melting point. Supercooled liquids usually crystallize on standing, or adding a seed crystal of the same or another substance can induce crystallization. \n", + "Top result: Under the right pressure conditions, lowering the temperature of a substance in the liquid state causes the substance to solidify. The opposite effect occurs if the temperature is increased.\n", + "\n", + "Question: Kilauea in hawaii is the world’s most continuously active volcano. very active volcanoes characteristically eject red-hot rocks and lava rather than this? \n", + "Support: Example 3.5 Calculating Projectile Motion: Hot Rock Projectile Kilauea in Hawaii is the world’s most continuously active volcano. Very active volcanoes characteristically eject red-hot rocks and lava rather than smoke and ash. Suppose a large rock is ejected from the volcano with a speed of 25.0 m/s and at an angle 35.0º above the horizontal, as shown in Figure 3.40. The rock strikes the side of the volcano at an altitude 20.0 m lower than its starting point. (a) Calculate the time it takes the rock to follow this path. (b) What are the magnitude and direction of the rock’s velocity at impact?. \n", + "Top result: Volcanoes can be active, dormant, or extinct.\n", + "\n", + "Question: When a meteoroid reaches earth, what is the remaining object called? \n", + "Support: Meteoroids are smaller than asteroids, ranging from the size of boulders to the size of sand grains. When meteoroids enter Earth’s atmosphere, they vaporize, creating a trail of glowing gas called a meteor. If any of the meteoroid reaches Earth, the remaining object is called a meteorite. \n", + "Top result: A meteoroid is dragged toward Earth by gravity and enters the atmosphere. Friction with the atmosphere heats the object quickly, so it starts to vaporize. As it flies through the atmosphere, it leaves a trail of glowing gases. The object is now a meteor. Most meteors vaporize in the atmosphere. They never reach Earth’s surface. Large meteoroids may not burn up entirely in the atmosphere. A small core may remain and hit Earth’s surface. This is called a meteorite .\n", + "\n", + "Question: What kind of a reaction occurs when a substance reacts quickly with oxygen? \n", + "Support: A combustion reaction occurs when a substance reacts quickly with oxygen (O 2 ). For example, in the Figure below , charcoal is combining with oxygen. Combustion is commonly called burning, and the substance that burns is usually referred to as fuel. The products of a complete combustion reaction include carbon dioxide (CO 2 ) and water vapor (H 2 O). The reaction typically gives off heat and light as well. The general equation for a complete combustion reaction is:. \n", + "Top result: A combustion reaction occurs when a substance reacts quickly with oxygen (O 2 ). You can see an example of a combustion reaction in Figure below . Combustion is commonly called burning. The substance that burns is usually referred to as fuel. The products of a combustion reaction include carbon dioxide (CO 2 ) and water (H 2 O). The reaction typically gives off heat and light as well. The general equation for a combustion reaction can be represented by:.\n", + "\n", + "Question: Organisms categorized by what species descriptor demonstrate a version of allopatric speciation and have limited regions of overlap with one another, but where they overlap they interbreed successfully?. \n", + "Support: Ring species Ring species demonstrate a version of allopatric speciation. Imagine populations of the species A. Over the geographic range of A there exist a number of subpopulations. These subpopulations (A1 to A5) and (Aa to Ae) have limited regions of overlap with one another but where they overlap they interbreed successfully. But populations A5 and Ae no longer interbreed successfully – are these populations separate species?  In this case, there is no clear-cut answer, but it is likely that in the link between the various populations will be broken and one or more species may form in the future. Consider the black bear Ursus americanus. Originally distributed across all of North America, its distribution is now much more fragmented. Isolated populations are free to adapt to their own particular environments and migration between populations is limited. Clearly the environment in Florida is different from that in Mexico, Alaska, or Newfoundland. Different environments will favor different adaptations. If, over time, these populations were to come back into contact with one another, they might or might not be able to interbreed successfully - reproductive isolation may occur and one species may become many. \n", + "Top result: Allopatric speciation occurs when groups from the same species are geographically isolated for long periods. Imagine all the ways that plants or animals could be isolated from each other:.\n", + "\n", + "Question: Zinc is more easily oxidized than iron because zinc has a lower reduction potential. since zinc has a lower reduction potential, it is a more what? \n", + "Support: One way to keep iron from corroding is to keep it painted. The layer of paint prevents the water and oxygen necessary for rust formation from coming into contact with the iron. As long as the paint remains intact, the iron is protected from corrosion. Other strategies include alloying the iron with other metals. For example, stainless steel is mostly iron with a bit of chromium. The chromium tends to collect near the surface, where it forms an oxide layer that protects the iron. Zinc-plated or galvanized iron uses a different strategy. Zinc is more easily oxidized than iron because zinc has a lower reduction potential. Since zinc has a lower reduction potential, it is a more active metal. Thus, even if the zinc coating is scratched, the zinc will still oxidize before the iron. This suggests that this approach should work with other active metals. Another important way to protect metal is to make it the cathode in a galvanic cell. This is cathodic protection and can be used for metals other than just iron. For example, the rusting of underground iron storage tanks and pipes can be prevented or greatly reduced by connecting them to a more active metal such as zinc or magnesium (Figure 17.18). This is also used to protect the metal parts in water heaters. The more active metals (lower reduction potential) are called sacrificial anodes because as they get used up as they corrode (oxidize) at the anode. The metal being protected serves as the cathode, and so does not oxidize (corrode). When the anodes are properly monitored and periodically replaced, the useful lifetime of the iron storage tank can be greatly extended. \n", + "Top result: In the reaction above, the zinc is being oxidized by losing electrons. However, there must be another substance present that gains those electrons and in this case that is the sulfur. In other words, the sulfur is causing the zinc to be oxidized. Sulfur is called the oxidizing agent. The zinc causes the sulfur to gain electrons and become reduced and so the zinc is called the reducing agent. The oxidizing agent is a substance that causes oxidation by accepting electrons. The reducing agent is a substance that causes reduction by losing electrons. The simplest way to think of this is that the oxidizing agent is the substance that is reduced, while the reducing agent is the substance that is oxidized. The sample problem below shows how to analyze a redox reaction.\n", + "\n", + "Question: What are used to write nuclear equations for radioactive decay? \n", + "Support: Nuclear symbols are used to write nuclear equations for radioactive decay. Let’s consider the example of the beta-minus decay of thorium-234 to protactinium-234. This reaction is represented by the equation:. \n", + "Top result: Nuclear symbols are used to write nuclear equations for radioactive decay. Let’s consider an example. Uranium-238 undergoes alpha decay to become thorium-234. (The numbers following the chemical names refer to the number of protons plus neutrons. ) In this reaction, uranium-238 loses two protons and two neutrons to become the element thorium-234. The reaction can be represented by this nuclear equation:.\n", + "\n", + "Question: What is controlled by regulatory proteins that bind to regulatory elements on dna? \n", + "Support: Gene transcription is controlled by regulatory proteins that bind to regulatory elements on DNA. The proteins usually either activate or repress transcription. \n", + "Top result: As shown in Figure below , transcription is controlled by regulatory proteins . The proteins bind to regions of DNA, called regulatory elements , which are located near promoters. After regulatory proteins bind to regulatory elements, they can interact with RNA polymerase, the enzyme that transcribes DNA to mRNA. Regulatory proteins are typically either activators or repressors.\n", + "\n", + "Question: What occurs when the immune system attacks a harmless substance that enters the body from the outside? \n", + "Support: An allergy occurs when the immune system attacks a harmless substance that enters the body from the outside. A substance that causes an allergy is called an allergen. It is the immune system, not the allergen, that causes the symptoms of an allergy. \n", + "Top result: The second line of defense attacks pathogens that manage to enter the body. It includes the inflammatory response and phagocytosis by nonspecific leukocytes.\n", + "\n", + "Question: The plants alternation between haploid and diploud generations allow it to do what? \n", + "Support: All plants have a characteristic life cycle that includes alternation of generations . Plants alternate between haploid and diploid generations. Alternation of generations allows for both asexual and sexual reproduction. Asexual reproduction with spores produces haploid individuals called gametophytes . Sexual reproduction with gametes and fertilization produces diploid individuals called sporophytes . A typical plant’s life cycle is diagrammed in Figure below . \n", + "Top result: Plants alternate between diploid-cell plants and haploid-cell plants. This is called alternation of generations , because the plant type alternates from generation to generation. In alternation of generations, the plant alternates between a sporophyte that has diploid cells and a gametophyte that has haploid cells.\n", + "\n" + ] + } + ], + "source": [ + "for i, q in enumerate(dataset['question'][:20]):\n", + " support = dataset['support'][i]\n", + " top_result = question_results['documents'][i][0]\n", + "\n", + " if support != top_result:\n", + " print(f\"Question: {q} \\nSupport: {support} \\nTop result: {top_result}\\n\")" + ] + }, + { + "attachments": {}, + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Conclusion\n", + "\n", + "This notebook presents one possible approach to computing a relevance score for embeddings-based retreival, based on the distribution of distances between embeddings in the dataset. We have done some initial evaluation, but there is a lot left to do. \n", + "\n", + "Some things to try include:\n", + "- Construct the distance distribution on the basis of the query-support pairs, rather than between nearest neighbor supports. \n", + "- Additional evaluations comparing different embedding models for the same dataset, as well as datasets with less redundancy. \n", + "- Using the distance distribution to deduplicate data, by finding low-percentile outliers. One idea is to use an LLM in the loop to create summaries of document pairs, creating a single point from several which are near one another. \n", + "- Using relevance as a signal for automatically fine-tuning embedding space. One approach may be to learn an affine transform based on question/answer pairs, to increase the relevance of the correct points relative to others. \n", + "\n", + "We welcome contributions and ideas! " + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "chroma", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.10.12" + }, + "orig_nbformat": 4 + }, + "nbformat": 4, + "nbformat_minor": 2 +} diff --git a/python/user_packages/Python313/site-packages/chromadb/ingest/__init__.py b/python/user_packages/Python313/site-packages/chromadb/ingest/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..71ae6a1439847390098efa516b01940ace5c49d9 --- /dev/null +++ b/python/user_packages/Python313/site-packages/chromadb/ingest/__init__.py @@ -0,0 +1,121 @@ +from abc import abstractmethod +from typing import Callable, Optional, Sequence +from chromadb.types import ( + OperationRecord, + LogRecord, + SeqId, + Vector, + ScalarEncoding, +) +from chromadb.config import Component +from uuid import UUID +import numpy as np + + +def encode_vector(vector: Vector, encoding: ScalarEncoding) -> bytes: + """Encode a vector into a byte array.""" + + if encoding == ScalarEncoding.FLOAT32: + return np.array(vector, dtype=np.float32).tobytes() + elif encoding == ScalarEncoding.INT32: + return np.array(vector, dtype=np.int32).tobytes() + else: + raise ValueError(f"Unsupported encoding: {encoding.value}") + + +def decode_vector(vector: bytes, encoding: ScalarEncoding) -> Vector: + """Decode a byte array into a vector""" + + if encoding == ScalarEncoding.FLOAT32: + return np.frombuffer(vector, dtype=np.float32) + elif encoding == ScalarEncoding.INT32: + return np.frombuffer(vector, dtype=np.float32) + else: + raise ValueError(f"Unsupported encoding: {encoding.value}") + + +class Producer(Component): + """Interface for writing embeddings to an ingest stream""" + + @abstractmethod + def delete_log(self, collection_id: UUID) -> None: + pass + + @abstractmethod + def purge_log(self, collection_id: UUID) -> None: + """Truncates the log for the given collection, removing all seen records.""" + pass + + @abstractmethod + def submit_embedding( + self, collection_id: UUID, embedding: OperationRecord + ) -> SeqId: + """Add an embedding record to the given collections log. Returns the SeqID of the record.""" + pass + + @abstractmethod + def submit_embeddings( + self, collection_id: UUID, embeddings: Sequence[OperationRecord] + ) -> Sequence[SeqId]: + """Add a batch of embedding records to the given collections log. Returns the SeqIDs of + the records. The returned SeqIDs will be in the same order as the given + SubmitEmbeddingRecords. However, it is not guaranteed that the SeqIDs will be + processed in the same order as the given SubmitEmbeddingRecords. If the number + of records exceeds the maximum batch size, an exception will be thrown.""" + pass + + @property + @abstractmethod + def max_batch_size(self) -> int: + """Return the maximum number of records that can be submitted in a single call + to submit_embeddings.""" + pass + + +ConsumerCallbackFn = Callable[[Sequence[LogRecord]], None] + + +class Consumer(Component): + """Interface for reading embeddings off an ingest stream""" + + @abstractmethod + def subscribe( + self, + collection_id: UUID, + consume_fn: ConsumerCallbackFn, + start: Optional[SeqId] = None, + end: Optional[SeqId] = None, + id: Optional[UUID] = None, + ) -> UUID: + """Register a function that will be called to receive embeddings for a given + collections log stream. The given function may be called any number of times, with any number of + records, and may be called concurrently. + + Only records between start (exclusive) and end (inclusive) SeqIDs will be + returned. If start is None, the first record returned will be the next record + generated, not including those generated before creating the subscription. If + end is None, the consumer will consume indefinitely, otherwise it will + automatically be unsubscribed when the end SeqID is reached. + + If the function throws an exception, the function may be called again with the + same or different records. + + Takes an optional UUID as a unique subscription ID. If no ID is provided, a new + ID will be generated and returned.""" + pass + + @abstractmethod + def unsubscribe(self, subscription_id: UUID) -> None: + """Unregister a subscription. The consume function will no longer be invoked, + and resources associated with the subscription will be released.""" + pass + + @abstractmethod + def min_seqid(self) -> SeqId: + """Return the minimum possible SeqID in this implementation.""" + pass + + @abstractmethod + def max_seqid(self) -> SeqId: + """Return the maximum possible SeqID in this implementation.""" + pass diff --git a/python/user_packages/Python313/site-packages/chromadb/logservice/logservice.py b/python/user_packages/Python313/site-packages/chromadb/logservice/logservice.py new file mode 100644 index 0000000000000000000000000000000000000000..b228e249c6d62ea3c8a7078ccbc4883ed5f92ac2 --- /dev/null +++ b/python/user_packages/Python313/site-packages/chromadb/logservice/logservice.py @@ -0,0 +1,181 @@ +import sys + +from chromadb.proto.utils import RetryOnRpcErrorClientInterceptor +import grpc +import time +from chromadb.ingest import ( + Producer, + Consumer, + ConsumerCallbackFn, +) +from chromadb.proto.convert import to_proto_submit +from chromadb.proto.logservice_pb2 import PushLogsRequest, PullLogsRequest, LogRecord +from chromadb.proto.logservice_pb2_grpc import LogServiceStub +from chromadb.telemetry.opentelemetry.grpc import OtelInterceptor +from chromadb.types import ( + OperationRecord, + SeqId, +) +from chromadb.config import System +from chromadb.telemetry.opentelemetry import ( + OpenTelemetryClient, + OpenTelemetryGranularity, + add_attributes_to_current_span, + trace_method, +) +from overrides import override +from typing import Sequence, Optional, cast +from uuid import UUID +import logging + +logger = logging.getLogger(__name__) + + +class LogService(Producer, Consumer): + """ + Distributed Chroma Log Service + """ + + _log_service_stub: LogServiceStub + _request_timeout_seconds: int + _channel: grpc.Channel + _log_service_url: str + _log_service_port: int + + def __init__(self, system: System): + self._log_service_url = system.settings.require("chroma_logservice_host") + self._log_service_port = system.settings.require("chroma_logservice_port") + self._request_timeout_seconds = system.settings.require( + "chroma_logservice_request_timeout_seconds" + ) + self._opentelemetry_client = system.require(OpenTelemetryClient) + super().__init__(system) + + @trace_method("LogService.start", OpenTelemetryGranularity.ALL) + @override + def start(self) -> None: + self._channel = grpc.insecure_channel( + f"{self._log_service_url}:{self._log_service_port}", + ) + interceptors = [OtelInterceptor(), RetryOnRpcErrorClientInterceptor()] + self._channel = grpc.intercept_channel(self._channel, *interceptors) + self._log_service_stub = LogServiceStub(self._channel) # type: ignore + super().start() + + @trace_method("LogService.stop", OpenTelemetryGranularity.ALL) + @override + def stop(self) -> None: + self._channel.close() + super().stop() + + @trace_method("LogService.reset_state", OpenTelemetryGranularity.ALL) + @override + def reset_state(self) -> None: + super().reset_state() + + @trace_method("LogService.delete_log", OpenTelemetryGranularity.ALL) + @override + def delete_log(self, collection_id: UUID) -> None: + raise NotImplementedError("Not implemented") + + @trace_method("LogService.purge_log", OpenTelemetryGranularity.ALL) + @override + def purge_log(self, collection_id: UUID) -> None: + raise NotImplementedError("Not implemented") + + @trace_method("LogService.submit_embedding", OpenTelemetryGranularity.ALL) + @override + def submit_embedding( + self, collection_id: UUID, embedding: OperationRecord + ) -> SeqId: + if not self._running: + raise RuntimeError("Component not running") + + return self.submit_embeddings(collection_id, [embedding])[0] + + @trace_method("LogService.submit_embeddings", OpenTelemetryGranularity.ALL) + @override + def submit_embeddings( + self, collection_id: UUID, embeddings: Sequence[OperationRecord] + ) -> Sequence[SeqId]: + logger.info( + f"Submitting {len(embeddings)} embeddings to log for collection {collection_id}" + ) + + add_attributes_to_current_span( + { + "records_count": len(embeddings), + } + ) + + if not self._running: + raise RuntimeError("Component not running") + + if len(embeddings) == 0: + return [] + + # push records to the log service + counts = [] + protos_to_submit = [to_proto_submit(record) for record in embeddings] + counts.append( + self.push_logs( + collection_id, + cast(Sequence[OperationRecord], protos_to_submit), + ) + ) + + # This returns counts, which is completely incorrect + # TODO: Fix this + return counts + + @trace_method("LogService.subscribe", OpenTelemetryGranularity.ALL) + @override + def subscribe( + self, + collection_id: UUID, + consume_fn: ConsumerCallbackFn, + start: Optional[SeqId] = None, + end: Optional[SeqId] = None, + id: Optional[UUID] = None, + ) -> UUID: + logger.info(f"Subscribing to log for {collection_id}, noop for logservice") + return UUID(int=0) + + @trace_method("LogService.unsubscribe", OpenTelemetryGranularity.ALL) + @override + def unsubscribe(self, subscription_id: UUID) -> None: + logger.info(f"Unsubscribing from {subscription_id}, noop for logservice") + + @override + def min_seqid(self) -> SeqId: + return 0 + + @override + def max_seqid(self) -> SeqId: + return sys.maxsize + + @property + @override + def max_batch_size(self) -> int: + return 100 + + def push_logs(self, collection_id: UUID, records: Sequence[OperationRecord]) -> int: + request = PushLogsRequest(collection_id=str(collection_id), records=records) + response = self._log_service_stub.PushLogs( + request, timeout=self._request_timeout_seconds + ) + return response.record_count # type: ignore + + def pull_logs( + self, collection_id: UUID, start_offset: int, batch_size: int + ) -> Sequence[LogRecord]: + request = PullLogsRequest( + collection_id=str(collection_id), + start_from_offset=start_offset, + batch_size=batch_size, + end_timestamp=time.time_ns(), + ) + response = self._log_service_stub.PullLogs( + request, timeout=self._request_timeout_seconds + ) + return response.records # type: ignore diff --git a/python/user_packages/Python313/site-packages/chromadb/migrations/__init__.py b/python/user_packages/Python313/site-packages/chromadb/migrations/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/python/user_packages/Python313/site-packages/chromadb/proto/.gitignore b/python/user_packages/Python313/site-packages/chromadb/proto/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..6d2a6dd14a7310806630d0977e9fc0b0256c8fb2 --- /dev/null +++ b/python/user_packages/Python313/site-packages/chromadb/proto/.gitignore @@ -0,0 +1,2 @@ +*_pb2.py* +*_pb2_grpc.py diff --git a/python/user_packages/Python313/site-packages/chromadb/proto/__init__.py b/python/user_packages/Python313/site-packages/chromadb/proto/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/python/user_packages/Python313/site-packages/chromadb/proto/convert.py b/python/user_packages/Python313/site-packages/chromadb/proto/convert.py new file mode 100644 index 0000000000000000000000000000000000000000..0e5f5b7e0daaa53d43aecdc572cc3d7afae24e6f --- /dev/null +++ b/python/user_packages/Python313/site-packages/chromadb/proto/convert.py @@ -0,0 +1,688 @@ +from typing import Dict, Optional, Sequence, Tuple, TypedDict, Union, cast +from uuid import UUID +import json + +import numpy as np +from numpy.typing import NDArray + +import chromadb.proto.chroma_pb2 as chroma_pb +import chromadb.proto.query_executor_pb2 as query_pb +from chromadb.api.collection_configuration import ( + collection_configuration_to_json_str, +) +from chromadb.api.types import Embedding, Where, WhereDocument +from chromadb.execution.expression.operator import ( + KNN, + Filter, + Limit, + Projection, + Scan, +) +from chromadb.execution.expression.plan import CountPlan, GetPlan, KNNPlan +from chromadb.types import ( + Collection, + LogRecord, + Metadata, + Operation, + OperationRecord, + RequestVersionContext, + ScalarEncoding, + Segment, + SegmentScope, + SeqId, + UpdateMetadata, + Vector, + VectorEmbeddingRecord, + VectorQueryResult, +) + + +class ProjectionRecord(TypedDict): + id: str + document: Optional[str] + embedding: Optional[Vector] + metadata: Optional[Metadata] + + +class KNNProjectionRecord(TypedDict): + record: ProjectionRecord + distance: Optional[float] + + +# TODO: Unit tests for this file, handling optional states etc +def to_proto_vector(vector: Vector, encoding: ScalarEncoding) -> chroma_pb.Vector: + if encoding == ScalarEncoding.FLOAT32: + as_bytes = np.array(vector, dtype=np.float32).tobytes() + proto_encoding = chroma_pb.ScalarEncoding.FLOAT32 + elif encoding == ScalarEncoding.INT32: + as_bytes = np.array(vector, dtype=np.int32).tobytes() + proto_encoding = chroma_pb.ScalarEncoding.INT32 + else: + raise ValueError( + f"Unknown encoding {encoding}, expected one of {ScalarEncoding.FLOAT32} \ + or {ScalarEncoding.INT32}" + ) + + return chroma_pb.Vector( + dimension=vector.size, vector=as_bytes, encoding=proto_encoding + ) + + +def from_proto_vector(vector: chroma_pb.Vector) -> Tuple[Embedding, ScalarEncoding]: + encoding = vector.encoding + as_array: Union[NDArray[np.int32], NDArray[np.float32]] + if encoding == chroma_pb.ScalarEncoding.FLOAT32: + as_array = np.frombuffer(vector.vector, dtype=np.float32) + out_encoding = ScalarEncoding.FLOAT32 + elif encoding == chroma_pb.ScalarEncoding.INT32: + as_array = np.frombuffer(vector.vector, dtype=np.int32) + out_encoding = ScalarEncoding.INT32 + else: + raise ValueError( + f"Unknown encoding {encoding}, expected one of \ + {chroma_pb.ScalarEncoding.FLOAT32} or {chroma_pb.ScalarEncoding.INT32}" + ) + + return (as_array, out_encoding) + + +def from_proto_operation(operation: chroma_pb.Operation) -> Operation: + if operation == chroma_pb.Operation.ADD: + return Operation.ADD + elif operation == chroma_pb.Operation.UPDATE: + return Operation.UPDATE + elif operation == chroma_pb.Operation.UPSERT: + return Operation.UPSERT + elif operation == chroma_pb.Operation.DELETE: + return Operation.DELETE + else: + # TODO: full error + raise RuntimeError(f"Unknown operation {operation}") + + +def from_proto_metadata(metadata: chroma_pb.UpdateMetadata) -> Optional[Metadata]: + return cast(Optional[Metadata], _from_proto_metadata_handle_none(metadata, False)) + + +def from_proto_update_metadata( + metadata: chroma_pb.UpdateMetadata, +) -> Optional[UpdateMetadata]: + return cast( + Optional[UpdateMetadata], _from_proto_metadata_handle_none(metadata, True) + ) + + +def _from_proto_metadata_handle_none( + metadata: chroma_pb.UpdateMetadata, is_update: bool +) -> Optional[Union[UpdateMetadata, Metadata]]: + if not metadata.metadata: + return None + out_metadata: Dict[str, Union[str, int, float, bool, None]] = {} + for key, value in metadata.metadata.items(): + if value.HasField("bool_value"): + out_metadata[key] = value.bool_value + elif value.HasField("string_value"): + out_metadata[key] = value.string_value + elif value.HasField("int_value"): + out_metadata[key] = value.int_value + elif value.HasField("float_value"): + out_metadata[key] = value.float_value + elif is_update: + out_metadata[key] = None + else: + raise ValueError(f"Metadata key {key} value cannot be None") + return out_metadata + + +def to_proto_update_metadata(metadata: UpdateMetadata) -> chroma_pb.UpdateMetadata: + return chroma_pb.UpdateMetadata( + metadata={k: to_proto_metadata_update_value(v) for k, v in metadata.items()} + ) + + +def from_proto_submit( + operation_record: chroma_pb.OperationRecord, seq_id: SeqId +) -> LogRecord: + embedding, encoding = from_proto_vector(operation_record.vector) + record = LogRecord( + log_offset=seq_id, + record=OperationRecord( + id=operation_record.id, + embedding=embedding, + encoding=encoding, + metadata=from_proto_update_metadata(operation_record.metadata), + operation=from_proto_operation(operation_record.operation), + ), + ) + return record + + +def from_proto_segment(segment: chroma_pb.Segment) -> Segment: + return Segment( + id=UUID(hex=segment.id), + type=segment.type, + scope=from_proto_segment_scope(segment.scope), + collection=UUID(hex=segment.collection), + metadata=from_proto_metadata(segment.metadata) + if segment.HasField("metadata") + else None, + file_paths={ + name: [path for path in paths.paths] + for name, paths in segment.file_paths.items() + }, + ) + + +def to_proto_segment(segment: Segment) -> chroma_pb.Segment: + return chroma_pb.Segment( + id=segment["id"].hex, + type=segment["type"], + scope=to_proto_segment_scope(segment["scope"]), + collection=segment["collection"].hex, + metadata=None + if segment["metadata"] is None + else to_proto_update_metadata(segment["metadata"]), + file_paths={ + name: chroma_pb.FilePaths(paths=paths) + for name, paths in segment["file_paths"].items() + }, + ) + + +def from_proto_segment_scope(segment_scope: chroma_pb.SegmentScope) -> SegmentScope: + if segment_scope == chroma_pb.SegmentScope.VECTOR: + return SegmentScope.VECTOR + elif segment_scope == chroma_pb.SegmentScope.METADATA: + return SegmentScope.METADATA + elif segment_scope == chroma_pb.SegmentScope.RECORD: + return SegmentScope.RECORD + else: + raise RuntimeError(f"Unknown segment scope {segment_scope}") + + +def to_proto_segment_scope(segment_scope: SegmentScope) -> chroma_pb.SegmentScope: + if segment_scope == SegmentScope.VECTOR: + return chroma_pb.SegmentScope.VECTOR + elif segment_scope == SegmentScope.METADATA: + return chroma_pb.SegmentScope.METADATA + elif segment_scope == SegmentScope.RECORD: + return chroma_pb.SegmentScope.RECORD + else: + raise RuntimeError(f"Unknown segment scope {segment_scope}") + + +def to_proto_metadata_update_value( + value: Union[str, int, float, bool, None] +) -> chroma_pb.UpdateMetadataValue: + # Be careful with the order here. Since bools are a subtype of int in python, + # isinstance(value, bool) and isinstance(value, int) both return true + # for a value of bool type. + if isinstance(value, bool): + return chroma_pb.UpdateMetadataValue(bool_value=value) + elif isinstance(value, str): + return chroma_pb.UpdateMetadataValue(string_value=value) + elif isinstance(value, int): + return chroma_pb.UpdateMetadataValue(int_value=value) + elif isinstance(value, float): + return chroma_pb.UpdateMetadataValue(float_value=value) + # None is used to delete the metadata key. + elif value is None: + return chroma_pb.UpdateMetadataValue() + else: + raise ValueError( + f"Unknown metadata value type {type(value)}, expected one of str, int, \ + float, or None" + ) + + +def from_proto_collection(collection: chroma_pb.Collection) -> Collection: + return Collection( + id=UUID(hex=collection.id), + name=collection.name, + configuration_json=json.loads(collection.configuration_json_str), + metadata=from_proto_metadata(collection.metadata) + if collection.HasField("metadata") + else None, + dimension=collection.dimension + if collection.HasField("dimension") and collection.dimension + else None, + database=collection.database, + tenant=collection.tenant, + version=collection.version, + log_position=collection.log_position, + ) + + +def to_proto_collection(collection: Collection) -> chroma_pb.Collection: + return chroma_pb.Collection( + id=collection["id"].hex, + name=collection["name"], + configuration_json_str=collection_configuration_to_json_str( + collection.get_configuration() + ), + metadata=None + if collection["metadata"] is None + else to_proto_update_metadata(collection["metadata"]), + dimension=collection["dimension"], + tenant=collection["tenant"], + database=collection["database"], + log_position=collection["log_position"], + version=collection["version"], + ) + + +def to_proto_operation(operation: Operation) -> chroma_pb.Operation: + if operation == Operation.ADD: + return chroma_pb.Operation.ADD + elif operation == Operation.UPDATE: + return chroma_pb.Operation.UPDATE + elif operation == Operation.UPSERT: + return chroma_pb.Operation.UPSERT + elif operation == Operation.DELETE: + return chroma_pb.Operation.DELETE + else: + raise ValueError( + f"Unknown operation {operation}, expected one of {Operation.ADD}, \ + {Operation.UPDATE}, {Operation.UPDATE}, or {Operation.DELETE}" + ) + + +def to_proto_submit( + submit_record: OperationRecord, +) -> chroma_pb.OperationRecord: + vector = None + if submit_record["embedding"] is not None and submit_record["encoding"] is not None: + vector = to_proto_vector(submit_record["embedding"], submit_record["encoding"]) + + metadata = None + if submit_record["metadata"] is not None: + metadata = to_proto_update_metadata(submit_record["metadata"]) + + return chroma_pb.OperationRecord( + id=submit_record["id"], + vector=vector, + metadata=metadata, + operation=to_proto_operation(submit_record["operation"]), + ) + + +def from_proto_vector_embedding_record( + embedding_record: chroma_pb.VectorEmbeddingRecord, +) -> VectorEmbeddingRecord: + return VectorEmbeddingRecord( + id=embedding_record.id, + embedding=from_proto_vector(embedding_record.vector)[0], + ) + + +def to_proto_vector_embedding_record( + embedding_record: VectorEmbeddingRecord, + encoding: ScalarEncoding, +) -> chroma_pb.VectorEmbeddingRecord: + return chroma_pb.VectorEmbeddingRecord( + id=embedding_record["id"], + vector=to_proto_vector(embedding_record["embedding"], encoding), + ) + + +def from_proto_vector_query_result( + vector_query_result: chroma_pb.VectorQueryResult, +) -> VectorQueryResult: + return VectorQueryResult( + id=vector_query_result.id, + distance=vector_query_result.distance, + embedding=from_proto_vector(vector_query_result.vector)[0], + ) + + +def from_proto_request_version_context( + request_version_context: chroma_pb.RequestVersionContext, +) -> RequestVersionContext: + return RequestVersionContext( + collection_version=request_version_context.collection_version, + log_position=request_version_context.log_position, + ) + + +def to_proto_request_version_context( + request_version_context: RequestVersionContext, +) -> chroma_pb.RequestVersionContext: + return chroma_pb.RequestVersionContext( + collection_version=request_version_context["collection_version"], + log_position=request_version_context["log_position"], + ) + + +def to_proto_where(where: Where) -> chroma_pb.Where: + response = chroma_pb.Where() + if len(where) != 1: + raise ValueError(f"Expected where to have exactly one operator, got {where}") + + for key, value in where.items(): + if not isinstance(key, str): + raise ValueError(f"Expected where key to be a str, got {key}") + + if key == "$and" or key == "$or": + if not isinstance(value, list): + raise ValueError( + f"Expected where value for $and or $or to be a list of where expressions, got {value}" + ) + children: chroma_pb.WhereChildren = chroma_pb.WhereChildren( + children=[to_proto_where(w) for w in value] + ) + if key == "$and": + children.operator = chroma_pb.BooleanOperator.AND + else: + children.operator = chroma_pb.BooleanOperator.OR + + response.children.CopyFrom(children) + return response + + # At this point we know we're at a direct comparison. It can either + # be of the form {"key": "value"} or {"key": {"$operator": "value"}}. + + dc = chroma_pb.DirectComparison() + dc.key = key + + if not isinstance(value, dict): + # {'key': 'value'} case + if type(value) is str: + ssc = chroma_pb.SingleStringComparison() + ssc.value = value + ssc.comparator = chroma_pb.GenericComparator.EQ + dc.single_string_operand.CopyFrom(ssc) + elif type(value) is bool: + sbc = chroma_pb.SingleBoolComparison() + sbc.value = value + sbc.comparator = chroma_pb.GenericComparator.EQ + dc.single_bool_operand.CopyFrom(sbc) + elif type(value) is int: + sic = chroma_pb.SingleIntComparison() + sic.value = value + sic.generic_comparator = chroma_pb.GenericComparator.EQ + dc.single_int_operand.CopyFrom(sic) + elif type(value) is float: + sdc = chroma_pb.SingleDoubleComparison() + sdc.value = value + sdc.generic_comparator = chroma_pb.GenericComparator.EQ + dc.single_double_operand.CopyFrom(sdc) + else: + raise ValueError( + f"Expected where value to be a string, int, or float, got {value}" + ) + else: + for operator, operand in value.items(): + if operator in ["$in", "$nin"]: + if not isinstance(operand, list): + raise ValueError( + f"Expected where value for $in or $nin to be a list of values, got {value}" + ) + if len(operand) == 0 or not all( + isinstance(x, type(operand[0])) for x in operand + ): + raise ValueError( + f"Expected where operand value to be a non-empty list, and all values to be of the same type " + f"got {operand}" + ) + list_operator = None + if operator == "$in": + list_operator = chroma_pb.ListOperator.IN + else: + list_operator = chroma_pb.ListOperator.NIN + if type(operand[0]) is str: + slo = chroma_pb.StringListComparison() + for x in operand: + slo.values.extend([x]) # type: ignore + slo.list_operator = list_operator + dc.string_list_operand.CopyFrom(slo) + elif type(operand[0]) is bool: + blo = chroma_pb.BoolListComparison() + for x in operand: + blo.values.extend([x]) # type: ignore + blo.list_operator = list_operator + dc.bool_list_operand.CopyFrom(blo) + elif type(operand[0]) is int: + ilo = chroma_pb.IntListComparison() + for x in operand: + ilo.values.extend([x]) # type: ignore + ilo.list_operator = list_operator + dc.int_list_operand.CopyFrom(ilo) + elif type(operand[0]) is float: + dlo = chroma_pb.DoubleListComparison() + for x in operand: + dlo.values.extend([x]) # type: ignore + dlo.list_operator = list_operator + dc.double_list_operand.CopyFrom(dlo) + else: + raise ValueError( + f"Expected where operand value to be a list of strings, ints, or floats, got {operand}" + ) + elif operator in ["$eq", "$ne", "$gt", "$lt", "$gte", "$lte"]: + # Direct comparison to a single value. + if type(operand) is str: + ssc = chroma_pb.SingleStringComparison() + ssc.value = operand + if operator == "$eq": + ssc.comparator = chroma_pb.GenericComparator.EQ + elif operator == "$ne": + ssc.comparator = chroma_pb.GenericComparator.NE + else: + raise ValueError( + f"Expected where operator to be $eq or $ne, got {operator}" + ) + dc.single_string_operand.CopyFrom(ssc) + elif type(operand) is bool: + sbc = chroma_pb.SingleBoolComparison() + sbc.value = operand + if operator == "$eq": + sbc.comparator = chroma_pb.GenericComparator.EQ + elif operator == "$ne": + sbc.comparator = chroma_pb.GenericComparator.NE + else: + raise ValueError( + f"Expected where operator to be $eq or $ne, got {operator}" + ) + dc.single_bool_operand.CopyFrom(sbc) + elif type(operand) is int: + sic = chroma_pb.SingleIntComparison() + sic.value = operand + if operator == "$eq": + sic.generic_comparator = chroma_pb.GenericComparator.EQ + elif operator == "$ne": + sic.generic_comparator = chroma_pb.GenericComparator.NE + elif operator == "$gt": + sic.number_comparator = chroma_pb.NumberComparator.GT + elif operator == "$lt": + sic.number_comparator = chroma_pb.NumberComparator.LT + elif operator == "$gte": + sic.number_comparator = chroma_pb.NumberComparator.GTE + elif operator == "$lte": + sic.number_comparator = chroma_pb.NumberComparator.LTE + else: + raise ValueError( + f"Expected where operator to be one of $eq, $ne, $gt, $lt, $gte, $lte, got {operator}" + ) + dc.single_int_operand.CopyFrom(sic) + elif type(operand) is float: + sfc = chroma_pb.SingleDoubleComparison() + sfc.value = operand + if operator == "$eq": + sfc.generic_comparator = chroma_pb.GenericComparator.EQ + elif operator == "$ne": + sfc.generic_comparator = chroma_pb.GenericComparator.NE + elif operator == "$gt": + sfc.number_comparator = chroma_pb.NumberComparator.GT + elif operator == "$lt": + sfc.number_comparator = chroma_pb.NumberComparator.LT + elif operator == "$gte": + sfc.number_comparator = chroma_pb.NumberComparator.GTE + elif operator == "$lte": + sfc.number_comparator = chroma_pb.NumberComparator.LTE + else: + raise ValueError( + f"Expected where operator to be one of $eq, $ne, $gt, $lt, $gte, $lte, got {operator}" + ) + dc.single_double_operand.CopyFrom(sfc) + else: + raise ValueError( + f"Expected where operand value to be a string, int, or float, got {operand}" + ) + else: + # This case should never happen, as we've already + # handled the case for direct comparisons. + pass + + response.direct_comparison.CopyFrom(dc) + return response + + +def to_proto_where_document(where_document: WhereDocument) -> chroma_pb.WhereDocument: + response = chroma_pb.WhereDocument() + if len(where_document) != 1: + raise ValueError( + f"Expected where_document to have exactly one operator, got {where_document}" + ) + + for operator, operand in where_document.items(): + if operator == "$and" or operator == "$or": + # Nested "$and" or "$or" expression. + if not isinstance(operand, list): + raise ValueError( + f"Expected where_document value for $and or $or to be a list of where_document expressions, got {operand}" + ) + children: chroma_pb.WhereDocumentChildren = chroma_pb.WhereDocumentChildren( + children=[to_proto_where_document(w) for w in operand] + ) + if operator == "$and": + children.operator = chroma_pb.BooleanOperator.AND + else: + children.operator = chroma_pb.BooleanOperator.OR + + response.children.CopyFrom(children) + else: + # Direct "$contains" or "$not_contains" comparison to a single + # value. + if not isinstance(operand, str): + raise ValueError( + f"Expected where_document operand to be a string, got {operand}" + ) + dwd = chroma_pb.DirectWhereDocument() + dwd.document = operand + if operator == "$contains": + dwd.operator = chroma_pb.WhereDocumentOperator.CONTAINS + elif operator == "$not_contains": + dwd.operator = chroma_pb.WhereDocumentOperator.NOT_CONTAINS + else: + raise ValueError( + f"Expected where_document operator to be one of $contains, $not_contains, got {operator}" + ) + response.direct.CopyFrom(dwd) + + return response + + +def to_proto_scan(scan: Scan) -> query_pb.ScanOperator: + return query_pb.ScanOperator( + collection=to_proto_collection(scan.collection), + knn=to_proto_segment(scan.knn), + metadata=to_proto_segment(scan.metadata), + record=to_proto_segment(scan.record), + ) + + +def to_proto_filter(filter: Filter) -> query_pb.FilterOperator: + return query_pb.FilterOperator( + ids=chroma_pb.UserIds(ids=filter.user_ids) + if filter.user_ids is not None + else None, + where=to_proto_where(filter.where) if filter.where else None, + where_document=to_proto_where_document(filter.where_document) + if filter.where_document + else None, + ) + + +def to_proto_knn(knn: KNN) -> query_pb.KNNOperator: + return query_pb.KNNOperator( + embeddings=[ + to_proto_vector(vector=embedding, encoding=ScalarEncoding.FLOAT32) + for embedding in knn.embeddings + ], + fetch=knn.fetch, + ) + + +def to_proto_limit(limit: Limit) -> query_pb.LimitOperator: + return query_pb.LimitOperator(offset=limit.offset, limit=limit.limit) + + +def to_proto_projection(projection: Projection) -> query_pb.ProjectionOperator: + return query_pb.ProjectionOperator( + document=projection.document, + embedding=projection.embedding, + metadata=projection.metadata, + ) + + +def to_proto_knn_projection(projection: Projection) -> query_pb.KNNProjectionOperator: + return query_pb.KNNProjectionOperator( + projection=to_proto_projection(projection), distance=projection.rank + ) + + +def to_proto_count_plan(count: CountPlan) -> query_pb.CountPlan: + return query_pb.CountPlan(scan=to_proto_scan(count.scan)) + + +def from_proto_count_result(result: query_pb.CountResult) -> int: + return result.count + + +def to_proto_get_plan(get: GetPlan) -> query_pb.GetPlan: + return query_pb.GetPlan( + scan=to_proto_scan(get.scan), + filter=to_proto_filter(get.filter), + limit=to_proto_limit(get.limit), + projection=to_proto_projection(get.projection), + ) + + +def from_proto_projection_record(record: query_pb.ProjectionRecord) -> ProjectionRecord: + return ProjectionRecord( + id=record.id, + document=record.document if record.document else None, + embedding=from_proto_vector(record.embedding)[0] + if record.embedding is not None + else None, + metadata=from_proto_metadata(record.metadata), + ) + + +def from_proto_get_result(result: query_pb.GetResult) -> Sequence[ProjectionRecord]: + return [from_proto_projection_record(record) for record in result.records] + + +def to_proto_knn_plan(knn: KNNPlan) -> query_pb.KNNPlan: + return query_pb.KNNPlan( + scan=to_proto_scan(knn.scan), + filter=to_proto_filter(knn.filter), + knn=to_proto_knn(knn.knn), + projection=to_proto_knn_projection(knn.projection), + ) + + +def from_proto_knn_projection_record( + record: query_pb.KNNProjectionRecord, +) -> KNNProjectionRecord: + return KNNProjectionRecord( + record=from_proto_projection_record(record.record), distance=record.distance + ) + + +def from_proto_knn_batch_result( + results: query_pb.KNNBatchResult, +) -> Sequence[Sequence[KNNProjectionRecord]]: + return [ + [from_proto_knn_projection_record(record) for record in result.records] + for result in results.results + ] diff --git a/python/user_packages/Python313/site-packages/chromadb/proto/utils.py b/python/user_packages/Python313/site-packages/chromadb/proto/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..040f733d2610edf1be977a757b1190c4030a1d3e --- /dev/null +++ b/python/user_packages/Python313/site-packages/chromadb/proto/utils.py @@ -0,0 +1,68 @@ +from typing import Optional, Set +import grpc +from tenacity import retry, stop_after_attempt, wait_exponential_jitter, retry_if_result +from opentelemetry.trace import Span + + +class RetryOnRpcErrorClientInterceptor( + grpc.UnaryUnaryClientInterceptor, grpc.UnaryStreamClientInterceptor +): + """ + A gRPC client interceptor that retries RPCs on specific status codes. By default, it retries on UNAVAILABLE and UNKNOWN status codes. + + This interceptor should be placed after the OpenTelemetry interceptor in the interceptor list. + """ + + max_attempts: int + retryable_status_codes: Set[grpc.StatusCode] + + def __init__( + self, + max_attempts: int = 5, + retryable_status_codes: Set[grpc.StatusCode] = set( + [grpc.StatusCode.UNAVAILABLE, grpc.StatusCode.UNKNOWN] + ), + ) -> None: + self.max_attempts = max_attempts + self.retryable_status_codes = retryable_status_codes + + def _intercept_call(self, continuation, client_call_details, request_or_iterator): + sleep_span: Optional[Span] = None + + def before_sleep(_): + from chromadb.telemetry.opentelemetry import tracer + + nonlocal sleep_span + if tracer is not None: + sleep_span = tracer.start_span("Waiting to retry RPC") + + @retry( + wait=wait_exponential_jitter(0.1, jitter=0.1), + stop=stop_after_attempt(self.max_attempts), + retry=retry_if_result(lambda x: x.code() in self.retryable_status_codes), + before_sleep=before_sleep, + ) + def wrapped(*args, **kwargs): + nonlocal sleep_span + if sleep_span is not None: + sleep_span.end() + sleep_span = None + return continuation(*args, **kwargs) + + return wrapped(client_call_details, request_or_iterator) + + def intercept_unary_unary(self, continuation, client_call_details, request): + return self._intercept_call(continuation, client_call_details, request) + + def intercept_unary_stream(self, continuation, client_call_details, request): + return self._intercept_call(continuation, client_call_details, request) + + def intercept_stream_unary( + self, continuation, client_call_details, request_iterator + ): + return self._intercept_call(continuation, client_call_details, request_iterator) + + def intercept_stream_stream( + self, continuation, client_call_details, request_iterator + ): + return self._intercept_call(continuation, client_call_details, request_iterator) diff --git a/python/user_packages/Python313/site-packages/chromadb/quota/__init__.py b/python/user_packages/Python313/site-packages/chromadb/quota/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..a684ec33838d6b5e83c65b94be52a4c13f8e1a35 --- /dev/null +++ b/python/user_packages/Python313/site-packages/chromadb/quota/__init__.py @@ -0,0 +1,71 @@ +from abc import abstractmethod +from enum import Enum +from typing import Dict, Any, Optional +from uuid import UUID + +from chromadb.api.types import ( + Embeddings, + Metadatas, + Documents, + URIs, + IDs, + CollectionMetadata, + Where, + WhereDocument, +) +from chromadb.config import Component, System + + +class Action(str, Enum): + CREATE_DATABASE = "create_database" + CREATE_COLLECTION = "create_collection" + LIST_COLLECTIONS = "list_collections" + UPDATE_COLLECTION = "update_collection" + ADD = "add" + GET = "get" + DELETE = "delete" + UPDATE = "update" + UPSERT = "upsert" + QUERY = "query" + + +class QuotaEnforcer(Component): + """ + Exposes hooks to enforce quotas. + """ + + def __init__(self, system: System) -> None: + super().__init__(system) + + @abstractmethod + def set_context(self, context: Dict[str, Any]) -> None: + """ + Sets the context for a given request. + """ + pass + + @abstractmethod + def enforce( + self, + action: Action, + tenant: str, + metadatas: Optional[Metadatas] = None, + documents: Optional[Documents] = None, + embeddings: Optional[Embeddings] = None, + uris: Optional[URIs] = None, + ids: Optional[IDs] = None, + name: Optional[str] = None, + new_name: Optional[str] = None, + metadata: Optional[CollectionMetadata] = None, + new_metadata: Optional[CollectionMetadata] = None, + limit: Optional[int] = None, + where: Optional[Where] = None, + where_document: Optional[WhereDocument] = None, + n_results: Optional[int] = None, + query_embeddings: Optional[Embeddings] = None, + collection_id: Optional[UUID] = None, + ) -> None: + """ + Enforces a quota. + """ + pass diff --git a/python/user_packages/Python313/site-packages/chromadb/rate_limit/__init__.py b/python/user_packages/Python313/site-packages/chromadb/rate_limit/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..6937ebfcc9ed6a0039d8468b71cc3fe3e872453e --- /dev/null +++ b/python/user_packages/Python313/site-packages/chromadb/rate_limit/__init__.py @@ -0,0 +1,36 @@ +from abc import abstractmethod +from typing import Awaitable, Callable, TypeVar, Any +from chromadb.config import Component, System + +T = TypeVar("T", bound=Callable[..., Any]) +A = TypeVar("A", bound=Awaitable[Any]) + + +class RateLimitEnforcer(Component): + """ + Rate limit enforcer. + + Implemented as a wrapper around server functions to block requests if rate limits are exceeded. + """ + + def __init__(self, system: System) -> None: + super().__init__(system) + + @abstractmethod + def rate_limit(self, func: T) -> T: + pass + + +class AsyncRateLimitEnforcer(Component): + """ + Rate limit enforcer. + + Implemented as a wrapper around async functions to block requests if rate limits are exceeded. + """ + + def __init__(self, system: System) -> None: + super().__init__(system) + + @abstractmethod + def rate_limit(self, func: A) -> A: + pass diff --git a/python/user_packages/Python313/site-packages/chromadb/segment/__init__.py b/python/user_packages/Python313/site-packages/chromadb/segment/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..7a2b8c9e5dd27d25bbbc3166db6375e2f9f33c92 --- /dev/null +++ b/python/user_packages/Python313/site-packages/chromadb/segment/__init__.py @@ -0,0 +1,125 @@ +from typing import Optional, Sequence, TypeVar +from abc import abstractmethod +from chromadb.types import ( + Collection, + MetadataEmbeddingRecord, + Operation, + RequestVersionContext, + VectorEmbeddingRecord, + Where, + WhereDocument, + VectorQuery, + VectorQueryResult, + Segment, + SeqId, + Metadata, +) +from chromadb.config import Component, System +from uuid import UUID +from enum import Enum + + +class SegmentType(Enum): + SQLITE = "urn:chroma:segment/metadata/sqlite" + HNSW_LOCAL_MEMORY = "urn:chroma:segment/vector/hnsw-local-memory" + HNSW_LOCAL_PERSISTED = "urn:chroma:segment/vector/hnsw-local-persisted" + HNSW_DISTRIBUTED = "urn:chroma:segment/vector/hnsw-distributed" + BLOCKFILE_RECORD = "urn:chroma:segment/record/blockfile" + BLOCKFILE_METADATA = "urn:chroma:segment/metadata/blockfile" + + +class SegmentImplementation(Component): + @abstractmethod + def __init__(self, sytstem: System, segment: Segment): + pass + + @abstractmethod + def count(self, request_version_context: RequestVersionContext) -> int: + """Get the number of embeddings in this segment""" + pass + + @abstractmethod + def max_seqid(self) -> SeqId: + """Get the maximum SeqID currently indexed by this segment""" + pass + + @staticmethod + def propagate_collection_metadata(metadata: Metadata) -> Optional[Metadata]: + """Given an arbitrary metadata map (e.g, from a collection), validate it and + return metadata (if any) that is applicable and should be applied to the + segment. Validation errors will be reported to the user.""" + return None + + @abstractmethod + def delete(self) -> None: + """Delete the segment and all its data""" + ... + + +S = TypeVar("S", bound=SegmentImplementation) + + +class MetadataReader(SegmentImplementation): + """Embedding Metadata segment interface""" + + @abstractmethod + def get_metadata( + self, + request_version_context: RequestVersionContext, + where: Optional[Where] = None, + where_document: Optional[WhereDocument] = None, + ids: Optional[Sequence[str]] = None, + limit: Optional[int] = None, + offset: Optional[int] = None, + include_metadata: bool = True, + ) -> Sequence[MetadataEmbeddingRecord]: + """Query for embedding metadata.""" + pass + + +class VectorReader(SegmentImplementation): + """Embedding Vector segment interface""" + + @abstractmethod + def get_vectors( + self, + request_version_context: RequestVersionContext, + ids: Optional[Sequence[str]] = None, + ) -> Sequence[VectorEmbeddingRecord]: + """Get embeddings from the segment. If no IDs are provided, all embeddings are + returned.""" + pass + + @abstractmethod + def query_vectors( + self, query: VectorQuery + ) -> Sequence[Sequence[VectorQueryResult]]: + """Given a vector query, return the top-k nearest neighbors for vector in the + query.""" + pass + + +class SegmentManager(Component): + """Interface for a pluggable strategy for creating, retrieving and instantiating + segments as required""" + + @abstractmethod + def prepare_segments_for_new_collection( + self, collection: Collection + ) -> Sequence[Segment]: + """Return the segments required for a new collection. Returns only segment data, + does not persist to the SysDB""" + pass + + @abstractmethod + def delete_segments(self, collection_id: UUID) -> Sequence[UUID]: + """Delete any local state for all the segments associated with a collection, and + returns a sequence of their IDs. Does not update the SysDB.""" + pass + + @abstractmethod + def hint_use_collection(self, collection_id: UUID, hint_type: Operation) -> None: + """Signal to the segment manager that a collection is about to be used, so that + it can preload segments as needed. This is only a hint, and implementations are + free to ignore it.""" + pass diff --git a/python/user_packages/Python313/site-packages/chromadb/server/__init__.py b/python/user_packages/Python313/site-packages/chromadb/server/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..52b1cf16e3b1d13a88198161676a5b4632b06235 --- /dev/null +++ b/python/user_packages/Python313/site-packages/chromadb/server/__init__.py @@ -0,0 +1,9 @@ +from abc import ABC, abstractmethod + +from chromadb.config import Settings + + +class Server(ABC): + @abstractmethod + def __init__(self, settings: Settings): + pass diff --git a/python/user_packages/Python313/site-packages/chromadb/telemetry/README.md b/python/user_packages/Python313/site-packages/chromadb/telemetry/README.md new file mode 100644 index 0000000000000000000000000000000000000000..efaff31aa6f5a47fbb6a9aebb9a790680005c569 --- /dev/null +++ b/python/user_packages/Python313/site-packages/chromadb/telemetry/README.md @@ -0,0 +1,10 @@ +# Telemetry + +This directory holds all the telemetry for Chroma. + +- `product/` contains anonymized product telemetry which we, Chroma, collect so we can + understand usage patterns. For more information, see https://docs.trychroma.com/telemetry. +- `opentelemetry/` contains all of the config for Chroma's [OpenTelemetry](https://opentelemetry.io/docs/instrumentation/python/getting-started/) + setup. These metrics are *not* sent back to Chroma -- anyone operating a Chroma instance + can use the OpenTelemetry metrics and traces to understand how their instance of Chroma + is behaving. diff --git a/python/user_packages/Python313/site-packages/chromadb/telemetry/__init__.py b/python/user_packages/Python313/site-packages/chromadb/telemetry/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/python/user_packages/Python313/site-packages/chromadb/test/__init__.py b/python/user_packages/Python313/site-packages/chromadb/test/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/python/user_packages/Python313/site-packages/chromadb/test/__pycache__/__init__.cpython-313.pyc b/python/user_packages/Python313/site-packages/chromadb/test/__pycache__/__init__.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..aa1dde6d4eaa5415836e431e5a571266a023b3a4 Binary files /dev/null and b/python/user_packages/Python313/site-packages/chromadb/test/__pycache__/__init__.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/chromadb/test/__pycache__/conftest.cpython-313.pyc b/python/user_packages/Python313/site-packages/chromadb/test/__pycache__/conftest.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a2f8d900c5ba1742427f02032fabd06b55dff298 Binary files /dev/null and b/python/user_packages/Python313/site-packages/chromadb/test/__pycache__/conftest.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/chromadb/test/__pycache__/test_chroma.cpython-313.pyc b/python/user_packages/Python313/site-packages/chromadb/test/__pycache__/test_chroma.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0341db7d33253a70ff152e59765da733705f214d Binary files /dev/null and b/python/user_packages/Python313/site-packages/chromadb/test/__pycache__/test_chroma.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/chromadb/test/__pycache__/test_cli.cpython-313.pyc b/python/user_packages/Python313/site-packages/chromadb/test/__pycache__/test_cli.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..62cc26fdd0237dac4c9f14746d96e52ae2b2f6ce Binary files /dev/null and b/python/user_packages/Python313/site-packages/chromadb/test/__pycache__/test_cli.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/chromadb/test/__pycache__/test_client.cpython-313.pyc b/python/user_packages/Python313/site-packages/chromadb/test/__pycache__/test_client.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e06c1e2e8c58e3ea97adf97f1e3c53893310d609 Binary files /dev/null and b/python/user_packages/Python313/site-packages/chromadb/test/__pycache__/test_client.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/chromadb/test/__pycache__/test_config.cpython-313.pyc b/python/user_packages/Python313/site-packages/chromadb/test/__pycache__/test_config.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6f7f48f88f9d4eb0cc402e6f743b9119f2973ff5 Binary files /dev/null and b/python/user_packages/Python313/site-packages/chromadb/test/__pycache__/test_config.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/chromadb/test/__pycache__/test_multithreaded.cpython-313.pyc b/python/user_packages/Python313/site-packages/chromadb/test/__pycache__/test_multithreaded.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1cf7abbebad0d8c5d3f6f48b27185779f1beb2f9 Binary files /dev/null and b/python/user_packages/Python313/site-packages/chromadb/test/__pycache__/test_multithreaded.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/chromadb/test/api/test_collection.py b/python/user_packages/Python313/site-packages/chromadb/test/api/test_collection.py new file mode 100644 index 0000000000000000000000000000000000000000..d1309cb696dc3434e90363e4fe75040c5706e78b --- /dev/null +++ b/python/user_packages/Python313/site-packages/chromadb/test/api/test_collection.py @@ -0,0 +1,76 @@ +from concurrent.futures import ThreadPoolExecutor +import uuid +from chromadb.api import ClientAPI +from chromadb.errors import ChromaError, UniqueConstraintError +from chromadb.test.conftest import multi_region_test + + +@multi_region_test +def test_duplicate_collection_create( + client: ClientAPI, +) -> None: + client.reset() + + client.create_collection( + name="test", + metadata={"hnsw:construction_ef": 128, "hnsw:search_ef": 128, "hnsw:M": 128}, + ) + + try: + client.create_collection( + name="test", + metadata={ + "hnsw:construction_ef": 128, + "hnsw:search_ef": 128, + "hnsw:M": 128, + }, + ) + assert False, "Expected exception" + except Exception as e: + print("Collection creation failed as expected with error ", e) + assert "already exists" in e.args[0] or isinstance(e, UniqueConstraintError) + + +def test_not_existing_collection_delete( + client: ClientAPI, +) -> None: + try: + client.delete_collection( + name="test101", + ) + assert False, "Expected exception" + except Exception as e: + print("Collection deletion failed as expected with error ", e) + assert "does not exist" in e.args[0] + + +# TODO: Spanner emulator only supports one transaction at a time +def test_multithreaded_get_or_create(client: ClientAPI) -> None: + N_THREADS = 50 + new_name = str(uuid.uuid4()) + + def create_maybe_delete_collection(i: int) -> None: + try: + coll = client.get_or_create_collection(new_name) + assert coll.name == new_name + except ChromaError as e: + if "concurrent" not in e.message(): + raise e + + try: + if i % 2 == 0: + client.delete_collection(new_name) + except ChromaError as e: + if "does not exist" not in e.message(): + raise e + + # Stress to trigger a potential race condition + with ThreadPoolExecutor(max_workers=N_THREADS) as executor: + futures = [ + executor.submit(create_maybe_delete_collection, i) for i in range(N_THREADS) + ] + for future in futures: + try: + future.result() + except Exception as e: + assert False, f"Thread raised an exception: {e}" diff --git a/python/user_packages/Python313/site-packages/chromadb/test/api/test_count_api.py b/python/user_packages/Python313/site-packages/chromadb/test/api/test_count_api.py new file mode 100644 index 0000000000000000000000000000000000000000..bfb7338584775719db9019ae59299cc057a5de2e --- /dev/null +++ b/python/user_packages/Python313/site-packages/chromadb/test/api/test_count_api.py @@ -0,0 +1,102 @@ +"""Tests for the Count API endpoint with read_level support.""" + +from typing import Tuple +from uuid import uuid4 + +import pytest + +from chromadb.api import ClientAPI +from chromadb.api.models.Collection import Collection +from chromadb.api.types import ReadLevel +from chromadb.test.conftest import ( + ClientFactories, + is_spann_disabled_mode, + skip_reason_spann_disabled, +) + + +def _create_test_collection( + client_factories: ClientFactories, +) -> Tuple[Collection, ClientAPI]: + """Create a test collection with some data.""" + client = client_factories.create_client_from_system() + client.reset() + + collection_name = f"count_api_test_{uuid4().hex}" + collection = client.get_or_create_collection(name=collection_name) + + return collection, client + + +@pytest.mark.skipif(is_spann_disabled_mode, reason=skip_reason_spann_disabled) +def test_count_with_read_level_index_and_wal( + client_factories: ClientFactories, +) -> None: + """Test count with ReadLevel.INDEX_AND_WAL (default) returns correct count.""" + collection, _ = _create_test_collection(client_factories) + + collection.add( + ids=["doc1", "doc2", "doc3"], + documents=["apple fruit", "banana fruit", "car vehicle"], + embeddings=[[0.1, 0.2, 0.3, 0.4], [0.2, 0.3, 0.4, 0.5], [0.9, 0.8, 0.7, 0.6]], + ) + + count = collection.count(read_level=ReadLevel.INDEX_AND_WAL) + assert count == 3 + + +@pytest.mark.skipif(is_spann_disabled_mode, reason=skip_reason_spann_disabled) +def test_count_with_read_level_index_only( + client_factories: ClientFactories, +) -> None: + """Test count with ReadLevel.INDEX_ONLY returns a valid count.""" + collection, _ = _create_test_collection(client_factories) + + collection.add( + ids=["doc1", "doc2", "doc3"], + documents=["apple fruit", "banana fruit", "car vehicle"], + embeddings=[[0.1, 0.2, 0.3, 0.4], [0.2, 0.3, 0.4, 0.5], [0.9, 0.8, 0.7, 0.6]], + ) + + # Count with INDEX_ONLY skips the WAL. + # Result may be less than 3 if data hasn't been compacted yet. + count = collection.count(read_level=ReadLevel.INDEX_ONLY) + assert isinstance(count, int) + assert count >= 0 + + +@pytest.mark.skipif(is_spann_disabled_mode, reason=skip_reason_spann_disabled) +def test_count_with_read_level_index_and_bounded_wal( + client_factories: ClientFactories, +) -> None: + """Test count with ReadLevel.INDEX_AND_BOUNDED_WAL returns a valid count.""" + collection, _ = _create_test_collection(client_factories) + + collection.add( + ids=["doc1", "doc2", "doc3"], + documents=["apple fruit", "banana fruit", "car vehicle"], + embeddings=[[0.1, 0.2, 0.3, 0.4], [0.2, 0.3, 0.4, 0.5], [0.9, 0.8, 0.7, 0.6]], + ) + + # Count with INDEX_AND_BOUNDED_WAL reads up to a server-configured number of WAL entries. + # Result depends on the configured limit and WAL size. + count = collection.count(read_level=ReadLevel.INDEX_AND_BOUNDED_WAL) + assert isinstance(count, int) + assert count >= 0 + + +@pytest.mark.skipif(is_spann_disabled_mode, reason=skip_reason_spann_disabled) +def test_count_default_read_level( + client_factories: ClientFactories, +) -> None: + """Test count without explicit read_level uses default (INDEX_AND_WAL).""" + collection, _ = _create_test_collection(client_factories) + + collection.add( + ids=["doc1", "doc2"], + documents=["hello world", "goodbye world"], + embeddings=[[0.1, 0.2, 0.3, 0.4], [0.5, 0.6, 0.7, 0.8]], + ) + + count = collection.count() + assert count == 2 diff --git a/python/user_packages/Python313/site-packages/chromadb/test/api/test_delete_database.py b/python/user_packages/Python313/site-packages/chromadb/test/api/test_delete_database.py new file mode 100644 index 0000000000000000000000000000000000000000..d34a220fd534a20ef07affbeed781669f0813f46 --- /dev/null +++ b/python/user_packages/Python313/site-packages/chromadb/test/api/test_delete_database.py @@ -0,0 +1,82 @@ +import pytest +from chromadb.api.client import AdminClient, Client +from chromadb.config import System +from chromadb.db.impl.sqlite import SqliteDB +from chromadb.errors import NotFoundError +from chromadb.test.conftest import ClientFactories + + +def test_deletes_database(client_factories: ClientFactories) -> None: + client = client_factories.create_client() + client.reset() + + admin_client = client_factories.create_admin_client_from_system() + + admin_client.create_database("test_delete_database") + + client = client_factories.create_client(database="test_delete_database") + collection = client.create_collection("foo") + + admin_client.delete_database("test_delete_database") + + with pytest.raises(NotFoundError): + admin_client.get_database("test_delete_database") + + with pytest.raises(NotFoundError): + client.get_collection("foo") + + with pytest.raises(NotFoundError): + collection.upsert(["foo"], [0.0, 0.0, 0.0]) + + +def test_does_not_affect_other_databases(client_factories: ClientFactories) -> None: + client = client_factories.create_client() + client.reset() + + admin_client = client_factories.create_admin_client_from_system() + + admin_client.create_database("first") + admin_client.create_database("second") + + first_client = client_factories.create_client(database="first") + first_client.create_collection("test") + + second_client = client_factories.create_client(database="second") + second_collection = second_client.create_collection("test") + + admin_client.delete_database("first") + + assert second_client.get_collection("test").id == second_collection.id + + with pytest.raises(NotFoundError): + first_client.get_collection("test") + + +def test_collection_was_removed(sqlite_persistent: System) -> None: + sqlite = sqlite_persistent.instance(SqliteDB) + + admin_client = AdminClient.from_system(sqlite_persistent) + admin_client.create_database("test_delete_database") + + client = Client.from_system(sqlite_persistent, database="test_delete_database") + client.create_collection("foo") + + admin_client.delete_database("test_delete_database") + + with pytest.raises(NotFoundError): + client.get_collection("foo") + + # Check table + with sqlite.tx() as cur: + row = cur.execute("SELECT COUNT(*) from collections").fetchone() + assert row[0] == 0 + + +def test_errors_when_database_does_not_exist(client_factories: ClientFactories) -> None: + client = client_factories.create_client() + client.reset() + + admin_client = client_factories.create_admin_client_from_system() + + with pytest.raises(NotFoundError): + admin_client.delete_database("foo") diff --git a/python/user_packages/Python313/site-packages/chromadb/test/api/test_fork_count_api.py b/python/user_packages/Python313/site-packages/chromadb/test/api/test_fork_count_api.py new file mode 100644 index 0000000000000000000000000000000000000000..5421ee9f688bd13689d715685df5fd93e4a487f1 --- /dev/null +++ b/python/user_packages/Python313/site-packages/chromadb/test/api/test_fork_count_api.py @@ -0,0 +1,125 @@ +"""Tests for the Fork Count API endpoint.""" + +from typing import Tuple +from uuid import uuid4 + + +from chromadb.api import ClientAPI +from chromadb.api.models.Collection import Collection +from chromadb.test.conftest import ( + ClientFactories, + skip_if_not_cluster, +) + + +def _create_test_collection( + client_factories: ClientFactories, +) -> Tuple[Collection, ClientAPI]: + """Create a test collection with some data.""" + client = client_factories.create_client_from_system() + client.reset() + + collection_name = f"fork_count_api_test_{uuid4().hex}" + collection = client.get_or_create_collection(name=collection_name) + + return collection, client + + +@skip_if_not_cluster() +def test_fork_count_no_forks( + client_factories: ClientFactories, +) -> None: + """Test fork_count returns 0 for a collection with no forks.""" + collection, _ = _create_test_collection(client_factories) + + # Add some data to the collection + collection.add( + ids=["doc1", "doc2", "doc3"], + documents=["apple fruit", "banana fruit", "car vehicle"], + embeddings=[[0.1, 0.2, 0.3, 0.4], [0.2, 0.3, 0.4, 0.5], [0.9, 0.8, 0.7, 0.6]], + ) + + fork_count = collection.fork_count() + assert fork_count == 0 + + +@skip_if_not_cluster() +def test_fork_count_after_single_fork( + client_factories: ClientFactories, +) -> None: + """Test fork_count returns 1 after creating one fork.""" + collection, client = _create_test_collection(client_factories) + + # Add some data to the collection + collection.add( + ids=["doc1", "doc2"], + documents=["hello world", "goodbye world"], + embeddings=[[0.1, 0.2, 0.3, 0.4], [0.5, 0.6, 0.7, 0.8]], + ) + + # Fork the collection + fork_name = f"forked_collection_{uuid4().hex}" + forked_collection = collection.fork(fork_name) + + # The source collection should now have 1 fork + fork_count = collection.fork_count() + assert fork_count == 1 + + # The forked collection should also have 1 fork (it shares the lineage) + forked_fork_count = forked_collection.fork_count() + assert forked_fork_count == 1 + + +@skip_if_not_cluster() +def test_fork_count_after_multiple_forks( + client_factories: ClientFactories, +) -> None: + """Test fork_count returns correct count after creating multiple forks.""" + collection, client = _create_test_collection(client_factories) + + # Add some data to the collection + collection.add( + ids=["doc1"], + documents=["test document"], + embeddings=[[0.1, 0.2, 0.3, 0.4]], + ) + + # Create 5 forks + num_forks = 5 + forked_collections = [] + for _ in range(num_forks): + fork_name = f"forked_collection_{uuid4().hex}" + forked_collection = collection.fork(fork_name) + forked_collections.append(forked_collection) + + # The source collection should have 5 forks + fork_count = collection.fork_count() + assert fork_count == num_forks + + # Each forked collection should also report 5 forks (same lineage) + for forked in forked_collections: + assert forked.fork_count() == num_forks + + +@skip_if_not_cluster() +def test_fork_count_empty_collection( + client_factories: ClientFactories, +) -> None: + """Test fork_count works on an empty collection.""" + collection, _ = _create_test_collection(client_factories) + + # Don't add any data - collection is empty + fork_count = collection.fork_count() + assert fork_count == 0 + + +@skip_if_not_cluster() +def test_fork_count_returns_integer( + client_factories: ClientFactories, +) -> None: + """Test fork_count returns an integer type.""" + collection, _ = _create_test_collection(client_factories) + + fork_count = collection.fork_count() + assert isinstance(fork_count, int) + assert fork_count >= 0 diff --git a/python/user_packages/Python313/site-packages/chromadb/test/api/test_get_database.py b/python/user_packages/Python313/site-packages/chromadb/test/api/test_get_database.py new file mode 100644 index 0000000000000000000000000000000000000000..634ac82d73993a64307375786384157c52f4a1bb --- /dev/null +++ b/python/user_packages/Python313/site-packages/chromadb/test/api/test_get_database.py @@ -0,0 +1,8 @@ +import pytest +from chromadb.errors import NotFoundError +from chromadb.test.conftest import ClientFactories + + +def test_get_database_not_found(client_factories: ClientFactories) -> None: + with pytest.raises(NotFoundError): + client_factories.create_client(database="does_not_exist") diff --git a/python/user_packages/Python313/site-packages/chromadb/test/api/test_indexing_status.py b/python/user_packages/Python313/site-packages/chromadb/test/api/test_indexing_status.py new file mode 100644 index 0000000000000000000000000000000000000000..ca3c3cc9ecbca95841b27ec72cd9a1dc66e57a3b --- /dev/null +++ b/python/user_packages/Python313/site-packages/chromadb/test/api/test_indexing_status.py @@ -0,0 +1,256 @@ +from time import sleep + +from chromadb.api import ClientAPI +from chromadb.api.types import IndexingStatus +from chromadb.test.conftest import skip_if_not_cluster +from chromadb.test.utils.wait_for_version_increase import ( + get_collection_version, + wait_for_version_increase, +) + + +@skip_if_not_cluster() +def test_indexing_status_empty_collection(client: ClientAPI) -> None: + """Test indexing status on empty collection""" + client.reset() + + collection = client.create_collection(name="test_collection") + status = collection.get_indexing_status() + + assert isinstance(status, IndexingStatus) + assert status.num_indexed_ops == 0 + assert status.num_unindexed_ops == 0 + assert status.total_ops == 0 + assert status.op_indexing_progress == 1.0 + + +@skip_if_not_cluster() +def test_indexing_status_after_add(client: ClientAPI) -> None: + """Test indexing status after adding embeddings""" + client.reset() + + collection = client.create_collection(name="test_collection") + + ids = [f"id_{i}" for i in range(300)] + embeddings = [[float(i), float(i + 1), float(i + 2)] for i in range(300)] + initial_version = get_collection_version(client, collection.name) + collection.add(ids=ids, embeddings=embeddings) # type: ignore + + status = collection.get_indexing_status() + assert status.total_ops == 300 + + if initial_version == get_collection_version(client, collection.name): + assert isinstance(status, IndexingStatus) + assert status.num_unindexed_ops == 300 + assert status.num_indexed_ops == 0 + assert status.op_indexing_progress == 0.0 + wait_for_version_increase(client, collection.name, initial_version) + # Give some time to invalidate the frontend query cache + sleep(60) + + # Check status after indexing completes + final_status = collection.get_indexing_status() + assert isinstance(final_status, IndexingStatus) + assert final_status.num_indexed_ops == 300 + assert final_status.num_unindexed_ops == 0 + assert final_status.op_indexing_progress == 1.0 + + +@skip_if_not_cluster() +def test_indexing_status_after_upsert(client: ClientAPI) -> None: + """Test indexing status after upsert operations""" + client.reset() + + collection = client.create_collection(name="test_collection") + initial_version = get_collection_version(client, collection.name) + + collection.upsert(ids=["id1", "id2"], embeddings=[[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]]) # type: ignore + + status = collection.get_indexing_status() + assert status.total_ops == 2 + + if initial_version == get_collection_version(client, collection.name): + assert isinstance(status, IndexingStatus) + assert status.num_unindexed_ops == 2 + assert status.num_indexed_ops == 0 + assert status.op_indexing_progress == 0.0 + wait_for_version_increase(client, collection.name, initial_version) + sleep(60) + + collection.upsert(ids=["id1", "id3"], embeddings=[[1.1, 2.1, 3.1], [7.0, 8.0, 9.0]]) # type: ignore + + status = collection.get_indexing_status() + assert status.total_ops == 4 + + +@skip_if_not_cluster() +def test_indexing_status_after_delete(client: ClientAPI) -> None: + """Test indexing status after delete operations""" + client.reset() + + collection = client.create_collection(name="test_collection") + initial_version = get_collection_version(client, collection.name) + + collection.add( + ids=["id1", "id2", "id3"], + embeddings=[[1.0, 2.0, 3.0], [4.0, 5.0, 6.0], [7.0, 8.0, 9.0]], # type: ignore + ) + + if initial_version == get_collection_version(client, collection.name): + status = collection.get_indexing_status() + assert isinstance(status, IndexingStatus) + assert status.num_unindexed_ops == 3 + assert status.num_indexed_ops == 0 + assert status.op_indexing_progress == 0.0 + wait_for_version_increase(client, collection.name, initial_version) + sleep(60) + + initial_status = collection.get_indexing_status() + assert initial_status.total_ops == 3 + + collection.delete(ids=["id1", "id2"]) + + # Delete adds operations to the log, so total_ops increases + status_after_delete = collection.get_indexing_status() + assert status_after_delete.total_ops == 5 + + +@skip_if_not_cluster() +def test_indexing_status_field_types(client: ClientAPI) -> None: + """Test that indexing status returns correct field types""" + client.reset() + + collection = client.create_collection(name="field_types_collection") + initial_version = get_collection_version(client, collection.name) + + collection.add(ids=["type_test_id"], embeddings=[[1.0, 2.0, 3.0]]) # type: ignore + + status = collection.get_indexing_status() + + if initial_version == get_collection_version(client, collection.name): + assert isinstance(status, IndexingStatus) + assert status.num_unindexed_ops == 1 + assert status.num_indexed_ops == 0 + assert status.op_indexing_progress == 0.0 + wait_for_version_increase(client, collection.name, initial_version) + sleep(60) + + final_status = collection.get_indexing_status() + + assert isinstance(final_status.num_indexed_ops, int) + assert isinstance(final_status.num_unindexed_ops, int) + assert isinstance(final_status.total_ops, int) + assert isinstance(final_status.op_indexing_progress, float) + + assert final_status.num_indexed_ops >= 0 + assert final_status.num_unindexed_ops >= 0 + assert final_status.total_ops >= 0 + assert 0.0 <= final_status.op_indexing_progress <= 1.0 + + +@skip_if_not_cluster() +def test_indexing_status_batch_progression(client: ClientAPI) -> None: + """Test indexing status with 2000 records based on index version progression""" + client.reset() + + collection = client.create_collection(name="batch_test_collection") + get_collection_version(client, collection.name) + + # Insert 2000 records in two batches of 1000 (max batch size) + ids_1 = [f"batch_id_{i}" for i in range(1000)] + embeddings_1 = [[float(i), float(i + 1), float(i + 2)] for i in range(1000)] + collection.add(ids=ids_1, embeddings=embeddings_1) # type: ignore + + ids_2 = [f"batch_id_{i}" for i in range(1000, 2000)] + embeddings_2 = [[float(i), float(i + 1), float(i + 2)] for i in range(1000, 2000)] + collection.add(ids=ids_2, embeddings=embeddings_2) # type: ignore + + current_version = get_collection_version(client, collection.name) + + allowed_statuses = [ + IndexingStatus( + num_indexed_ops=0, + num_unindexed_ops=2000, + total_ops=2000, + op_indexing_progress=0.0, + ), + IndexingStatus( + num_indexed_ops=1000, + num_unindexed_ops=1000, + total_ops=2000, + op_indexing_progress=0.5, + ), + IndexingStatus( + num_indexed_ops=2000, + num_unindexed_ops=0, + total_ops=2000, + op_indexing_progress=1.0, + ), + ] + + ops_indexed = 0 + while ops_indexed < 2000: + status = collection.get_indexing_status() + assert status in allowed_statuses + print("witnessed status: ", status) + ops_indexed = status.num_indexed_ops + wait_for_version_increase(client, collection.name, current_version) + sleep(60) + + +@skip_if_not_cluster() +def test_indexing_status_not_found(client: ClientAPI) -> None: + """Test indexing status on non-existent collection""" + client.reset() + + collection = client.create_collection(name="temp_collection") + client.delete_collection("temp_collection") + + try: + collection.get_indexing_status() + assert False, "Expected exception for non-existent collection" + except Exception as e: + assert ( + "not found" in str(e).lower() + or "does not exist" in str(e).lower() + or "soft deleted" in str(e).lower() + or "collection not found" in str(e).lower() + ) + + +@skip_if_not_cluster() +def test_indexing_status_concurrent_progress_variation(client: ClientAPI) -> None: + """Test that progress values vary as indexing completes""" + client.reset() + + collection = client.create_collection(name="concurrent_test_collection") + initial_version = get_collection_version(client, collection.name) + + ids = [f"concurrent_id_{i}" for i in range(300)] + embeddings = [[float(i), float(i + 1), float(i + 2)] for i in range(300)] + collection.add(ids=ids, embeddings=embeddings) # type: ignore + + progress_values = set() + + # Record status before compaction completes + status = collection.get_indexing_status() + progress_values.add(status.op_indexing_progress) + + if initial_version == get_collection_version(client, collection.name): + assert status.op_indexing_progress == 0.0 + wait_for_version_increase(client, collection.name, initial_version) + # Give time to invalidate the frontend query cache + sleep(60) + + # Record status after compaction + final_status = collection.get_indexing_status() + progress_values.add(final_status.op_indexing_progress) + + assert final_status.op_indexing_progress == 1.0 + + # We should have observed at least two distinct progress values (0.0 and 1.0) + assert len(progress_values) > 1, ( + f"Expected variation in progress values, but only got: {progress_values}" + ) + + print(f"Unique progress values: {sorted(progress_values)}") diff --git a/python/user_packages/Python313/site-packages/chromadb/test/api/test_invalid_update.py b/python/user_packages/Python313/site-packages/chromadb/test/api/test_invalid_update.py new file mode 100644 index 0000000000000000000000000000000000000000..2ae78ff1f27a406669953074749046f361da59dd --- /dev/null +++ b/python/user_packages/Python313/site-packages/chromadb/test/api/test_invalid_update.py @@ -0,0 +1,17 @@ +import numpy as np +from chromadb.api import ClientAPI + + +def test_invalid_update(client: ClientAPI) -> None: + client.reset() + + collection = client.create_collection("test") + + # Update is invalid because ID does not exist + collection.update(ids=["foo"], embeddings=[[0.0, 0.0, 0.0]]) + + collection.add(ids=["foo"], embeddings=[[1.0, 1.0, 1.0]]) + result = collection.get(ids=["foo"], include=["embeddings"]) + # Embeddings should be the same as what was provided to .add() + assert result["embeddings"] is not None + assert np.allclose(result["embeddings"][0], np.array([1.0, 1.0, 1.0])) diff --git a/python/user_packages/Python313/site-packages/chromadb/test/api/test_limit_offset.py b/python/user_packages/Python313/site-packages/chromadb/test/api/test_limit_offset.py new file mode 100644 index 0000000000000000000000000000000000000000..4ddc0c7d4fbcad523477ab23de9dec875a8fd3c3 --- /dev/null +++ b/python/user_packages/Python313/site-packages/chromadb/test/api/test_limit_offset.py @@ -0,0 +1,66 @@ +import logging + +import chromadb.test.property.strategies as strategies +import hypothesis.strategies as st +from chromadb.api import ClientAPI +from chromadb.test.conftest import NOT_CLUSTER_ONLY, reset +from chromadb.test.property import invariants +from chromadb.test.utils.wait_for_version_increase import wait_for_version_increase +from hypothesis import HealthCheck, given, settings + +collection_st = st.shared( + strategies.collections(add_filterable_data=True, with_hnsw_params=True), + key="coll", +) +recordset_st = st.shared( + strategies.recordsets(collection_st, max_size=1000), key="recordset" +) + + +@settings( + deadline=90000, + suppress_health_check=[ + HealthCheck.function_scoped_fixture, + HealthCheck.large_base_example, + HealthCheck.filter_too_much, + ], +) # type: ignore +@given( + collection=collection_st, + record_set=recordset_st, + limit=st.integers(min_value=1, max_value=10), + offset=st.integers(min_value=0, max_value=10), + should_compact=st.booleans(), +) +def test_get_limit_offset( + caplog, + client: ClientAPI, + collection: strategies.Collection, + record_set: dict, + limit: int, + offset: int, + should_compact: bool, +) -> None: + caplog.set_level(logging.ERROR) + + reset(client) + coll = client.create_collection( + name=collection.name, + metadata=collection.metadata, # type: ignore + embedding_function=collection.embedding_function, + ) + + initial_version = coll.get_model()["version"] + + coll.add(**record_set) + + if not NOT_CLUSTER_ONLY: + # Only wait for compaction if the size of the collection is + # some minimal size + if should_compact and len(invariants.wrap(record_set["ids"])) > 10: + # Wait for the model to be updated + wait_for_version_increase(client, collection.name, initial_version) + + result_ids = coll.get(offset=offset, limit=limit)["ids"] + all_offset_ids = coll.get()["ids"] + assert result_ids == all_offset_ids[offset : offset + limit] diff --git a/python/user_packages/Python313/site-packages/chromadb/test/api/test_list_databases.py b/python/user_packages/Python313/site-packages/chromadb/test/api/test_list_databases.py new file mode 100644 index 0000000000000000000000000000000000000000..15a7566c4196bdc4b58ff982e08877e29904bef9 --- /dev/null +++ b/python/user_packages/Python313/site-packages/chromadb/test/api/test_list_databases.py @@ -0,0 +1,96 @@ +from typing import Dict, List +from hypothesis import given +from chromadb.test.conftest import ( + ClientFactories, +) +import hypothesis.strategies as st +from chromadb.test.conftest import MULTI_REGION_ENABLED + + +def test_list_databases(client_factories: ClientFactories) -> None: + client = client_factories.create_client() + client.reset() + admin_client = client_factories.create_admin_client_from_system() + + for i in range(10): + admin_client.create_database(f"test_list_databases_{i}") + + databases = admin_client.list_databases() + total_default_databases = 2 if MULTI_REGION_ENABLED else 1 + assert len(databases) == 10 + total_default_databases + + for i in range(10): + assert any(d["name"] == f"test_list_databases_{i}" for d in databases) + + assert any(d["name"] == "default_database" for d in databases) + + if MULTI_REGION_ENABLED: + assert any(d["name"] == "tilt-spanning+default_database" for d in databases) + + +@st.composite +def tenants_and_databases_st( + draw: st.DrawFn, max_tenants: int, max_databases: int +) -> Dict[str, List[str]]: + """Generates a set of random tenants and databases. Each database is assigned to a random tenant. Returns a dictionary where the key is the tenant name and the value is a list of database names for that tenant.""" + num_tenants = draw(st.integers(min_value=1, max_value=max_tenants)) + num_databases = draw(st.integers(min_value=0, max_value=max_databases)) + + database_i_to_tenant_i = draw( + st.lists( + st.integers(min_value=0, max_value=num_tenants - 1), + min_size=num_databases, + max_size=num_databases, + ) + ) + + tenants = [f"tenant_{i}" for i in range(num_tenants)] + databases = [f"database_{i}" for i in range(num_databases)] + + result: Dict[str, List[str]] = {} + for database_i, tenant_i in enumerate(database_i_to_tenant_i): + tenant = tenants[tenant_i] + database = databases[database_i] + + if tenant not in result: + result[tenant] = [] + + result[tenant].append(database) + + return result + + +@given( + limit=st.integers(min_value=1, max_value=10), + offset=st.integers(min_value=0, max_value=10), + tenants_and_databases=tenants_and_databases_st(max_tenants=10, max_databases=10), +) +def test_list_databases_with_limit_offset( + limit: int, + offset: int, + tenants_and_databases: Dict[str, List[str]], + client_factories: ClientFactories, +) -> None: + client = client_factories.create_client() + client.reset() + + admin_client = client_factories.create_admin_client_from_system() + + for tenant, databases in tenants_and_databases.items(): + admin_client.create_tenant(tenant) + + for database in databases: + admin_client.create_database(database, tenant) + + for tenant, all_databases in tenants_and_databases.items(): + listed_databases = admin_client.list_databases( + limit=limit, offset=offset, tenant=tenant + ) + expected_databases = all_databases[offset : offset + limit] + + if limit + offset > len(all_databases): + assert len(listed_databases) == max(len(all_databases) - offset, 0) + assert [d["name"] for d in listed_databases] == expected_databases + else: + assert len(listed_databases) == limit + assert [d["name"] for d in listed_databases] == expected_databases diff --git a/python/user_packages/Python313/site-packages/chromadb/test/api/test_numpy_list_inputs.py b/python/user_packages/Python313/site-packages/chromadb/test/api/test_numpy_list_inputs.py new file mode 100644 index 0000000000000000000000000000000000000000..7a6e66ad4b408e29a1e692aab61ed5781356f8d1 --- /dev/null +++ b/python/user_packages/Python313/site-packages/chromadb/test/api/test_numpy_list_inputs.py @@ -0,0 +1,62 @@ +# Tests that various combinations of numpy and python lists work as expected as inputs +# to add/query/update/upsert operations + +from typing import Any, Dict, List +import numpy as np +from chromadb.api import ClientAPI +from chromadb.api.models.Collection import Collection +from chromadb.test.conftest import reset + + +def add_and_validate( + collection: Collection, + ids: List[str], + embeddings: Any, + metadatas: List[Dict[str, Any]], + documents: List[str], +) -> None: + collection.add(ids=ids, embeddings=embeddings, metadatas=metadatas, documents=documents) # type: ignore + + results = collection.get(include=["metadatas", "documents", "embeddings"]) # type: ignore + assert results["ids"] == ids + assert results["metadatas"] == metadatas + assert results["documents"] == documents + # Using integers instead of floats to avoid floating point comparison issues + assert np.array_equal(results["embeddings"], embeddings) # type: ignore + + +def test_py_list_of_numpy(client: ClientAPI) -> None: + reset(client) + coll = client.create_collection("test") + ids = ["1", "2", "3"] + embeddings = [np.array([1, 2, 3]), np.array([1, 2, 3]), np.array([1, 2, 3])] + metadatas = [{"a": 1}, {"a": 2}, {"a": 3}] + documents = ["a", "b", "c"] + + # List of numpy arrays + add_and_validate(coll, ids, embeddings, metadatas, documents) + + +def test_py_list_of_py(client: ClientAPI) -> None: + reset(client) + coll = client.create_collection("test") + ids = ["4", "5", "6"] + embeddings = [[1, 2, 3], [1, 2, 3], [1, 2, 3]] + metadatas = [{"a": 4}, {"a": 5}, {"a": 6}] + documents = ["d", "e", "f"] + + # List of python lists + add_and_validate(coll, ids, embeddings, metadatas, documents) + + +def test_numpy(client: ClientAPI) -> None: + reset(client) + coll = client.create_collection("test") + + ids = ["7", "8", "9"] + embeddings = np.array([[1, 2, 3], [1, 2, 3], [1, 2, 3]]) + metadata = [{"a": 7}, {"a": 8}, {"a": 9}] + documents = ["g", "h", "i"] + + # Numpy array + add_and_validate(coll, ids, embeddings, metadata, documents) diff --git a/python/user_packages/Python313/site-packages/chromadb/test/api/test_schema.py b/python/user_packages/Python313/site-packages/chromadb/test/api/test_schema.py new file mode 100644 index 0000000000000000000000000000000000000000..37a2dbb12b7985bc08b3607d7ec62013c99dcc9b --- /dev/null +++ b/python/user_packages/Python313/site-packages/chromadb/test/api/test_schema.py @@ -0,0 +1,3265 @@ +from chromadb.api.types import ( + Schema, + SparseVectorIndexConfig, + SparseEmbeddingFunction, + SparseVector, + StringInvertedIndexConfig, + IntInvertedIndexConfig, + FloatInvertedIndexConfig, + BoolInvertedIndexConfig, + VectorIndexConfig, + HnswIndexConfig, + SpannIndexConfig, + FtsIndexConfig, + EmbeddingFunction, + Embeddings, + Cmek, + CmekProvider, +) +from chromadb.execution.expression.operator import Key +from typing import List, Dict, Any +from pydantic import ValidationError +import pytest + + +class MockSparseEmbeddingFunction(SparseEmbeddingFunction[List[str]]): + """Mock sparse embedding function for testing.""" + + def __init__(self, name: str = "mock_sparse"): + self._name = name + + def __call__(self, input: List[str]) -> List[SparseVector]: + return [SparseVector(indices=[0, 1], values=[1.0, 1.0]) for _ in input] + + @staticmethod + def name() -> str: + return "mock_sparse" + + def get_config(self) -> Dict[str, Any]: + return {"name": self._name} + + @staticmethod + def build_from_config(config: Dict[str, Any]) -> "MockSparseEmbeddingFunction": + return MockSparseEmbeddingFunction(config.get("name", "mock_sparse")) + + +class MockEmbeddingFunction(EmbeddingFunction[List[str]]): + """Mock embedding function for testing.""" + + def __init__(self, model_name: str = "mock_model"): + self._model_name = model_name + + def __call__(self, input: List[str]) -> Embeddings: + import numpy as np + + # Return mock embeddings (3-dimensional) + return [np.array([1.0, 2.0, 3.0], dtype=np.float32) for _ in input] + + @staticmethod + def name() -> str: + return "mock_embedding" + + def get_config(self) -> Dict[str, Any]: + return {"model_name": self._model_name} + + @staticmethod + def build_from_config(config: Dict[str, Any]) -> "MockEmbeddingFunction": + return MockEmbeddingFunction(config.get("model_name", "mock_model")) + + def default_space(self) -> str: # type: ignore + return "cosine" + + def supported_spaces(self) -> List[str]: # type: ignore + return ["cosine", "l2", "ip"] + + +class TestNewSchema: + """Test cases for the new Schema class.""" + + def test_default_schema_initialization(self) -> None: + """Test that Schema() initializes with correct defaults.""" + schema = Schema() + + # Verify defaults are populated + assert schema.defaults is not None + + # Verify string value type defaults + assert schema.defaults.string is not None + assert schema.defaults.string.fts_index is not None + assert schema.defaults.string.fts_index.enabled is False # Disabled by default + assert schema.defaults.string.string_inverted_index is not None + assert ( + schema.defaults.string.string_inverted_index.enabled is True + ) # Enabled by default + + # Verify float_list value type defaults + assert schema.defaults.float_list is not None + assert schema.defaults.float_list.vector_index is not None + assert ( + schema.defaults.float_list.vector_index.enabled is False + ) # Disabled by default + + # Verify sparse_vector value type defaults + assert schema.defaults.sparse_vector is not None + assert schema.defaults.sparse_vector.sparse_vector_index is not None + assert ( + schema.defaults.sparse_vector.sparse_vector_index.enabled is False + ) # Disabled by default + + # Verify int_value type defaults + assert schema.defaults.int_value is not None + assert schema.defaults.int_value.int_inverted_index is not None + assert ( + schema.defaults.int_value.int_inverted_index.enabled is True + ) # Enabled by default + + # Verify float_value type defaults + assert schema.defaults.float_value is not None + assert schema.defaults.float_value.float_inverted_index is not None + assert ( + schema.defaults.float_value.float_inverted_index.enabled is True + ) # Enabled by default + + # Verify boolean type defaults + assert schema.defaults.boolean is not None + assert schema.defaults.boolean.bool_inverted_index is not None + assert ( + schema.defaults.boolean.bool_inverted_index.enabled is True + ) # Enabled by default + + # Verify keys are populated + assert schema.keys is not None + assert len(schema.keys) == 2 # Should have #document and #embedding + + # Verify #document key override (FTS enabled, string inverted disabled) + assert "#document" in schema.keys + assert schema.keys["#document"].string is not None + assert schema.keys["#document"].string.fts_index is not None + assert schema.keys["#document"].string.fts_index.enabled is True + assert schema.keys["#document"].string.string_inverted_index is not None + assert schema.keys["#document"].string.string_inverted_index.enabled is False + + # Verify #embedding key override (vector index enabled) + assert "#embedding" in schema.keys + assert schema.keys["#embedding"].float_list is not None + assert schema.keys["#embedding"].float_list.vector_index is not None + assert schema.keys["#embedding"].float_list.vector_index.enabled is True + assert ( + schema.keys["#embedding"].float_list.vector_index.config.source_key + == "#document" + ) + + def test_create_sparse_vector_index_on_key(self) -> None: + """Test creating a sparse vector index on a specific key with default config.""" + schema = Schema() + + # Create sparse vector index on a custom key with default config + config = SparseVectorIndexConfig() + result = schema.create_index(config=config, key="custom_sparse_key") + + # Should return self for chaining + assert result is schema + + # Verify the key override was created + assert "custom_sparse_key" in schema.keys + + # Verify sparse_vector type was set for this key + assert schema.keys["custom_sparse_key"].sparse_vector is not None + assert ( + schema.keys["custom_sparse_key"].sparse_vector.sparse_vector_index + is not None + ) + + # Verify it's enabled and has the correct config + assert ( + schema.keys["custom_sparse_key"].sparse_vector.sparse_vector_index.enabled + is True + ) + assert ( + schema.keys["custom_sparse_key"].sparse_vector.sparse_vector_index.config + == config + ) + + # Verify other value types for this key are None (not initialized) + assert schema.keys["custom_sparse_key"].string is None + assert schema.keys["custom_sparse_key"].float_list is None + assert schema.keys["custom_sparse_key"].int_value is None + assert schema.keys["custom_sparse_key"].float_value is None + assert schema.keys["custom_sparse_key"].boolean is None + + # Verify defaults were not affected + assert schema.defaults.sparse_vector is not None + assert schema.defaults.sparse_vector.sparse_vector_index is not None + assert ( + schema.defaults.sparse_vector.sparse_vector_index.enabled is False + ) # Still disabled by default + + def test_create_sparse_vector_index_with_custom_config(self) -> None: + """Test creating a sparse vector index with custom config including embedding function.""" + schema = Schema() + + # Create custom sparse vector config with embedding function and source key + embedding_func = MockSparseEmbeddingFunction(name="custom_sparse_ef") + config = SparseVectorIndexConfig( + embedding_function=embedding_func, source_key="custom_document_field" + ) + + # Create sparse vector index on a custom key + result = schema.create_index(config=config, key="sparse_embeddings") + + # Should return self for chaining + assert result is schema + + # Verify the key override was created + assert "sparse_embeddings" in schema.keys + assert schema.keys["sparse_embeddings"].sparse_vector is not None + assert ( + schema.keys["sparse_embeddings"].sparse_vector.sparse_vector_index + is not None + ) + + # Verify it's enabled + sparse_index = schema.keys[ + "sparse_embeddings" + ].sparse_vector.sparse_vector_index + assert sparse_index.enabled is True + + # Verify the config has our custom settings + assert sparse_index.config.embedding_function == embedding_func + assert sparse_index.config.source_key == "custom_document_field" + + # Verify the embedding function is the same instance + assert sparse_index.config.embedding_function.name() == "mock_sparse" + assert sparse_index.config.embedding_function.get_config() == { + "name": "custom_sparse_ef" + } + + # Verify global defaults were not overridden + assert schema.defaults.sparse_vector is not None + assert schema.defaults.sparse_vector.sparse_vector_index is not None + assert ( + schema.defaults.sparse_vector.sparse_vector_index.enabled is False + ) # Still disabled by default + assert ( + schema.defaults.sparse_vector.sparse_vector_index.config.embedding_function + is None + ) # No custom embedding function + + def test_delete_index_on_key(self) -> None: + """Test disabling string inverted index on a specific key.""" + schema = Schema() + + # Create a config and disable it on a specific key + config = StringInvertedIndexConfig() + result = schema.delete_index(config=config, key="custom_text_key") + + # Should return self for chaining + assert result is schema + + # Verify the key override was created + assert "custom_text_key" in schema.keys + + # Verify string inverted index is disabled for this key + assert schema.keys["custom_text_key"].string is not None + assert schema.keys["custom_text_key"].string.string_inverted_index is not None + assert ( + schema.keys["custom_text_key"].string.string_inverted_index.enabled is False + ) + + # Verify other keys are not affected - check #document key + assert "#document" in schema.keys + assert schema.keys["#document"].string is not None + assert schema.keys["#document"].string.string_inverted_index is not None + assert ( + schema.keys["#document"].string.string_inverted_index.enabled is False + ) # Was disabled by default in #document + + # Verify other keys are not affected - check #embedding key (shouldn't have string config) + assert "#embedding" in schema.keys + assert ( + schema.keys["#embedding"].string is None + ) # #embedding doesn't have string configs + + # Verify global defaults are not affected + assert schema.defaults.string is not None + assert schema.defaults.string.string_inverted_index is not None + assert ( + schema.defaults.string.string_inverted_index.enabled is True + ) # Global default is still enabled + + def test_chained_create_and_delete_operations(self) -> None: + """Test chaining create_index() and delete_index() operations together.""" + schema = Schema() + + # Chain multiple operations: + # 1. Create sparse vector index on "embeddings_key" + # 2. Disable string inverted index on "text_key_1" + # 3. Disable string inverted index on "text_key_2" + sparse_config = SparseVectorIndexConfig( + source_key="raw_text", embedding_function=MockSparseEmbeddingFunction() + ) + string_config = StringInvertedIndexConfig() + + result = ( + schema.create_index(config=sparse_config, key="embeddings_key") + .delete_index(config=string_config, key="text_key_1") + .delete_index(config=string_config, key="text_key_2") + ) + + # Should return self for chaining + assert result is schema + + # Verify all three key overrides were created + assert "embeddings_key" in schema.keys + assert "text_key_1" in schema.keys + assert "text_key_2" in schema.keys + + # Verify sparse vector index on "embeddings_key" is enabled + assert schema.keys["embeddings_key"].sparse_vector is not None + assert ( + schema.keys["embeddings_key"].sparse_vector.sparse_vector_index is not None + ) + assert ( + schema.keys["embeddings_key"].sparse_vector.sparse_vector_index.enabled + is True + ) + assert ( + schema.keys[ + "embeddings_key" + ].sparse_vector.sparse_vector_index.config.source_key + == "raw_text" + ) + + # Verify only sparse_vector is set for embeddings_key (other types are None) + assert schema.keys["embeddings_key"].string is None + assert schema.keys["embeddings_key"].float_list is None + assert schema.keys["embeddings_key"].int_value is None + assert schema.keys["embeddings_key"].float_value is None + assert schema.keys["embeddings_key"].boolean is None + + # Verify string inverted index on "text_key_1" is disabled + assert schema.keys["text_key_1"].string is not None + assert schema.keys["text_key_1"].string.string_inverted_index is not None + assert schema.keys["text_key_1"].string.string_inverted_index.enabled is False + + # Verify only string is set for text_key_1 (other types are None) + assert schema.keys["text_key_1"].sparse_vector is None + assert schema.keys["text_key_1"].float_list is None + assert schema.keys["text_key_1"].int_value is None + assert schema.keys["text_key_1"].float_value is None + assert schema.keys["text_key_1"].boolean is None + + # Verify string inverted index on "text_key_2" is disabled + assert schema.keys["text_key_2"].string is not None + assert schema.keys["text_key_2"].string.string_inverted_index is not None + assert schema.keys["text_key_2"].string.string_inverted_index.enabled is False + + # Verify only string is set for text_key_2 (other types are None) + assert schema.keys["text_key_2"].sparse_vector is None + assert schema.keys["text_key_2"].float_list is None + assert schema.keys["text_key_2"].int_value is None + assert schema.keys["text_key_2"].float_value is None + assert schema.keys["text_key_2"].boolean is None + + # Verify global defaults are not affected + assert schema.defaults.sparse_vector is not None + assert schema.defaults.sparse_vector.sparse_vector_index is not None + assert ( + schema.defaults.sparse_vector.sparse_vector_index.enabled is False + ) # Still disabled globally + + assert schema.defaults.string is not None + assert schema.defaults.string.string_inverted_index is not None + assert ( + schema.defaults.string.string_inverted_index.enabled is True + ) # Still enabled globally + + # Verify pre-existing key overrides (#document, #embedding) are not affected + assert "#document" in schema.keys + assert "#embedding" in schema.keys + assert schema.keys["#document"].string is not None + assert schema.keys["#document"].string.fts_index is not None + assert ( + schema.keys["#document"].string.fts_index.enabled is True + ) # Still enabled + assert schema.keys["#embedding"].float_list is not None + assert schema.keys["#embedding"].float_list.vector_index is not None + assert ( + schema.keys["#embedding"].float_list.vector_index.enabled is True + ) # Still enabled + + def test_vector_index_config_and_restrictions(self) -> None: + """Test vector index configuration and key restrictions.""" + schema = Schema() + vector_config = VectorIndexConfig(space="cosine", source_key="custom_source") + + # Test 1: CAN set vector config globally - applies to defaults and #embedding + result = schema.create_index(config=vector_config) + assert result is schema # Should return self for chaining + + # Verify the vector config was applied to defaults (enabled state preserved as False) + assert schema.defaults.float_list is not None + assert schema.defaults.float_list.vector_index is not None + assert ( + schema.defaults.float_list.vector_index.enabled is False + ) # Still disabled in defaults + assert schema.defaults.float_list.vector_index.config.space == "cosine" + assert ( + schema.defaults.float_list.vector_index.config.source_key == "custom_source" + ) + + # Verify the vector config was also applied to #embedding (enabled state preserved as True) + # Note: source_key should NOT be overridden on #embedding - it should stay as "#document" + assert schema.keys["#embedding"].float_list is not None + assert schema.keys["#embedding"].float_list.vector_index is not None + assert ( + schema.keys["#embedding"].float_list.vector_index.enabled is True + ) # Still enabled on #embedding + assert ( + schema.keys["#embedding"].float_list.vector_index.config.space == "cosine" + ) + assert ( + schema.keys["#embedding"].float_list.vector_index.config.source_key + == "#document" + ) # Preserved, NOT overridden + + # Test 2: Cannot create vector index on custom key + vector_config2 = VectorIndexConfig(space="l2") + with pytest.raises( + ValueError, match="Vector index cannot be enabled on specific keys" + ): + schema.create_index(config=vector_config2, key="my_vectors") + + # Test 3: Cannot create vector index on #document key (special key blocked globally) + with pytest.raises( + ValueError, match="Cannot create index on special key '#document'" + ): + schema.create_index(config=vector_config2, key="#document") + + # Test 4: Cannot create vector index on #embedding key (special key blocked globally) + vector_config3 = VectorIndexConfig(space="ip") + with pytest.raises( + ValueError, match="Cannot create index on special key '#embedding'" + ): + schema.create_index(config=vector_config3, key="#embedding") + + def test_vector_index_with_embedding_function_and_hnsw(self) -> None: + """Test setting embedding function and HNSW config for vector index.""" + schema = Schema() + + # Create a custom embedding function and HNSW config + mock_ef = MockEmbeddingFunction(model_name="custom_model_v2") + hnsw_config = HnswIndexConfig( + ef_construction=200, max_neighbors=32, ef_search=100 + ) + + # Set vector config with embedding function, space, and HNSW config + vector_config = VectorIndexConfig( + embedding_function=mock_ef, + space="l2", # Override default space from EF + hnsw=hnsw_config, + source_key="custom_document_field", + ) + + result = schema.create_index(config=vector_config) + assert result is schema + + # Verify defaults: should have EF, space, HNSW, and source_key + assert schema.defaults.float_list is not None + defaults_vector = schema.defaults.float_list.vector_index + assert defaults_vector is not None + assert defaults_vector.enabled is False + assert defaults_vector.config.embedding_function is mock_ef + assert defaults_vector.config.embedding_function.name() == "mock_embedding" + assert defaults_vector.config.embedding_function.get_config() == { + "model_name": "custom_model_v2" + } + assert defaults_vector.config.space == "l2" + assert defaults_vector.config.hnsw is not None + assert defaults_vector.config.hnsw.ef_construction == 200 + assert defaults_vector.config.hnsw.max_neighbors == 32 + assert defaults_vector.config.hnsw.ef_search == 100 + assert defaults_vector.config.source_key == "custom_document_field" + + # Verify #embedding: should have EF, space, HNSW, but source_key is preserved as "#document" + assert schema.keys["#embedding"].float_list is not None + embedding_vector = schema.keys["#embedding"].float_list.vector_index + assert embedding_vector is not None + assert embedding_vector.enabled is True + assert embedding_vector.config.embedding_function is mock_ef + assert embedding_vector.config.space == "l2" + assert embedding_vector.config.hnsw is not None + assert embedding_vector.config.hnsw.ef_construction == 200 + assert ( + embedding_vector.config.source_key == "#document" + ) # Preserved, NOT overridden by user config + + def test_fts_index_config_and_restrictions(self) -> None: + """Test FTS index configuration and key restrictions.""" + schema = Schema() + fts_config = FtsIndexConfig() + + # Test 1: MUST specify key="#document" for FTS — global (no key) is not allowed + with pytest.raises( + ValueError, match="FTS index can only be enabled on #document key" + ): + schema.create_index(config=fts_config) + + # Enable FTS explicitly on #document + result = schema.create_index(config=fts_config, key="#document") + assert result is schema # Should return self for chaining + + # Verify FTS is enabled on #document + assert schema.keys["#document"].string is not None + assert schema.keys["#document"].string.fts_index is not None + assert schema.keys["#document"].string.fts_index.enabled is True + assert schema.keys["#document"].string.fts_index.config == fts_config + + # Test 2: Cannot create FTS index on custom key + fts_config2 = FtsIndexConfig() + with pytest.raises( + ValueError, match="FTS index can only be enabled on #document key" + ): + schema.create_index(config=fts_config2, key="custom_text_field") + + # Test 3: Cannot create FTS index on #embedding key (special key blocked) + with pytest.raises( + ValueError, match="Cannot create index on special key '#embedding'" + ): + schema.create_index(config=fts_config2, key="#embedding") + + # Test 4: Cannot create non-FTS index on #document key + with pytest.raises( + ValueError, match="Cannot create index on special key '#document'" + ): + schema.create_index(config=StringInvertedIndexConfig(), key="#document") + + def test_special_keys_blocked_for_all_index_types(self) -> None: + """Test that #embedding and #document keys are blocked for all index types.""" + schema = Schema() + + # Test with StringInvertedIndexConfig on #document + string_config = StringInvertedIndexConfig() + with pytest.raises( + ValueError, match="Cannot create index on special key '#document'" + ): + schema.create_index(config=string_config, key="#document") + + # Test with StringInvertedIndexConfig on #embedding + with pytest.raises( + ValueError, match="Cannot create index on special key '#embedding'" + ): + schema.create_index(config=string_config, key="#embedding") + + # Test with SparseVectorIndexConfig on #document + sparse_config = SparseVectorIndexConfig() + with pytest.raises( + ValueError, match="Cannot create index on special key '#document'" + ): + schema.create_index(config=sparse_config, key="#document") + + # Test with SparseVectorIndexConfig on #embedding + with pytest.raises( + ValueError, match="Cannot create index on special key '#embedding'" + ): + schema.create_index(config=sparse_config, key="#embedding") + + def test_cannot_enable_all_indexes_for_key(self) -> None: + """Test that enabling all indexes for a key is not allowed.""" + schema = Schema() + + # Try to enable all indexes for a custom key (config=None, key="my_key") + with pytest.raises( + ValueError, match="Cannot enable all index types for key 'my_key'" + ): + schema.create_index(key="my_key") + + # Try to disable all indexes for a custom key (config=None, key="my_key") + with pytest.raises( + ValueError, match="Cannot disable all index types for key 'my_key'" + ): + schema.delete_index(key="my_key") + + def test_cannot_delete_vector_or_fts_index(self) -> None: + """Test that deleting vector index is not allowed and FTS delete is restricted.""" + schema = Schema() + + # Vector delete - fully disallowed + vector_config = VectorIndexConfig() + with pytest.raises( + ValueError, match="Deleting vector index is not currently supported" + ): + schema.delete_index(config=vector_config) + + # Try to delete vector index on a custom key + with pytest.raises( + ValueError, match="Deleting vector index is not currently supported" + ): + schema.delete_index(config=vector_config, key="my_vectors") + + # FTS delete: only allowed on #document, other cases must error + fts_config = FtsIndexConfig() + with pytest.raises( + ValueError, match="Deleting FTS index is only supported on #document key" + ): + schema.delete_index(config=fts_config) + + # Try to delete FTS index on a custom key + with pytest.raises( + ValueError, match="Deleting FTS index is only supported on #document key" + ): + schema.delete_index(config=fts_config, key="my_text") + + # Positive case: deleting FTS index on #document should succeed and disable FTS + schema.delete_index(config=fts_config, key="#document") + assert schema.keys["#document"].string is not None + assert schema.keys["#document"].string.fts_index is not None + assert schema.keys["#document"].string.fts_index.enabled is False + assert schema.keys["#document"].string.fts_index.config == fts_config + + def test_disable_string_inverted_index_globally(self) -> None: + """Test disabling string inverted index globally.""" + schema = Schema() + + # Verify string inverted index is enabled by default in global defaults + assert schema.defaults.string is not None + assert schema.defaults.string.string_inverted_index is not None + assert schema.defaults.string.string_inverted_index.enabled is True + + # Disable string inverted index globally + string_config = StringInvertedIndexConfig() + result = schema.delete_index(config=string_config) + assert result is schema # Should return self for chaining + + # Verify it's now disabled in defaults + assert schema.defaults.string.string_inverted_index is not None + assert schema.defaults.string.string_inverted_index.enabled is False + assert schema.defaults.string.string_inverted_index.config == string_config + + # Verify key overrides are not affected (e.g., #document still has its config) + assert schema.keys["#document"].string is not None + assert schema.keys["#document"].string.string_inverted_index is not None + assert ( + schema.keys["#document"].string.string_inverted_index.enabled is False + ) # #document has it disabled + + def test_disable_string_inverted_index_on_key(self) -> None: + """Test disabling string inverted index on a specific key.""" + schema = Schema() + + # Disable string inverted index on a custom key + string_config = StringInvertedIndexConfig() + result = schema.delete_index(config=string_config, key="my_text_field") + assert result is schema + + # Verify it's disabled on the custom key + assert "my_text_field" in schema.keys + assert schema.keys["my_text_field"].string is not None + assert schema.keys["my_text_field"].string.string_inverted_index is not None + assert ( + schema.keys["my_text_field"].string.string_inverted_index.enabled is False + ) + assert ( + schema.keys["my_text_field"].string.string_inverted_index.config + == string_config + ) + + # Verify other value types on this key are None (sparse override) + assert schema.keys["my_text_field"].float_list is None + assert schema.keys["my_text_field"].sparse_vector is None + assert schema.keys["my_text_field"].int_value is None + + # Verify global defaults are not affected + assert schema.defaults.string is not None + assert schema.defaults.string.string_inverted_index is not None + assert schema.defaults.string.string_inverted_index.enabled is True + + # Verify other key overrides are not affected + assert schema.keys["#document"].string is not None + assert schema.keys["#document"].string.string_inverted_index is not None + assert schema.keys["#document"].string.string_inverted_index.enabled is False + assert schema.keys["#embedding"].float_list is not None + assert schema.keys["#embedding"].float_list.vector_index is not None + assert schema.keys["#embedding"].float_list.vector_index.enabled is True + + def test_disable_int_inverted_index(self) -> None: + """Test disabling int inverted index globally and on a specific key.""" + schema = Schema() + + # Verify int inverted index is enabled by default + assert schema.defaults.int_value is not None + assert schema.defaults.int_value.int_inverted_index is not None + assert schema.defaults.int_value.int_inverted_index.enabled is True + + # Test 1: Disable int inverted index globally + int_config = IntInvertedIndexConfig() + result = schema.delete_index(config=int_config) + assert result is schema + + # Verify it's now disabled in defaults + assert schema.defaults.int_value.int_inverted_index.enabled is False + assert schema.defaults.int_value.int_inverted_index.config == int_config + + # Test 2: Disable int inverted index on a specific key + int_config2 = IntInvertedIndexConfig() + result = schema.delete_index(config=int_config2, key="age_field") + assert result is schema + + # Verify it's disabled on the custom key + assert "age_field" in schema.keys + assert schema.keys["age_field"].int_value is not None + assert schema.keys["age_field"].int_value.int_inverted_index is not None + assert schema.keys["age_field"].int_value.int_inverted_index.enabled is False + assert ( + schema.keys["age_field"].int_value.int_inverted_index.config == int_config2 + ) + + # Verify sparse override (only int_value is set) + assert schema.keys["age_field"].string is None + assert schema.keys["age_field"].float_list is None + assert schema.keys["age_field"].sparse_vector is None + assert schema.keys["age_field"].float_value is None + assert schema.keys["age_field"].boolean is None + + # Verify other keys are not affected + assert schema.keys["#document"].string is not None + assert schema.keys["#embedding"].float_list is not None + + def test_serialize_deserialize_default_schema(self) -> None: + """Test serialization and deserialization of a default Schema.""" + # Create a default schema + original = Schema() + + # Serialize to JSON + json_data = original.serialize_to_json() + + # Verify the top-level structure + assert "defaults" in json_data + assert "keys" in json_data + assert isinstance(json_data["defaults"], dict) + assert isinstance(json_data["keys"], dict) + + # Verify defaults structure in detail + defaults = json_data["defaults"] + + # Check string + assert "string" in defaults + assert "fts_index" in defaults["string"] + assert defaults["string"]["fts_index"]["enabled"] is False + assert defaults["string"]["fts_index"]["config"] == {} + assert "string_inverted_index" in defaults["string"] + assert defaults["string"]["string_inverted_index"]["enabled"] is True + assert defaults["string"]["string_inverted_index"]["config"] == {} + + # Check float_list + assert "float_list" in defaults + assert "vector_index" in defaults["float_list"] + assert defaults["float_list"]["vector_index"]["enabled"] is False + vector_config = defaults["float_list"]["vector_index"]["config"] + assert "space" in vector_config + assert vector_config["space"] == "l2" # Default space + assert "embedding_function" in vector_config + assert vector_config["embedding_function"]["type"] == "known" + assert vector_config["embedding_function"]["name"] == "default" + assert vector_config["embedding_function"]["config"] == {} + + # Check sparse_vector + assert "sparse_vector" in defaults + assert "sparse_vector_index" in defaults["sparse_vector"] + assert defaults["sparse_vector"]["sparse_vector_index"]["enabled"] is False + sparse_vector_config = defaults["sparse_vector"]["sparse_vector_index"][ + "config" + ] + # SparseVectorIndexConfig has embedding_function field with unknown default + assert "embedding_function" in sparse_vector_config + assert sparse_vector_config["embedding_function"] == {"type": "unknown"} + + # Check int + assert "int" in defaults + assert "int_inverted_index" in defaults["int"] + assert defaults["int"]["int_inverted_index"]["enabled"] is True + assert defaults["int"]["int_inverted_index"]["config"] == {} + + # Check float + assert "float" in defaults + assert "float_inverted_index" in defaults["float"] + assert defaults["float"]["float_inverted_index"]["enabled"] is True + assert defaults["float"]["float_inverted_index"]["config"] == {} + + # Check bool + assert "bool" in defaults + assert "bool_inverted_index" in defaults["bool"] + assert defaults["bool"]["bool_inverted_index"]["enabled"] is True + assert defaults["bool"]["bool_inverted_index"]["config"] == {} + + # Verify key overrides structure in detail + keys = json_data["keys"] + + # Check #document + assert "#document" in keys + assert "string" in keys["#document"] + assert "fts_index" in keys["#document"]["string"] + assert keys["#document"]["string"]["fts_index"]["enabled"] is True + assert keys["#document"]["string"]["fts_index"]["config"] == {} + assert "string_inverted_index" in keys["#document"]["string"] + assert keys["#document"]["string"]["string_inverted_index"]["enabled"] is False + assert keys["#document"]["string"]["string_inverted_index"]["config"] == {} + + # Check #embedding + assert "#embedding" in keys + assert "float_list" in keys["#embedding"] + assert "vector_index" in keys["#embedding"]["float_list"] + assert keys["#embedding"]["float_list"]["vector_index"]["enabled"] is True + embedding_vector_config = keys["#embedding"]["float_list"]["vector_index"][ + "config" + ] + assert "space" in embedding_vector_config + assert embedding_vector_config["space"] == "l2" # Default space + assert "source_key" in embedding_vector_config + assert embedding_vector_config["source_key"] == "#document" + assert "embedding_function" in embedding_vector_config + assert embedding_vector_config["embedding_function"]["type"] == "known" + assert embedding_vector_config["embedding_function"]["name"] == "default" + assert embedding_vector_config["embedding_function"]["config"] == {} + + # Deserialize back to Schema + deserialized = Schema.deserialize_from_json(json_data) + + # Verify deserialized schema matches original - exhaustive validation + # Check defaults.string + assert deserialized.defaults.string is not None + assert deserialized.defaults.string.fts_index is not None + assert deserialized.defaults.string.fts_index.enabled is False + assert ( + deserialized.defaults.string.fts_index.enabled + == original.defaults.string.fts_index.enabled + ) # type: ignore[union-attr] + assert deserialized.defaults.string.string_inverted_index is not None + assert deserialized.defaults.string.string_inverted_index.enabled is True + assert ( + deserialized.defaults.string.string_inverted_index.enabled + == original.defaults.string.string_inverted_index.enabled + ) # type: ignore[union-attr] + + # Check defaults.float_list (vector index) + assert deserialized.defaults.float_list is not None + assert deserialized.defaults.float_list.vector_index is not None + assert deserialized.defaults.float_list.vector_index.enabled is False + assert ( + deserialized.defaults.float_list.vector_index.enabled + == original.defaults.float_list.vector_index.enabled + ) # type: ignore[union-attr] + # Space is resolved during serialization, so deserialized has explicit value + assert deserialized.defaults.float_list.vector_index.config.space == "l2" + # Check embedding function is preserved + assert ( + deserialized.defaults.float_list.vector_index.config.embedding_function + is not None + ) + assert ( + deserialized.defaults.float_list.vector_index.config.embedding_function.name() + == "default" + ) + assert ( + original.defaults.float_list.vector_index.config.embedding_function.name() + == "default" + ) # type: ignore[union-attr] + + # Check defaults.sparse_vector + assert deserialized.defaults.sparse_vector is not None + assert deserialized.defaults.sparse_vector.sparse_vector_index is not None + assert deserialized.defaults.sparse_vector.sparse_vector_index.enabled is False + assert ( + deserialized.defaults.sparse_vector.sparse_vector_index.enabled + == original.defaults.sparse_vector.sparse_vector_index.enabled + ) # type: ignore[union-attr] + + # Check defaults.int_value + assert deserialized.defaults.int_value is not None + assert deserialized.defaults.int_value.int_inverted_index is not None + assert deserialized.defaults.int_value.int_inverted_index.enabled is True + assert ( + deserialized.defaults.int_value.int_inverted_index.enabled + == original.defaults.int_value.int_inverted_index.enabled + ) # type: ignore[union-attr] + + # Check defaults.float_value + assert deserialized.defaults.float_value is not None + assert deserialized.defaults.float_value.float_inverted_index is not None + assert deserialized.defaults.float_value.float_inverted_index.enabled is True + assert ( + deserialized.defaults.float_value.float_inverted_index.enabled + == original.defaults.float_value.float_inverted_index.enabled + ) # type: ignore[union-attr] + + # Check defaults.boolean + assert deserialized.defaults.boolean is not None + assert deserialized.defaults.boolean.bool_inverted_index is not None + assert deserialized.defaults.boolean.bool_inverted_index.enabled is True + assert ( + deserialized.defaults.boolean.bool_inverted_index.enabled + == original.defaults.boolean.bool_inverted_index.enabled + ) # type: ignore[union-attr] + + # Check keys.#document + assert "#document" in deserialized.keys + assert deserialized.keys["#document"].string is not None + assert deserialized.keys["#document"].string.fts_index is not None + assert deserialized.keys["#document"].string.fts_index.enabled is True + assert ( + deserialized.keys["#document"].string.fts_index.enabled + == original.keys["#document"].string.fts_index.enabled + ) # type: ignore[union-attr] + assert deserialized.keys["#document"].string.string_inverted_index is not None + assert ( + deserialized.keys["#document"].string.string_inverted_index.enabled is False + ) + assert ( + deserialized.keys["#document"].string.string_inverted_index.enabled + == original.keys["#document"].string.string_inverted_index.enabled + ) # type: ignore[union-attr] + + # Check keys.#embedding + assert "#embedding" in deserialized.keys + assert deserialized.keys["#embedding"].float_list is not None + assert deserialized.keys["#embedding"].float_list.vector_index is not None + assert deserialized.keys["#embedding"].float_list.vector_index.enabled is True + assert ( + deserialized.keys["#embedding"].float_list.vector_index.enabled + == original.keys["#embedding"].float_list.vector_index.enabled + ) # type: ignore[union-attr] + # Verify source_key is preserved + assert ( + deserialized.keys["#embedding"].float_list.vector_index.config.source_key + == "#document" + ) + assert ( + original.keys["#embedding"].float_list.vector_index.config.source_key + == "#document" + ) # type: ignore[union-attr] + # Verify space is preserved (resolved during serialization) + assert ( + deserialized.keys["#embedding"].float_list.vector_index.config.space == "l2" + ) + # Verify embedding function is preserved + assert ( + deserialized.keys[ + "#embedding" + ].float_list.vector_index.config.embedding_function + is not None + ) + assert ( + deserialized.keys[ + "#embedding" + ].float_list.vector_index.config.embedding_function.name() + == "default" + ) + assert ( + original.keys[ + "#embedding" + ].float_list.vector_index.config.embedding_function.name() + == "default" + ) # type: ignore[union-attr] + + def test_serialize_deserialize_with_vector_config_no_ef(self) -> None: + """Test serialization/deserialization of Schema with vector config where embedding_function=None.""" + # Create a default schema and modify vector config with ef=None + original = Schema() + vector_config = VectorIndexConfig( + space="cosine", + embedding_function=None, # Explicitly set to None + ) + original.create_index(config=vector_config) + + # Serialize to JSON + json_data = original.serialize_to_json() + + # Verify defaults structure - vector index should reflect the changes + defaults = json_data["defaults"] + assert "float_list" in defaults + assert "vector_index" in defaults["float_list"] + vector_json = defaults["float_list"]["vector_index"] + assert vector_json["enabled"] is False # Still disabled in defaults + assert vector_json["config"]["space"] == "cosine" # User-specified space + # When ef=None, it should serialize as legacy + assert vector_json["config"]["embedding_function"]["type"] == "legacy" + + # Verify #embedding also has the updated config + keys = json_data["keys"] + assert "#embedding" in keys + embedding_vector_json = keys["#embedding"]["float_list"]["vector_index"] + assert embedding_vector_json["enabled"] is True # Still enabled on #embedding + assert ( + embedding_vector_json["config"]["space"] == "cosine" + ) # User-specified space + assert embedding_vector_json["config"]["source_key"] == "#document" # Preserved + # When ef=None, it should serialize as legacy + assert embedding_vector_json["config"]["embedding_function"]["type"] == "legacy" + + # Deserialize back to Schema + deserialized = Schema.deserialize_from_json(json_data) + + # Verify deserialized schema has the correct values + # Check defaults.float_list (vector index) + assert deserialized.defaults.float_list is not None + assert deserialized.defaults.float_list.vector_index is not None + assert deserialized.defaults.float_list.vector_index.enabled is False + assert ( + deserialized.defaults.float_list.vector_index.config.space == "cosine" + ) # User space preserved + # ef=None should deserialize as None (legacy) + assert ( + deserialized.defaults.float_list.vector_index.config.embedding_function + is None + ) + + # Check #embedding vector index + assert "#embedding" in deserialized.keys + assert deserialized.keys["#embedding"].float_list is not None + assert deserialized.keys["#embedding"].float_list.vector_index is not None + assert deserialized.keys["#embedding"].float_list.vector_index.enabled is True + assert ( + deserialized.keys["#embedding"].float_list.vector_index.config.space + == "cosine" + ) # User space preserved + assert ( + deserialized.keys["#embedding"].float_list.vector_index.config.source_key + == "#document" + ) # Preserved + # ef=None should deserialize as None (legacy) + assert ( + deserialized.keys[ + "#embedding" + ].float_list.vector_index.config.embedding_function + is None + ) + + def test_serialize_deserialize_with_custom_ef(self) -> None: + """Test serialization/deserialization of Schema with custom embedding function.""" + # Register the mock embedding function so it can be deserialized + from chromadb.utils.embedding_functions import known_embedding_functions + + known_embedding_functions["mock_embedding"] = MockEmbeddingFunction + + try: + # Create a default schema and modify vector config with custom EF + original = Schema() + custom_ef = MockEmbeddingFunction(model_name="custom_model_v3") + hnsw_config = HnswIndexConfig( + ef_construction=256, max_neighbors=48, ef_search=128 + ) + vector_config = VectorIndexConfig( + embedding_function=custom_ef, + space="ip", # Inner product + hnsw=hnsw_config, + ) + original.create_index(config=vector_config) + + # Serialize to JSON + json_data = original.serialize_to_json() + + # Verify defaults structure - vector index should reflect the changes + defaults = json_data["defaults"] + assert "float_list" in defaults + assert "vector_index" in defaults["float_list"] + vector_json = defaults["float_list"]["vector_index"] + assert vector_json["enabled"] is False # Still disabled in defaults + assert vector_json["config"]["space"] == "ip" # User-specified space + # Custom EF should serialize as known type + assert vector_json["config"]["embedding_function"]["type"] == "known" + assert ( + vector_json["config"]["embedding_function"]["name"] == "mock_embedding" + ) + assert ( + vector_json["config"]["embedding_function"]["config"]["model_name"] + == "custom_model_v3" + ) + # HNSW config should be present + assert "hnsw" in vector_json["config"] + assert vector_json["config"]["hnsw"]["ef_construction"] == 256 + assert vector_json["config"]["hnsw"]["max_neighbors"] == 48 + assert vector_json["config"]["hnsw"]["ef_search"] == 128 + + # Verify #embedding also has the updated config + keys = json_data["keys"] + assert "#embedding" in keys + embedding_vector_json = keys["#embedding"]["float_list"]["vector_index"] + assert ( + embedding_vector_json["enabled"] is True + ) # Still enabled on #embedding + assert ( + embedding_vector_json["config"]["space"] == "ip" + ) # User-specified space + assert ( + embedding_vector_json["config"]["source_key"] == "#document" + ) # Preserved + # Custom EF should serialize as known type + assert ( + embedding_vector_json["config"]["embedding_function"]["type"] == "known" + ) + assert ( + embedding_vector_json["config"]["embedding_function"]["name"] + == "mock_embedding" + ) + assert ( + embedding_vector_json["config"]["embedding_function"]["config"][ + "model_name" + ] + == "custom_model_v3" + ) + # HNSW config should be present + assert "hnsw" in embedding_vector_json["config"] + assert embedding_vector_json["config"]["hnsw"]["ef_construction"] == 256 + assert embedding_vector_json["config"]["hnsw"]["max_neighbors"] == 48 + assert embedding_vector_json["config"]["hnsw"]["ef_search"] == 128 + + # Deserialize back to Schema + deserialized = Schema.deserialize_from_json(json_data) + + # Verify deserialized schema has the correct values + # Check defaults.float_list (vector index) + assert deserialized.defaults.float_list is not None + assert deserialized.defaults.float_list.vector_index is not None + assert deserialized.defaults.float_list.vector_index.enabled is False + assert ( + deserialized.defaults.float_list.vector_index.config.space == "ip" + ) # User space preserved + # Custom EF should be reconstructed + assert ( + deserialized.defaults.float_list.vector_index.config.embedding_function + is not None + ) + assert ( + deserialized.defaults.float_list.vector_index.config.embedding_function.name() + == "mock_embedding" + ) + # Verify the EF config is correct + ef_config = deserialized.defaults.float_list.vector_index.config.embedding_function.get_config() + assert ef_config["model_name"] == "custom_model_v3" + # HNSW config should be preserved + assert deserialized.defaults.float_list.vector_index.config.hnsw is not None + assert ( + deserialized.defaults.float_list.vector_index.config.hnsw.ef_construction + == 256 + ) + assert ( + deserialized.defaults.float_list.vector_index.config.hnsw.max_neighbors + == 48 + ) + assert ( + deserialized.defaults.float_list.vector_index.config.hnsw.ef_search + == 128 + ) + + # Check #embedding vector index + assert "#embedding" in deserialized.keys + assert deserialized.keys["#embedding"].float_list is not None + assert deserialized.keys["#embedding"].float_list.vector_index is not None + assert ( + deserialized.keys["#embedding"].float_list.vector_index.enabled is True + ) + assert ( + deserialized.keys["#embedding"].float_list.vector_index.config.space + == "ip" + ) # User space preserved + assert ( + deserialized.keys[ + "#embedding" + ].float_list.vector_index.config.source_key + == "#document" + ) # Preserved + # Custom EF should be reconstructed + assert ( + deserialized.keys[ + "#embedding" + ].float_list.vector_index.config.embedding_function + is not None + ) + assert ( + deserialized.keys[ + "#embedding" + ].float_list.vector_index.config.embedding_function.name() + == "mock_embedding" + ) + # Verify the EF config is correct + ef_config_embedding = deserialized.keys[ + "#embedding" + ].float_list.vector_index.config.embedding_function.get_config() + assert ef_config_embedding["model_name"] == "custom_model_v3" + # HNSW config should be preserved + assert ( + deserialized.keys["#embedding"].float_list.vector_index.config.hnsw + is not None + ) + assert ( + deserialized.keys[ + "#embedding" + ].float_list.vector_index.config.hnsw.ef_construction + == 256 + ) + assert ( + deserialized.keys[ + "#embedding" + ].float_list.vector_index.config.hnsw.max_neighbors + == 48 + ) + assert ( + deserialized.keys[ + "#embedding" + ].float_list.vector_index.config.hnsw.ef_search + == 128 + ) + finally: + # Clean up: remove the mock function from known_embedding_functions + if "mock_embedding" in known_embedding_functions: + del known_embedding_functions["mock_embedding"] + + def test_serialize_deserialize_with_spann_config(self) -> None: + """Test serialization/deserialization of Schema with SPANN index config.""" + # Register the mock embedding function so it can be deserialized + from chromadb.utils.embedding_functions import known_embedding_functions + + known_embedding_functions["mock_embedding"] = MockEmbeddingFunction + + try: + # Create a default schema and modify vector config with SPANN + original = Schema() + custom_ef = MockEmbeddingFunction(model_name="spann_model") + spann_config = SpannIndexConfig( + search_nprobe=100, write_nprobe=50, ef_construction=200, ef_search=150 + ) + vector_config = VectorIndexConfig( + embedding_function=custom_ef, space="cosine", spann=spann_config + ) + original.create_index(config=vector_config) + + # Serialize to JSON + json_data = original.serialize_to_json() + + # Verify defaults structure - vector index should reflect the changes + defaults = json_data["defaults"] + assert "float_list" in defaults + assert "vector_index" in defaults["float_list"] + vector_json = defaults["float_list"]["vector_index"] + assert vector_json["enabled"] is False # Still disabled in defaults + assert vector_json["config"]["space"] == "cosine" # User-specified space + # Custom EF should serialize as known type + assert vector_json["config"]["embedding_function"]["type"] == "known" + assert ( + vector_json["config"]["embedding_function"]["name"] == "mock_embedding" + ) + assert ( + vector_json["config"]["embedding_function"]["config"]["model_name"] + == "spann_model" + ) + # SPANN config should be present + assert "spann" in vector_json["config"] + assert vector_json["config"]["spann"]["search_nprobe"] == 100 + assert vector_json["config"]["spann"]["write_nprobe"] == 50 + assert vector_json["config"]["spann"]["ef_construction"] == 200 + assert vector_json["config"]["spann"]["ef_search"] == 150 + # HNSW should not be present + assert vector_json["config"].get("hnsw") is None + + # Verify #embedding also has the updated config + keys = json_data["keys"] + assert "#embedding" in keys + embedding_vector_json = keys["#embedding"]["float_list"]["vector_index"] + assert ( + embedding_vector_json["enabled"] is True + ) # Still enabled on #embedding + assert ( + embedding_vector_json["config"]["space"] == "cosine" + ) # User-specified space + assert ( + embedding_vector_json["config"]["source_key"] == "#document" + ) # Preserved + # Custom EF should serialize as known type + assert ( + embedding_vector_json["config"]["embedding_function"]["type"] == "known" + ) + assert ( + embedding_vector_json["config"]["embedding_function"]["name"] + == "mock_embedding" + ) + assert ( + embedding_vector_json["config"]["embedding_function"]["config"][ + "model_name" + ] + == "spann_model" + ) + # SPANN config should be present + assert "spann" in embedding_vector_json["config"] + assert embedding_vector_json["config"]["spann"]["search_nprobe"] == 100 + assert embedding_vector_json["config"]["spann"]["write_nprobe"] == 50 + assert embedding_vector_json["config"]["spann"]["ef_construction"] == 200 + assert embedding_vector_json["config"]["spann"]["ef_search"] == 150 + # HNSW should not be present + assert embedding_vector_json["config"].get("hnsw") is None + + # Deserialize back to Schema + deserialized = Schema.deserialize_from_json(json_data) + + # Verify deserialized schema has the correct values + # Check defaults.float_list (vector index) + assert deserialized.defaults.float_list is not None + assert deserialized.defaults.float_list.vector_index is not None + assert deserialized.defaults.float_list.vector_index.enabled is False + assert ( + deserialized.defaults.float_list.vector_index.config.space == "cosine" + ) # User space preserved + # Custom EF should be reconstructed + assert ( + deserialized.defaults.float_list.vector_index.config.embedding_function + is not None + ) + assert ( + deserialized.defaults.float_list.vector_index.config.embedding_function.name() + == "mock_embedding" + ) + # Verify the EF config is correct + ef_config = deserialized.defaults.float_list.vector_index.config.embedding_function.get_config() + assert ef_config["model_name"] == "spann_model" + # SPANN config should be preserved + assert ( + deserialized.defaults.float_list.vector_index.config.spann is not None + ) + assert ( + deserialized.defaults.float_list.vector_index.config.spann.search_nprobe + == 100 + ) + assert ( + deserialized.defaults.float_list.vector_index.config.spann.write_nprobe + == 50 + ) + assert ( + deserialized.defaults.float_list.vector_index.config.spann.ef_construction + == 200 + ) + assert ( + deserialized.defaults.float_list.vector_index.config.spann.ef_search + == 150 + ) + # HNSW should be None + assert deserialized.defaults.float_list.vector_index.config.hnsw is None + + # Check #embedding vector index + assert "#embedding" in deserialized.keys + assert deserialized.keys["#embedding"].float_list is not None + assert deserialized.keys["#embedding"].float_list.vector_index is not None + assert ( + deserialized.keys["#embedding"].float_list.vector_index.enabled is True + ) + assert ( + deserialized.keys["#embedding"].float_list.vector_index.config.space + == "cosine" + ) # User space preserved + assert ( + deserialized.keys[ + "#embedding" + ].float_list.vector_index.config.source_key + == "#document" + ) # Preserved + # Custom EF should be reconstructed + assert ( + deserialized.keys[ + "#embedding" + ].float_list.vector_index.config.embedding_function + is not None + ) + assert ( + deserialized.keys[ + "#embedding" + ].float_list.vector_index.config.embedding_function.name() + == "mock_embedding" + ) + # Verify the EF config is correct + ef_config_embedding = deserialized.keys[ + "#embedding" + ].float_list.vector_index.config.embedding_function.get_config() + assert ef_config_embedding["model_name"] == "spann_model" + # SPANN config should be preserved + assert ( + deserialized.keys["#embedding"].float_list.vector_index.config.spann + is not None + ) + assert ( + deserialized.keys[ + "#embedding" + ].float_list.vector_index.config.spann.search_nprobe + == 100 + ) + assert ( + deserialized.keys[ + "#embedding" + ].float_list.vector_index.config.spann.write_nprobe + == 50 + ) + assert ( + deserialized.keys[ + "#embedding" + ].float_list.vector_index.config.spann.ef_construction + == 200 + ) + assert ( + deserialized.keys[ + "#embedding" + ].float_list.vector_index.config.spann.ef_search + == 150 + ) + # HNSW should be None + assert ( + deserialized.keys["#embedding"].float_list.vector_index.config.hnsw + is None + ) + finally: + # Clean up: remove the mock function from known_embedding_functions + if "mock_embedding" in known_embedding_functions: + del known_embedding_functions["mock_embedding"] + + def test_serialize_deserialize_complex_mixed_modifications(self) -> None: + """Test serialization/deserialization with multiple mixed schema modifications.""" + # Register the mock embedding functions so they can be deserialized + from chromadb.utils.embedding_functions import known_embedding_functions + + known_embedding_functions["mock_embedding"] = MockEmbeddingFunction + known_embedding_functions["mock_sparse"] = MockSparseEmbeddingFunction # type: ignore[assignment] + + try: + # Create a default schema and apply multiple modifications + original = Schema() + + # 1. Set custom vector config globally (space + HNSW) + custom_ef = MockEmbeddingFunction(model_name="mixed_test_model") + hnsw_config = HnswIndexConfig(ef_construction=300, max_neighbors=64) + vector_config = VectorIndexConfig( + embedding_function=custom_ef, space="ip", hnsw=hnsw_config + ) + original.create_index(config=vector_config) + + # 2. Enable sparse vector index on "embeddings_field" key + sparse_ef = MockSparseEmbeddingFunction(name="sparse_model") + sparse_config = SparseVectorIndexConfig( + embedding_function=sparse_ef, source_key="text_field" + ) + original.create_index(config=sparse_config, key="embeddings_field") + + # 3. Disable string_inverted_index on "tags" key + string_config = StringInvertedIndexConfig() + original.delete_index(config=string_config, key="tags") + + # 4. Disable int_inverted_index on "count" key + int_config = IntInvertedIndexConfig() + original.delete_index(config=int_config, key="count") + + # 5. Disable float_inverted_index on "price" key + float_config = FloatInvertedIndexConfig() + original.delete_index(config=float_config, key="price") + + # Serialize to JSON + json_data = original.serialize_to_json() + + # Verify JSON structure has all modifications + defaults = json_data["defaults"] + keys = json_data["keys"] + + # Check defaults reflect global vector config changes + assert defaults["float_list"]["vector_index"]["config"]["space"] == "ip" + assert ( + defaults["float_list"]["vector_index"]["config"]["hnsw"][ + "ef_construction" + ] + == 300 + ) + assert ( + defaults["float_list"]["vector_index"]["config"]["hnsw"][ + "max_neighbors" + ] + == 64 + ) + + # Check key overrides exist for all modified keys + assert "embeddings_field" in keys + assert "tags" in keys + assert "count" in keys + assert "price" in keys + assert "#document" in keys # Default key + assert "#embedding" in keys # Default key with vector config + + # Exhaustive validation of embeddings_field + embeddings_field_json = keys["embeddings_field"] + assert "sparse_vector" in embeddings_field_json + assert ( + embeddings_field_json["sparse_vector"]["sparse_vector_index"]["enabled"] + is True + ) + assert ( + embeddings_field_json["sparse_vector"]["sparse_vector_index"]["config"][ + "source_key" + ] + == "text_field" + ) + assert ( + embeddings_field_json["sparse_vector"]["sparse_vector_index"]["config"][ + "embedding_function" + ]["type"] + == "known" + ) + assert ( + embeddings_field_json["sparse_vector"]["sparse_vector_index"]["config"][ + "embedding_function" + ]["name"] + == "mock_sparse" + ) + assert ( + embeddings_field_json["sparse_vector"]["sparse_vector_index"]["config"][ + "embedding_function" + ]["config"]["name"] + == "sparse_model" + ) + # Verify sparse override: only sparse_vector should be present + assert "string" not in embeddings_field_json + assert "float_list" not in embeddings_field_json + assert "int" not in embeddings_field_json + assert "float" not in embeddings_field_json + assert "bool" not in embeddings_field_json + + # Exhaustive validation of tags + tags_json = keys["tags"] + assert "string" in tags_json + assert tags_json["string"]["string_inverted_index"]["enabled"] is False + assert tags_json["string"]["string_inverted_index"]["config"] == {} + # FTS should not be present (not modified) + assert "fts_index" not in tags_json["string"] + # Verify sparse override: only string should be present + assert "sparse_vector" not in tags_json + assert "float_list" not in tags_json + assert "int" not in tags_json + assert "float" not in tags_json + assert "bool" not in tags_json + + # Exhaustive validation of count + count_json = keys["count"] + assert "int" in count_json + assert count_json["int"]["int_inverted_index"]["enabled"] is False + assert count_json["int"]["int_inverted_index"]["config"] == {} + # Verify sparse override: only int should be present + assert "string" not in count_json + assert "sparse_vector" not in count_json + assert "float_list" not in count_json + assert "float" not in count_json + assert "bool" not in count_json + + # Exhaustive validation of price + price_json = keys["price"] + assert "float" in price_json + assert price_json["float"]["float_inverted_index"]["enabled"] is False + assert price_json["float"]["float_inverted_index"]["config"] == {} + # Verify sparse override: only float should be present + assert "string" not in price_json + assert "sparse_vector" not in price_json + assert "float_list" not in price_json + assert "int" not in price_json + assert "bool" not in price_json + + # Exhaustive validation of #embedding + embedding_json = keys["#embedding"] + assert "float_list" in embedding_json + assert embedding_json["float_list"]["vector_index"]["enabled"] is True + assert ( + embedding_json["float_list"]["vector_index"]["config"]["space"] == "ip" + ) + assert ( + embedding_json["float_list"]["vector_index"]["config"]["source_key"] + == "#document" + ) + assert ( + embedding_json["float_list"]["vector_index"]["config"][ + "embedding_function" + ]["type"] + == "known" + ) + assert ( + embedding_json["float_list"]["vector_index"]["config"][ + "embedding_function" + ]["name"] + == "mock_embedding" + ) + assert ( + embedding_json["float_list"]["vector_index"]["config"][ + "embedding_function" + ]["config"]["model_name"] + == "mixed_test_model" + ) + assert ( + embedding_json["float_list"]["vector_index"]["config"]["hnsw"][ + "ef_construction" + ] + == 300 + ) + assert ( + embedding_json["float_list"]["vector_index"]["config"]["hnsw"][ + "max_neighbors" + ] + == 64 + ) + assert ( + embedding_json["float_list"]["vector_index"]["config"].get("spann") + is None + ) + # Verify sparse override: only float_list should be present + assert "string" not in embedding_json + assert "sparse_vector" not in embedding_json + assert "int" not in embedding_json + assert "float" not in embedding_json + assert "bool" not in embedding_json + + # Exhaustive validation of #document (unchanged, but with FTS enabled) + document_json = keys["#document"] + assert "string" in document_json + assert document_json["string"]["fts_index"]["enabled"] is True + assert document_json["string"]["fts_index"]["config"] == {} + assert document_json["string"]["string_inverted_index"]["enabled"] is False + assert document_json["string"]["string_inverted_index"]["config"] == {} + # Verify sparse override: only string should be present + assert "sparse_vector" not in document_json + assert "float_list" not in document_json + assert "int" not in document_json + assert "float" not in document_json + assert "bool" not in document_json + + # Deserialize back to Schema + deserialized = Schema.deserialize_from_json(json_data) + + # Verify all modifications are preserved after deserialization + # 1. Check global vector config + assert deserialized.defaults.float_list is not None + assert deserialized.defaults.float_list.vector_index is not None + assert deserialized.defaults.float_list.vector_index.config.space == "ip" + assert deserialized.defaults.float_list.vector_index.config.hnsw is not None + assert ( + deserialized.defaults.float_list.vector_index.config.hnsw.ef_construction + == 300 + ) + assert ( + deserialized.defaults.float_list.vector_index.config.hnsw.max_neighbors + == 64 + ) + assert ( + deserialized.defaults.float_list.vector_index.config.embedding_function + is not None + ) + assert ( + deserialized.defaults.float_list.vector_index.config.embedding_function.name() + == "mock_embedding" + ) + + # 2. Check embeddings_field sparse vector + assert "embeddings_field" in deserialized.keys + assert deserialized.keys["embeddings_field"].sparse_vector is not None + assert ( + deserialized.keys["embeddings_field"].sparse_vector.sparse_vector_index + is not None + ) + assert ( + deserialized.keys[ + "embeddings_field" + ].sparse_vector.sparse_vector_index.enabled + is True + ) + assert ( + deserialized.keys[ + "embeddings_field" + ].sparse_vector.sparse_vector_index.config.source_key + == "text_field" + ) + # Sparse override: other value types should be None + assert deserialized.keys["embeddings_field"].string is None + assert deserialized.keys["embeddings_field"].float_list is None + assert deserialized.keys["embeddings_field"].int_value is None + + # 3. Check tags has string_inverted_index disabled + assert "tags" in deserialized.keys + assert deserialized.keys["tags"].string is not None + assert deserialized.keys["tags"].string.string_inverted_index is not None + assert ( + deserialized.keys["tags"].string.string_inverted_index.enabled is False + ) + # Sparse override: other value types should be None + assert deserialized.keys["tags"].sparse_vector is None + assert deserialized.keys["tags"].float_list is None + + # 4. Check count has int_inverted_index disabled + assert "count" in deserialized.keys + assert deserialized.keys["count"].int_value is not None + assert deserialized.keys["count"].int_value.int_inverted_index is not None + assert ( + deserialized.keys["count"].int_value.int_inverted_index.enabled is False + ) + # Sparse override: other value types should be None + assert deserialized.keys["count"].string is None + assert deserialized.keys["count"].float_list is None + + # 5. Check price has float_inverted_index disabled + assert "price" in deserialized.keys + assert deserialized.keys["price"].float_value is not None + assert ( + deserialized.keys["price"].float_value.float_inverted_index is not None + ) + assert ( + deserialized.keys["price"].float_value.float_inverted_index.enabled + is False + ) + # Sparse override: other value types should be None + assert deserialized.keys["price"].string is None + assert deserialized.keys["price"].sparse_vector is None + + # 6. Check #embedding has updated vector config + assert "#embedding" in deserialized.keys + assert deserialized.keys["#embedding"].float_list is not None + assert deserialized.keys["#embedding"].float_list.vector_index is not None + assert ( + deserialized.keys["#embedding"].float_list.vector_index.config.space + == "ip" + ) + assert ( + deserialized.keys[ + "#embedding" + ].float_list.vector_index.config.source_key + == "#document" + ) + assert ( + deserialized.keys["#embedding"].float_list.vector_index.config.hnsw + is not None + ) + assert ( + deserialized.keys[ + "#embedding" + ].float_list.vector_index.config.hnsw.ef_construction + == 300 + ) + + # 7. Verify defaults for unchanged indexes remain correct + assert deserialized.defaults.string is not None + assert deserialized.defaults.string.string_inverted_index is not None + assert ( + deserialized.defaults.string.string_inverted_index.enabled is True + ) # Still enabled globally + assert deserialized.defaults.int_value is not None + assert deserialized.defaults.int_value.int_inverted_index is not None + assert ( + deserialized.defaults.int_value.int_inverted_index.enabled is True + ) # Still enabled globally + assert deserialized.defaults.sparse_vector is not None + assert deserialized.defaults.sparse_vector.sparse_vector_index is not None + assert ( + deserialized.defaults.sparse_vector.sparse_vector_index.enabled is False + ) # Still disabled globally + finally: + # Clean up: remove the mock functions from known_embedding_functions + if "mock_embedding" in known_embedding_functions: + del known_embedding_functions["mock_embedding"] + if "mock_sparse" in known_embedding_functions: + del known_embedding_functions["mock_sparse"] + + def test_multiple_index_types_on_same_key(self) -> None: + """Test that multiple index types can coexist on the same key.""" + schema = Schema() + + # Enable sparse vector on "multi_field" + sparse_config = SparseVectorIndexConfig( + source_key="source", embedding_function=MockSparseEmbeddingFunction() + ) + schema.create_index(config=sparse_config, key="multi_field") + + # Also enable string_inverted_index on the same key + string_config = StringInvertedIndexConfig() + schema.create_index(config=string_config, key="multi_field") + + # Verify both indexes exist on the same key + assert "multi_field" in schema.keys + multi_field = schema.keys["multi_field"] + assert multi_field.sparse_vector is not None + assert multi_field.sparse_vector.sparse_vector_index is not None + assert multi_field.sparse_vector.sparse_vector_index.enabled is True + + assert multi_field.string is not None + assert multi_field.string.string_inverted_index is not None + assert multi_field.string.string_inverted_index.enabled is True + + # Verify other value types are still None (sparse override) + assert schema.keys["multi_field"].float_list is None + assert schema.keys["multi_field"].int_value is None + assert schema.keys["multi_field"].float_value is None + assert schema.keys["multi_field"].boolean is None + + # Serialize and verify both are present in JSON + json_data = schema.serialize_to_json() + multi_field_json = json_data["keys"]["multi_field"] + assert "sparse_vector" in multi_field_json + assert "string" in multi_field_json + assert ( + multi_field_json["sparse_vector"]["sparse_vector_index"]["enabled"] is True + ) + assert multi_field_json["string"]["string_inverted_index"]["enabled"] is True + + # Deserialize and verify both survive roundtrip + deserialized = Schema.deserialize_from_json(json_data) + assert "multi_field" in deserialized.keys + des_multi_field = deserialized.keys["multi_field"] + assert des_multi_field.sparse_vector is not None + assert des_multi_field.sparse_vector.sparse_vector_index is not None + assert des_multi_field.sparse_vector.sparse_vector_index.enabled is True + assert des_multi_field.string is not None + assert des_multi_field.string.string_inverted_index is not None + assert des_multi_field.string.string_inverted_index.enabled is True + + def test_override_then_revert_to_default(self) -> None: + """Test that disabling an index reverts to default behavior (key may still exist with disabled state).""" + schema = Schema() + + # Enable string_inverted_index on "temp_field" + string_config = StringInvertedIndexConfig() + schema.create_index(config=string_config, key="temp_field") + + # Verify it's enabled + assert "temp_field" in schema.keys + temp_field_initial = schema.keys["temp_field"] + assert temp_field_initial.string is not None + assert temp_field_initial.string.string_inverted_index is not None + assert temp_field_initial.string.string_inverted_index.enabled is True + + # Now disable it + schema.delete_index(config=string_config, key="temp_field") + + # Verify it's now disabled (key still exists but with disabled state) + assert "temp_field" in schema.keys + temp_field = schema.keys["temp_field"] + assert temp_field.string is not None + assert temp_field.string.string_inverted_index is not None + assert temp_field.string.string_inverted_index.enabled is False + + # Serialize and verify disabled state is preserved + json_data = schema.serialize_to_json() + assert "temp_field" in json_data["keys"] + temp_field_json = json_data["keys"]["temp_field"] + assert "string" in temp_field_json + assert temp_field_json["string"]["string_inverted_index"]["enabled"] is False + + # Deserialize and verify disabled state survives roundtrip + deserialized = Schema.deserialize_from_json(json_data) + assert "temp_field" in deserialized.keys + des_temp_field = deserialized.keys["temp_field"] + assert des_temp_field.string is not None + assert des_temp_field.string.string_inverted_index is not None + assert des_temp_field.string.string_inverted_index.enabled is False + + def test_error_handling_invalid_operations(self) -> None: + """Test that invalid operations raise appropriate errors.""" + schema = Schema() + + # Test 1: Cannot create index on #embedding key + vector_config = VectorIndexConfig() + with pytest.raises( + ValueError, match="Cannot create index on special key '#embedding'" + ): + schema.create_index(config=vector_config, key="#embedding") + + # Test 2: Cannot create non-FTS index on #document key + with pytest.raises( + ValueError, match="Cannot create index on special key '#document'" + ): + schema.create_index(config=StringInvertedIndexConfig(), key="#document") + + # FTS index on #document IS allowed + fts_config = FtsIndexConfig() + schema.create_index(config=fts_config, key="#document") + + # Test 3: Cannot disable all indexes globally (no config, no key) + with pytest.raises(ValueError, match="Cannot disable all indexes"): + schema.delete_index() + + # Test 4: Cannot enable all indexes globally + with pytest.raises(ValueError, match="Cannot enable all index types globally"): + schema.create_index() + + # Test 5: Cannot enable all indexes for a specific key + with pytest.raises( + ValueError, match="Cannot enable all index types for key 'mykey'" + ): + schema.create_index(key="mykey") + + # Test 6: Cannot disable all indexes for a specific key + with pytest.raises( + ValueError, match="Cannot disable all index types for key 'mykey'" + ): + schema.delete_index(key="mykey") + + # Test 7: Cannot delete vector index + with pytest.raises( + ValueError, match="Deleting vector index is not currently supported" + ): + schema.delete_index(config=vector_config) + + # Test 8: Cannot delete FTS index except on #document + with pytest.raises( + ValueError, match="Deleting FTS index is only supported on #document key" + ): + schema.delete_index(config=fts_config) + + # Test 9: Cannot create vector index on custom key + with pytest.raises( + ValueError, match="Vector index cannot be enabled on specific keys" + ): + schema.create_index(config=vector_config, key="custom_field") + + # Test 10: Cannot create FTS index on custom key + with pytest.raises( + ValueError, match="FTS index can only be enabled on #document key" + ): + schema.create_index(config=fts_config, key="custom_field") + + def test_empty_schema_serialization(self) -> None: + """Test serialization/deserialization of an unmodified schema.""" + # Create a schema without any modifications + original = Schema() + + # Serialize + json_data = original.serialize_to_json() + + # Verify only default keys exist in keys + assert len(json_data["keys"]) == 2 + assert "#document" in json_data["keys"] + assert "#embedding" in json_data["keys"] + + # Deserialize + deserialized = Schema.deserialize_from_json(json_data) + + # Verify defaults match + defaults = deserialized.defaults + assert defaults.string is not None + assert defaults.string.string_inverted_index is not None + assert defaults.string.string_inverted_index.enabled is True + assert defaults.string.fts_index is not None + assert defaults.string.fts_index.enabled is False + assert defaults.float_list is not None + assert defaults.float_list.vector_index is not None + assert defaults.float_list.vector_index.enabled is False + assert defaults.sparse_vector is not None + assert defaults.sparse_vector.sparse_vector_index is not None + assert defaults.sparse_vector.sparse_vector_index.enabled is False + assert defaults.int_value is not None + assert defaults.int_value.int_inverted_index is not None + assert defaults.int_value.int_inverted_index.enabled is True + assert defaults.float_value is not None + assert defaults.float_value.float_inverted_index is not None + assert defaults.float_value.float_inverted_index.enabled is True + assert defaults.boolean is not None + assert defaults.boolean.bool_inverted_index is not None + assert defaults.boolean.bool_inverted_index.enabled is True + + # Verify only default keys exist in keys + assert len(deserialized.keys) == 2 + assert "#document" in deserialized.keys + assert "#embedding" in deserialized.keys + + def test_multiple_serialize_deserialize_roundtrips(self) -> None: + """Test that multiple serialization/deserialization cycles preserve schema integrity.""" + # Register the mock embedding function + from chromadb.utils.embedding_functions import known_embedding_functions + + known_embedding_functions["mock_embedding"] = MockEmbeddingFunction + + try: + # Create a complex schema + original = Schema() + custom_ef = MockEmbeddingFunction(model_name="roundtrip_model") + hnsw_config = HnswIndexConfig(ef_construction=150, max_neighbors=40) + vector_config = VectorIndexConfig( + embedding_function=custom_ef, space="cosine", hnsw=hnsw_config + ) + original.create_index(config=vector_config) + original.create_index( + config=SparseVectorIndexConfig( + source_key="text", embedding_function=MockSparseEmbeddingFunction() + ), + key="embeddings", + ) + original.delete_index(config=StringInvertedIndexConfig(), key="tags") + + # First roundtrip + json1 = original.serialize_to_json() + schema1 = Schema.deserialize_from_json(json1) + + # Second roundtrip + json2 = schema1.serialize_to_json() + schema2 = Schema.deserialize_from_json(json2) + + # Third roundtrip + json3 = schema2.serialize_to_json() + schema3 = Schema.deserialize_from_json(json3) + + # Verify all schemas are identical + # Check vector config persists + for schema in [schema1, schema2, schema3]: + assert schema.defaults.float_list is not None + assert schema.defaults.float_list.vector_index is not None + assert schema.defaults.float_list.vector_index.config.space == "cosine" + assert schema.defaults.float_list.vector_index.config.hnsw is not None + assert ( + schema.defaults.float_list.vector_index.config.hnsw.ef_construction + == 150 + ) + assert ( + schema.defaults.float_list.vector_index.config.hnsw.max_neighbors + == 40 + ) + assert ( + schema.defaults.float_list.vector_index.config.embedding_function + is not None + ) + assert ( + schema.defaults.float_list.vector_index.config.embedding_function.name() + == "mock_embedding" + ) + + # Check sparse vector on embeddings key + assert "embeddings" in schema.keys + embeddings_override = schema.keys["embeddings"] + assert embeddings_override.sparse_vector is not None + assert embeddings_override.sparse_vector.sparse_vector_index is not None + assert ( + embeddings_override.sparse_vector.sparse_vector_index.enabled + is True + ) + assert ( + embeddings_override.sparse_vector.sparse_vector_index.config.source_key + == "text" + ) + + # Check disabled string index on tags key + assert "tags" in schema.keys + tags_override = schema.keys["tags"] + assert tags_override.string is not None + assert tags_override.string.string_inverted_index is not None + assert tags_override.string.string_inverted_index.enabled is False + + # Verify semantic equivalence: all three schemas should have same number of overrides + assert len(schema1.keys) == len(schema2.keys) == len(schema3.keys) + assert ( + set(schema1.keys.keys()) + == set(schema2.keys.keys()) + == set(schema3.keys.keys()) + ) + + finally: + # Clean up + if "mock_embedding" in known_embedding_functions: + del known_embedding_functions["mock_embedding"] + + def test_many_keys_stress(self) -> None: + """Test schema with many key overrides (stress test).""" + schema = Schema() + + # Create 50 key overrides with different configurations + for i in range(50): + key_name = f"field_{i}" + if i == 0: + # Enable sparse vector on ONE key only + schema.create_index( + config=SparseVectorIndexConfig( + source_key=f"source_{i}", + embedding_function=MockSparseEmbeddingFunction(), + ), + key=key_name, + ) + elif i % 2 == 1: + # Disable string inverted index + schema.delete_index(config=StringInvertedIndexConfig(), key=key_name) + else: + # Disable int inverted index + schema.delete_index(config=IntInvertedIndexConfig(), key=key_name) + + # Verify all 50 keys + 2 defaults exist + assert len(schema.keys) == 52 # 50 custom + #document + #embedding + + # Verify a sample of keys + assert "field_0" in schema.keys + field_0 = schema.keys["field_0"] + assert field_0.sparse_vector is not None + assert field_0.sparse_vector.sparse_vector_index is not None + assert field_0.sparse_vector.sparse_vector_index.enabled is True + + assert "field_1" in schema.keys + field_1 = schema.keys["field_1"] + assert field_1.string is not None + assert field_1.string.string_inverted_index is not None + assert field_1.string.string_inverted_index.enabled is False + + assert "field_2" in schema.keys + field_2 = schema.keys["field_2"] + assert field_2.int_value is not None + assert field_2.int_value.int_inverted_index is not None + assert field_2.int_value.int_inverted_index.enabled is False + + # Serialize + json_data = schema.serialize_to_json() + assert len(json_data["keys"]) == 52 + + # Deserialize + deserialized = Schema.deserialize_from_json(json_data) + assert len(deserialized.keys) == 52 + + # Spot check deserialized values + assert "field_0" in deserialized.keys # i == 0 -> sparse vector + des_field_0 = deserialized.keys["field_0"] + assert des_field_0.sparse_vector is not None + assert des_field_0.sparse_vector.sparse_vector_index is not None + assert des_field_0.sparse_vector.sparse_vector_index.enabled is True + assert ( + des_field_0.sparse_vector.sparse_vector_index.config.source_key + == "source_0" + ) + + assert "field_49" in deserialized.keys # 49 % 2 == 1 -> string disabled + des_field_49 = deserialized.keys["field_49"] + assert des_field_49.string is not None + assert des_field_49.string.string_inverted_index is not None + assert des_field_49.string.string_inverted_index.enabled is False + + assert "field_48" in deserialized.keys # 48 % 2 == 0 -> int disabled + des_field_48 = deserialized.keys["field_48"] + assert des_field_48.int_value is not None + assert des_field_48.int_value.int_inverted_index is not None + assert des_field_48.int_value.int_inverted_index.enabled is False + + def test_chained_operations(self) -> None: + """Test chaining multiple create_index and delete_index operations.""" + schema = Schema() + + # Chain multiple operations + result = ( + schema.create_index( + config=SparseVectorIndexConfig( + source_key="text", embedding_function=MockSparseEmbeddingFunction() + ), + key="field1", + ) + .delete_index(config=StringInvertedIndexConfig(), key="field2") + .delete_index(config=StringInvertedIndexConfig(), key="field3") + .delete_index(config=IntInvertedIndexConfig(), key="field4") + ) + + # Verify chaining returns the same schema object + assert result is schema + + # Verify all operations were applied + assert "field1" in schema.keys + field1 = schema.keys["field1"] + assert field1.sparse_vector is not None + assert field1.sparse_vector.sparse_vector_index is not None + assert field1.sparse_vector.sparse_vector_index.enabled is True + + assert "field2" in schema.keys + field2 = schema.keys["field2"] + assert field2.string is not None + assert field2.string.string_inverted_index is not None + assert field2.string.string_inverted_index.enabled is False + + assert "field3" in schema.keys + field3 = schema.keys["field3"] + assert field3.string is not None + assert field3.string.string_inverted_index is not None + assert field3.string.string_inverted_index.enabled is False + + assert "field4" in schema.keys + field4 = schema.keys["field4"] + assert field4.int_value is not None + assert field4.int_value.int_inverted_index is not None + assert field4.int_value.int_inverted_index.enabled is False + + def test_float_and_bool_inverted_indexes(self) -> None: + """Test enabling/disabling float and bool inverted indexes.""" + schema = Schema() + + # Verify defaults + assert schema.defaults.float_value is not None + assert schema.defaults.float_value.float_inverted_index is not None + assert schema.defaults.float_value.float_inverted_index.enabled is True + assert schema.defaults.boolean is not None + assert schema.defaults.boolean.bool_inverted_index is not None + assert schema.defaults.boolean.bool_inverted_index.enabled is True + + # Disable float inverted index globally + float_config = FloatInvertedIndexConfig() + schema.delete_index(config=float_config) + assert schema.defaults.float_value.float_inverted_index is not None + assert schema.defaults.float_value.float_inverted_index.enabled is False + + # Disable bool inverted index globally + bool_config = BoolInvertedIndexConfig() + schema.delete_index(config=bool_config) + assert schema.defaults.boolean.bool_inverted_index is not None + assert schema.defaults.boolean.bool_inverted_index.enabled is False + + # Enable float inverted index on a specific key + schema.create_index(config=FloatInvertedIndexConfig(), key="price") + assert "price" in schema.keys + assert schema.keys["price"].float_value.float_inverted_index.enabled is True + + # Disable bool inverted index on a specific key + schema.delete_index(config=BoolInvertedIndexConfig(), key="is_active") + assert "is_active" in schema.keys + assert schema.keys["is_active"].boolean.bool_inverted_index.enabled is False + + # Serialize and verify + json_data = schema.serialize_to_json() + assert ( + json_data["defaults"]["float"]["float_inverted_index"]["enabled"] is False + ) + assert json_data["defaults"]["bool"]["bool_inverted_index"]["enabled"] is False + assert ( + json_data["keys"]["price"]["float"]["float_inverted_index"]["enabled"] + is True + ) + assert ( + json_data["keys"]["is_active"]["bool"]["bool_inverted_index"]["enabled"] + is False + ) + + # Deserialize and verify + deserialized = Schema.deserialize_from_json(json_data) + assert deserialized.defaults.float_value.float_inverted_index.enabled is False + assert deserialized.defaults.boolean.bool_inverted_index.enabled is False + assert ( + deserialized.keys["price"].float_value.float_inverted_index.enabled is True + ) + assert ( + deserialized.keys["is_active"].boolean.bool_inverted_index.enabled is False + ) + + def test_space_inference_from_embedding_function(self) -> None: + """Test that space is correctly inferred from embedding function when not explicitly set.""" + # Register the mock embedding function + from chromadb.utils.embedding_functions import known_embedding_functions + + known_embedding_functions["mock_embedding"] = MockEmbeddingFunction + + try: + schema = Schema() + + # Create vector config with EF but WITHOUT explicit space + # MockEmbeddingFunction has default_space() = "cosine" + custom_ef = MockEmbeddingFunction(model_name="space_inference_test") + vector_config = VectorIndexConfig( + embedding_function=custom_ef + # Note: space is NOT specified, should be inferred from EF + ) + schema.create_index(config=vector_config) + + # Serialize to JSON + json_data = schema.serialize_to_json() + + # Verify that space was inferred and set to "cosine" in serialized JSON + defaults_vector = json_data["defaults"]["float_list"]["vector_index"] + assert defaults_vector["config"]["space"] == "cosine" # Inferred from EF + + # Verify #embedding key also has inferred space + embedding_vector = json_data["keys"]["#embedding"]["float_list"][ + "vector_index" + ] + assert embedding_vector["config"]["space"] == "cosine" # Inferred from EF + + # Deserialize and verify space is preserved + deserialized = Schema.deserialize_from_json(json_data) + assert deserialized.defaults.float_list is not None + assert deserialized.defaults.float_list.vector_index is not None + assert ( + deserialized.defaults.float_list.vector_index.config.space == "cosine" + ) + + assert deserialized.keys["#embedding"].float_list is not None + assert deserialized.keys["#embedding"].float_list.vector_index is not None + assert ( + deserialized.keys["#embedding"].float_list.vector_index.config.space + == "cosine" + ) + + finally: + # Clean up + if "mock_embedding" in known_embedding_functions: + del known_embedding_functions["mock_embedding"] + + def test_explicit_space_overrides_embedding_function_default(self) -> None: + """Test that explicit space parameter overrides the embedding function's default space.""" + # Register the mock embedding function + from chromadb.utils.embedding_functions import known_embedding_functions + + known_embedding_functions["mock_embedding"] = MockEmbeddingFunction + + try: + schema = Schema() + + # Create vector config with EF and EXPLICIT space that differs from EF default + # MockEmbeddingFunction has default_space() = "cosine" + # But we explicitly set space = "l2" + custom_ef = MockEmbeddingFunction(model_name="override_test") + vector_config = VectorIndexConfig( + embedding_function=custom_ef, + space="l2", # Explicitly override the EF's default + ) + schema.create_index(config=vector_config) + + # Serialize to JSON + json_data = schema.serialize_to_json() + + # Verify that explicit space overrode the EF default + defaults_vector = json_data["defaults"]["float_list"]["vector_index"] + assert ( + defaults_vector["config"]["space"] == "l2" + ) # User-specified, not "cosine" + + embedding_vector = json_data["keys"]["#embedding"]["float_list"][ + "vector_index" + ] + assert ( + embedding_vector["config"]["space"] == "l2" + ) # User-specified, not "cosine" + + # Deserialize and verify explicit space is preserved + deserialized = Schema.deserialize_from_json(json_data) + assert deserialized.defaults.float_list is not None + assert deserialized.defaults.float_list.vector_index is not None + assert deserialized.defaults.float_list.vector_index.config.space == "l2" + + assert deserialized.keys["#embedding"].float_list is not None + assert deserialized.keys["#embedding"].float_list.vector_index is not None + assert ( + deserialized.keys["#embedding"].float_list.vector_index.config.space + == "l2" + ) + + finally: + # Clean up + if "mock_embedding" in known_embedding_functions: + del known_embedding_functions["mock_embedding"] + + def test_space_inference_with_no_embedding_function(self) -> None: + """Test space handling when no embedding function is provided (legacy mode).""" + schema = Schema() + + # Create vector config with explicit space but NO embedding function (legacy) + vector_config = VectorIndexConfig( + embedding_function=None, + space="ip", # Must be explicit since no EF to infer from + ) + schema.create_index(config=vector_config) + + # Serialize to JSON + json_data = schema.serialize_to_json() + + # Verify space is correctly set + defaults_vector = json_data["defaults"]["float_list"]["vector_index"] + assert defaults_vector["config"]["space"] == "ip" + assert defaults_vector["config"]["embedding_function"]["type"] == "legacy" + + embedding_vector = json_data["keys"]["#embedding"]["float_list"]["vector_index"] + assert embedding_vector["config"]["space"] == "ip" + assert embedding_vector["config"]["embedding_function"]["type"] == "legacy" + + # Deserialize and verify + deserialized = Schema.deserialize_from_json(json_data) + assert deserialized.defaults.float_list is not None + assert deserialized.defaults.float_list.vector_index is not None + assert deserialized.defaults.float_list.vector_index.config.space == "ip" + assert ( + deserialized.defaults.float_list.vector_index.config.embedding_function + is None + ) + + def test_space_inference_multiple_roundtrips(self) -> None: + """Test that inferred space remains stable across multiple serialization roundtrips.""" + # Register the mock embedding function + from chromadb.utils.embedding_functions import known_embedding_functions + + known_embedding_functions["mock_embedding"] = MockEmbeddingFunction + + try: + # Create schema with inferred space (no explicit space) + original = Schema() + custom_ef = MockEmbeddingFunction(model_name="roundtrip_space_test") + vector_config = VectorIndexConfig( + embedding_function=custom_ef + ) # No explicit space + original.create_index(config=vector_config) + + # First roundtrip + json1 = original.serialize_to_json() + assert ( + json1["defaults"]["float_list"]["vector_index"]["config"]["space"] + == "cosine" + ) + schema1 = Schema.deserialize_from_json(json1) + + # Second roundtrip + json2 = schema1.serialize_to_json() + assert ( + json2["defaults"]["float_list"]["vector_index"]["config"]["space"] + == "cosine" + ) + schema2 = Schema.deserialize_from_json(json2) + + # Third roundtrip + json3 = schema2.serialize_to_json() + assert ( + json3["defaults"]["float_list"]["vector_index"]["config"]["space"] + == "cosine" + ) + + # Verify all schemas have the inferred space + for schema in [schema1, schema2]: + assert schema.defaults.float_list is not None + assert schema.defaults.float_list.vector_index is not None + assert schema.defaults.float_list.vector_index.config.space == "cosine" + + finally: + # Clean up + if "mock_embedding" in known_embedding_functions: + del known_embedding_functions["mock_embedding"] + + def test_keys_have_independent_configs(self) -> None: + """Test that each key override has its own independent config (no inheritance from defaults).""" + schema = Schema() + + # Enable sparse vector on a key - it gets exactly what we specify + sparse_config = SparseVectorIndexConfig( + source_key="default_source", + embedding_function=MockSparseEmbeddingFunction(), + ) + schema.create_index(config=sparse_config, key="field1") + + # Verify field1 has the sparse vector with the specified source_key + assert "field1" in schema.keys + field1 = schema.keys["field1"] + assert field1.sparse_vector is not None + assert field1.sparse_vector.sparse_vector_index is not None + assert field1.sparse_vector.sparse_vector_index.enabled is True + assert ( + field1.sparse_vector.sparse_vector_index.config.source_key + == "default_source" + ) + + # Now create another key with a DIFFERENT config (use string_inverted_index instead) + string_config = StringInvertedIndexConfig() + schema.create_index(config=string_config, key="field2") + + # Verify field2 has its own config + assert "field2" in schema.keys + field2 = schema.keys["field2"] + assert field2.string is not None + assert field2.string.string_inverted_index is not None + assert field2.string.string_inverted_index.enabled is True + + # Verify field1 is unchanged + assert ( + field1.sparse_vector.sparse_vector_index.config.source_key + == "default_source" + ) + + def test_global_default_changes_dont_affect_existing_overrides(self) -> None: + """Test that changes to global defaults don't affect already-created key overrides.""" + # Register the mock embedding function + from chromadb.utils.embedding_functions import known_embedding_functions + + known_embedding_functions["mock_embedding"] = MockEmbeddingFunction + + try: + schema = Schema() + + # Create initial vector config with HNSW + ef1 = MockEmbeddingFunction(model_name="initial_model") + hnsw1 = HnswIndexConfig(ef_construction=100, max_neighbors=16) + vector_config1 = VectorIndexConfig( + embedding_function=ef1, space="cosine", hnsw=hnsw1 + ) + schema.create_index(config=vector_config1) + + # Capture the initial state of #embedding + initial_embedding_hnsw = schema.keys[ + "#embedding" + ].float_list.vector_index.config.hnsw # type: ignore[union-attr] + assert initial_embedding_hnsw is not None + assert initial_embedding_hnsw.ef_construction == 100 + assert initial_embedding_hnsw.max_neighbors == 16 + + # Now change the global vector config to different values + ef2 = MockEmbeddingFunction(model_name="updated_model") + hnsw2 = HnswIndexConfig(ef_construction=200, max_neighbors=32) + vector_config2 = VectorIndexConfig( + embedding_function=ef2, space="l2", hnsw=hnsw2 + ) + schema.create_index(config=vector_config2) + + # Verify global defaults changed + assert schema.defaults.float_list is not None + assert schema.defaults.float_list.vector_index is not None + assert schema.defaults.float_list.vector_index.config.space == "l2" + assert schema.defaults.float_list.vector_index.config.hnsw is not None + assert ( + schema.defaults.float_list.vector_index.config.hnsw.ef_construction + == 200 + ) + assert ( + schema.defaults.float_list.vector_index.config.hnsw.max_neighbors == 32 + ) + + # Verify #embedding was also updated (since it's the target of vector config) + assert schema.keys["#embedding"].float_list is not None + assert schema.keys["#embedding"].float_list.vector_index is not None + updated_embedding_hnsw = schema.keys[ + "#embedding" + ].float_list.vector_index.config.hnsw + assert updated_embedding_hnsw is not None + assert updated_embedding_hnsw.ef_construction == 200 + assert updated_embedding_hnsw.max_neighbors == 32 + assert ( + schema.keys["#embedding"].float_list.vector_index.config.space == "l2" + ) + + finally: + # Clean up + if "mock_embedding" in known_embedding_functions: + del known_embedding_functions["mock_embedding"] + + def test_key_specific_overrides_are_independent(self) -> None: + """Test that modifying one key's overrides doesn't affect other keys.""" + schema = Schema() + + # Create sparse vector on one key and string indexes on others + schema.create_index( + config=SparseVectorIndexConfig( + source_key="source_a", embedding_function=MockSparseEmbeddingFunction() + ), + key="key_a", + ) + schema.create_index(config=StringInvertedIndexConfig(), key="key_b") + schema.create_index(config=StringInvertedIndexConfig(), key="key_c") + + # Verify each key has its own config + assert ( + schema.keys["key_a"].sparse_vector.sparse_vector_index.config.source_key + == "source_a" + ) # type: ignore[union-attr] + assert schema.keys["key_b"].string.string_inverted_index.enabled is True # type: ignore[union-attr] + assert schema.keys["key_c"].string.string_inverted_index.enabled is True # type: ignore[union-attr] + + # Now disable string inverted index on key_b + schema.delete_index(config=StringInvertedIndexConfig(), key="key_b") + + # Verify key_b is disabled + assert schema.keys["key_b"].string.string_inverted_index.enabled is False # type: ignore[union-attr] + + # Verify key_a and key_c are unaffected + key_a = schema.keys["key_a"] + assert key_a.sparse_vector is not None + assert key_a.sparse_vector.sparse_vector_index is not None + assert key_a.sparse_vector.sparse_vector_index.enabled is True + assert key_a.sparse_vector.sparse_vector_index.config.source_key == "source_a" + + key_c = schema.keys["key_c"] + assert key_c.string is not None + assert key_c.string.string_inverted_index is not None + assert key_c.string.string_inverted_index.enabled is True + + # Serialize and deserialize to ensure independence is preserved + json_data = schema.serialize_to_json() + deserialized = Schema.deserialize_from_json(json_data) + + # Verify after roundtrip + assert ( + deserialized.keys[ + "key_a" + ].sparse_vector.sparse_vector_index.config.source_key + == "source_a" + ) + assert deserialized.keys["key_b"].string.string_inverted_index.enabled is False + assert deserialized.keys["key_c"].string.string_inverted_index.enabled is True + + def test_global_default_disable_then_key_enable(self) -> None: + """Test disabling an index globally, then enabling it on specific keys.""" + schema = Schema() + + # Verify string_inverted_index is enabled by default + assert schema.defaults.string is not None + assert schema.defaults.string.string_inverted_index is not None + assert schema.defaults.string.string_inverted_index.enabled is True + + # Disable string_inverted_index globally + schema.delete_index(config=StringInvertedIndexConfig()) + assert schema.defaults.string.string_inverted_index.enabled is False + + # Now enable it on specific keys + schema.create_index(config=StringInvertedIndexConfig(), key="important_field") + schema.create_index(config=StringInvertedIndexConfig(), key="searchable_field") + + # Verify global default is still disabled + assert schema.defaults.string.string_inverted_index.enabled is False + + # Verify specific keys have it enabled + important = schema.keys["important_field"] + assert important.string is not None + assert important.string.string_inverted_index is not None + assert important.string.string_inverted_index.enabled is True + + searchable = schema.keys["searchable_field"] + assert searchable.string is not None + assert searchable.string.string_inverted_index is not None + assert searchable.string.string_inverted_index.enabled is True + + # Verify other keys would inherit the disabled global default + # (by checking serialization - keys without overrides shouldn't appear) + json_data = schema.serialize_to_json() + + # Only our explicitly modified keys + defaults (#document, #embedding) should be in overrides + assert "important_field" in json_data["keys"] + assert "searchable_field" in json_data["keys"] + assert "#document" in json_data["keys"] + assert "#embedding" in json_data["keys"] + + # A hypothetical "other_field" would NOT be in overrides (uses global default) + assert "other_field" not in json_data["keys"] + + def test_partial_override_fills_from_defaults(self) -> None: + """Test that when you override one aspect of a value type, other indexes still follow defaults.""" + schema = Schema() + + # Enable sparse vector on a key + schema.create_index( + config=SparseVectorIndexConfig( + source_key="my_source", embedding_function=MockSparseEmbeddingFunction() + ), + key="multi_index_field", + ) + + # This key now has sparse_vector overridden, but string, int, etc. should still follow global defaults + field = schema.keys["multi_index_field"] + + # Sparse vector is explicitly set + assert field.sparse_vector is not None + assert field.sparse_vector.sparse_vector_index is not None + assert field.sparse_vector.sparse_vector_index.enabled is True + + # Other value types are None (will fall back to global defaults) + assert field.string is None + assert field.int_value is None + assert field.float_value is None + assert field.boolean is None + assert field.float_list is None + + # Serialize to verify sparse override behavior + json_data = schema.serialize_to_json() + field_json = json_data["keys"]["multi_index_field"] + + # Only sparse_vector should be in the JSON for this key + assert "sparse_vector" in field_json + assert "string" not in field_json # Falls back to global + assert "int" not in field_json + assert "float" not in field_json + assert "bool" not in field_json + assert "float_list" not in field_json + + # Deserialize and verify + deserialized = Schema.deserialize_from_json(json_data) + des_field = deserialized.keys["multi_index_field"] + + # Sparse vector is set + assert des_field.sparse_vector is not None + assert des_field.sparse_vector.sparse_vector_index is not None + assert des_field.sparse_vector.sparse_vector_index.enabled is True + + # Others are None (sparse override) + assert des_field.string is None + assert des_field.int_value is None + + def test_cmek_basic_creation(self) -> None: + """Test basic CMEK creation and validation.""" + # Test GCP CMEK creation + cmek = Cmek.gcp( + "projects/test-project/locations/us-central1/keyRings/test-ring/cryptoKeys/test-key" + ) + assert cmek.provider == CmekProvider.GCP + assert ( + cmek.resource + == "projects/test-project/locations/us-central1/keyRings/test-ring/cryptoKeys/test-key" + ) + + # Test valid pattern + assert cmek.validate_pattern() is True + + # Test invalid pattern + invalid_cmek = Cmek.gcp("invalid-format") + assert invalid_cmek.validate_pattern() is False + + def test_cmek_serialization(self) -> None: + """Test CMEK serialization and deserialization.""" + cmek = Cmek.gcp("projects/p/locations/l/keyRings/r/cryptoKeys/k") + + # Serialize - should use snake_case format matching Rust serde + cmek_dict = cmek.to_dict() + assert cmek_dict == {"gcp": "projects/p/locations/l/keyRings/r/cryptoKeys/k"} + assert "gcp" in cmek_dict + assert cmek_dict["gcp"] == "projects/p/locations/l/keyRings/r/cryptoKeys/k" + + # Deserialize + restored = Cmek.from_dict(cmek_dict) + assert restored.provider == CmekProvider.GCP + assert restored.resource == cmek.resource + + def test_cmek_in_schema(self) -> None: + """Test CMEK integration with Schema using set_cmek() method.""" + schema = Schema() + + # Initially no CMEK + assert schema.cmek is None + + # Add CMEK using set_cmek() + cmek = Cmek.gcp("projects/test/locations/us/keyRings/ring/cryptoKeys/key") + result = schema.set_cmek(cmek) + + # Verify method returns self for chaining + assert result is schema + + # Verify CMEK is set + assert schema.cmek is not None + assert schema.cmek.provider == CmekProvider.GCP + assert ( + schema.cmek.resource + == "projects/test/locations/us/keyRings/ring/cryptoKeys/key" + ) + + # Test removing CMEK by passing None + schema.set_cmek(None) + assert schema.cmek is None + + # Test method chaining + cmek2 = Cmek.gcp("projects/p/locations/l/keyRings/r/cryptoKeys/k") + schema2 = Schema().set_cmek(cmek2) + assert schema2.cmek is not None + assert schema2.cmek.resource == "projects/p/locations/l/keyRings/r/cryptoKeys/k" + + def test_cmek_schema_serialization(self) -> None: + """Test Schema serialization with CMEK.""" + cmek = Cmek.gcp("projects/p/locations/l/keyRings/r/cryptoKeys/k") + schema = Schema().set_cmek(cmek) + + # Serialize + json_data = schema.serialize_to_json() + + # Verify CMEK is in JSON with snake_case format + assert "cmek" in json_data + assert json_data["cmek"] == { + "gcp": "projects/p/locations/l/keyRings/r/cryptoKeys/k" + } + assert "gcp" in json_data["cmek"] + assert ( + json_data["cmek"]["gcp"] == "projects/p/locations/l/keyRings/r/cryptoKeys/k" + ) + + # Deserialize + deserialized = Schema.deserialize_from_json(json_data) + assert deserialized.cmek is not None + assert deserialized.cmek.provider == CmekProvider.GCP + assert deserialized.cmek.resource == cmek.resource + + def test_cmek_schema_without_cmek_serialization(self) -> None: + """Test Schema serialization without CMEK (backward compatibility).""" + schema = Schema() + # Don't set CMEK + + # Serialize + json_data = schema.serialize_to_json() + + # CMEK should not be in JSON + assert "cmek" not in json_data + + # Deserialize + deserialized = Schema.deserialize_from_json(json_data) + assert deserialized.cmek is None + + def test_cmek_invalid_deserialization(self) -> None: + """Test that invalid CMEK data raises a warning and sets cmek to None.""" + with pytest.raises( + ValueError, match="Unsupported or missing CMEK provider in data" + ): + Schema.deserialize_from_json({"defaults": {}, "keys": {}, "cmek": {}}) + + with pytest.raises( + ValueError, match="Unsupported or missing CMEK provider in data" + ): + Schema.deserialize_from_json( + { + "defaults": {}, + "keys": {}, + "cmek": {"invalid_provider": "some-resource"}, + } + ) + + +def test_sparse_vector_cannot_be_created_globally() -> None: + """Test that sparse vector index cannot be created globally (without a key).""" + schema = Schema() + sparse_config = SparseVectorIndexConfig() + + # Try to enable sparse vector globally - should fail + with pytest.raises( + ValueError, match="Sparse vector index must be created on a specific key" + ): + schema.create_index(config=sparse_config) + + +def test_sparse_vector_cannot_be_deleted() -> None: + """Test that sparse vector index cannot be deleted (temporarily disallowed).""" + schema = Schema() + sparse_config = SparseVectorIndexConfig() + + # Create sparse vector on a key first + schema.create_index(config=sparse_config, key="my_key") + assert schema.keys["my_key"].sparse_vector is not None + assert schema.keys["my_key"].sparse_vector.sparse_vector_index is not None + assert schema.keys["my_key"].sparse_vector.sparse_vector_index.enabled is True + + # Try to delete it - should fail + with pytest.raises( + ValueError, match="Deleting sparse vector index is not currently supported" + ): + schema.delete_index(config=sparse_config, key="my_key") + + +def test_create_index_accepts_key_type() -> None: + """Test that create_index accepts both str and Key types for the key parameter.""" + schema = Schema() + + # Test with string key + string_config = StringInvertedIndexConfig() + schema.create_index(config=string_config, key="test_field_str") + + # Verify the index was created with string key + assert "test_field_str" in schema.keys + assert schema.keys["test_field_str"].string is not None + assert schema.keys["test_field_str"].string.string_inverted_index is not None + assert schema.keys["test_field_str"].string.string_inverted_index.enabled is True + + # Test with Key type + int_config = IntInvertedIndexConfig() + schema.create_index(config=int_config, key=Key("test_field_key")) + + # Verify the index was created with Key type (should be stored as string internally) + assert "test_field_key" in schema.keys + assert schema.keys["test_field_key"].int_value is not None + assert schema.keys["test_field_key"].int_value.int_inverted_index is not None + assert schema.keys["test_field_key"].int_value.int_inverted_index.enabled is True + + # Test that both approaches produce equivalent results + schema2 = Schema() + schema2.create_index(config=string_config, key="same_field") + + schema3 = Schema() + schema3.create_index(config=string_config, key=Key("same_field")) + + # Both should have the same configuration + assert schema2.keys["same_field"].string is not None + assert schema2.keys["same_field"].string.string_inverted_index is not None + assert schema3.keys["same_field"].string is not None + assert schema3.keys["same_field"].string.string_inverted_index is not None + assert ( + schema2.keys["same_field"].string.string_inverted_index.enabled + == schema3.keys["same_field"].string.string_inverted_index.enabled + ) + + +def test_delete_index_accepts_key_type() -> None: + """Test that delete_index accepts both str and Key types for the key parameter.""" + schema = Schema() + + # First, create some indexes to delete + string_config = StringInvertedIndexConfig() + int_config = IntInvertedIndexConfig() + + # Test delete with string key + schema.delete_index(config=string_config, key="test_field_str") + + # Verify the index was disabled with string key + assert "test_field_str" in schema.keys + assert schema.keys["test_field_str"].string is not None + assert schema.keys["test_field_str"].string.string_inverted_index is not None + assert schema.keys["test_field_str"].string.string_inverted_index.enabled is False + + # Test delete with Key type + schema.delete_index(config=int_config, key=Key("test_field_key")) + + # Verify the index was disabled with Key type (should be stored as string internally) + assert "test_field_key" in schema.keys + assert schema.keys["test_field_key"].int_value is not None + assert schema.keys["test_field_key"].int_value.int_inverted_index is not None + assert schema.keys["test_field_key"].int_value.int_inverted_index.enabled is False + + # Test that both approaches produce equivalent results + schema2 = Schema() + schema2.delete_index(config=string_config, key="same_field") + + schema3 = Schema() + schema3.delete_index(config=string_config, key=Key("same_field")) + + # Both should have the same configuration + assert schema2.keys["same_field"].string is not None + assert schema2.keys["same_field"].string.string_inverted_index is not None + assert schema3.keys["same_field"].string is not None + assert schema3.keys["same_field"].string.string_inverted_index is not None + assert ( + schema2.keys["same_field"].string.string_inverted_index.enabled + == schema3.keys["same_field"].string.string_inverted_index.enabled + ) + + +def test_create_index_rejects_special_keys() -> None: + """Test that create_index rejects special keys like Key.DOCUMENT and Key.EMBEDDING.""" + schema = Schema() + string_config = StringInvertedIndexConfig() + + # Test that Key.DOCUMENT is rejected (first check catches it) + with pytest.raises( + ValueError, match="Cannot create index on special key '#document'" + ): + schema.create_index(config=string_config, key=Key.DOCUMENT) + + # Test that Key.EMBEDDING is rejected (first check catches it) + with pytest.raises( + ValueError, match="Cannot create index on special key '#embedding'" + ): + schema.create_index(config=string_config, key=Key.EMBEDDING) + + # Test that string "#document" is also rejected (for consistency) + with pytest.raises( + ValueError, match="Cannot create index on special key '#document'" + ): + schema.create_index(config=string_config, key="#document") + + # Test that any other key starting with # is rejected (second check) + with pytest.raises(ValueError, match="key cannot begin with '#'"): + schema.create_index(config=string_config, key="#custom_key") + + # Test with Key object for custom special key + with pytest.raises(ValueError, match="key cannot begin with '#'"): + schema.create_index(config=string_config, key=Key("#custom")) + + +def test_delete_index_rejects_special_keys() -> None: + """Test that delete_index rejects special keys like Key.DOCUMENT and Key.EMBEDDING.""" + schema = Schema() + string_config = StringInvertedIndexConfig() + + # Test that Key.DOCUMENT with non-FTS config is rejected + with pytest.raises( + ValueError, match="Cannot delete index on special key '#document'" + ): + schema.delete_index(config=string_config, key=Key.DOCUMENT) + + # Test that Key.EMBEDDING is rejected + with pytest.raises(ValueError, match="Cannot modify #embedding"): + schema.delete_index(config=string_config, key=Key.EMBEDDING) + + # Test that string "#embedding" is also rejected (for consistency) + with pytest.raises(ValueError, match="Cannot modify #embedding"): + schema.delete_index(config=string_config, key="#embedding") + + # Test that any other key starting with # is rejected (second check) + with pytest.raises(ValueError, match="key cannot begin with '#'"): + schema.delete_index(config=string_config, key="#custom_key") + + # Test with Key object for custom special key + with pytest.raises(ValueError, match="key cannot begin with '#'"): + schema.delete_index(config=string_config, key=Key("#custom")) + + +def test_vector_index_config_source_key_accepts_key_type() -> None: + """Test that VectorIndexConfig.source_key accepts both str and Key types.""" + # Test with string + config1 = VectorIndexConfig(source_key="my_field") + assert config1.source_key == "my_field" + assert isinstance(config1.source_key, str) + + # Test with Key object + config2 = VectorIndexConfig(source_key=Key("my_field")) # type: ignore[arg-type] + assert config2.source_key == "my_field" + assert isinstance(config2.source_key, str) + + # Test with Key.DOCUMENT + config3 = VectorIndexConfig(source_key=Key.DOCUMENT) # type: ignore[arg-type] + assert config3.source_key == "#document" + assert isinstance(config3.source_key, str) + + # Test that both approaches produce the same result + config4 = VectorIndexConfig(source_key="test") + config5 = VectorIndexConfig(source_key=Key("test")) # type: ignore[arg-type] + assert config4.source_key == config5.source_key + + # Test with None + config6 = VectorIndexConfig(source_key=None) + assert config6.source_key is None + + # Test serialization works correctly + config7 = VectorIndexConfig(source_key=Key("serialize_test")) # type: ignore[arg-type] + config_dict = config7.model_dump() + assert config_dict["source_key"] == "serialize_test" + assert isinstance(config_dict["source_key"], str) + + +def test_sparse_vector_index_config_source_key_accepts_key_type() -> None: + """Test that SparseVectorIndexConfig.source_key accepts both str and Key types.""" + # Test with string + config1 = SparseVectorIndexConfig(source_key="my_field") + assert config1.source_key == "my_field" + assert isinstance(config1.source_key, str) + + # Test with Key object + config2 = SparseVectorIndexConfig(source_key=Key("my_field")) # type: ignore[arg-type] + assert config2.source_key == "my_field" + assert isinstance(config2.source_key, str) + + # Test with Key.DOCUMENT + config3 = SparseVectorIndexConfig(source_key=Key.DOCUMENT) # type: ignore[arg-type] + assert config3.source_key == "#document" + assert isinstance(config3.source_key, str) + + # Test that both approaches produce the same result + config4 = SparseVectorIndexConfig(source_key="test") + config5 = SparseVectorIndexConfig(source_key=Key("test")) # type: ignore[arg-type] + assert config4.source_key == config5.source_key + + # Test with None + config6 = SparseVectorIndexConfig(source_key=None) + assert config6.source_key is None + + # Test serialization works correctly + config7 = SparseVectorIndexConfig(source_key=Key("serialize_test")) # type: ignore[arg-type] + config_dict = config7.model_dump() + assert config_dict["source_key"] == "serialize_test" + assert isinstance(config_dict["source_key"], str) + + +def test_config_source_key_rejects_invalid_types() -> None: + """Test that config validators reject invalid types for source_key.""" + # Test VectorIndexConfig rejects invalid types + with pytest.raises(ValueError, match="source_key must be str or Key"): + VectorIndexConfig(source_key=123) # type: ignore[arg-type] + + with pytest.raises(ValueError, match="source_key must be str or Key"): + VectorIndexConfig(source_key=["not", "valid"]) # type: ignore[arg-type] + + # Test SparseVectorIndexConfig rejects invalid types + with pytest.raises(ValueError, match="source_key must be str or Key"): + SparseVectorIndexConfig(source_key=123) # type: ignore[arg-type] + + with pytest.raises(ValueError, match="source_key must be str or Key"): + SparseVectorIndexConfig(source_key={"not": "valid"}) # type: ignore[arg-type] + + +def test_config_source_key_validates_special_keys() -> None: + """Test that source_key only allows #document, rejects other special keys.""" + # Test VectorIndexConfig + # #document is allowed (string) + config1 = VectorIndexConfig(source_key="#document") + assert config1.source_key == "#document" + + # #document is allowed (Key) + config2 = VectorIndexConfig(source_key=Key.DOCUMENT) # type: ignore[arg-type] + assert config2.source_key == "#document" + + # #embedding is rejected (string) + with pytest.raises(ValueError, match="source_key cannot begin with '#'"): + VectorIndexConfig(source_key="#embedding") + + # #embedding is rejected (Key) + with pytest.raises(ValueError, match="source_key cannot begin with '#'"): + VectorIndexConfig(source_key=Key.EMBEDDING) # type: ignore[arg-type] + + # #metadata is rejected + with pytest.raises(ValueError, match="source_key cannot begin with '#'"): + VectorIndexConfig(source_key="#metadata") + + # #score is rejected + with pytest.raises(ValueError, match="source_key cannot begin with '#'"): + VectorIndexConfig(source_key="#score") + + # Any other key starting with # is rejected + with pytest.raises(ValueError, match="source_key cannot begin with '#'"): + VectorIndexConfig(source_key="#custom") + + # Regular keys (no #) are allowed + config3 = VectorIndexConfig(source_key="my_field") + assert config3.source_key == "my_field" + + # Test SparseVectorIndexConfig + # #document is allowed (string) + config4 = SparseVectorIndexConfig(source_key="#document") + assert config4.source_key == "#document" + + # #document is allowed (Key) + config5 = SparseVectorIndexConfig(source_key=Key.DOCUMENT) # type: ignore[arg-type] + assert config5.source_key == "#document" + + # #embedding is rejected (string) + with pytest.raises(ValueError, match="source_key cannot begin with '#'"): + SparseVectorIndexConfig(source_key="#embedding") + + # #embedding is rejected (Key) + with pytest.raises(ValueError, match="source_key cannot begin with '#'"): + SparseVectorIndexConfig(source_key=Key.EMBEDDING) # type: ignore[arg-type] + + # #metadata is rejected + with pytest.raises(ValueError, match="source_key cannot begin with '#'"): + SparseVectorIndexConfig(source_key="#metadata") + + # Regular keys (no #) are allowed + config6 = SparseVectorIndexConfig(source_key="my_field") + assert config6.source_key == "my_field" + + +def test_sparse_vector_config_requires_ef_with_source_key() -> None: + """Test that SparseVectorIndexConfig raises ValueError when source_key is provided without embedding_function.""" + schema = Schema() + + # Attempt to create sparse vector index with source_key but no embedding_function + with pytest.raises(ValueError) as exc_info: + schema.create_index( + key="invalid_sparse", + config=SparseVectorIndexConfig( + source_key="text_field", + # No embedding_function provided - should raise ValueError + ), + ) + + # Verify the error message mentions both source_key and embedding_function + error_msg = str(exc_info.value) + assert "source_key" in error_msg.lower() + assert "embedding_function" in error_msg.lower() + + +def test_config_classes_reject_invalid_fields() -> None: + """Test that all config classes reject invalid/unknown fields.""" + # Test SparseVectorIndexConfig rejects invalid field 'key' instead of 'source_key' + with pytest.raises((ValueError, ValidationError)) as exc_info: + SparseVectorIndexConfig(key=Key.DOCUMENT) # type: ignore[call-arg] + + error_msg = str(exc_info.value) + assert "key" in error_msg.lower() + assert ( + "extra" in error_msg.lower() + or "permitted" in error_msg.lower() + or "not a valid field" in error_msg.lower() + ) + + # Test VectorIndexConfig rejects invalid fields + with pytest.raises((ValueError, ValidationError)) as exc_info: + VectorIndexConfig(invalid_field="test") # type: ignore[call-arg] + + error_msg = str(exc_info.value) + assert "invalid_field" in error_msg.lower() + assert "extra" in error_msg.lower() or "permitted" in error_msg.lower() + + # Test FtsIndexConfig rejects invalid fields + with pytest.raises((ValueError, ValidationError)) as exc_info: + FtsIndexConfig(invalid_field="test") # type: ignore[call-arg] + + error_msg = str(exc_info.value) + assert "invalid_field" in error_msg.lower() + assert "extra" in error_msg.lower() or "permitted" in error_msg.lower() + + # Test StringInvertedIndexConfig rejects invalid fields + with pytest.raises((ValueError, ValidationError)) as exc_info: + StringInvertedIndexConfig(invalid_field="test") # type: ignore[call-arg] + + error_msg = str(exc_info.value) + assert "invalid_field" in error_msg.lower() + assert "extra" in error_msg.lower() or "permitted" in error_msg.lower() + + # Test IntInvertedIndexConfig rejects invalid fields + with pytest.raises((ValueError, ValidationError)) as exc_info: + IntInvertedIndexConfig(invalid_field=123) # type: ignore[call-arg] + + error_msg = str(exc_info.value) + assert "invalid_field" in error_msg.lower() + assert "extra" in error_msg.lower() or "permitted" in error_msg.lower() + + # Test FloatInvertedIndexConfig rejects invalid fields + with pytest.raises((ValueError, ValidationError)) as exc_info: + FloatInvertedIndexConfig(invalid_field=1.23) # type: ignore[call-arg] + + error_msg = str(exc_info.value) + assert "invalid_field" in error_msg.lower() + assert "extra" in error_msg.lower() or "permitted" in error_msg.lower() + + # Test BoolInvertedIndexConfig rejects invalid fields + with pytest.raises((ValueError, ValidationError)) as exc_info: + BoolInvertedIndexConfig(invalid_field=True) # type: ignore[call-arg] + + error_msg = str(exc_info.value) + assert "invalid_field" in error_msg.lower() + assert "extra" in error_msg.lower() or "permitted" in error_msg.lower() + + # Test HnswIndexConfig rejects invalid fields + with pytest.raises((ValueError, ValidationError)) as exc_info: + HnswIndexConfig(invalid_field=123) # type: ignore[call-arg] + + error_msg = str(exc_info.value) + assert "invalid_field" in error_msg.lower() + + # Test HnswIndexConfig accepts all valid fields (all are defined in the model) + # This should not raise an error + config = HnswIndexConfig( + ef_construction=100, + max_neighbors=16, + ef_search=100, + num_threads=4, + batch_size=100, + sync_threshold=1000, + resize_factor=1.2, + ) + assert config.ef_construction == 100 + assert config.max_neighbors == 16 + + # Test SpannIndexConfig rejects invalid fields + with pytest.raises((ValueError, ValidationError)) as exc_info: + SpannIndexConfig(invalid_field=123) # type: ignore[call-arg] + + error_msg = str(exc_info.value) + assert "invalid_field" in error_msg.lower() + + # Test SpannIndexConfig accepts internal fields (allowed by validator but not stored) + # These should not raise an error but won't be stored as attributes + spann_config = SpannIndexConfig( + search_nprobe=64, + search_rng_factor=1.0, # type: ignore[call-arg] # internal field - allowed but not stored + search_rng_epsilon=10.0, # type: ignore[call-arg] # internal field - allowed but not stored + nreplica_count=8, # type: ignore[call-arg] # internal field - allowed but not stored + write_nprobe=32, + write_rng_factor=1.0, # type: ignore[call-arg] # internal field - allowed but not stored + write_rng_epsilon=5.0, # type: ignore[call-arg] # internal field - allowed but not stored + split_threshold=50, + num_samples_kmeans=1000, # type: ignore[call-arg] # internal field - allowed but not stored + initial_lambda=100.0, # type: ignore[call-arg] # internal field - allowed but not stored + reassign_neighbor_count=64, + merge_threshold=25, + num_centers_to_merge_to=8, # type: ignore[call-arg] # internal field - allowed but not stored + ef_construction=200, + ef_search=200, + max_neighbors=64, + ) + # Verify defined fields are stored + assert spann_config.search_nprobe == 64 + assert spann_config.write_nprobe == 32 + assert spann_config.ef_construction == 200 + # Verify internal fields are not stored (they're ignored due to "extra": "ignore") + assert not hasattr(spann_config, "search_rng_factor") + assert not hasattr(spann_config, "nreplica_count") + assert not hasattr(spann_config, "num_samples_kmeans") diff --git a/python/user_packages/Python313/site-packages/chromadb/test/api/test_schema_e2e.py b/python/user_packages/Python313/site-packages/chromadb/test/api/test_schema_e2e.py new file mode 100644 index 0000000000000000000000000000000000000000..1dde67b84a71a9f2b9770c4c773c9f15a06ff4de --- /dev/null +++ b/python/user_packages/Python313/site-packages/chromadb/test/api/test_schema_e2e.py @@ -0,0 +1,2843 @@ +from chromadb.api import ClientAPI, ServerAPI +from chromadb.api.types import ( + Schema, + FtsIndexConfig, + SparseVectorIndexConfig, + SparseEmbeddingFunction, + SparseVector, + StringInvertedIndexConfig, + IntInvertedIndexConfig, + FloatInvertedIndexConfig, + BoolInvertedIndexConfig, + VectorIndexConfig, + SpannIndexConfig, + EmbeddingFunction, + Embeddings, +) +from chromadb.execution.expression.operator import Key +from chromadb.test.conftest import ( + ClientFactories, + is_spann_disabled_mode, + skip_if_not_cluster, + skip_reason_spann_disabled, + skip_reason_spann_enabled, +) +from chromadb.test.utils.wait_for_version_increase import ( + get_collection_version, + wait_for_version_increase, +) +from chromadb.utils.embedding_functions import ( + register_embedding_function, + register_sparse_embedding_function, +) +from chromadb.api.models.Collection import Collection +from chromadb.api.models.CollectionCommon import CollectionCommon +from chromadb.errors import InvalidArgumentError +from chromadb.execution.expression import Knn, Search +from chromadb.types import Collection as CollectionModel +from typing import Any, Callable, Dict, List, Mapping, Optional, Tuple, cast +from uuid import uuid4 +import numpy as np +import pytest + + +@register_embedding_function +class SimpleEmbeddingFunction(EmbeddingFunction[List[str]]): + """Simple embedding function with stable configuration for persistence tests.""" + + def __init__(self, dim: int = 4): + self._dim = dim + + def __call__(self, input: List[str]) -> Embeddings: + vector = [float(i) for i in range(self._dim)] + return cast(Embeddings, [vector for _ in input]) + + @staticmethod + def name() -> str: + return "simple_ef" + + def get_config(self) -> Dict[str, Any]: + return {"dim": self._dim} + + @staticmethod + def build_from_config(config: Dict[str, Any]) -> "SimpleEmbeddingFunction": + return SimpleEmbeddingFunction(dim=config["dim"]) + + def default_space(self) -> str: # type: ignore[override] + return "cosine" + + +@register_embedding_function +class RecordingSearchEmbeddingFunction(EmbeddingFunction[List[str]]): + """Embedding function that records inputs for search embedding tests.""" + + def __init__(self, label: str = "default") -> None: + self._label = label + self.call_inputs: List[List[str]] = [] + self.query_inputs: List[List[str]] = [] + + def __call__(self, input: List[str]) -> Embeddings: + self.call_inputs.append(list(input)) + vectors = [[float(len(text)), float(len(text)) + 0.5] for text in input] + return cast(Embeddings, vectors) + + def embed_query(self, input: List[str]) -> Embeddings: + self.query_inputs.append(list(input)) + vectors = [[float(len(text)), float(len(text)) + 1.5] for text in input] + return cast(Embeddings, vectors) + + @staticmethod + def name() -> str: + return "recording_search_ef" + + def get_config(self) -> Dict[str, Any]: + return {"label": self._label} + + @staticmethod + def build_from_config(config: Dict[str, Any]) -> "RecordingSearchEmbeddingFunction": + return RecordingSearchEmbeddingFunction(config.get("label", "default")) + + +def test_schema_vector_config_persistence( + client_factories: "ClientFactories", +) -> None: + """Ensure schema-provided SPANN settings persist across client restarts.""" + + client = client_factories.create_client_from_system() + client.reset() + + collection_name = f"schema_spann_{uuid4().hex}" + + schema = Schema() + schema.create_index( + config=VectorIndexConfig( + space="cosine", + spann=SpannIndexConfig( + search_nprobe=16, + write_nprobe=32, + ef_construction=120, + max_neighbors=24, + ), + ) + ) + + collection = client.get_or_create_collection( + name=collection_name, + schema=schema, + ) + + persisted_schema = collection.schema + assert persisted_schema is not None + + print(persisted_schema.serialize_to_json()) + + embedding_override = persisted_schema.keys["#embedding"].float_list + assert embedding_override is not None + vector_index = embedding_override.vector_index + assert vector_index is not None + assert vector_index.enabled is True + assert vector_index.config is not None + assert vector_index.config.space is not None + assert vector_index.config.space == "cosine" + + client_reloaded = client_factories.create_client_from_system() + reloaded_collection = client_reloaded.get_collection( + name=collection_name, + ) + + reloaded_schema = reloaded_collection.schema + assert reloaded_schema is not None + reloaded_embedding_override = reloaded_schema.keys["#embedding"].float_list + assert reloaded_embedding_override is not None + reloaded_vector_index = reloaded_embedding_override.vector_index + assert reloaded_vector_index is not None + assert reloaded_vector_index.config is not None + assert reloaded_vector_index.config.space is not None + assert reloaded_vector_index.config.space == "cosine" + + +def test_schema_vector_config_persistence_with_ef( + client_factories: "ClientFactories", +) -> None: + """Ensure schema-provided SPANN settings persist across client restarts.""" + + client = client_factories.create_client_from_system() + client.reset() + + collection_name = f"schema_spann_{uuid4().hex}" + + schema = Schema() + embedding_function = SimpleEmbeddingFunction(dim=6) + schema.create_index( + config=VectorIndexConfig( + space="cosine", + embedding_function=embedding_function, + spann=SpannIndexConfig( + search_nprobe=16, + write_nprobe=32, + ef_construction=120, + max_neighbors=24, + ), + ) + ) + + collection = client.get_or_create_collection( + name=collection_name, + schema=schema, + ) + + persisted_schema = collection.schema + assert persisted_schema is not None + + print(persisted_schema.serialize_to_json()) + + embedding_override = persisted_schema.keys["#embedding"].float_list + assert embedding_override is not None + vector_index = embedding_override.vector_index + assert vector_index is not None + assert vector_index.enabled is True + assert vector_index.config is not None + assert vector_index.config.space is not None + assert vector_index.config.space == "cosine" + + if not is_spann_disabled_mode: + assert vector_index.config.spann is not None + spann_config = vector_index.config.spann + assert spann_config.search_nprobe == 16 + assert spann_config.write_nprobe == 32 + assert spann_config.ef_construction == 120 + assert spann_config.max_neighbors == 24 + else: + assert vector_index.config.spann is None + assert vector_index.config.hnsw is not None + hnsw_config = vector_index.config.hnsw + assert hnsw_config.ef_construction == 100 + assert hnsw_config.ef_search == 100 + assert hnsw_config.max_neighbors == 16 + assert hnsw_config.resize_factor == 1.2 + + ef = vector_index.config.embedding_function + assert ef is not None + assert ef.name() == "simple_ef" + assert ef.get_config() == {"dim": 6} + + persisted_json = persisted_schema.serialize_to_json() + if not is_spann_disabled_mode: + spann_json = persisted_json["keys"]["#embedding"]["float_list"]["vector_index"][ + "config" + ]["spann"] + assert spann_json["search_nprobe"] == 16 + assert spann_json["write_nprobe"] == 32 + else: + hnsw_json = persisted_json["keys"]["#embedding"]["float_list"]["vector_index"][ + "config" + ]["hnsw"] + assert hnsw_json["ef_construction"] == 100 + assert hnsw_json["ef_search"] == 100 + assert hnsw_json["max_neighbors"] == 16 + + client_reloaded = client_factories.create_client_from_system() + reloaded_collection = client_reloaded.get_collection( + name=collection_name, + ) + + reloaded_schema = reloaded_collection.schema + assert reloaded_schema is not None + reloaded_embedding_override = reloaded_schema.keys["#embedding"].float_list + assert reloaded_embedding_override is not None + reloaded_vector_index = reloaded_embedding_override.vector_index + assert reloaded_vector_index is not None + assert reloaded_vector_index.config is not None + assert reloaded_vector_index.config.space is not None + assert reloaded_vector_index.config.space == "cosine" + if not is_spann_disabled_mode: + assert reloaded_vector_index.config.spann is not None + assert reloaded_vector_index.config.spann.search_nprobe == 16 + assert reloaded_vector_index.config.spann.write_nprobe == 32 + else: + assert reloaded_vector_index.config.hnsw is not None + assert reloaded_vector_index.config.hnsw.ef_construction == 100 + assert reloaded_vector_index.config.hnsw.ef_search == 100 + assert reloaded_vector_index.config.hnsw.max_neighbors == 16 + assert reloaded_vector_index.config.hnsw.resize_factor == 1.2 + + config = reloaded_collection.configuration + assert config is not None + config_ef = config.get("embedding_function") + assert config_ef is not None + assert config_ef.name() == "simple_ef" + assert config_ef.get_config() == {"dim": 6} + + +@register_sparse_embedding_function +class DeterministicSparseEmbeddingFunction(SparseEmbeddingFunction[List[str]]): + """Sparse embedding function that emits predictable token/value pairs.""" + + def __init__(self, label: str = "det_sparse"): + self._label = label + + def __call__(self, input: List[str]) -> List[SparseVector]: + return [ + SparseVector(indices=[idx], values=[float(len(text) + idx)]) + for idx, text in enumerate(input) + ] + + @staticmethod + def name() -> str: + return "det_sparse" + + def get_config(self) -> Dict[str, Any]: + return {"label": self._label} + + @staticmethod + def build_from_config( + config: Dict[str, Any] + ) -> "DeterministicSparseEmbeddingFunction": + return DeterministicSparseEmbeddingFunction(config.get("label", "det_sparse")) + + +def _create_isolated_collection( + client_factories: "ClientFactories", + schema: Optional[Schema] = None, + embedding_function: Optional[EmbeddingFunction[Any]] = None, +) -> Tuple[Collection, ClientAPI]: + """Provision a new temporary collection and return it with the backing client.""" + client = client_factories.create_client_from_system() + client.reset() + + collection_name = f"schema_e2e_{uuid4().hex}" + if schema is not None: + collection = client.get_or_create_collection( + name=collection_name, + schema=schema, + ) + else: + if embedding_function is not None: + collection = client.get_or_create_collection( + name=collection_name, + embedding_function=embedding_function, + ) + else: + collection = client.get_or_create_collection( + name=collection_name, + ) + + return collection, client + + +def _collect_knn_queries(rank: Any) -> List[Any]: + if rank is None: + return [] + + if isinstance(rank, Knn): + return [rank.query] + + queries: List[Any] = [] + + child_rank = getattr(rank, "rank", None) + if child_rank is not None: + queries.extend(_collect_knn_queries(child_rank)) + + left_rank = getattr(rank, "left", None) + if left_rank is not None: + queries.extend(_collect_knn_queries(left_rank)) + + right_rank = getattr(rank, "right", None) + if right_rank is not None: + queries.extend(_collect_knn_queries(right_rank)) + + ranks = getattr(rank, "ranks", None) + if ranks: + for child in ranks: + queries.extend(_collect_knn_queries(child)) + + return queries + + +def test_schema_defaults_enable_indexed_operations( + client_factories: "ClientFactories", +) -> None: + """Validate default schema indexes support filtering, updates, and embeddings.""" + collection, client = _create_isolated_collection(client_factories) + + schema = collection.schema + assert schema is not None + assert schema.defaults is not None + assert schema.defaults.string is not None + string_index = schema.defaults.string.string_inverted_index + assert string_index is not None + assert string_index.enabled is True + assert schema.defaults.int_value is not None + int_index = schema.defaults.int_value.int_inverted_index + assert int_index is not None + assert int_index.enabled is True + assert schema.defaults.float_value is not None + float_index = schema.defaults.float_value.float_inverted_index + assert float_index is not None + assert float_index.enabled is True + assert schema.defaults.boolean is not None + bool_index = schema.defaults.boolean.bool_inverted_index + assert bool_index is not None + assert bool_index.enabled is True + + document_override = schema.keys["#document"].string + assert document_override is not None + fts_index = document_override.fts_index + assert fts_index is not None + assert fts_index.enabled is True + + embedding_override = schema.keys["#embedding"].float_list + assert embedding_override is not None + vector_index = embedding_override.vector_index + assert vector_index is not None + assert vector_index.enabled is True + + ids = ["doc-1", "doc-2", "doc-3"] + documents = ["alpha", "beta", "gamma"] + metadatas: List[Mapping[str, Any]] = [ + {"category": "news", "rating": 5, "price": 9.5, "is_active": True}, + {"category": "science", "rating": 7, "price": 2.5, "is_active": False}, + {"category": "news", "rating": 3, "price": 5.0, "is_active": True}, + ] + + collection.add(ids=ids, documents=documents, metadatas=metadatas) + + filtered = collection.get(where={"category": "science"}) + assert set(filtered["ids"]) == {"doc-2"} + + numeric_filter = collection.get(where={"rating": 3}) + assert set(numeric_filter["ids"]) == {"doc-3"} + + bool_filter = collection.get(where={"is_active": False}) + assert set(bool_filter["ids"]) == {"doc-2"} + + collection.update(ids=["doc-1"], metadatas=[{"rating": 6, "category": "updates"}]) + rating_after_update = collection.get(where={"rating": 6}) + assert set(rating_after_update["ids"]) == {"doc-1"} + + collection.upsert( + ids=["doc-2"], + documents=["beta-updated"], + metadatas=[{"price": 2.5, "category": "science"}], + ) + + embeddings_payload = collection.get(ids=["doc-1"], include=["embeddings"]) + assert embeddings_payload["embeddings"] is not None + assert len(embeddings_payload["embeddings"]) == 1 + + # Ensure underlying schema persisted across fetches + reloaded = client.get_collection(collection.name) + assert reloaded.schema is not None + if not is_spann_disabled_mode: + assert reloaded.schema.serialize_to_json() == schema.serialize_to_json() + + +def test_get_or_create_and_get_collection_preserve_schema( + client_factories: "ClientFactories", +) -> None: + """Ensure repeated collection lookups reuse the persisted schema definition.""" + base_schema = Schema() + base_schema.create_index( + key="custom_tag", + config=StringInvertedIndexConfig(), + ) + base_schema.create_index( + key="importance", + config=IntInvertedIndexConfig(), + ) + + collection, client = _create_isolated_collection( + client_factories, + schema=base_schema, + ) + + assert collection.schema is not None + initial_schema_json = collection.schema.serialize_to_json() + assert "custom_tag" in initial_schema_json["keys"] + assert "importance" in initial_schema_json["keys"] + + second_reference = client.get_or_create_collection(name=collection.name) + assert second_reference.schema is not None + assert second_reference.schema.serialize_to_json() == initial_schema_json + + fetched = client.get_collection(name=collection.name) + assert fetched.schema is not None + assert fetched.schema.serialize_to_json() == initial_schema_json + + second_reference.add( + ids=["schema-preserve"], + documents=["doc"], + metadatas=[{"custom_tag": "alpha", "importance": 10}], + ) + + stored = fetched.get(where={"custom_tag": "alpha"}) + assert set(stored["ids"]) == {"schema-preserve"} + + +def test_delete_collection_resets_schema_configuration( + client_factories: "ClientFactories", +) -> None: + """Deleting and recreating a collection should drop prior schema overrides.""" + schema = Schema() + schema.create_index( + key="transient_key", + config=StringInvertedIndexConfig(), + ) + + collection, client = _create_isolated_collection( + client_factories, + schema=schema, + ) + + assert collection.schema is not None + assert "transient_key" in collection.schema.keys + + client.delete_collection(name=collection.name) + + recreated = client.create_collection(name=collection.name) + assert recreated.schema is not None + recreated_json = recreated.schema.serialize_to_json() + baseline_json = Schema().serialize_to_json() + assert "transient_key" not in recreated_json["keys"] + assert set(recreated_json["keys"].keys()) == set(baseline_json["keys"].keys()) + + +@pytest.mark.skipif(not is_spann_disabled_mode, reason=skip_reason_spann_enabled) +def test_sparse_vector_not_allowed_locally( + client_factories: "ClientFactories", +) -> None: + """Sparse vector configs are not allowed to be created locally.""" + schema = Schema() + schema.create_index(key="sparse_metadata", config=SparseVectorIndexConfig()) + with pytest.raises( + InvalidArgumentError, match="Sparse vector indexing is not enabled in local" + ): + _create_isolated_collection(client_factories, schema=schema) + + +@pytest.mark.skipif(is_spann_disabled_mode, reason=skip_reason_spann_disabled) +def test_sparse_vector_source_key_and_index_constraints( + client_factories: "ClientFactories", +) -> None: + """Sparse vector configs honor source key embedding and single-index enforcement.""" + sparse_ef = DeterministicSparseEmbeddingFunction(label="source-test") + + schema = Schema() + schema.create_index( + key="sparse_metadata", + config=SparseVectorIndexConfig( + source_key="raw_text", + embedding_function=sparse_ef, + ), + ) + schema.create_index(key="tag_a", config=StringInvertedIndexConfig()) + schema.create_index(key="tag_b", config=StringInvertedIndexConfig()) + + collection, _ = _create_isolated_collection(client_factories, schema=schema) + + assert collection.schema is not None + assert "sparse_metadata" in collection.schema.keys + assert "tag_a" in collection.schema.keys + assert "tag_b" in collection.schema.keys + + collection.add( + ids=["sparse-1"], + documents=["source document"], + metadatas=[{"raw_text": "oranges", "tag_a": "citrus", "tag_b": "fruit"}], + ) + + stored = collection.get(ids=["sparse-1"], include=["metadatas"]) + assert stored["metadatas"] is not None + metadata = stored["metadatas"][0] + assert metadata is not None + assert metadata["tag_a"] == "citrus" + assert metadata["tag_b"] == "fruit" + assert metadata["raw_text"] == "oranges" + assert "sparse_metadata" in metadata + sparse_payload = cast(SparseVector, metadata["sparse_metadata"]) + assert sparse_payload == sparse_ef(["oranges"])[0] + + search_result = collection.search( + Search().rank(Knn(key="sparse_metadata", query=cast(Any, sparse_payload))) + ) + assert len(search_result["ids"]) == 1 + assert "sparse-1" in search_result["ids"][0] + + with pytest.raises(ValueError): + collection.schema.create_index( + key="another_sparse", + config=SparseVectorIndexConfig(source_key="raw_text"), + ) + + string_filter = collection.get(where={"tag_b": "fruit"}) + assert set(string_filter["ids"]) == {"sparse-1"} + + +def test_schema_persistence_with_custom_overrides( + client_factories: "ClientFactories", +) -> None: + """Custom schema overrides persist across new client instances.""" + schema = Schema() + schema.create_index(key="title", config=StringInvertedIndexConfig()) + schema.create_index(key="published_year", config=IntInvertedIndexConfig()) + schema.create_index(key="score", config=FloatInvertedIndexConfig()) + schema.create_index(key="is_featured", config=BoolInvertedIndexConfig()) + + collection, client = _create_isolated_collection( + client_factories, + schema=schema, + ) + + collection.add( + ids=["persist-1"], + documents=["persistent doc"], + metadatas=[ + { + "title": "Schema Persistence", + "published_year": 2024, + "score": 4.5, + "is_featured": True, + } + ], + ) + + assert collection.schema is not None + expected_schema_json = collection.schema.serialize_to_json() + + reloaded_client = client_factories.create_client_from_system() + reloaded_collection = reloaded_client.get_collection(name=collection.name) + assert reloaded_collection.schema is not None + if not is_spann_disabled_mode: + assert reloaded_collection.schema.serialize_to_json() == expected_schema_json + + fetched = reloaded_collection.get(where={"title": "Schema Persistence"}) + assert set(fetched["ids"]) == {"persist-1"} + + +def test_collection_embed_uses_schema_or_collection_embedding_function( + client_factories: "ClientFactories", +) -> None: + """_embed should respect schema-provided and direct embedding functions.""" + + schema_emb_fn = SimpleEmbeddingFunction(dim=5) + schema = Schema().create_index( + config=VectorIndexConfig(embedding_function=schema_emb_fn) + ) + schema_collection, _ = _create_isolated_collection( + client_factories, + schema=schema, + ) + + schema_embeddings = schema_collection._embed(["schema document"]) + assert schema_embeddings is not None + assert np.allclose(schema_embeddings[0], [0.0, 1.0, 2.0, 3.0, 4.0]) + + direct_emb_fn = SimpleEmbeddingFunction(dim=3) + direct_collection, _ = _create_isolated_collection( + client_factories, + embedding_function=direct_emb_fn, + ) + + direct_embeddings = direct_collection._embed(["direct document"]) + assert direct_embeddings is not None + assert np.allclose(direct_embeddings[0], [0.0, 1.0, 2.0]) + + +@pytest.mark.skipif(is_spann_disabled_mode, reason=skip_reason_spann_disabled) +def test_search_embeds_string_knn_queries( + client_factories: "ClientFactories", +) -> None: + """_embed_search_string_queries should embed string KNN queries using collection EF.""" + + embedding_fn = RecordingSearchEmbeddingFunction(label="primary") + collection, _ = _create_isolated_collection( + client_factories, embedding_function=embedding_fn + ) + + search = Search().rank(Knn(query="hello world")) + + print(collection.schema) + + embedded_search = collection._embed_search_string_queries(search) + + assert embedding_fn.query_inputs == [["hello world"]] + assert not embedding_fn.call_inputs + + assert isinstance(search._rank, Knn) + assert search._rank.query == "hello world" + + embedded_rank = embedded_search._rank + assert isinstance(embedded_rank, Knn) + assert embedded_rank.query == [11.0, 12.5] + + +@pytest.mark.skipif(is_spann_disabled_mode, reason=skip_reason_spann_disabled) +def test_search_embeds_string_knn_queries_with_sparse_embedding_function( + client_factories: "ClientFactories", +) -> None: + """_embed_search_string_queries should embed string KNN queries using collection EF.""" + + sparse_ef = DeterministicSparseEmbeddingFunction(label="sparse") + schema = Schema().create_index( + key="sparse_metadata", + config=SparseVectorIndexConfig( + source_key="raw_text", embedding_function=sparse_ef + ), + ) + collection, _ = _create_isolated_collection(client_factories, schema=schema) + + search = Search().rank(Knn(key="sparse_metadata", query="hello world")) + + embedded_search = collection._embed_search_string_queries(search) + + assert isinstance(search._rank, Knn) + assert search._rank.key == "sparse_metadata" + assert search._rank.query == "hello world" + + embedded_rank = embedded_search._rank + assert isinstance(embedded_rank, Knn) + assert embedded_rank.key == "sparse_metadata" + print(embedded_rank.query) + assert embedded_rank.query == SparseVector(indices=[0], values=[11.0]) + + +@pytest.mark.skipif(is_spann_disabled_mode, reason=skip_reason_spann_disabled) +def test_search_embeds_string_queries_in_nested_ranks( + client_factories: "ClientFactories", +) -> None: + """String queries in composite rank trees should all be embedded.""" + + embedding_fn = RecordingSearchEmbeddingFunction(label="nested") + collection, _ = _create_isolated_collection( + client_factories, embedding_function=embedding_fn + ) + + rank_one = (Knn(query="alpha") + Knn(query="beta")).max(Knn(query="gamma")) + rank_two = (Knn(query="delta") / 2).abs() + + searches = [Search().rank(rank_one), Search().rank(rank_two)] + embedded_searches = [collection._embed_search_string_queries(s) for s in searches] + + expected_queries = [["alpha"], ["beta"], ["gamma"], ["delta"]] + assert embedding_fn.query_inputs == expected_queries + + all_queries = [] + for embedded_search in embedded_searches: + all_queries.extend(_collect_knn_queries(embedded_search._rank)) + + assert all_queries + assert all(not isinstance(query, str) for query in all_queries) + assert all(isinstance(query, list) for query in all_queries) + + +def test_schema_delete_index_and_restore( + client_factories: "ClientFactories", +) -> None: + """Toggling inverted index enablement reflects in query behavior.""" + disabled_defaults = Schema().delete_index(config=StringInvertedIndexConfig()) + collection, client = _create_isolated_collection( + client_factories, + schema=disabled_defaults, + ) + + collection.add( + ids=["no-index"], + documents=["doc"], + metadatas=[{"global_field": "value"}], + ) + + with pytest.raises(Exception): + collection.get(where={"global_field": "value"}) + + client.delete_collection(name=collection.name) + + disabled_key_schema = ( + Schema() + .create_index(config=StringInvertedIndexConfig()) + .delete_index(key="category", config=StringInvertedIndexConfig()) + ) + recreated = client.get_or_create_collection( + name=collection.name, schema=disabled_key_schema + ) + recreated.add( + ids=["key-disabled"], + documents=["doc"], + metadatas=[{"category": "news"}], + ) + + with pytest.raises(Exception): + recreated.get(where={"category": "news"}) + + client.delete_collection(name=collection.name) + + restored_schema = Schema().create_index( + key="category", config=StringInvertedIndexConfig() + ) + restored = client.get_or_create_collection( + name=collection.name, schema=restored_schema + ) + restored.add( + ids=["key-enabled"], + documents=["doc"], + metadatas=[{"category": "news"}], + ) + + search = restored.get(where={"category": "news"}) + assert set(search["ids"]) == {"key-enabled"} + + +def test_disabled_metadata_index_filters_raise_invalid_argument_all_modes( + client_factories: "ClientFactories", +) -> None: + """Disabled metadata inverted index should block filter-based operations in get, query, and delete for local, single node, and distributed.""" + schema = Schema().delete_index( + key="restricted_tag", config=StringInvertedIndexConfig() + ) + collection, _ = _create_isolated_collection(client_factories, schema=schema) + + collection.add( + ids=["restricted-doc"], + embeddings=cast(Embeddings, [[0.1, 0.2, 0.3, 0.4]]), + metadatas=[{"restricted_tag": "blocked"}], + documents=["doc"], + ) + + assert collection.schema is not None + schema_entry = collection.schema.keys["restricted_tag"].string + assert schema_entry is not None + index_config = schema_entry.string_inverted_index + assert index_config is not None + assert index_config.enabled is False + + filter_payload: Dict[str, Any] = {"restricted_tag": "blocked"} + + def _expect_disabled_error(operation: Callable[[], Any]) -> None: + with pytest.raises(InvalidArgumentError) as exc_info: + operation() + assert "Cannot filter using metadata key 'restricted_tag'" in str( + exc_info.value + ) + + operations: List[Callable[[], Any]] = [ + lambda: collection.get(where=filter_payload), + lambda: collection.query( + query_embeddings=cast(Embeddings, [[0.1, 0.2, 0.3, 0.4]]), + n_results=1, + where=filter_payload, + ), + lambda: collection.delete(where=filter_payload), + ] + + for operation in operations: + _expect_disabled_error(operation) + + +@pytest.mark.skipif(is_spann_disabled_mode, reason=skip_reason_spann_disabled) +def test_disabled_metadata_index_filters_raise_invalid_argument( + client_factories: "ClientFactories", +) -> None: + """Disabled metadata inverted index should block filter-based operations.""" + schema = Schema().delete_index( + key="restricted_tag", config=StringInvertedIndexConfig() + ) + collection, _ = _create_isolated_collection(client_factories, schema=schema) + + collection.add( + ids=["restricted-doc"], + embeddings=cast(Embeddings, [[0.1, 0.2, 0.3, 0.4]]), + metadatas=[{"restricted_tag": "blocked"}], + documents=["doc"], + ) + + assert collection.schema is not None + schema_entry = collection.schema.keys["restricted_tag"].string + assert schema_entry is not None + index_config = schema_entry.string_inverted_index + assert index_config is not None + assert index_config.enabled is False + + filter_payload: Dict[str, Any] = {"restricted_tag": "blocked"} + search_request = Search(where=filter_payload) + + def _expect_disabled_error(operation: Callable[[], Any]) -> None: + with pytest.raises(InvalidArgumentError) as exc_info: + operation() + assert "Cannot filter using metadata key 'restricted_tag'" in str( + exc_info.value + ) + + operations: List[Callable[[], Any]] = [ + lambda: collection.get(where=filter_payload), + lambda: collection.query( + query_embeddings=cast(Embeddings, [[0.1, 0.2, 0.3, 0.4]]), + n_results=1, + where=filter_payload, + ), + lambda: collection.search(search_request), + lambda: collection.delete(where=filter_payload), + ] + + for operation in operations: + _expect_disabled_error(operation) + + +def test_schema_discovers_new_keys_after_compaction( + client_factories: "ClientFactories", +) -> None: + """Compaction promotes unseen metadata keys into discoverable schema entries.""" + collection, client = _create_isolated_collection(client_factories) + + initial_version = get_collection_version(client, collection.name) + + batch_size = 251 + ids = [f"discover-add-{i}" for i in range(batch_size)] + documents = [f"doc {i}" for i in range(batch_size)] + metadatas: List[Mapping[str, Any]] = [ + {"discover_add": f"topic_{i}"} for i in range(batch_size) + ] + + collection.add(ids=ids, documents=documents, metadatas=metadatas) + + if not is_spann_disabled_mode: + wait_for_version_increase(client, collection.name, initial_version) + + reloaded = client.get_collection(collection.name) + assert reloaded.schema is not None + assert "discover_add" in reloaded.schema.keys + discover_add_config = reloaded.schema.keys["discover_add"].string + assert discover_add_config is not None + string_inverted_index = discover_add_config.string_inverted_index + assert string_inverted_index is not None + assert string_inverted_index.enabled is True + + next_version = get_collection_version(client, collection.name) + + upsert_count = 260 + upsert_ids = [f"discover-upsert-{i}" for i in range(upsert_count)] + upsert_docs = [f"upsert doc {i}" for i in range(upsert_count)] + upsert_metadatas: List[Mapping[str, Any]] = [ + {"discover_upsert": f"topic_{i}"} for i in range(upsert_count) + ] + + collection.upsert( + ids=upsert_ids, + documents=upsert_docs, + metadatas=upsert_metadatas, + ) + + if not is_spann_disabled_mode: + wait_for_version_increase(client, collection.name, next_version) + + post_upsert = client.get_collection(collection.name) + assert post_upsert.schema is not None + assert "discover_upsert" in post_upsert.schema.keys + discover_upsert_config = post_upsert.schema.keys["discover_upsert"].string + assert discover_upsert_config is not None + upsert_inverted_index = discover_upsert_config.string_inverted_index + assert upsert_inverted_index is not None + assert upsert_inverted_index.enabled is True + + result = collection.get(where={"discover_add": "topic_42"}) + assert set(result["ids"]) == {"discover-add-42"} + + result_upsert = collection.get(where={"discover_upsert": "topic_42"}) + assert set(result_upsert["ids"]) == {"discover-upsert-42"} + + reload_client = client_factories.create_client_from_system() + persisted = reload_client.get_collection(collection.name) + assert persisted.schema is not None + assert "discover_add" in persisted.schema.keys + assert "discover_upsert" in persisted.schema.keys + + +def test_schema_rejects_conflicting_discoverable_key_types( + client_factories: "ClientFactories", +) -> None: + """Conflicting value types should not corrupt discoverable schema entries.""" + collection, client = _create_isolated_collection(client_factories) + + initial_version = get_collection_version(client, collection.name) + + ids = [f"conflict-{i}" for i in range(251)] + metadatas: List[Mapping[str, Any]] = [ + {"conflict_key": f"value_{i}"} for i in range(251) + ] + documents = [f"doc {i}" for i in range(251)] + collection.add(ids=ids, documents=documents, metadatas=metadatas) + + if not is_spann_disabled_mode: + wait_for_version_increase(client, collection.name, initial_version) + + collection.upsert( + ids=["conflict-bad"], + documents=["bad doc"], + metadatas=[{"conflict_key": 100}], + ) + + collection.update( + ids=["conflict-0"], + metadatas=[{"conflict_key": 200}], + ) + + schema = client.get_collection(collection.name).schema + assert schema is not None + assert "conflict_key" in schema.keys + conflict_entry = schema.keys["conflict_key"] + if ( + conflict_entry.string is not None + and conflict_entry.string.string_inverted_index is not None + ): + assert conflict_entry.string.string_inverted_index.enabled is True + + fetch = collection.get(where={"conflict_key": "value_10"}) + assert set(fetch["ids"]) == {"conflict-10"} + + conflict_bad_meta = collection.get(ids=["conflict-bad"], include=["metadatas"]) + assert conflict_bad_meta["metadatas"] is not None + bad_metadata = conflict_bad_meta["metadatas"][0] + assert bad_metadata is not None + assert isinstance(bad_metadata["conflict_key"], (int, float)) + + +@skip_if_not_cluster() +@pytest.mark.skipif(is_spann_disabled_mode, reason=skip_reason_spann_disabled) +def test_collection_fork_inherits_and_isolates_schema( + client_factories: "ClientFactories", +) -> None: + """Assert forked collections inherit schema and evolve independently of the parent.""" + schema = Schema() + schema.create_index(key="shared_key", config=StringInvertedIndexConfig()) + + collection, client = _create_isolated_collection( + client_factories, + schema=schema, + ) + + parent_version_before_add = get_collection_version(client, collection.name) + + parent_ids = [f"parent-{i}" for i in range(251)] + parent_docs = [f"parent doc {i}" for i in range(251)] + parent_metadatas: List[Mapping[str, Any]] = [ + {"shared_key": f"parent_{i}"} for i in range(251) + ] + + collection.add( + ids=parent_ids, + documents=parent_docs, + metadatas=parent_metadatas, + ) + + # Wait for parent to compact before forking. Otherwise, the fork inherits + # uncompacted logs, and compaction of those inherited logs could increment + # the fork's version before the fork's own data is compacted. + wait_for_version_increase(client, collection.name, parent_version_before_add) + + assert collection.schema is not None + parent_schema_json = collection.schema.serialize_to_json() + + fork_name = f"{collection.name}_fork" + forked = collection.fork(fork_name) + + assert forked.schema is not None + assert forked.schema.serialize_to_json() == parent_schema_json + + fork_version = get_collection_version(client, forked.name) + + fork_ids = [f"fork-{i}" for i in range(251)] + fork_docs = [f"fork doc {i}" for i in range(251)] + fork_metadatas: List[Mapping[str, Any]] = [ + {"shared_key": "parent", "child_only": f"value_{i}"} for i in range(251) + ] + forked.upsert(ids=fork_ids, documents=fork_docs, metadatas=fork_metadatas) + + wait_for_version_increase(client, forked.name, fork_version) + + updated_child = client.get_collection(forked.name) + assert updated_child.schema is not None + assert "child_only" in updated_child.schema.keys + child_only_config = updated_child.schema.keys["child_only"].string + assert child_only_config is not None + child_inverted_index = child_only_config.string_inverted_index + assert child_inverted_index is not None + assert child_inverted_index.enabled is True + + reloaded_parent = client.get_collection(collection.name) + assert reloaded_parent.schema is not None + assert "child_only" not in reloaded_parent.schema.keys + + parent_results = reloaded_parent.get(where={"shared_key": "parent_10"}) + assert set(parent_results["ids"]) == {"parent-10"} + + child_results = forked.get(where={"child_only": "value_10"}) + assert set(child_results["ids"]) == {"fork-10"} + + +@pytest.mark.skipif(is_spann_disabled_mode, reason=skip_reason_spann_disabled) +def test_schema_embedding_configuration_enforced( + client_factories: "ClientFactories", +) -> None: + """Schema-provided embedding functions drive both dense and sparse embeddings.""" + vector_schema = Schema().create_index( + config=VectorIndexConfig(embedding_function=SimpleEmbeddingFunction(dim=5)) + ) + vector_collection, _ = _create_isolated_collection( + client_factories, + schema=vector_schema, + embedding_function=SimpleEmbeddingFunction(dim=5), + ) + + vector_collection.add( + ids=["embed-1"], + documents=["embedding document"], + ) + + embedded = vector_collection.get(ids=["embed-1"], include=["embeddings"]) + assert embedded["embeddings"] is not None + assert np.allclose(embedded["embeddings"][0], [0.0, 1.0, 2.0, 3.0, 4.0]) + + sparse_ef = DeterministicSparseEmbeddingFunction() + sparse_schema = Schema().create_index( + key="sparse_auto", + config=SparseVectorIndexConfig( + source_key="text_to_embed", + embedding_function=sparse_ef, + ), + ) + sparse_collection, _ = _create_isolated_collection( + client_factories, + schema=sparse_schema, + ) + + sparse_collection.add( + ids=["sparse-text"], + documents=["doc"], + metadatas=[{"text_to_embed": "schema embedding"}], + ) + sparse_query = sparse_ef(["schema embedding"])[0] + sparse_result = sparse_collection.get(ids=["sparse-text"], include=["metadatas"]) + assert sparse_result["metadatas"] is not None + sparse_meta = sparse_result["metadatas"][0] + assert sparse_meta is not None + assert "sparse_auto" in sparse_meta + sparse_payload = cast(SparseVector, sparse_meta["sparse_auto"]) + assert sparse_payload == sparse_query + + sparse_search = sparse_collection.search( + Search().rank(Knn(key="sparse_auto", query=cast(Any, sparse_payload))) + ) + assert len(sparse_search["ids"]) == 1 + assert "sparse-text" in sparse_search["ids"][0] + + sparse_collection.add( + ids=["sparse-numeric"], + documents=["doc"], + metadatas=[{"text_to_embed": 5}], + ) + + numeric_meta = sparse_collection.get(ids=["sparse-numeric"], include=["metadatas"]) + assert numeric_meta["metadatas"] is not None + numeric_metadata = numeric_meta["metadatas"][0] + assert numeric_metadata is not None + assert "sparse_auto" not in numeric_metadata + + +def test_schema_precedence_for_overrides_discoverables_and_defaults( + client_factories: "ClientFactories", +) -> None: + """Explicit overrides take precedence over disabled defaults and discoverables.""" + schema = ( + Schema() + .delete_index(config=StringInvertedIndexConfig()) + .create_index(key="explicit_key", config=StringInvertedIndexConfig()) + ) + + collection, client = _create_isolated_collection( + client_factories, + schema=schema, + ) + + ids = [f"precedence-{i}" for i in range(260)] + documents = [f"doc {i}" for i in range(260)] + metadatas: List[Mapping[str, Any]] = [ + {"explicit_key": "explicit", "discover_key": f"discover_{i}"} + for i in range(260) + ] + + initial_version = get_collection_version(client, collection.name) + collection.add(ids=ids, documents=documents, metadatas=metadatas) + + if not is_spann_disabled_mode: + wait_for_version_increase(client, collection.name, initial_version) + + schema_state = client.get_collection(collection.name).schema + assert schema_state is not None + assert "explicit_key" in schema_state.keys + explicit_key_string = schema_state.keys["explicit_key"].string + assert explicit_key_string is not None + explicit_inverted_index = explicit_key_string.string_inverted_index + assert explicit_inverted_index is not None + assert explicit_inverted_index.enabled is True + + assert "discover_key" in schema_state.keys + discover_key_string = schema_state.keys["discover_key"].string + assert discover_key_string is not None + discover_inverted_index = discover_key_string.string_inverted_index + assert discover_inverted_index is not None + assert discover_inverted_index.enabled is False + + explicit_result = collection.get(where={"explicit_key": "explicit"}) + assert set(explicit_result["ids"]) == set(ids) + + with pytest.raises(Exception): + collection.get(where={"discover_key": "discover_5"}) + + +@pytest.mark.skipif(is_spann_disabled_mode, reason=skip_reason_spann_disabled) +def test_sparse_auto_embedding_with_document_source_no_metadata( + client_factories: "ClientFactories", +) -> None: + """Test sparse embedding auto-generation using #document as source with no metadata.""" + sparse_ef = DeterministicSparseEmbeddingFunction(label="doc_no_meta") + + schema = Schema().create_index( + key="auto_sparse", + config=SparseVectorIndexConfig( + source_key="#document", + embedding_function=sparse_ef, + ), + ) + + collection, _ = _create_isolated_collection(client_factories, schema=schema) + + # Add documents without metadata + collection.add( + ids=["doc1", "doc2", "doc3"], + documents=["hello world", "test document", "short"], + ) + + # Verify sparse embeddings were auto-generated in metadata + result = collection.get(ids=["doc1", "doc2", "doc3"], include=["metadatas"]) + assert result["metadatas"] is not None + + # Expected embeddings from batched call (indices will be [0, 1, 2]) + expected_batch = sparse_ef(["hello world", "test document", "short"]) + + for i, doc_id in enumerate(["doc1", "doc2", "doc3"]): + metadata = result["metadatas"][i] + assert metadata is not None + assert "auto_sparse" in metadata + + # Verify the sparse embedding matches expected output from batch + actual = cast(SparseVector, metadata["auto_sparse"]) + assert actual.indices == expected_batch[i].indices + assert actual.values == expected_batch[i].values + + +@pytest.mark.skipif(is_spann_disabled_mode, reason=skip_reason_spann_disabled) +def test_sparse_auto_embedding_with_document_source_and_metadata( + client_factories: "ClientFactories", +) -> None: + """Test sparse embedding with #document source when metadata is also provided.""" + sparse_ef = DeterministicSparseEmbeddingFunction(label="doc_with_meta") + + schema = Schema().create_index( + key="doc_sparse", + config=SparseVectorIndexConfig( + source_key="#document", + embedding_function=sparse_ef, + ), + ) + + collection, _ = _create_isolated_collection(client_factories, schema=schema) + + # Add documents with metadata + collection.add( + ids=["m1", "m2"], + documents=["alpha", "beta"], + metadatas=[ + {"category": "test", "value": 42}, + {"category": "prod", "value": 99}, + ], + ) + + result = collection.get(ids=["m1", "m2"], include=["metadatas"]) + assert result["metadatas"] is not None + + # Verify original metadata is preserved + assert result["metadatas"][0]["category"] == "test" + assert result["metadatas"][0]["value"] == 42 + assert result["metadatas"][1]["category"] == "prod" + assert result["metadatas"][1]["value"] == 99 + + # Verify sparse embeddings were added + assert "doc_sparse" in result["metadatas"][0] + assert "doc_sparse" in result["metadatas"][1] + + # Expected from batch call + expected_batch = sparse_ef(["alpha", "beta"]) + actual_m1 = cast(SparseVector, result["metadatas"][0]["doc_sparse"]) + assert actual_m1.indices == expected_batch[0].indices + + +@pytest.mark.skipif(is_spann_disabled_mode, reason=skip_reason_spann_disabled) +def test_sparse_auto_embedding_with_metadata_source_key( + client_factories: "ClientFactories", +) -> None: + """Test sparse embedding using a metadata field as source.""" + sparse_ef = DeterministicSparseEmbeddingFunction(label="meta_source") + + schema = Schema().create_index( + key="content_sparse", + config=SparseVectorIndexConfig( + source_key="content", + embedding_function=sparse_ef, + ), + ) + + collection, _ = _create_isolated_collection(client_factories, schema=schema) + + # Add with source field in metadata + collection.add( + ids=["s1", "s2", "s3"], + documents=["doc1", "doc2", "doc3"], + metadatas=[ + {"content": "sparse content one"}, + {"content": "sparse content two"}, + {"content": "sparse content three"}, + ], + ) + + result = collection.get(ids=["s1", "s2", "s3"], include=["metadatas"]) + assert result["metadatas"] is not None + + # Expected from batch call + expected_batch = sparse_ef( + ["sparse content one", "sparse content two", "sparse content three"] + ) + + for i in range(3): + metadata = result["metadatas"][i] + assert metadata is not None + assert "content_sparse" in metadata + + # Original content field should still exist + assert "content" in metadata + + # Verify sparse embedding was generated from content field + actual = cast(SparseVector, metadata["content_sparse"]) + assert actual.indices == expected_batch[i].indices + assert actual.values == expected_batch[i].values + + +@pytest.mark.skipif(is_spann_disabled_mode, reason=skip_reason_spann_disabled) +def test_sparse_auto_embedding_with_mixed_metadata_none_and_filled( + client_factories: "ClientFactories", +) -> None: + """Test sparse embedding with mixed metadata (None, empty, filled).""" + sparse_ef = DeterministicSparseEmbeddingFunction(label="mixed_meta") + + schema = Schema().create_index( + key="mixed_sparse", + config=SparseVectorIndexConfig( + source_key="#document", + embedding_function=sparse_ef, + ), + ) + + collection, _ = _create_isolated_collection(client_factories, schema=schema) + + # Add with None metadata items mixed in + collection.add( + ids=["n1", "n2", "n3", "n4"], + documents=["doc one", "doc two", "doc three", "doc four"], + metadatas=[ + None, # type: ignore + None, # type: ignore + {"existing": "data"}, # Filled metadata + None, # type: ignore + ], + ) + + result = collection.get(ids=["n1", "n2", "n3", "n4"], include=["metadatas"]) + assert result["metadatas"] is not None + + # Expected from batch call + expected_batch = sparse_ef(["doc one", "doc two", "doc three", "doc four"]) + + # All should have sparse embeddings added + for i, metadata in enumerate(result["metadatas"]): + assert metadata is not None + assert "mixed_sparse" in metadata + + # Verify correct embedding for each document + actual = cast(SparseVector, metadata["mixed_sparse"]) + assert actual.indices == expected_batch[i].indices + + # Third one should still have existing data + assert result["metadatas"][2]["existing"] == "data" + + +@pytest.mark.skipif(is_spann_disabled_mode, reason=skip_reason_spann_disabled) +def test_sparse_auto_embedding_skips_existing_values( + client_factories: "ClientFactories", +) -> None: + """Test that sparse auto-embedding doesn't overwrite existing values.""" + sparse_ef = DeterministicSparseEmbeddingFunction(label="preserve") + + schema = Schema().create_index( + key="preserve_sparse", + config=SparseVectorIndexConfig( + source_key="#document", + embedding_function=sparse_ef, + ), + ) + + collection, _ = _create_isolated_collection(client_factories, schema=schema) + + # Pre-create a sparse vector + existing_sparse = SparseVector(indices=[999], values=[123.456]) + + collection.add( + ids=["preserve1", "preserve2"], + documents=["auto document", "manual document"], + metadatas=[ + None, # type: ignore + {"preserve_sparse": existing_sparse}, # Should be preserved + ], + ) + + result = collection.get(ids=["preserve1", "preserve2"], include=["metadatas"]) + assert result["metadatas"] is not None + + # First should have auto-generated embedding (only one doc was auto-embedded) + auto_meta = result["metadatas"][0] + assert auto_meta is not None + assert "preserve_sparse" in auto_meta + expected_auto = sparse_ef(["auto document"])[0] # Single item batch + actual_auto = cast(SparseVector, auto_meta["preserve_sparse"]) + assert actual_auto.indices == expected_auto.indices + + # Second should preserve the manually provided one + manual_meta = result["metadatas"][1] + assert manual_meta is not None + actual_manual = cast(SparseVector, manual_meta["preserve_sparse"]) + assert actual_manual.indices == [999] + assert actual_manual.values == [123.456] + + +@pytest.mark.skipif(is_spann_disabled_mode, reason=skip_reason_spann_disabled) +def test_sparse_auto_embedding_with_missing_source_field( + client_factories: "ClientFactories", +) -> None: + """Test sparse embedding when source metadata field is missing or wrong type.""" + sparse_ef = DeterministicSparseEmbeddingFunction(label="missing_field") + + schema = Schema().create_index( + key="field_sparse", + config=SparseVectorIndexConfig( + source_key="text_field", + embedding_function=sparse_ef, + ), + ) + + collection, _ = _create_isolated_collection(client_factories, schema=schema) + + collection.add( + ids=["f1", "f2", "f3", "f4"], + documents=["doc1", "doc2", "doc3", "doc4"], + metadatas=[ + {"text_field": "valid text"}, # Valid string + {"text_field": 123}, # Wrong type (int) + {"other_field": "value"}, # Missing source field + None, # type: ignore + ], + ) + + result = collection.get(ids=["f1", "f2", "f3", "f4"], include=["metadatas"]) + assert result["metadatas"] is not None + + # Only first one should have sparse embedding (single item batch) + assert "field_sparse" in result["metadatas"][0] + expected = sparse_ef(["valid text"])[0] # Single item batch + actual = cast(SparseVector, result["metadatas"][0]["field_sparse"]) + assert actual.indices == expected.indices + + # Others should NOT have sparse embedding + assert "field_sparse" not in result["metadatas"][1] + assert "field_sparse" not in result["metadatas"][2] + assert result["metadatas"][3] is None # No metadata provided, stays None + + +@pytest.mark.skipif(is_spann_disabled_mode, reason=skip_reason_spann_disabled) +def test_sparse_auto_embedding_with_string_inverted_index( + client_factories: "ClientFactories", +) -> None: + """Test sparse auto-embedding works alongside string inverted indexes.""" + sparse_ef = DeterministicSparseEmbeddingFunction(label="with_string_index") + + schema = Schema() + schema.create_index( + key="category", + config=StringInvertedIndexConfig(), + ) + schema.create_index( + key="sparse_field", + config=SparseVectorIndexConfig( + source_key="custom_text", + embedding_function=sparse_ef, + ), + ) + + collection, _ = _create_isolated_collection(client_factories, schema=schema) + + collection.add( + ids=["multi1", "multi2"], + documents=["main document", "another document"], + metadatas=[ + {"custom_text": "field content", "category": "cat1"}, + {"custom_text": "different content", "category": "cat2"}, + ], + ) + + result = collection.get(ids=["multi1", "multi2"], include=["metadatas"]) + assert result["metadatas"] is not None + + # Expected from batch call + expected_batch = sparse_ef(["field content", "different content"]) + + for i, metadata in enumerate(result["metadatas"]): + assert metadata is not None + + # Sparse embedding should be present + assert "sparse_field" in metadata + + # Verify sparse embedding uses custom_text field + actual_field = cast(SparseVector, metadata["sparse_field"]) + assert actual_field.indices == expected_batch[i].indices + + # Category should be searchable + assert "category" in metadata + + # Test filtering with string inverted index + filtered = collection.get(where={"category": "cat1"}) + assert set(filtered["ids"]) == {"multi1"} + + +@pytest.mark.skipif(is_spann_disabled_mode, reason=skip_reason_spann_disabled) +def test_dense_and_sparse_auto_embeddings_together( + client_factories: "ClientFactories", +) -> None: + """Test that dense and sparse auto-embeddings work together.""" + dense_ef = SimpleEmbeddingFunction(dim=4) + sparse_ef = DeterministicSparseEmbeddingFunction(label="with_dense") + + schema = Schema() + schema.create_index(config=VectorIndexConfig(embedding_function=dense_ef)) + schema.create_index( + key="sparse_key", + config=SparseVectorIndexConfig( + source_key="#document", + embedding_function=sparse_ef, + ), + ) + + collection, _ = _create_isolated_collection( + client_factories, + schema=schema, + embedding_function=dense_ef, + ) + + collection.add( + ids=["both1", "both2"], + documents=["combined document", "another doc"], + ) + + result = collection.get( + ids=["both1", "both2"], + include=["embeddings", "metadatas"], + ) + + # Verify dense embeddings + assert result["embeddings"] is not None + assert len(result["embeddings"]) == 2 + assert len(result["embeddings"][0]) == 4 + + # Verify sparse embeddings in metadata + assert result["metadatas"] is not None + for metadata in result["metadatas"]: + assert metadata is not None + assert "sparse_key" in metadata + + +@pytest.mark.skipif(is_spann_disabled_mode, reason=skip_reason_spann_disabled) +def test_sparse_auto_embedding_with_update_and_upsert( + client_factories: "ClientFactories", +) -> None: + """Test sparse auto-embedding with update and upsert operations.""" + sparse_ef = DeterministicSparseEmbeddingFunction(label="update_upsert") + + schema = Schema().create_index( + key="update_sparse", + config=SparseVectorIndexConfig( + source_key="#document", + embedding_function=sparse_ef, + ), + ) + + collection, _ = _create_isolated_collection(client_factories, schema=schema) + + # Initial add + collection.add( + ids=["up1"], + documents=["original doc"], + ) + + # Update with new document + collection.update( + ids=["up1"], + documents=["updated doc"], + ) + + result_update = collection.get(ids=["up1"], include=["metadatas", "documents"]) + assert result_update["metadatas"] is not None + assert result_update["documents"] is not None + assert result_update["documents"][0] == "updated doc" + assert "update_sparse" in result_update["metadatas"][0] + + # Verify sparse embedding matches updated document (single item batch) + expected = sparse_ef(["updated doc"])[0] + actual = cast(SparseVector, result_update["metadatas"][0]["update_sparse"]) + assert actual.indices == expected.indices + + # Upsert new document + collection.upsert( + ids=["up2"], + documents=["upserted doc"], + ) + + result_upsert = collection.get(ids=["up2"], include=["metadatas"]) + assert result_upsert["metadatas"] is not None + assert "update_sparse" in result_upsert["metadatas"][0] + + # Single item batch + expected_upsert = sparse_ef(["upserted doc"])[0] + actual_upsert = cast(SparseVector, result_upsert["metadatas"][0]["update_sparse"]) + assert actual_upsert.indices == expected_upsert.indices + + +@pytest.mark.skipif(is_spann_disabled_mode, reason=skip_reason_spann_disabled) +def test_sparse_auto_embedding_persistence_across_client_reload( + client_factories: "ClientFactories", +) -> None: + """Test that sparse auto-embedding config persists across client reloads.""" + sparse_ef = DeterministicSparseEmbeddingFunction(label="persist_test") + + schema = Schema().create_index( + key="persist_sparse", + config=SparseVectorIndexConfig( + source_key="#document", + embedding_function=sparse_ef, + ), + ) + + collection, client = _create_isolated_collection(client_factories, schema=schema) + collection_name = collection.name + + collection.add( + ids=["persist1"], + documents=["persistent document"], + ) + + # Reload client + reloaded_client = client_factories.create_client_from_system() + reloaded_collection = reloaded_client.get_collection( + name=collection_name, + ) + + # Verify schema persisted + assert reloaded_collection.schema is not None + assert "persist_sparse" in reloaded_collection.schema.keys + + # Add new document with reloaded collection + reloaded_collection.add( + ids=["persist2"], + documents=["new document after reload"], + ) + + # Verify both documents have sparse embeddings + result = reloaded_collection.get( + ids=["persist1", "persist2"], + include=["metadatas"], + ) + assert result["metadatas"] is not None + assert "persist_sparse" in result["metadatas"][0] + assert "persist_sparse" in result["metadatas"][1] + + +@pytest.mark.skipif(is_spann_disabled_mode, reason=skip_reason_spann_disabled) +def test_sparse_auto_embedding_with_batch_operations( + client_factories: "ClientFactories", +) -> None: + """Test sparse auto-embedding with large batch of documents.""" + sparse_ef = DeterministicSparseEmbeddingFunction(label="batch_test") + + schema = Schema().create_index( + key="batch_sparse", + config=SparseVectorIndexConfig( + source_key="#document", + embedding_function=sparse_ef, + ), + ) + + collection, _ = _create_isolated_collection(client_factories, schema=schema) + + # Add large batch + batch_size = 100 + ids = [f"batch-{i}" for i in range(batch_size)] + documents = [f"document number {i}" for i in range(batch_size)] + + collection.add(ids=ids, documents=documents) + + # Verify all have sparse embeddings + result = collection.get(ids=ids[:10], include=["metadatas"]) + assert result["metadatas"] is not None + + # Expected from batch call (batch of 100, we check first 10) + expected_batch = sparse_ef(documents) + + for i, metadata in enumerate(result["metadatas"]): + assert metadata is not None + assert "batch_sparse" in metadata + + actual = cast(SparseVector, metadata["batch_sparse"]) + assert actual.indices == expected_batch[i].indices + + +@pytest.mark.skipif(is_spann_disabled_mode, reason=skip_reason_spann_disabled) +def test_sparse_auto_embedding_with_empty_documents( + client_factories: "ClientFactories", +) -> None: + """Test sparse auto-embedding handles empty/None documents gracefully.""" + sparse_ef = DeterministicSparseEmbeddingFunction(label="empty_test") + + schema = Schema().create_index( + key="empty_sparse", + config=SparseVectorIndexConfig( + source_key="#document", + embedding_function=sparse_ef, + ), + ) + + collection, _ = _create_isolated_collection(client_factories, schema=schema) + + # Add with empty string document + collection.add( + ids=["empty1"], + documents=[""], + ) + + result = collection.get(ids=["empty1"], include=["metadatas"]) + assert result["metadatas"] is not None + + # Should still generate sparse embedding (empty vector) + metadata = result["metadatas"][0] + assert metadata is not None + assert "empty_sparse" in metadata + + +def test_default_embedding_function_when_no_schema_provided( + client_factories: "ClientFactories", +) -> None: + """Verify that when no schema is provided, the collection uses DefaultEmbeddingFunction (not legacy).""" + # Create collection without providing any schema + collection, client = _create_isolated_collection(client_factories) + + # Get the schema from the collection + schema = collection.schema + assert schema is not None + + # Check the embedding key configuration + assert "#embedding" in schema.keys + embedding_override = schema.keys["#embedding"].float_list + assert embedding_override is not None + vector_index = embedding_override.vector_index + assert vector_index is not None + assert vector_index.enabled is True + assert vector_index.config is not None + assert vector_index.config.space is not None + assert vector_index.config.space == "l2" + + # Get the embedding function + ef = vector_index.config.embedding_function + assert ef is not None + + # Verify it's the DefaultEmbeddingFunction, not legacy + assert ef.name() == "default" + + config = collection.configuration + assert config is not None + config_ef = config.get("embedding_function") + assert config_ef is not None + assert config_ef.name() == "default" + + # Serialize the schema to JSON and verify the embedding function type + json_data = schema.serialize_to_json() + embedding_vector = json_data["keys"]["#embedding"]["float_list"]["vector_index"] + ef_config = embedding_vector["config"]["embedding_function"] + + # Should be "known" type with name "default", NOT "legacy" + assert ef_config["type"] == "known" + assert ef_config["name"] == "default" + + # Also verify the defaults have the same embedding function + defaults_vector = json_data["defaults"]["float_list"]["vector_index"] + defaults_ef_config = defaults_vector["config"]["embedding_function"] + assert defaults_ef_config["type"] == "known" + assert defaults_ef_config["name"] == "default" + + # Verify sparse vector has unknown embedding function when not specified + defaults_sparse = json_data["defaults"]["sparse_vector"]["sparse_vector_index"] + assert defaults_sparse is not None + sparse_ef_config = defaults_sparse["config"]["embedding_function"] + assert sparse_ef_config["type"] == "unknown" + + +def test_custom_embedding_function_without_schema( + client_factories: "ClientFactories", +) -> None: + """Verify that custom embedding function is reflected in schema when no schema is provided.""" + client = client_factories.create_client_from_system() + client.reset() + + collection_name = f"custom_ef_no_schema_{uuid4().hex}" + + # Create custom embedding function + custom_ef = SimpleEmbeddingFunction(dim=8) + + # Create collection with embedding function but no schema + client.create_collection( + name=collection_name, + embedding_function=custom_ef, # type: ignore[arg-type] + ) + + # Get the collection back + collection = client.get_collection( + name=collection_name, + embedding_function=custom_ef, # type: ignore[arg-type] + ) + + # Get the schema from the collection + schema = collection.schema + assert schema is not None + + # Check the embedding key configuration + assert "#embedding" in schema.keys + embedding_override = schema.keys["#embedding"].float_list + assert embedding_override is not None + vector_index = embedding_override.vector_index + assert vector_index is not None + assert vector_index.enabled is True + assert vector_index.config is not None + assert vector_index.config.space is not None + assert vector_index.config.space == "cosine" + + # Get the embedding function from schema + ef = vector_index.config.embedding_function + assert ef is not None + + # Verify it's our custom embedding function + assert ef.name() == "simple_ef" + assert ef.get_config() == {"dim": 8} + + # Serialize the schema to JSON and verify + json_data = schema.serialize_to_json() + embedding_vector = json_data["keys"]["#embedding"]["float_list"]["vector_index"] + ef_config = embedding_vector["config"]["embedding_function"] + + # Should be "known" type with name "simple_ef" + assert ef_config["type"] == "known" + assert ef_config["name"] == "simple_ef" + assert ef_config["config"] == {"dim": 8} + + # Also verify the defaults have the same embedding function + defaults_vector = json_data["defaults"]["float_list"]["vector_index"] + defaults_ef_config = defaults_vector["config"]["embedding_function"] + assert defaults_ef_config["type"] == "known" + assert defaults_ef_config["name"] == "simple_ef" + assert defaults_ef_config["config"] == {"dim": 8} + + # Verify the collection actually works with the custom embedding function + collection.add( + ids=["test1"], + documents=["test document"], + ) + + result = collection.get(ids=["test1"], include=["embeddings"]) + assert result["embeddings"] is not None + # Custom EF with dim=8 should produce 8-dimensional vectors + assert len(result["embeddings"][0]) == 8 + + +def test_custom_embedding_function_with_default_schema( + client_factories: "ClientFactories", +) -> None: + """Verify that custom embedding function is reflected in schema when default Schema() is provided.""" + client = client_factories.create_client_from_system() + client.reset() + + collection_name = f"custom_ef_default_schema_{uuid4().hex}" + + # Create custom embedding function + custom_ef = SimpleEmbeddingFunction(dim=8) + + # Create collection with embedding function and explicit default Schema() + client.create_collection( + name=collection_name, + embedding_function=custom_ef, # type: ignore[arg-type] + schema=Schema(), # Explicit default schema + ) + + # Get the collection back + collection = client.get_collection( + name=collection_name, + embedding_function=custom_ef, # type: ignore[arg-type] + ) + + # Get the schema from the collection + schema = collection.schema + assert schema is not None + + # Check the embedding key configuration + assert "#embedding" in schema.keys + embedding_override = schema.keys["#embedding"].float_list + assert embedding_override is not None + vector_index = embedding_override.vector_index + assert vector_index is not None + assert vector_index.enabled is True + assert vector_index.config is not None + assert vector_index.config.space is not None + assert vector_index.config.space == "cosine" + + # Get the embedding function from schema + ef = vector_index.config.embedding_function + assert ef is not None + + # Verify it's our custom embedding function + assert ef.name() == "simple_ef" + assert ef.get_config() == {"dim": 8} + + # Serialize the schema to JSON and verify + json_data = schema.serialize_to_json() + embedding_vector = json_data["keys"]["#embedding"]["float_list"]["vector_index"] + ef_config = embedding_vector["config"]["embedding_function"] + + # Should be "known" type with name "simple_ef" + assert ef_config["type"] == "known" + assert ef_config["name"] == "simple_ef" + assert ef_config["config"] == {"dim": 8} + + # Also verify the defaults have the same embedding function + defaults_vector = json_data["defaults"]["float_list"]["vector_index"] + defaults_ef_config = defaults_vector["config"]["embedding_function"] + assert defaults_ef_config["type"] == "known" + assert defaults_ef_config["name"] == "simple_ef" + assert defaults_ef_config["config"] == {"dim": 8} + + # Verify the collection actually works with the custom embedding function + collection.add( + ids=["test1"], + documents=["test document"], + ) + + result = collection.get(ids=["test1"], include=["embeddings"]) + assert result["embeddings"] is not None + # Custom EF with dim=8 should produce 8-dimensional vectors + assert len(result["embeddings"][0]) == 8 + + +def test_conflicting_embedding_functions_in_schema_and_config_fails( + client_factories: "ClientFactories", +) -> None: + """Verify that setting different custom embedding functions in schema and config fails.""" + client = client_factories.create_client_from_system() + client.reset() + + collection_name = f"conflict_ef_{uuid4().hex}" + + # Create two different custom embedding functions + config_ef = SimpleEmbeddingFunction(dim=4) + schema_ef = SimpleEmbeddingFunction(dim=6) + + # Create a schema with its own custom embedding function + schema = Schema().create_index( + config=VectorIndexConfig(embedding_function=schema_ef) + ) + + # Attempting to create collection with different embedding functions in both + # schema and config should fail + with pytest.raises(Exception) as exc_info: + client.create_collection( + name=collection_name, + embedding_function=config_ef, # type: ignore[arg-type] + schema=schema, + ) + + # Verify the error message indicates the conflict + error_msg = str(exc_info.value) + assert "schema" in error_msg.lower() or "conflict" in error_msg.lower() + + +@pytest.mark.skipif(is_spann_disabled_mode, reason=skip_reason_spann_disabled) +def test_create_index_with_key_type( + client_factories: "ClientFactories", +) -> None: + """Test that create_index accepts both str and Key types.""" + # Create schema using both str and Key types + schema = Schema() + schema.create_index(config=StringInvertedIndexConfig(), key="field_str") + schema.create_index(config=IntInvertedIndexConfig(), key=Key("field_key")) + + collection, _ = _create_isolated_collection(client_factories, schema=schema) + + # Verify both fields are in the schema + assert collection.schema is not None + assert "field_str" in collection.schema.keys + assert "field_key" in collection.schema.keys + + # Verify both indexes work + collection.add( + ids=["key-test-1"], + documents=["test doc"], + metadatas=[{"field_str": "value1", "field_key": 42}], + ) + + # Test string field filter + str_result = collection.get(where={"field_str": "value1"}) + assert set(str_result["ids"]) == {"key-test-1"} + + # Test int field filter + int_result = collection.get(where={"field_key": 42}) + assert set(int_result["ids"]) == {"key-test-1"} + + +@pytest.mark.skipif(is_spann_disabled_mode, reason=skip_reason_spann_disabled) +def test_delete_index_with_key_type( + client_factories: "ClientFactories", +) -> None: + """Test that delete_index accepts both str and Key types.""" + # Disable indexes using both str and Key types + schema = Schema() + schema.delete_index(config=StringInvertedIndexConfig(), key="disabled_str") + schema.delete_index(config=IntInvertedIndexConfig(), key=Key("disabled_key")) + + collection, _ = _create_isolated_collection(client_factories, schema=schema) + + # Verify both fields have disabled indexes + assert collection.schema is not None + assert "disabled_str" in collection.schema.keys + assert "disabled_key" in collection.schema.keys + + # Add data + collection.add( + ids=["disable-test-1"], + documents=["test doc"], + metadatas=[{"disabled_str": "value", "disabled_key": 100}], + ) + + # Verify filtering on disabled fields raises errors + with pytest.raises(Exception): + collection.get(where={"disabled_str": "value"}) + + with pytest.raises(Exception): + collection.get(where={"disabled_key": 100}) + + +@pytest.mark.skipif(is_spann_disabled_mode, reason=skip_reason_spann_disabled) +def test_vector_index_config_with_key_document_source( + client_factories: "ClientFactories", +) -> None: + """Test that VectorIndexConfig source_key accepts Key.DOCUMENT.""" + schema = Schema() + schema.create_index( + config=VectorIndexConfig( + source_key=Key.DOCUMENT, # type: ignore[arg-type] + embedding_function=SimpleEmbeddingFunction(dim=5), + ) + ) + + collection, _ = _create_isolated_collection( + client_factories, + schema=schema, + embedding_function=SimpleEmbeddingFunction(dim=5), + ) + + # Verify source_key was properly converted to "#document" + assert collection.schema is not None + embedding_config = collection.schema.keys["#embedding"].float_list + assert embedding_config is not None + assert embedding_config.vector_index is not None + assert embedding_config.vector_index.config.space is not None + assert embedding_config.vector_index.config.space == "cosine" + assert embedding_config.vector_index.config.source_key == "#document" + + # Add test data + collection.add( + ids=["vec-1", "vec-2", "vec-3"], + documents=["apple fruit", "banana fruit", "car vehicle"], + ) + + # Verify embeddings were generated + result = collection.get(ids=["vec-1"], include=["embeddings"]) + assert result["embeddings"] is not None + assert len(result["embeddings"][0]) == 5 # dim=5 + + # Perform vector search + search_result = collection.search( + Search().rank(Knn(query=[0.0, 1.0, 2.0, 3.0, 4.0], limit=2)) + ) + assert len(search_result["ids"]) > 0 + assert len(search_result["ids"][0]) <= 2 # limit=2 + + +@pytest.mark.skipif(is_spann_disabled_mode, reason=skip_reason_spann_disabled) +def test_sparse_vector_index_config_with_key_types( + client_factories: "ClientFactories", +) -> None: + """Test that SparseVectorIndexConfig source_key accepts both str and Key types.""" + sparse_ef = DeterministicSparseEmbeddingFunction(label="key_types") + + # Test with Key.DOCUMENT + schema1 = Schema().create_index( + key="sparse1", + config=SparseVectorIndexConfig( + source_key=Key.DOCUMENT, # type: ignore[arg-type] + embedding_function=sparse_ef, + ), + ) + + collection1, _ = _create_isolated_collection(client_factories, schema=schema1) + assert collection1.schema is not None + sparse1_config = collection1.schema.keys["sparse1"].sparse_vector + assert sparse1_config is not None + assert sparse1_config.sparse_vector_index is not None + assert sparse1_config.sparse_vector_index.config.source_key == "#document" + + # Add data and verify sparse embeddings were generated from documents + collection1.add( + ids=["s1", "s2", "s3"], + documents=["apple", "banana", "orange"], + ) + + # Verify sparse embeddings in metadata + result1 = collection1.get(ids=["s1"], include=["metadatas"]) + assert result1["metadatas"] is not None + assert "sparse1" in result1["metadatas"][0] + sparse_vec = cast(SparseVector, result1["metadatas"][0]["sparse1"]) + + # Perform sparse vector search + search_result1 = collection1.search( + Search().rank(Knn(key="sparse1", query=cast(Any, sparse_vec), limit=2)) + ) + assert len(search_result1["ids"]) > 0 + assert "s1" in search_result1["ids"][0] # Should find itself + + # Test with Key("field_name") + schema2 = Schema().create_index( + key="sparse2", + config=SparseVectorIndexConfig( + source_key=Key("text_field"), # type: ignore[arg-type] + embedding_function=sparse_ef, + ), + ) + + collection2, _ = _create_isolated_collection(client_factories, schema=schema2) + assert collection2.schema is not None + sparse2_config = collection2.schema.keys["sparse2"].sparse_vector + assert sparse2_config is not None + assert sparse2_config.sparse_vector_index is not None + assert sparse2_config.sparse_vector_index.config.source_key == "text_field" + + # Add data with metadata source field + collection2.add( + ids=["sparse-key-1", "sparse-key-2"], + documents=["doc1", "doc2"], + metadatas=[{"text_field": "content one"}, {"text_field": "content two"}], + ) + + # Verify sparse embeddings were generated from text_field + result2 = collection2.get( + ids=["sparse-key-1", "sparse-key-2"], include=["metadatas"] + ) + assert result2["metadatas"] is not None + assert "sparse2" in result2["metadatas"][0] + assert "sparse2" in result2["metadatas"][1] + + # Get the sparse vector for search + sparse_query = cast(SparseVector, result2["metadatas"][0]["sparse2"]) + + # Perform sparse vector search + search_result2 = collection2.search( + Search().rank(Knn(key="sparse2", query=cast(Any, sparse_query), limit=1)) + ) + assert len(search_result2["ids"]) > 0 + assert "sparse-key-1" in search_result2["ids"][0] # Should find itself + + +def test_schema_rejects_special_key_in_create_index() -> None: + """Test that create_index rejects keys starting with # (except system keys).""" + # Test with string starting with # + schema = Schema() + with pytest.raises(ValueError, match="key cannot begin with '#'"): + schema.create_index(config=StringInvertedIndexConfig(), key="#custom_field") + + # Test with Key object starting with # + with pytest.raises( + ValueError, match="Cannot create index on special key '#embedding'" + ): + schema.create_index(config=StringInvertedIndexConfig(), key=Key.EMBEDDING) + + +def test_schema_rejects_special_key_in_delete_index() -> None: + """Test that delete_index rejects keys starting with # (except system keys).""" + # Test with string starting with # + schema = Schema() + with pytest.raises(ValueError, match="key cannot begin with '#'"): + schema.delete_index(config=StringInvertedIndexConfig(), key="#custom_field") + + # Test with Key object starting with # + with pytest.raises( + ValueError, match="Cannot delete index on special key '#document'" + ): + schema.delete_index(config=StringInvertedIndexConfig(), key=Key.DOCUMENT) + + +def test_schema_rejects_invalid_source_key_in_configs() -> None: + """Test that config validators reject invalid source_key values.""" + # Test VectorIndexConfig rejects non-#document special keys + with pytest.raises(ValueError, match="source_key cannot begin with '#'"): + VectorIndexConfig(source_key="#embedding") + + with pytest.raises(ValueError, match="source_key cannot begin with '#'"): + VectorIndexConfig(source_key=Key.EMBEDDING) # type: ignore[arg-type] + + # Test SparseVectorIndexConfig rejects non-#document special keys + with pytest.raises(ValueError, match="source_key cannot begin with '#'"): + SparseVectorIndexConfig(source_key="#embedding") + + with pytest.raises(ValueError, match="source_key cannot begin with '#'"): + SparseVectorIndexConfig(source_key=Key.EMBEDDING) # type: ignore[arg-type] + + with pytest.raises(ValueError, match="source_key cannot begin with '#'"): + SparseVectorIndexConfig(source_key="#metadata") + + +@pytest.mark.skipif(is_spann_disabled_mode, reason=skip_reason_spann_disabled) +def test_server_validates_schema_with_special_keys( + client_factories: "ClientFactories", +) -> None: + """Test that server-side validation rejects schemas with invalid special keys.""" + client = client_factories.create_client_from_system() + client.reset() + + collection_name = f"server_validate_{uuid4().hex}" + + # Try to create collection with invalid key in schema + # This should be caught server-side by validate_schema() + schema = Schema() + # Bypass client-side validation by directly manipulating schema.keys + from chromadb.api.types import ( + ValueTypes, + StringValueType, + StringInvertedIndexType, + StringInvertedIndexConfig, + ) + + schema.keys["#invalid_key"] = ValueTypes( + string=StringValueType( + string_inverted_index=StringInvertedIndexType( + enabled=True, + config=StringInvertedIndexConfig(), + ) + ) + ) + + # Server should reject this + with pytest.raises(Exception) as exc_info: + client.create_collection(name=collection_name, schema=schema) + + # Verify server caught the invalid key + error_msg = str(exc_info.value) + assert ( + "#" in error_msg or "key" in error_msg.lower() or "invalid" in error_msg.lower() + ) + + +@pytest.mark.skipif(is_spann_disabled_mode, reason=skip_reason_spann_disabled) +def test_server_validates_invalid_source_key_in_sparse_vector_config( + client_factories: "ClientFactories", +) -> None: + """Test that server-side validation rejects invalid source_key in SparseVectorIndexConfig.""" + client = client_factories.create_client_from_system() + client.reset() + + collection_name = f"server_source_key_{uuid4().hex}" + + # Create schema with invalid source_key + # Bypass client-side validation by directly creating the config + from chromadb.api.types import ( + ValueTypes, + SparseVectorValueType, + SparseVectorIndexType, + ) + + schema = Schema() + # Manually construct config with invalid source_key using model_construct to bypass validation + invalid_config = SparseVectorIndexConfig.model_construct( + embedding_function=None, + source_key="#embedding", # Invalid - should be rejected + bm25=None, + ) + + schema.keys["test_sparse"] = ValueTypes( + sparse_vector=SparseVectorValueType( + sparse_vector_index=SparseVectorIndexType( + enabled=True, + config=invalid_config, + ) + ) + ) + + # Server should reject this + with pytest.raises(Exception) as exc_info: + client.create_collection(name=collection_name, schema=schema) + + # Verify server caught the invalid source_key + error_msg = str(exc_info.value) + assert ( + "source_key" in error_msg.lower() + or "#" in error_msg + or "document" in error_msg.lower() + ) + + +@pytest.mark.skipif(is_spann_disabled_mode, reason=skip_reason_spann_disabled) +def test_modify_collection_no_initial_config_creates_default_schema( + client: ClientAPI, +) -> None: + """Test that modifying a collection without initial config/schema creates and updates default schema.""" + collection_name = f"test_modify_no_init_{uuid4()}" + + # Create collection WITHOUT any configuration (uses defaults) + collection = client.create_collection(name=collection_name) + + # Verify default schema was created (SPANN by default in SPANN mode) + schema = collection.schema + assert schema is not None + assert schema.defaults.float_list is not None + assert schema.defaults.float_list.vector_index is not None + # Should have SPANN config by default + assert schema.defaults.float_list.vector_index.config.spann is not None + + # Modify configuration + collection.modify(configuration={"spann": {"search_nprobe": 32}}) + + # Verify schema was updated + updated_schema = collection.schema + assert updated_schema is not None + assert updated_schema.defaults.float_list.vector_index.config.spann.search_nprobe == 32 # type: ignore + assert updated_schema.keys["#embedding"].float_list.vector_index.config.spann.search_nprobe == 32 # type: ignore + + # Re-fetch from server + collection_refreshed = client.get_collection(collection_name) + refreshed_schema = collection_refreshed.schema + assert refreshed_schema is not None + assert refreshed_schema.defaults.float_list.vector_index.config.spann.search_nprobe == 32 # type: ignore + + +@pytest.mark.skipif(not is_spann_disabled_mode, reason="SPANN is disabled") +def test_modify_collection_no_initial_config_creates_default_schema_local( + client: ClientAPI, +) -> None: + """Test that modifying a collection without initial config/schema creates and updates default schema.""" + collection_name = f"test_modify_no_init_{uuid4()}" + + # Create collection WITHOUT any configuration (uses defaults) + collection = client.create_collection(name=collection_name) + + # Verify default schema was created (SPANN by default in SPANN mode) + schema = collection.schema + assert schema is not None + assert schema.defaults.float_list is not None + assert schema.defaults.float_list.vector_index is not None + # Should have SPANN config by default + assert schema.defaults.float_list.vector_index.config.hnsw is not None + + # Modify configuration + collection.modify(configuration={"hnsw": {"ef_search": 100}}) + + # Verify schema was updated + updated_schema = collection.schema + assert updated_schema is not None + assert updated_schema.defaults.float_list.vector_index.config.hnsw.ef_search == 100 # type: ignore + assert updated_schema.keys["#embedding"].float_list.vector_index.config.hnsw.ef_search == 100 # type: ignore + + # Re-fetch from server + collection_refreshed = client.get_collection(collection_name) + refreshed_schema = collection_refreshed.schema + assert refreshed_schema is not None + assert refreshed_schema.defaults.float_list.vector_index.config.hnsw.ef_search == 100 # type: ignore + + +@pytest.mark.skipif(is_spann_disabled_mode, reason=skip_reason_spann_disabled) +def test_modify_collection_with_initial_spann_schema(client: ClientAPI) -> None: + """Test creating collection with SPANN schema within server limits and modifying it.""" + collection_name = f"test_modify_with_schema_{uuid4()}" + + # Create collection with explicit SPANN configuration within limits + collection = client.create_collection( + name=collection_name, + configuration={ + "spann": { + "search_nprobe": 10, # Within limit (max 128) + "ef_search": 50, # Within limit (max 200) + } + }, + ) + + # Verify initial schema has the specified config + schema = collection.schema + assert schema is not None + assert schema.defaults.float_list.vector_index.config.spann is not None # type: ignore + assert schema.defaults.float_list.vector_index.config.spann.search_nprobe == 10 # type: ignore + assert schema.defaults.float_list.vector_index.config.spann.ef_search == 50 # type: ignore + + # Modify to update search_nprobe to a different value within limits + collection.modify(configuration={"spann": {"search_nprobe": 20}}) + + # Verify update + updated_schema = collection.schema + assert updated_schema is not None + assert updated_schema.defaults.float_list.vector_index.config.spann.search_nprobe == 20 # type: ignore + # ef_search should remain unchanged + assert updated_schema.defaults.float_list.vector_index.config.spann.ef_search == 50 # type: ignore + + # Verify both locations updated + assert updated_schema.keys["#embedding"].float_list.vector_index.config.spann.search_nprobe == 20 # type: ignore + assert updated_schema.keys["#embedding"].float_list.vector_index.config.spann.ef_search == 50 # type: ignore + + # Re-fetch and verify + collection_refreshed = client.get_collection(collection_name) + refreshed_schema = collection_refreshed.schema + assert refreshed_schema is not None + assert refreshed_schema.defaults.float_list.vector_index.config.spann.search_nprobe == 20 # type: ignore + assert refreshed_schema.defaults.float_list.vector_index.config.spann.ef_search == 50 # type: ignore + + +@pytest.mark.skipif(is_spann_disabled_mode, reason=skip_reason_spann_disabled) +def test_modify_collection_updates_schema_spann_multiple_fields( + client: ClientAPI, +) -> None: + """Test that modifying multiple SPANN fields updates schema correctly.""" + collection_name = f"test_modify_schema_multi_{uuid4()}" + + # Create collection with SPANN schema + collection = client.create_collection( + name=collection_name, + configuration={"spann": {"search_nprobe": 64, "ef_search": 100}}, + ) + + # Modify multiple fields + collection.modify( + configuration={ + "spann": { + "search_nprobe": 128, + "ef_search": 200, + } + } + ) + + # Verify all updated fields + schema = collection.schema + assert schema is not None + assert schema.defaults.float_list.vector_index.config.spann.search_nprobe == 128 # type: ignore + assert schema.defaults.float_list.vector_index.config.spann.ef_search == 200 # type: ignore + + # Verify other fields were preserved + assert schema.defaults.float_list.vector_index.config.spann.write_nprobe == 32 # type: ignore + + # Verify in both locations + assert schema.keys["#embedding"].float_list.vector_index.config.spann.search_nprobe == 128 # type: ignore + assert schema.keys["#embedding"].float_list.vector_index.config.spann.ef_search == 200 # type: ignore + + # Re-fetch from server + collection_refreshed = client.get_collection(collection_name) + refreshed_schema = collection_refreshed.schema + assert refreshed_schema is not None + assert refreshed_schema.defaults.float_list.vector_index.config.spann.search_nprobe == 128 # type: ignore + assert refreshed_schema.defaults.float_list.vector_index.config.spann.ef_search == 200 # type: ignore + assert refreshed_schema.defaults.float_list.vector_index.config.spann.write_nprobe == 32 # type: ignore + + +@pytest.mark.skipif(is_spann_disabled_mode, reason=skip_reason_spann_disabled) +def test_modify_collection_preserves_other_schema_fields(client: ClientAPI) -> None: + """Test that modifying configuration doesn't affect other schema value types.""" + collection_name = f"test_modify_schema_preserve_{uuid4()}" + + # Create collection with SPANN schema + collection = client.create_collection( + name=collection_name, + configuration={"spann": {"search_nprobe": 64}}, + ) + + # Get initial schema to verify all value types exist + initial_schema = collection.schema + assert initial_schema is not None + assert initial_schema.defaults.string is not None + assert initial_schema.defaults.int_value is not None + assert initial_schema.defaults.float_value is not None + assert initial_schema.defaults.boolean is not None + assert initial_schema.defaults.sparse_vector is not None + assert initial_schema.keys["#document"] is not None + + # Modify SPANN config + collection.modify(configuration={"spann": {"search_nprobe": 128}}) + + # Verify other value types were not affected + updated_schema = collection.schema + assert updated_schema is not None + + # Check that non-vector-index value types are unchanged + assert updated_schema.defaults.string is not None + assert updated_schema.defaults.string.string_inverted_index is not None + assert updated_schema.defaults.string.fts_index is not None + + assert updated_schema.defaults.int_value is not None + assert updated_schema.defaults.int_value.int_inverted_index is not None + + assert updated_schema.defaults.float_value is not None + assert updated_schema.defaults.float_value.float_inverted_index is not None + + assert updated_schema.defaults.boolean is not None + assert updated_schema.defaults.boolean.bool_inverted_index is not None + + assert updated_schema.defaults.sparse_vector is not None + assert updated_schema.defaults.sparse_vector.sparse_vector_index is not None + + # Check #document key is preserved + assert updated_schema.keys["#document"] is not None + assert updated_schema.keys["#document"].string is not None + assert updated_schema.keys["#document"].string.fts_index is not None + assert updated_schema.keys["#document"].string.fts_index.enabled is True + + # Verify vector index WAS updated + assert updated_schema.defaults.float_list.vector_index.config.spann.search_nprobe == 128 # type: ignore + + # Re-fetch from server to verify persistence + collection_refreshed = client.get_collection(collection_name) + refreshed_schema = collection_refreshed.schema + assert refreshed_schema is not None + + # Verify vector index was updated on server + assert refreshed_schema.defaults.float_list.vector_index.config.spann.search_nprobe == 128 # type: ignore + + # Verify other value types are still intact on server + assert refreshed_schema.defaults.string is not None + assert refreshed_schema.defaults.string.string_inverted_index is not None + assert refreshed_schema.defaults.string.fts_index is not None + assert refreshed_schema.defaults.int_value is not None + assert refreshed_schema.defaults.float_value is not None + assert refreshed_schema.defaults.boolean is not None + assert refreshed_schema.defaults.sparse_vector is not None + assert refreshed_schema.keys["#document"] is not None + + +def test_embeds_using_schema_embedding_function() -> None: + """Test that embeddings are using the schema embedding function.""" + schema = Schema().create_index( + config=VectorIndexConfig(embedding_function=SimpleEmbeddingFunction()), + ) + + collection_model = CollectionModel( + id=uuid4(), + name="schema_only_collection", + configuration_json={}, + serialized_schema=schema.serialize_to_json(), + metadata=None, + dimension=4, + tenant="tenant", + database="database", + version=0, + log_position=0, + ) + + collection = CollectionCommon( + client=cast(ServerAPI, object()), + model=collection_model, + embedding_function=None, + ) + + assert collection._embedding_function is None + assert collection.configuration is not None + assert collection.configuration.get("embedding_function") is None + + embeddings = collection._embed(["hello world"]) + assert embeddings is not None + assert np.allclose(embeddings[0], [0.0, 1.0, 2.0, 3.0]) + + +@register_sparse_embedding_function +class TestSparseEmbeddingFunction(SparseEmbeddingFunction[List[str]]): + """Sparse embedding function for testing search API with string queries.""" + + def __init__(self, label: str = "test_sparse"): + self._label = label + + def __call__(self, input: List[str]) -> List[SparseVector]: + return [ + SparseVector(indices=[idx], values=[float(len(text) + idx)]) + for idx, text in enumerate(input) + ] + + def embed_query(self, input: List[str]) -> List[SparseVector]: + return [ + SparseVector(indices=[idx], values=[float(len(text) + idx + 1)]) + for idx, text in enumerate(input) + ] + + @staticmethod + def name() -> str: + return "test_sparse_ef" + + def get_config(self) -> Dict[str, Any]: + return {"label": self._label} + + @staticmethod + def build_from_config(config: Dict[str, Any]) -> "TestSparseEmbeddingFunction": + return TestSparseEmbeddingFunction(config.get("label", "test_sparse")) + + +@pytest.mark.skipif(is_spann_disabled_mode, reason=skip_reason_spann_disabled) +def test_search_api_uses_embedded_searches_with_sparse_embeddings( + client_factories: ClientFactories, +) -> None: + """Test that search API uses embedded_searches when string queries are embedded.""" + + sparse_ef = TestSparseEmbeddingFunction(label="search_test") + schema = Schema().create_index( + key="sparse_field", + config=SparseVectorIndexConfig( + source_key=Key.DOCUMENT, # type: ignore[arg-type] + embedding_function=sparse_ef, + ), + ) + + collection, _ = _create_isolated_collection(client_factories, schema=schema) + + collection.add( + ids=["doc1", "doc2"], + documents=["hello world", "test document"], + ) + + result = collection.get() + assert result is not None + assert result["documents"] is not None + assert len(result["documents"]) == 2 + + search = Search().rank(Knn(key="sparse_field", query="hello world")) + + results = collection.search(search) + + assert results["ids"] is not None + assert len(results["ids"]) == 1 + assert len(results["ids"][0]) > 0 + assert "doc1" in results["ids"][0] + + +# ============================================================================ +# FTS Disable / Enable Tests +# ============================================================================ + + +def test_fts_disabled_blocks_where_document_queries( + client_factories: "ClientFactories", +) -> None: + """Disabling FTS via schema should block where_document queries on get, query, and delete.""" + schema = Schema() + schema.delete_index(config=FtsIndexConfig(), key="#document") + + collection, _ = _create_isolated_collection(client_factories, schema=schema) + + # Verify FTS is disabled in the schema + assert collection.schema is not None + doc_override = collection.schema.keys["#document"].string + assert doc_override is not None + assert doc_override.fts_index is not None + assert doc_override.fts_index.enabled is False + + # Add documents — should succeed (documents are stored, just not FTS-indexed) + collection.add( + ids=["fts-off-1", "fts-off-2", "fts-off-3"], + documents=["alpha beta gamma", "delta epsilon zeta", "eta theta iota"], + metadatas=[ + {"category": "group_a"}, + {"category": "group_b"}, + {"category": "group_a"}, + ], + ) + + # where_document queries should fail with InvalidArgumentError + with pytest.raises(InvalidArgumentError) as exc_info: + collection.get(where_document={"$contains": "alpha"}) + assert "fts" in str(exc_info.value).lower() + + with pytest.raises(InvalidArgumentError) as exc_info: + collection.query( + query_texts=["some query text"], + n_results=1, + where_document={"$contains": "delta"}, + ) + assert "fts" in str(exc_info.value).lower() + + with pytest.raises(InvalidArgumentError) as exc_info: + collection.delete(where_document={"$contains": "eta"}) + assert "fts" in str(exc_info.value).lower() + + # Regular metadata filtering should still work + filtered = collection.get(where={"category": "group_a"}) + assert set(filtered["ids"]) == {"fts-off-1", "fts-off-3"} + + +def test_fts_enabled_by_default_where_document_works( + client_factories: "ClientFactories", +) -> None: + """Default schema should have FTS enabled and where_document queries should work.""" + collection, _ = _create_isolated_collection(client_factories) + + # Verify FTS is enabled in the default schema + assert collection.schema is not None + doc_override = collection.schema.keys["#document"].string + assert doc_override is not None + assert doc_override.fts_index is not None + assert doc_override.fts_index.enabled is True + + collection.add( + ids=["fts-on-1", "fts-on-2"], + documents=["the quick brown fox", "lazy dog sleeps"], + ) + + items = collection.get(where_document={"$contains": "fox"}) + assert set(items["ids"]) == {"fts-on-1"} + + items = collection.get(where_document={"$contains": "lazy"}) + assert set(items["ids"]) == {"fts-on-2"} + + +def test_fts_disabled_schema_persistence( + client_factories: "ClientFactories", +) -> None: + """FTS-disabled schema should persist across client reloads.""" + schema = Schema() + schema.delete_index(config=FtsIndexConfig(), key="#document") + + collection, client = _create_isolated_collection(client_factories, schema=schema) + collection_name = collection.name + + collection.add( + ids=["persist-fts-1"], + documents=["persistent doc for fts test"], + ) + + # Reload client + reloaded_client = client_factories.create_client_from_system() + reloaded_collection = reloaded_client.get_collection(name=collection_name) + + # Verify FTS is still disabled after reload + assert reloaded_collection.schema is not None + doc_override = reloaded_collection.schema.keys["#document"].string + assert doc_override is not None + assert doc_override.fts_index is not None + assert doc_override.fts_index.enabled is False + + # where_document should still fail + with pytest.raises(InvalidArgumentError): + reloaded_collection.get(where_document={"$contains": "persistent"}) + + +def test_fts_disabled_documents_still_stored( + client_factories: "ClientFactories", +) -> None: + """Documents should still be stored and retrievable when FTS is disabled.""" + schema = Schema() + schema.delete_index(config=FtsIndexConfig(), key="#document") + + collection, _ = _create_isolated_collection(client_factories, schema=schema) + + collection.add( + ids=["stored-1", "stored-2"], + documents=["document one content", "document two content"], + ) + + # Documents should be retrievable by ID + result = collection.get(ids=["stored-1", "stored-2"], include=["documents"]) + assert result["documents"] is not None + assert result["documents"][0] == "document one content" + assert result["documents"][1] == "document two content" + + # Count should be correct + assert collection.count() == 2 + + +def test_fts_disabled_then_new_collection_with_fts_enabled( + client_factories: "ClientFactories", +) -> None: + """Deleting a FTS-disabled collection and recreating with FTS enabled should restore FTS.""" + # Create with FTS disabled + schema_disabled = Schema() + schema_disabled.delete_index(config=FtsIndexConfig(), key="#document") + + collection, client = _create_isolated_collection( + client_factories, schema=schema_disabled + ) + col_name = collection.name + + collection.add( + ids=["fts-toggle-1"], + documents=["searchable text"], + ) + + with pytest.raises(InvalidArgumentError): + collection.get(where_document={"$contains": "searchable"}) + + # Delete and recreate with default schema (FTS enabled) + client.delete_collection(name=col_name) + restored = client.get_or_create_collection(name=col_name) + + restored.add( + ids=["fts-toggle-2"], + documents=["searchable text again"], + ) + + items = restored.get(where_document={"$contains": "searchable"}) + assert set(items["ids"]) == {"fts-toggle-2"} + + +@pytest.mark.skipif(is_spann_disabled_mode, reason=skip_reason_spann_disabled) +def test_fts_disabled_search_api_blocks_document_filter( + client_factories: "ClientFactories", +) -> None: + """Search API should also reject document filters when FTS is disabled.""" + schema = Schema() + schema.delete_index(config=FtsIndexConfig(), key="#document") + + collection, _ = _create_isolated_collection(client_factories, schema=schema) + + collection.add( + ids=["search-fts-1", "search-fts-2"], + documents=["alpha content", "beta content"], + ) + + with pytest.raises(InvalidArgumentError) as exc_info: + collection.search( + Search(where=Key.DOCUMENT.contains("alpha")) + ) + assert "fts" in str(exc_info.value).lower() diff --git a/python/user_packages/Python313/site-packages/chromadb/test/api/test_search_api.py b/python/user_packages/Python313/site-packages/chromadb/test/api/test_search_api.py new file mode 100644 index 0000000000000000000000000000000000000000..436c614c478d5cd5cf7ba5a5d6a89cfd4aeab506 --- /dev/null +++ b/python/user_packages/Python313/site-packages/chromadb/test/api/test_search_api.py @@ -0,0 +1,122 @@ +"""Tests for the Search API endpoint.""" + +from typing import Tuple +from uuid import uuid4 + +import pytest + +from chromadb.api import ClientAPI +from chromadb.api.models.Collection import Collection +from chromadb.api.types import Embeddings, ReadLevel +from chromadb.execution.expression import Knn, Search +from chromadb.test.conftest import ( + ClientFactories, + is_spann_disabled_mode, + skip_reason_spann_disabled, +) + + +def _create_test_collection( + client_factories: ClientFactories, +) -> Tuple[Collection, ClientAPI]: + """Create a test collection with some data.""" + client = client_factories.create_client_from_system() + client.reset() + + collection_name = f"search_api_test_{uuid4().hex}" + collection = client.get_or_create_collection(name=collection_name) + + return collection, client + + +@pytest.mark.skipif(is_spann_disabled_mode, reason=skip_reason_spann_disabled) +def test_search_with_read_level_index_and_wal( + client_factories: ClientFactories, +) -> None: + """Test search with ReadLevel.INDEX_AND_WAL (default) returns results.""" + collection, _ = _create_test_collection(client_factories) + + # Add some data + collection.add( + ids=["doc1", "doc2", "doc3"], + documents=["apple fruit", "banana fruit", "car vehicle"], + embeddings=[[0.1, 0.2, 0.3, 0.4], [0.2, 0.3, 0.4, 0.5], [0.9, 0.8, 0.7, 0.6]], + ) + + # Search with explicit INDEX_AND_WAL (default behavior) + search = Search().rank(Knn(query=[0.1, 0.2, 0.3, 0.4], limit=10)) + results = collection.search(search, read_level=ReadLevel.INDEX_AND_WAL) + + assert results["ids"] is not None + assert len(results["ids"]) == 1 + assert len(results["ids"][0]) > 0 + + +@pytest.mark.skipif(is_spann_disabled_mode, reason=skip_reason_spann_disabled) +def test_search_with_read_level_index_only( + client_factories: ClientFactories, +) -> None: + """Test search with ReadLevel.INDEX_ONLY returns results.""" + collection, _ = _create_test_collection(client_factories) + + # Add some data + collection.add( + ids=["doc1", "doc2", "doc3"], + documents=["apple fruit", "banana fruit", "car vehicle"], + embeddings=[[0.1, 0.2, 0.3, 0.4], [0.2, 0.3, 0.4, 0.5], [0.9, 0.8, 0.7, 0.6]], + ) + + # Search with INDEX_ONLY - this skips the WAL + # Note: Results may or may not include recent writes depending on compaction state + search = Search().rank(Knn(query=[0.1, 0.2, 0.3, 0.4], limit=10)) + results = collection.search(search, read_level=ReadLevel.INDEX_ONLY) + + # Just verify the API works and returns a valid response structure + assert results["ids"] is not None + assert len(results["ids"]) == 1 + # Results may be empty if data hasn't been compacted yet, which is expected behavior + + +@pytest.mark.skipif(is_spann_disabled_mode, reason=skip_reason_spann_disabled) +def test_search_with_read_level_index_and_bounded_wal( + client_factories: ClientFactories, +) -> None: + """Test search with ReadLevel.INDEX_AND_BOUNDED_WAL returns results.""" + collection, _ = _create_test_collection(client_factories) + + collection.add( + ids=["doc1", "doc2", "doc3"], + documents=["apple fruit", "banana fruit", "car vehicle"], + embeddings=[[0.1, 0.2, 0.3, 0.4], [0.2, 0.3, 0.4, 0.5], [0.9, 0.8, 0.7, 0.6]], + ) + + # Search with INDEX_AND_BOUNDED_WAL reads up to a server-configured number of WAL entries + search = Search().rank(Knn(query=[0.1, 0.2, 0.3, 0.4], limit=10)) + results = collection.search(search, read_level=ReadLevel.INDEX_AND_BOUNDED_WAL) + + assert results["ids"] is not None + assert len(results["ids"]) == 1 + + +@pytest.mark.skipif(is_spann_disabled_mode, reason=skip_reason_spann_disabled) +def test_search_default_read_level( + client_factories: ClientFactories, +) -> None: + """Test search without explicit read_level uses default (INDEX_AND_WAL).""" + collection, _ = _create_test_collection(client_factories) + + # Add some data + collection.add( + ids=["doc1", "doc2"], + documents=["hello world", "goodbye world"], + embeddings=[[0.1, 0.2, 0.3, 0.4], [0.5, 0.6, 0.7, 0.8]], + ) + + # Search without specifying read_level (should use default) + search = Search().rank(Knn(query=[0.1, 0.2, 0.3, 0.4], limit=10)) + results = collection.search(search) + + # Should return results since default is INDEX_AND_WAL (full consistency) + assert results["ids"] is not None + assert len(results["ids"]) == 1 + assert len(results["ids"][0]) > 0 diff --git a/python/user_packages/Python313/site-packages/chromadb/test/api/test_shared_system_client.py b/python/user_packages/Python313/site-packages/chromadb/test/api/test_shared_system_client.py new file mode 100644 index 0000000000000000000000000000000000000000..395a733ff0e5f197ad3a53a8a153adf4b6a581fb --- /dev/null +++ b/python/user_packages/Python313/site-packages/chromadb/test/api/test_shared_system_client.py @@ -0,0 +1,180 @@ +import pytest +from unittest.mock import MagicMock +from chromadb.api.shared_system_client import SharedSystemClient +from chromadb.api.base_http_client import BaseHTTPClient +from chromadb.config import System +from typing import Optional, Dict, Generator + + +@pytest.fixture(autouse=True) +def clear_cache() -> Generator[None, None, None]: + """Automatically clear the system cache before and after each test.""" + SharedSystemClient.clear_system_cache() + yield + SharedSystemClient.clear_system_cache() + + +def create_mock_http_client( + api_url: Optional[str] = None, + headers: Optional[Dict[str, str]] = None, +) -> MagicMock: + """Create a mock BaseHTTPClient instance with the specified configuration.""" + mock_server_api = MagicMock(spec=BaseHTTPClient) + + mock_server_api.get_api_url.return_value = api_url or "" + mock_server_api.get_request_headers.return_value = headers or {} + + return mock_server_api + + +def register_mock_system(system_id: str, mock_server_api: MagicMock) -> MagicMock: + """Register a mock system with the given ID and server API.""" + mock_system = MagicMock(spec=System) + mock_system.instance.return_value = mock_server_api + SharedSystemClient._identifier_to_system[system_id] = mock_system + return mock_system + + +def test_extracts_api_key_from_chroma_cloud_client() -> None: + mock_server_api = create_mock_http_client( + api_url="https://api.trychroma.com/api/v2", + headers={"X-Chroma-Token": "test-api-key-123"}, + ) + register_mock_system("test-id", mock_server_api) + + api_key = SharedSystemClient.get_chroma_cloud_api_key_from_clients() + + assert api_key == "test-api-key-123" + + +def test_extracts_api_key_with_lowercase_header() -> None: + mock_server_api = create_mock_http_client( + api_url="https://api.trychroma.com/api/v2", + headers={"x-chroma-token": "test-api-key-456"}, + ) + register_mock_system("test-id", mock_server_api) + + api_key = SharedSystemClient.get_chroma_cloud_api_key_from_clients() + + assert api_key == "test-api-key-456" + + +def test_extracts_api_key_from_gcp_chroma_cloud_client() -> None: + mock_server_api = create_mock_http_client( + api_url="https://dummy.gcp.trychroma.com/api/v2", + headers={"X-Chroma-Token": "gcp-test-api-key"}, + ) + register_mock_system("test-id", mock_server_api) + + api_key = SharedSystemClient.get_chroma_cloud_api_key_from_clients() + + assert api_key == "gcp-test-api-key" + + +def test_skips_non_chroma_cloud_clients() -> None: + mock_server_api = create_mock_http_client( + api_url="https://localhost:8000/api/v2", + headers={"X-Chroma-Token": "local-api-key"}, + ) + register_mock_system("test-id", mock_server_api) + + api_key = SharedSystemClient.get_chroma_cloud_api_key_from_clients() + + assert api_key is None + + +def test_skips_clients_without_api_url() -> None: + mock_server_api = create_mock_http_client( + api_url=None, + headers={"X-Chroma-Token": "test-api-key"}, + ) + register_mock_system("test-id", mock_server_api) + + api_key = SharedSystemClient.get_chroma_cloud_api_key_from_clients() + + assert api_key is None + + +def test_returns_none_when_no_api_key_in_headers() -> None: + mock_server_api = create_mock_http_client( + api_url="https://api.trychroma.com/api/v2", + headers={}, + ) + register_mock_system("test-id", mock_server_api) + + api_key = SharedSystemClient.get_chroma_cloud_api_key_from_clients() + + assert api_key is None + + +def test_returns_first_api_key_found_from_multiple_clients() -> None: + mock_server_api_1 = create_mock_http_client( + api_url="https://api.trychroma.com/api/v2", + headers={"X-Chroma-Token": "first-key"}, + ) + mock_server_api_2 = create_mock_http_client( + api_url="https://api.trychroma.com/api/v2", + headers={"X-Chroma-Token": "second-key"}, + ) + register_mock_system("test-id-1", mock_server_api_1) + register_mock_system("test-id-2", mock_server_api_2) + + api_key = SharedSystemClient.get_chroma_cloud_api_key_from_clients() + + assert api_key == "first-key" + + +def test_handles_exception_gracefully() -> None: + mock_system = MagicMock(spec=System) + mock_system.instance.side_effect = Exception("Test exception") + SharedSystemClient._identifier_to_system["test-id"] = mock_system + + api_key = SharedSystemClient.get_chroma_cloud_api_key_from_clients() + + assert api_key is None + + +def test_returns_none_when_no_clients_exist() -> None: + api_key = SharedSystemClient.get_chroma_cloud_api_key_from_clients() + + assert api_key is None + + +def test_skips_non_http_clients() -> None: + """Test that non-BaseHTTPClient instances are skipped.""" + mock_server_api = MagicMock() # Not a BaseHTTPClient + register_mock_system("test-id", mock_server_api) + + api_key = SharedSystemClient.get_chroma_cloud_api_key_from_clients() + + assert api_key is None + + +def test_extracts_api_key_with_mixed_case_header() -> None: + mock_server_api = create_mock_http_client( + api_url="https://api.trychroma.com/api/v2", + headers={"X-CHROMA-TOKEN": "mixed-case-key"}, + ) + register_mock_system("test-id", mock_server_api) + + api_key = SharedSystemClient.get_chroma_cloud_api_key_from_clients() + + assert api_key == "mixed-case-key" + + +def test_multiple_clients_returns_one_key() -> None: + """Test that multiple clients return one of the available keys.""" + mock_api_1 = create_mock_http_client( + api_url="https://api.trychroma.com/api/v2", + headers={"X-Chroma-Token": "key-1"}, + ) + mock_api_2 = create_mock_http_client( + api_url="https://api.trychroma.com/api/v2", + headers={"X-Chroma-Token": "key-2"}, + ) + register_mock_system("id-1", mock_api_1) + register_mock_system("id-2", mock_api_2) + + api_key = SharedSystemClient.get_chroma_cloud_api_key_from_clients() + + assert api_key in ["key-1", "key-2"] diff --git a/python/user_packages/Python313/site-packages/chromadb/test/api/test_types.py b/python/user_packages/Python313/site-packages/chromadb/test/api/test_types.py new file mode 100644 index 0000000000000000000000000000000000000000..89ba965afd8816e9687c1d912cf9c0198c7bf8df --- /dev/null +++ b/python/user_packages/Python313/site-packages/chromadb/test/api/test_types.py @@ -0,0 +1,105 @@ +import pytest +from typing import List, cast, Dict, Any +from chromadb.api.types import Documents, Image, Document, Embeddings +from chromadb.utils.embedding_functions import ( + EmbeddingFunction, + register_embedding_function, +) +import numpy as np + + +def random_embeddings() -> Embeddings: + return cast( + Embeddings, [embedding for embedding in np.random.random(size=(10, 10))] + ) + + +def random_image() -> Image: + return np.random.randint(0, 255, size=(10, 10, 3), dtype=np.int64) + + +def random_documents() -> List[Document]: + return [str(random_image()) for _ in range(10)] + + +def test_embedding_function_results_format_when_response_is_valid() -> None: + valid_embeddings = random_embeddings() + + @register_embedding_function + class TestEmbeddingFunction(EmbeddingFunction[Documents]): + def __init__(self) -> None: + pass + + @staticmethod + def name() -> str: + return "test" + + @staticmethod + def build_from_config(config: Dict[str, Any]) -> "EmbeddingFunction[Documents]": + return TestEmbeddingFunction() + + def get_config(self) -> Dict[str, Any]: + return {} + + def __call__(self, input: Documents) -> Embeddings: + return valid_embeddings + + @staticmethod + def validate_config(config: Dict[str, Any]) -> None: + pass + + def validate_config_update( + self, old_config: Dict[str, Any], new_config: Dict[str, Any] + ) -> None: + pass + + ef = TestEmbeddingFunction() + + embeddings = ef(random_documents()) + for i, e in enumerate(embeddings): + assert np.array_equal(e, valid_embeddings[i]) + + +def test_embedding_function_results_format_when_response_is_invalid() -> None: + invalid_embedding = {"error": "test"} + + @register_embedding_function + class TestEmbeddingFunction(EmbeddingFunction[Documents]): + def __init__(self) -> None: + pass + + @staticmethod + def name() -> str: + return "test" + + @staticmethod + def build_from_config(config: Dict[str, Any]) -> "EmbeddingFunction[Documents]": + return TestEmbeddingFunction() + + def get_config(self) -> Dict[str, Any]: + return {} + + @staticmethod + def validate_config(config: Dict[str, Any]) -> None: + pass + + def validate_config_update( + self, old_config: Dict[str, Any], new_config: Dict[str, Any] + ) -> None: + pass + + def __call__(self, input: Documents) -> Embeddings: + # Return something that's not a valid Embeddings type + return cast(Embeddings, invalid_embedding) + + ef = TestEmbeddingFunction() + + # The EmbeddingFunction protocol should validate the return value + # but we need to bypass the protocol's __call__ wrapper for this test + with pytest.raises(ValueError): + # This should raise a ValueError during normalization/validation + result = ef.__call__(random_documents()) + # The normalize_embeddings function will raise a ValueError when given an invalid embedding + from chromadb.api.types import normalize_embeddings + + normalize_embeddings(result) diff --git a/python/user_packages/Python313/site-packages/chromadb/test/auth/test_auth_utils.py b/python/user_packages/Python313/site-packages/chromadb/test/auth/test_auth_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..b6580deacd8c45f735073468d6f760d5e9919a00 --- /dev/null +++ b/python/user_packages/Python313/site-packages/chromadb/test/auth/test_auth_utils.py @@ -0,0 +1,87 @@ +import pytest + +from chromadb.auth.utils import maybe_set_tenant_and_database +from chromadb.auth import UserIdentity +from chromadb.config import DEFAULT_DATABASE, DEFAULT_TENANT +from chromadb.errors import ChromaAuthError + + +@pytest.fixture +def user_identity() -> UserIdentity: + return UserIdentity( + user_id="test_user_id", + tenant="test_tenant", + databases=["test_database"], + ) + + +def test_doesnt_overrite_from_auth(user_identity: UserIdentity) -> None: + resolved_tenant, resolved_database = maybe_set_tenant_and_database( + user_identity=user_identity, + overwrite_singleton_tenant_database_access_from_auth=False, + user_provided_tenant="user_provided_tenant", + user_provided_database="user_provided_database", + ) + + assert resolved_tenant == "user_provided_tenant" + assert resolved_database == "user_provided_database" + + +def test_sets_tenant_and_database_when_none_or_default_provided( + user_identity: UserIdentity, +) -> None: + resolved_tenant, resolved_database = maybe_set_tenant_and_database( + user_identity=user_identity, + overwrite_singleton_tenant_database_access_from_auth=True, + user_provided_tenant=DEFAULT_TENANT, + user_provided_database=DEFAULT_DATABASE, + ) + + assert resolved_tenant == "test_tenant" + assert resolved_database == "test_database" + + resolved_tenant, resolved_database = maybe_set_tenant_and_database( + user_identity=user_identity, + overwrite_singleton_tenant_database_access_from_auth=True, + user_provided_tenant=None, + user_provided_database=None, + ) + + assert resolved_tenant == "test_tenant" + assert resolved_database == "test_database" + + +def test_errors_when_provided_tenant_and_database_dont_match_from_auth( + user_identity: UserIdentity, +) -> None: + with pytest.raises(ChromaAuthError): + maybe_set_tenant_and_database( + user_identity=user_identity, + overwrite_singleton_tenant_database_access_from_auth=True, + user_provided_tenant="user_provided_tenant", + user_provided_database="user_provided_database", + ) + + +def test_doesnt_overrite_from_auth_when_ambiguous(user_identity: UserIdentity) -> None: + user_identity.tenant = "*" + user_identity.databases = ["*"] + resolved_tenant, resolved_database = maybe_set_tenant_and_database( + user_identity=user_identity, + overwrite_singleton_tenant_database_access_from_auth=True, + user_provided_tenant=None, + user_provided_database=None, + ) + + assert resolved_tenant is None + assert resolved_database is None + + resolved_tenant, resolved_database = maybe_set_tenant_and_database( + user_identity=user_identity, + overwrite_singleton_tenant_database_access_from_auth=True, + user_provided_tenant="user_provided_tenant", + user_provided_database="user_provided_database", + ) + + assert resolved_tenant == "user_provided_tenant" + assert resolved_database == "user_provided_database" diff --git a/python/user_packages/Python313/site-packages/chromadb/test/auth/test_rbac_authz.py b/python/user_packages/Python313/site-packages/chromadb/test/auth/test_rbac_authz.py new file mode 100644 index 0000000000000000000000000000000000000000..938fc4dd80bf6b76bd482158760f5ac18bc259ee --- /dev/null +++ b/python/user_packages/Python313/site-packages/chromadb/test/auth/test_rbac_authz.py @@ -0,0 +1,19 @@ +import uuid + +import pytest + +from chromadb.api import ServerAPI +from chromadb.config import DEFAULT_TENANT + + +def test_delete_database_requires_rbac_permission( + api_with_authn_rbac_authz: ServerAPI, +) -> None: + database_name = f"db_{uuid.uuid4().hex}" + api_with_authn_rbac_authz.create_database(database_name, tenant=DEFAULT_TENANT) + + with pytest.raises(Exception, match="Forbidden"): + api_with_authn_rbac_authz.delete_database(database_name, tenant=DEFAULT_TENANT) + + db = api_with_authn_rbac_authz.get_database(database_name, tenant=DEFAULT_TENANT) + assert db["name"] == database_name diff --git a/python/user_packages/Python313/site-packages/chromadb/test/client/__init__.py b/python/user_packages/Python313/site-packages/chromadb/test/client/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/python/user_packages/Python313/site-packages/chromadb/test/client/create_http_client_with_basic_auth.py b/python/user_packages/Python313/site-packages/chromadb/test/client/create_http_client_with_basic_auth.py new file mode 100644 index 0000000000000000000000000000000000000000..e4bf7e1c077a99ab39a43cf6b929328586a865f7 --- /dev/null +++ b/python/user_packages/Python313/site-packages/chromadb/test/client/create_http_client_with_basic_auth.py @@ -0,0 +1,28 @@ +# This file is used by test_create_http_client.py to test the initialization +# of an HttpClient class with auth settings. +# +# See https://github.com/chroma-core/chroma/issues/1554 + +import chromadb +from chromadb.config import Settings +import sys + + +def main() -> None: + try: + chromadb.HttpClient( + host="localhost", + port=8000, + settings=Settings( + chroma_client_auth_provider="chromadb.auth.basic_authn.BasicAuthClientProvider", + chroma_client_auth_credentials="admin:testDb@home2", + ), + ) + except ValueError: + # We don't expect to be able to connect to Chroma. We just want to make sure + # there isn't an ImportError. + sys.exit(0) + + +if __name__ == "__main__": + main() diff --git a/python/user_packages/Python313/site-packages/chromadb/test/client/test_cloud_client.py b/python/user_packages/Python313/site-packages/chromadb/test/client/test_cloud_client.py new file mode 100644 index 0000000000000000000000000000000000000000..23c788476c6bf2072334929248f89756dd4dd46c --- /dev/null +++ b/python/user_packages/Python313/site-packages/chromadb/test/client/test_cloud_client.py @@ -0,0 +1,334 @@ +import pytest +from unittest.mock import patch +from chromadb import CloudClient +from chromadb.errors import ChromaAuthError, NotFoundError +from chromadb.auth import UserIdentity +from chromadb.types import Tenant, Database +from uuid import uuid4 + + +def test_valid_key() -> None: + with patch( + "chromadb.api.fastapi.FastAPI.get_user_identity" + ) as mock_get_user_identity, patch( + "chromadb.api.client.AdminClient.get_tenant" + ) as mock_get_tenant, patch( + "chromadb.api.client.AdminClient.get_database" + ) as mock_get_database, patch( + "chromadb.api.fastapi.FastAPI.heartbeat" + ) as mock_heartbeat: + mock_get_user_identity.return_value = UserIdentity( + user_id="test_user", tenant="default_tenant", databases=["testdb"] + ) + mock_get_tenant.return_value = Tenant(name="default_tenant") + mock_get_database.return_value = Database( + id=uuid4(), name="testdb", tenant="default_tenant" + ) + mock_heartbeat.return_value = 1234567890 + + client = CloudClient(database="testdb", api_key="valid_token") + + assert client.get_user_identity().user_id == "test_user" + assert client.get_user_identity().tenant == "default_tenant" + assert client.get_user_identity().databases == ["testdb"] + + settings = client.get_settings() + assert settings.chroma_client_auth_credentials == "valid_token" + assert ( + settings.chroma_client_auth_provider + == "chromadb.auth.token_authn.TokenAuthClientProvider" + ) + + assert client.heartbeat() == 1234567890 + + +def test_invalid_key() -> None: + with patch( + "chromadb.api.fastapi.FastAPI.get_user_identity" + ) as mock_get_user_identity: + mock_get_user_identity.side_effect = ChromaAuthError("Authentication failed") + + with pytest.raises(ChromaAuthError): + CloudClient(database="testdb", api_key="invalid_token") + + +# Scoped API key to 1 database tests +def test_scoped_api_key_to_single_db_with_api_key_only() -> None: + with patch( + "chromadb.api.fastapi.FastAPI.get_user_identity" + ) as mock_get_user_identity, patch( + "chromadb.api.client.AdminClient.get_tenant" + ) as mock_get_tenant, patch( + "chromadb.api.client.AdminClient.get_database" + ) as mock_get_database: + # mock single db scoped api key + mock_get_user_identity.return_value = UserIdentity( + user_id="test_user", tenant="123-456-789", databases=["right-db"] + ) + mock_get_tenant.return_value = Tenant(name="123-456-789") + mock_get_database.return_value = Database( + id=uuid4(), name="right-db", tenant="123-456-789" + ) + + client = CloudClient(api_key="valid_token") + + # should resolve to single db + assert client.database == "right-db" + assert client.tenant == "123-456-789" + + +def test_scoped_api_key_to_single_db_with_correct_tenant() -> None: + with patch( + "chromadb.api.fastapi.FastAPI.get_user_identity" + ) as mock_get_user_identity, patch( + "chromadb.api.client.AdminClient.get_tenant" + ) as mock_get_tenant, patch( + "chromadb.api.client.AdminClient.get_database" + ) as mock_get_database: + mock_get_user_identity.return_value = UserIdentity( + user_id="test_user", tenant="123-456-789", databases=["right-db"] + ) + mock_get_tenant.return_value = Tenant(name="123-456-789") + mock_get_database.return_value = Database( + id=uuid4(), name="right-db", tenant="123-456-789" + ) + + client = CloudClient(tenant="123-456-789", api_key="valid_token") + + assert client.tenant == "123-456-789" + assert client.database == "right-db" + + +def test_scoped_api_key_to_single_db_with_correct_db() -> None: + with patch( + "chromadb.api.fastapi.FastAPI.get_user_identity" + ) as mock_get_user_identity, patch( + "chromadb.api.client.AdminClient.get_tenant" + ) as mock_get_tenant, patch( + "chromadb.api.client.AdminClient.get_database" + ) as mock_get_database: + mock_get_user_identity.return_value = UserIdentity( + user_id="test_user", tenant="123-456-789", databases=["right-db"] + ) + mock_get_tenant.return_value = Tenant(name="123-456-789") + mock_get_database.return_value = Database( + id=uuid4(), name="right-db", tenant="123-456-789" + ) + + client = CloudClient(database="right-db", api_key="valid_token") + + assert client.tenant == "123-456-789" + assert client.database == "right-db" + + +def test_scoped_api_key_to_single_db_with_correct_tenant_and_db() -> None: + with patch( + "chromadb.api.fastapi.FastAPI.get_user_identity" + ) as mock_get_user_identity, patch( + "chromadb.api.client.AdminClient.get_tenant" + ) as mock_get_tenant, patch( + "chromadb.api.client.AdminClient.get_database" + ) as mock_get_database: + mock_get_user_identity.return_value = UserIdentity( + user_id="test_user", tenant="123-456-789", databases=["right-db"] + ) + mock_get_tenant.return_value = Tenant(name="123-456-789") + mock_get_database.return_value = Database( + id=uuid4(), name="right-db", tenant="123-456-789" + ) + + client = CloudClient( + tenant="123-456-789", database="right-db", api_key="valid_token" + ) + + assert client.tenant == "123-456-789" + assert client.database == "right-db" + + +def test_scoped_api_key_to_single_db_with_wrong_tenant() -> None: + with patch( + "chromadb.api.fastapi.FastAPI.get_user_identity" + ) as mock_get_user_identity: + mock_get_user_identity.return_value = UserIdentity( + user_id="test_user", tenant="123-456-789", databases=["right-db"] + ) + + with pytest.raises( + ChromaAuthError, + match="Tenant wrong-tenant does not match 123-456-789 from the server. Are you sure the tenant is correct?", + ): + CloudClient(tenant="wrong-tenant", api_key="valid_token") + + +def test_scoped_api_key_to_single_db_with_wrong_database() -> None: + with patch( + "chromadb.api.fastapi.FastAPI.get_user_identity" + ) as mock_get_user_identity: + mock_get_user_identity.return_value = UserIdentity( + user_id="test_user", tenant="123-456-789", databases=["right-db"] + ) + + with pytest.raises( + ChromaAuthError, + match="Database wrong-db does not match right-db from the server. Are you sure the database is correct?", + ): + CloudClient(database="wrong-db", api_key="valid_token") + + +def test_scoped_api_key_to_single_db_with_wrong_api_key() -> None: + with patch( + "chromadb.api.fastapi.FastAPI.get_user_identity" + ) as mock_get_user_identity: + mock_get_user_identity.side_effect = ChromaAuthError("Permission denied.") + + with pytest.raises(ChromaAuthError, match="Permission denied."): + CloudClient(database="right-db", api_key="wrong-api-key") + + +# Scoped API key to multiple databases tests +def test_scoped_api_key_to_multiple_dbs_with_wrong_tenant() -> None: + with patch( + "chromadb.api.fastapi.FastAPI.get_user_identity" + ) as mock_get_user_identity: + mock_get_user_identity.return_value = UserIdentity( + user_id="test_user", + tenant="123-456-789", + databases=["right-db", "another-db"], + ) + + with pytest.raises( + ChromaAuthError, + match="Tenant wrong-tenant does not match 123-456-789 from the server. Are you sure the tenant is correct?", + ): + CloudClient( + tenant="wrong-tenant", database="right-db", api_key="valid_token" + ) + + +def test_scoped_api_key_to_multiple_dbs_with_correct_tenant_and_db() -> None: + with patch( + "chromadb.api.fastapi.FastAPI.get_user_identity" + ) as mock_get_user_identity, patch( + "chromadb.api.client.AdminClient.get_tenant" + ) as mock_get_tenant, patch( + "chromadb.api.client.AdminClient.get_database" + ) as mock_get_database: + mock_get_user_identity.return_value = UserIdentity( + user_id="test_user", + tenant="123-456-789", + databases=["right-db", "another-db"], + ) + mock_get_tenant.return_value = Tenant(name="123-456-789") + mock_get_database.return_value = Database( + id=uuid4(), name="right-db", tenant="123-456-789" + ) + + client = CloudClient( + tenant="123-456-789", database="right-db", api_key="valid_token" + ) + + assert client.tenant == "123-456-789" + assert client.database == "right-db" + + +def test_scoped_api_key_to_multiple_dbs_with_nonexistent_database() -> None: + with patch( + "chromadb.api.fastapi.FastAPI.get_user_identity" + ) as mock_get_user_identity, patch( + "chromadb.api.client.AdminClient.get_tenant" + ) as mock_get_tenant, patch( + "chromadb.api.client.AdminClient.get_database" + ) as mock_get_database: + mock_get_user_identity.return_value = UserIdentity( + user_id="test_user", + tenant="123-456-789", + databases=["right-db", "another-db"], + ) + mock_get_tenant.return_value = Tenant(name="123-456-789") + mock_get_database.side_effect = NotFoundError( + "Database [wrong-db] not found. Are you sure it exists?" + ) + + with pytest.raises( + NotFoundError, + match="Database \\[wrong-db\\] not found. Are you sure it exists?", + ): + CloudClient(database="wrong-db", api_key="valid_token") + + +def test_scoped_api_key_to_multiple_dbs_with_api_key_only() -> None: + with patch( + "chromadb.api.fastapi.FastAPI.get_user_identity" + ) as mock_get_user_identity: + mock_get_user_identity.return_value = UserIdentity( + user_id="test_user", + tenant="123-456-789", + databases=["right-db", "another-db"], + ) + + with pytest.raises( + ChromaAuthError, + match="Could not determine a database name from the current authentication method. Please provide a database name.", + ): + CloudClient(api_key="valid_token") + + +# Unscoped API key tests +def test_api_key_with_unscoped_tenant() -> None: + with patch( + "chromadb.api.fastapi.FastAPI.get_user_identity" + ) as mock_get_user_identity: + mock_get_user_identity.return_value = UserIdentity( + user_id="test_user", tenant="*", databases=["right-db"] + ) + + with pytest.raises( + ChromaAuthError, + match="Could not determine a tenant from the current authentication method. Please provide a tenant.", + ): + CloudClient(api_key="valid_token") + + +def test_api_key_with_unscoped_db() -> None: + with patch( + "chromadb.api.fastapi.FastAPI.get_user_identity" + ) as mock_get_user_identity: + mock_get_user_identity.return_value = UserIdentity( + user_id="test_user", tenant="123-456-789", databases=["*"] + ) + + with pytest.raises( + ChromaAuthError, + match="Could not determine a database name from the current authentication method. Please provide a database name.", + ): + CloudClient(api_key="valid_token") + + +def test_api_key_with_no_db_access() -> None: + with patch( + "chromadb.api.fastapi.FastAPI.get_user_identity" + ) as mock_get_user_identity: + mock_get_user_identity.return_value = UserIdentity( + user_id="test_user", tenant="123-456-789", databases=[] + ) + + with pytest.raises( + ChromaAuthError, + match="Could not determine a database name from the current authentication method. Please provide a database name.", + ): + CloudClient(api_key="valid_token") + + +def test_api_key_with_no_tenant_access() -> None: + with patch( + "chromadb.api.fastapi.FastAPI.get_user_identity" + ) as mock_get_user_identity: + mock_get_user_identity.return_value = UserIdentity( + user_id="test_user", tenant=None, databases=["right-db"] + ) + + with pytest.raises( + ChromaAuthError, + match="Could not determine a tenant from the current authentication method. Please provide a tenant.", + ): + CloudClient(api_key="valid_token") diff --git a/python/user_packages/Python313/site-packages/chromadb/test/client/test_create_http_client.py b/python/user_packages/Python313/site-packages/chromadb/test/client/test_create_http_client.py new file mode 100644 index 0000000000000000000000000000000000000000..b4e0823d0eea64bf3f0d3759cc5e796fe10c8136 --- /dev/null +++ b/python/user_packages/Python313/site-packages/chromadb/test/client/test_create_http_client.py @@ -0,0 +1,15 @@ +import subprocess + +# Needs to be a module, not a file, so that local imports work. +TEST_MODULE = "chromadb.test.client.create_http_client_with_basic_auth" + + +def test_main() -> None: + # This is the only way to test what we want to test: pytest does a bunch of + # importing and other module stuff in the background, so we need a clean + # python process to make sure we're not circular-importing. + # + # See https://github.com/chroma-core/chroma/issues/1554 + + res = subprocess.run(["python", "-m", TEST_MODULE]) + assert res.returncode == 0 diff --git a/python/user_packages/Python313/site-packages/chromadb/test/client/test_database_tenant.py b/python/user_packages/Python313/site-packages/chromadb/test/client/test_database_tenant.py new file mode 100644 index 0000000000000000000000000000000000000000..81d9948d7180a4610c9e5418d4ff24d479ca8512 --- /dev/null +++ b/python/user_packages/Python313/site-packages/chromadb/test/client/test_database_tenant.py @@ -0,0 +1,184 @@ +import pytest +from chromadb.config import DEFAULT_DATABASE, DEFAULT_TENANT +from chromadb.test.conftest import ClientFactories +from chromadb.errors import InvalidArgumentError +from chromadb.api.types import GetResult +from typing import Dict, Any +import numpy as np + + +def test_database_tenant_collections(client_factories: ClientFactories) -> None: + client = client_factories.create_client_from_system() + client.reset() + # Create a new database in the default tenant + admin_client = client_factories.create_admin_client_from_system() + admin_client.create_database("test_db") + + # Create collections in this new database + client.set_tenant(tenant=DEFAULT_TENANT, database="test_db") + client.create_collection("collection", metadata={"database": "test_db"}) + + # Create collections in the default database + client.set_tenant(tenant=DEFAULT_TENANT, database=DEFAULT_DATABASE) + client.create_collection("collection", metadata={"database": DEFAULT_DATABASE}) + + # List collections in the default database + collections = client.list_collections() + assert len(collections) == 1 + assert collections[0].name == "collection" + collection = client.get_collection(collections[0].name) + assert collection.metadata == {"database": DEFAULT_DATABASE} + + # List collections in the new database + client.set_tenant(tenant=DEFAULT_TENANT, database="test_db") + collections = client.list_collections() + assert len(collections) == 1 + assert collections[0].metadata == {"database": "test_db"} + + # Update the metadata in both databases to different values + client.set_tenant(tenant=DEFAULT_TENANT, database=DEFAULT_DATABASE) + client.list_collections()[0].modify(metadata={"database": "default2"}) + + client.set_tenant(tenant=DEFAULT_TENANT, database="test_db") + client.list_collections()[0].modify(metadata={"database": "test_db2"}) + + # Validate that the metadata was updated + client.set_tenant(tenant=DEFAULT_TENANT, database=DEFAULT_DATABASE) + collections = client.list_collections() + assert len(collections) == 1 + assert collections[0].metadata == {"database": "default2"} + + client.set_tenant(tenant=DEFAULT_TENANT, database="test_db") + collections = client.list_collections() + assert len(collections) == 1 + assert collections[0].metadata == {"database": "test_db2"} + + # Delete the collections and make sure databases are isolated + client.set_tenant(tenant=DEFAULT_TENANT, database=DEFAULT_DATABASE) + client.delete_collection("collection") + + collections = client.list_collections() + assert len(collections) == 0 + + client.set_tenant(tenant=DEFAULT_TENANT, database="test_db") + collections = client.list_collections() + assert len(collections) == 1 + + client.delete_collection("collection") + collections = client.list_collections() + assert len(collections) == 0 + + +def test_database_collections_add(client_factories: ClientFactories) -> None: + client = client_factories.create_client_from_system() + client.reset() + + # Create a new database in the default tenant + admin_client = client_factories.create_admin_client_from_system() + admin_client.create_database("test_db") + + # Create collections in this new database + client.set_database(database="test_db") + coll_new = client.create_collection("collection_new") + + # Create collections in the default database + client.set_database(database=DEFAULT_DATABASE) + coll_default = client.create_collection("collection_default") + + records_new = { + "ids": ["a", "b", "c"], + "embeddings": [[1.0, 2.0, 3.0] for _ in range(3)], + "documents": ["a", "b", "c"], + } + + records_default = { + "ids": ["c", "d", "e"], + "embeddings": [[4.0, 5.0, 6.0] for _ in range(3)], + "documents": ["c", "d", "e"], + } + + # Add to the new coll + coll_new.add(**records_new) # type: ignore + + # Add to the default coll + coll_default.add(**records_default) # type: ignore + + # Make sure the collections are isolated + res = coll_new.get(include=["embeddings", "documents"]) + assert res["ids"] == records_new["ids"] + check_embeddings(res=res, records=records_new) + assert res["documents"] == records_new["documents"] + + res = coll_default.get(include=["embeddings", "documents"]) + assert res["ids"] == records_default["ids"] + check_embeddings(res=res, records=records_default) + assert res["documents"] == records_default["documents"] + + +def test_tenant_collections_add(client_factories: ClientFactories) -> None: + client = client_factories.create_client_from_system() + client.reset() + + # Create two databases with same name in different tenants + admin_client = client_factories.create_admin_client_from_system() + admin_client.create_tenant("test_tenant1") + admin_client.create_tenant("test_tenant2") + admin_client.create_database("test_db", tenant="test_tenant1") + admin_client.create_database("test_db", tenant="test_tenant2") + + # Create collections in each database with same name + client.set_tenant(tenant="test_tenant1", database="test_db") + coll_tenant1 = client.create_collection("collection") + client.set_tenant(tenant="test_tenant2", database="test_db") + coll_tenant2 = client.create_collection("collection") + + records_tenant1 = { + "ids": ["a", "b", "c"], + "embeddings": [[1.0, 2.0, 3.0] for _ in range(3)], + "documents": ["a", "b", "c"], + } + + records_tenant2 = { + "ids": ["c", "d", "e"], + "embeddings": [[4.0, 5.0, 6.0] for _ in range(3)], + "documents": ["c", "d", "e"], + } + + # Add to the tenant1 coll + coll_tenant1.add(**records_tenant1) # type: ignore + + # Add to the tenant2 coll + coll_tenant2.add(**records_tenant2) # type: ignore + + # Make sure the collections are isolated + res = coll_tenant1.get(include=["embeddings", "documents"]) + assert res["ids"] == records_tenant1["ids"] + check_embeddings(res=res, records=records_tenant1) + assert res["documents"] == records_tenant1["documents"] + + res = coll_tenant2.get(include=["embeddings", "documents"]) + assert res["ids"] == records_tenant2["ids"] + check_embeddings(res=res, records=records_tenant2) + assert res["documents"] == records_tenant2["documents"] + + +def test_min_len_name(client_factories: ClientFactories) -> None: + client = client_factories.create_client_from_system() + client.reset() + + # Create a new database in the default tenant with a name of length 1 + # and expect an error + admin_client = client_factories.create_admin_client_from_system() + with pytest.raises((Exception, InvalidArgumentError)): + admin_client.create_database("a") + + # Create a tenant with a name of length 1 and expect an error + with pytest.raises((Exception, InvalidArgumentError)): + admin_client.create_tenant("a") + + +def check_embeddings(res: GetResult, records: Dict[str, Any]) -> None: + if res["embeddings"] is not None: + assert np.array_equal(res["embeddings"], records["embeddings"]) + else: + assert records["embeddings"] is None diff --git a/python/user_packages/Python313/site-packages/chromadb/test/client/test_database_tenant_auth.py b/python/user_packages/Python313/site-packages/chromadb/test/client/test_database_tenant_auth.py new file mode 100644 index 0000000000000000000000000000000000000000..07a142d86c0dc0b5b5a459a87c2f7eb88d063dc4 --- /dev/null +++ b/python/user_packages/Python313/site-packages/chromadb/test/client/test_database_tenant_auth.py @@ -0,0 +1,43 @@ +from typing import Dict +from fastapi import HTTPException +from overrides import override +from chromadb.auth import ( + AuthzAction, + AuthzResource, + ServerAuthenticationProvider, + ServerAuthorizationProvider, + UserIdentity, +) +from chromadb.config import System + + +class ExampleAuthenticationProvider(ServerAuthenticationProvider): + """In practice the tenant would likely be resolved from some other opaque value (e.g. key/token). Here, it's just passed directly as a header for simplicity.""" + + @override + def authenticate_or_raise(self, headers: Dict[str, str]) -> UserIdentity: + return UserIdentity( + user_id="test", + tenant=headers.get("x-tenant", None), + ) + + +class ExampleAuthorizationProvider(ServerAuthorizationProvider): + """A simple authz provider that asserts the user's tenant matches the resource's tenant.""" + + def __init__(self, system: System) -> None: + super().__init__(system) + self._settings = system.settings + + @override + def authorize_or_raise( + self, user: UserIdentity, action: AuthzAction, resource: AuthzResource + ) -> None: + if user.tenant is None: + return + + if action == AuthzAction.RESET: + return + + if user.tenant != resource.tenant: + raise HTTPException(status_code=403, detail="Unauthorized") diff --git a/python/user_packages/Python313/site-packages/chromadb/test/client/test_multiple_clients_concurrency.py b/python/user_packages/Python313/site-packages/chromadb/test/client/test_multiple_clients_concurrency.py new file mode 100644 index 0000000000000000000000000000000000000000..5050cd4a71abc945c9ce4f796ab809e6449ce907 --- /dev/null +++ b/python/user_packages/Python313/site-packages/chromadb/test/client/test_multiple_clients_concurrency.py @@ -0,0 +1,49 @@ +from concurrent.futures import ThreadPoolExecutor + +from chromadb.config import DEFAULT_TENANT +from chromadb.test.conftest import ClientFactories + + +def test_multiple_clients_concurrently(client_factories: ClientFactories) -> None: + """Tests running multiple clients, each against their own database, concurrently.""" + client = client_factories.create_client() + client.reset() + admin_client = client_factories.create_admin_client_from_system() + admin_client.create_database("test_db") + + CLIENT_COUNT = 50 + COLLECTION_COUNT = 10 + + # Each database will create the same collections by name, with differing metadata + databases = [f"db{i}" for i in range(CLIENT_COUNT)] + for database in databases: + admin_client.create_database(database) + + collections = [f"collection{i}" for i in range(COLLECTION_COUNT)] + + # Create N clients, each on a seperate thread, each with their own database + def run_target(n: int) -> None: + thread_client = client_factories.create_client( + tenant=DEFAULT_TENANT, + database=databases[n], + settings=client._system.settings, + ) + for collection in collections: + thread_client.create_collection( + collection, metadata={"database": databases[n]} + ) + + with ThreadPoolExecutor(max_workers=CLIENT_COUNT) as executor: + executor.map(run_target, range(CLIENT_COUNT)) + executor.shutdown(wait=True) + # Create a final client, which will be used to verify the collections were created + client = client_factories.create_client(settings=client._system.settings) + + # Verify that the collections were created + for database in databases: + client.set_database(database) + seen_collections = client.list_collections() + assert len(seen_collections) == COLLECTION_COUNT + for collection in seen_collections: + assert collection.name in collections + assert collection.metadata == {"database": database} diff --git a/python/user_packages/Python313/site-packages/chromadb/test/configurations/test_collection_configuration.py b/python/user_packages/Python313/site-packages/chromadb/test/configurations/test_collection_configuration.py new file mode 100644 index 0000000000000000000000000000000000000000..89ffc6c7b04147edc804e253232e86e656d3628e --- /dev/null +++ b/python/user_packages/Python313/site-packages/chromadb/test/configurations/test_collection_configuration.py @@ -0,0 +1,1743 @@ +import pytest +from typing import Dict, Any, cast, List +import numpy as np +import warnings +from chromadb.api.types import ( + EmbeddingFunction, + Embeddings, + Space, + Embeddable, +) +from chromadb.api import ClientAPI +from chromadb.api.collection_configuration import ( + CreateCollectionConfiguration, + UpdateCollectionConfiguration, + load_collection_configuration_from_json, + CreateHNSWConfiguration, + UpdateHNSWConfiguration, + CreateSpannConfiguration, + UpdateSpannConfiguration, + SpannConfiguration, + overwrite_spann_configuration, +) +import json +from chromadb.utils.embedding_functions import register_embedding_function +from chromadb.test.conftest import ClientFactories +from chromadb.test.conftest import is_spann_disabled_mode, skip_reason_spann_disabled +from chromadb.types import Collection as CollectionModel +from typing import Optional, TypedDict + + +class LegacyEmbeddingFunction(EmbeddingFunction[Embeddable]): + def __init__(self) -> None: + pass + + def __call__(self, input: Embeddable) -> Embeddings: + return cast(Embeddings, np.array([[1.0, 2.0]], dtype=np.float32)) + + +class LegacyEmbeddingFunctionWithName(EmbeddingFunction[Embeddable]): + def __init__(self) -> None: + pass + + def __call__(self, input: Embeddable) -> Embeddings: + return cast(Embeddings, np.array([[1.0, 2.0]], dtype=np.float32)) + + @staticmethod + def name() -> str: + return "legacy_ef" + + +@register_embedding_function +class CustomEmbeddingFunction(EmbeddingFunction[Embeddable]): + def __init__(self, dim: int = 3): + self._dim = dim + + def __call__(self, input: Embeddable) -> Embeddings: + return cast(Embeddings, np.array([[1.0] * self._dim], dtype=np.float32)) + + @staticmethod + def name() -> str: + return "custom_ef" + + def get_config(self) -> Dict[str, Any]: + return {"dim": self._dim} + + @staticmethod + def build_from_config(config: Dict[str, Any]) -> "CustomEmbeddingFunction": + return CustomEmbeddingFunction(dim=config["dim"]) + + def default_space(self) -> Space: + return "l2" + + +@register_embedding_function +class CustomEmbeddingFunction2(EmbeddingFunction[Embeddable]): + def __init__(self, dim: int = 4): + self._dim = dim + + def __call__(self, input: Embeddable) -> Embeddings: + return cast(Embeddings, np.array([[2.0] * self._dim], dtype=np.float32)) + + @staticmethod + def name() -> str: + return "custom_ef2" + + def get_config(self) -> Dict[str, Any]: + return {"dim": self._dim} + + @staticmethod + def build_from_config(config: Dict[str, Any]) -> "CustomEmbeddingFunction2": + return CustomEmbeddingFunction2(dim=config["dim"]) + + def default_space(self) -> Space: + return "l2" + + +def test_legacy_embedding_function(client: ClientAPI) -> None: + """Test creating and getting collections with legacy embedding functions""" + client.reset() + + # Create with legacy embedding function + coll = client.create_collection( + name="test_legacy", + embedding_function=LegacyEmbeddingFunction(), + ) + + # Verify the configuration marks it as legacy + config = load_collection_configuration_from_json(coll._model.configuration_json) + if config and isinstance(config, dict): + ef = config.get("embedding_function") + assert ef is None # legacy embedding functions return as None + else: + assert False, f"config: {config}" + + # Get with same legacy function + coll2 = client.get_collection( + name="test_legacy", + embedding_function=LegacyEmbeddingFunction(), + ) + + # Add and query should work + coll2.add(ids=["1"], documents=["test"]) + results = coll2.query(query_texts=["test"], n_results=1) + assert len(results["ids"]) == 1 + + +def test_legacy_embedding_function_with_name(client: ClientAPI) -> None: + """Test creating and getting collections with legacy embedding functions""" + client.reset() + + # Create with legacy embedding function + coll = client.create_collection( + name="test_legacy", + embedding_function=LegacyEmbeddingFunctionWithName(), + ) + + # Verify the configuration marks it as legacy + config = load_collection_configuration_from_json(coll._model.configuration_json) + if config and isinstance(config, dict): + ef = config.get("embedding_function") + assert ef is None # legacy embedding functions return as None + else: + assert False, f"config: {config}" + + # Get with same legacy function + coll2 = client.get_collection( + name="test_legacy", + embedding_function=LegacyEmbeddingFunctionWithName(), + ) + + # Add and query should work + coll2.add(ids=["1"], documents=["test"]) + results = coll2.query(query_texts=["test"], n_results=1) + assert len(results["ids"]) == 1 + + +def test_legacy_metadata(client: ClientAPI) -> None: + """Test creating collections with legacy metadata format""" + client.reset() + + # Create with legacy metadata + legacy_metadata = { + "hnsw:space": "cosine", + "hnsw:construction_ef": 200, + "hnsw:M": 10, # This is the legacy name for max_neighbors + } + coll = client.create_collection( + name="test_legacy_metadata", + metadata=legacy_metadata, + ) + + # Verify the configuration contains the legacy settings + config = load_collection_configuration_from_json(coll._model.configuration_json) + if config and isinstance(config, dict): + hnsw_config = cast(CreateHNSWConfiguration, config.get("hnsw", {})) + assert str(hnsw_config.get("space")) == str("cosine") + assert hnsw_config.get("ef_construction") == 200 + assert hnsw_config.get("max_neighbors") == 10 + assert hnsw_config.get("ef_search") == 100 + + ef = config.get("embedding_function") + assert ef is not None + assert ef.name() == "default" + + +def test_new_configuration(client: ClientAPI) -> None: + """Test creating collections with new configuration format""" + client.reset() + + # Create with new configuration + hnsw_config: CreateHNSWConfiguration = { + "space": "cosine", # Use enum value + "ef_construction": 100, + "max_neighbors": 10, # Changed from M to max_neighbors + "ef_search": 20, + "num_threads": 2, + } + config: CreateCollectionConfiguration = { + "hnsw": hnsw_config, + "embedding_function": CustomEmbeddingFunction(dim=5), + } + + coll = client.create_collection( + name="test_new_config", + configuration=config, + ) + + # Verify configuration is preserved + loaded_config = load_collection_configuration_from_json( + coll._model.configuration_json + ) + if loaded_config and isinstance(loaded_config, dict): + hnsw_config = cast(CreateHNSWConfiguration, loaded_config.get("hnsw", {})) + ef = loaded_config.get("embedding_function", {}) # type: ignore + assert hnsw_config.get("space") == "cosine" + assert hnsw_config.get("ef_construction") == 100 + assert hnsw_config.get("max_neighbors") == 10 + assert ef is not None + + +def test_invalid_configurations(client: ClientAPI) -> None: + """Test validation of invalid configurations""" + client.reset() + + # Test invalid HNSW parameters + with pytest.raises(Exception) as excinfo: + invalid_hnsw: CreateHNSWConfiguration = { + "ef_construction": -1, + "space": "cosine", + } + client.create_collection( + name="test_invalid", + configuration={"hnsw": invalid_hnsw}, + ) + + assert "invalid value" in str(excinfo.value) + + +def test_hnsw_configuration_updates(client: ClientAPI) -> None: + """Test updating collection configurations""" + client.reset() + + # Create initial collection + initial_hnsw: CreateHNSWConfiguration = { + "ef_search": 10, + "num_threads": 1, + "space": "cosine", + } + coll = client.create_collection( + name="test_updates", + configuration={"hnsw": initial_hnsw}, + ) + + # Update configuration + update_hnsw: UpdateHNSWConfiguration = { + "ef_search": 20, + "num_threads": 2, + } + update_config: UpdateCollectionConfiguration = { + "hnsw": update_hnsw, + } + coll.modify(configuration=update_config) + + # Verify updates + loaded_config = coll.configuration_json + if loaded_config and isinstance(loaded_config, dict): + hnsw_config = loaded_config.get("hnsw", {}) + if isinstance(hnsw_config, dict): + assert hnsw_config.get("ef_search") == 20 + # assert hnsw_config.get("num_threads") == 2 + assert hnsw_config.get("space") == "cosine" + assert hnsw_config.get("ef_construction") == 100 + assert hnsw_config.get("max_neighbors") == 16 + + coll = client.get_collection(name="test_updates") + loaded_config = coll.configuration_json + if loaded_config and isinstance(loaded_config, dict): + hnsw_config = loaded_config.get("hnsw", {}) + if isinstance(hnsw_config, dict): + assert hnsw_config.get("ef_search") == 20 + assert hnsw_config.get("space") == "cosine" + assert hnsw_config.get("ef_construction") == 100 + assert hnsw_config.get("max_neighbors") == 16 + + +def test_configuration_persistence(client_factories: "ClientFactories") -> None: + """Test configuration persistence across client restarts""" + # Use the factory to create the initial client + client = client_factories.create_client_from_system() + client.reset() + + # Create collection with specific configuration + hnsw_config: CreateHNSWConfiguration = { + "space": "cosine", + "ef_construction": 100, + "max_neighbors": 10, + } + config: CreateCollectionConfiguration = { + "hnsw": hnsw_config, + "embedding_function": CustomEmbeddingFunction(dim=5), + } + + client.create_collection( + name="test_persist_config", + configuration=config, + ) + + # Simulate client restart by creating a new client from the same system + client2 = client_factories.create_client_from_system() + + coll = client2.get_collection( + name="test_persist_config", + ) + + loaded_config = load_collection_configuration_from_json( + coll._model.configuration_json + ) + if loaded_config and isinstance(loaded_config, dict): + hnsw_config = cast(CreateHNSWConfiguration, loaded_config.get("hnsw", {})) + assert hnsw_config.get("space") == "cosine" + assert hnsw_config.get("ef_construction") == 100 + assert hnsw_config.get("max_neighbors") == 10 + assert hnsw_config.get("ef_search") == 100 + + ef = loaded_config.get("embedding_function") + assert ef is not None + assert ef.name() == "custom_ef" + + +def test_configuration_result_format(client: ClientAPI) -> None: + """Test updating collection configurations""" + client.reset() + + # Create initial collection + initial_hnsw: CreateHNSWConfiguration = { + "ef_search": 10, + "num_threads": 2, + "space": "cosine", # Required field + } + coll = client.create_collection( + name="test_updates", + configuration={"hnsw": initial_hnsw}, + ) + + assert coll._model.configuration_json is not None + hnsw_config = coll._model.configuration_json.get("hnsw") + assert hnsw_config is not None + assert hnsw_config.get("ef_search") == 10 + # assert hnsw_config.get("num_threads") == 2 + assert hnsw_config.get("space") == "cosine" + + +def test_empty_spann_configuration(client: ClientAPI) -> None: + """Test creating collections with SPANN configuration format""" + client.reset() + + # Create with SPANN configuration + spann_config: CreateSpannConfiguration = {} + config: CreateCollectionConfiguration = { + "spann": spann_config, + "embedding_function": CustomEmbeddingFunction(dim=5), + } + + if is_spann_disabled_mode: + coll = client.create_collection( + name="test_spann_config", + configuration=config, + ) + + # Verify configuration is preserved + loaded_config = load_collection_configuration_from_json( + coll._model.configuration_json + ) + if loaded_config and isinstance(loaded_config, dict): + hnsw_config_loaded = cast( + CreateHNSWConfiguration, loaded_config.get("hnsw", {}) + ) + ef = loaded_config.get("embedding_function") + assert hnsw_config_loaded.get("space") == "l2" + assert hnsw_config_loaded.get("ef_construction") == 100 + assert hnsw_config_loaded.get("ef_search") == 100 + assert hnsw_config_loaded.get("max_neighbors") == 16 + assert ef is not None + else: + coll = client.create_collection( + name="test_spann_config", + configuration=config, + ) + + # Verify configuration is preserved + loaded_config = load_collection_configuration_from_json( + coll._model.configuration_json + ) + if loaded_config and isinstance(loaded_config, dict): + spann_config_loaded = cast( + CreateSpannConfiguration, loaded_config.get("spann", {}) + ) + ef = loaded_config.get("embedding_function") + assert spann_config_loaded.get("space") == "l2" + assert spann_config_loaded.get("ef_construction") == 200 + assert spann_config_loaded.get("ef_search") == 200 + assert spann_config_loaded.get("max_neighbors") == 64 + assert spann_config_loaded.get("search_nprobe") == 128 + assert spann_config_loaded.get("write_nprobe") == 128 + assert ef is not None + + +def test_spann_configuration(client: ClientAPI) -> None: + """Test creating collections with SPANN configuration format""" + client.reset() + + # Create with SPANN configuration + spann_config: CreateSpannConfiguration = { + "space": "cosine", + "ef_construction": 100, + "max_neighbors": 10, + "ef_search": 20, + "search_nprobe": 5, + "write_nprobe": 10, + } + config: CreateCollectionConfiguration = { + "spann": spann_config, + "embedding_function": CustomEmbeddingFunction(dim=5), + } + + if is_spann_disabled_mode: + coll = client.create_collection( + name="test_spann_config", + configuration=config, + ) + + # Verify configuration is preserved + loaded_config = load_collection_configuration_from_json( + coll._model.configuration_json + ) + if loaded_config and isinstance(loaded_config, dict): + hnsw_config_loaded = cast( + CreateHNSWConfiguration, loaded_config.get("hnsw", {}) + ) + ef = loaded_config.get("embedding_function") + assert hnsw_config_loaded.get("space") == "cosine" + assert hnsw_config_loaded.get("ef_construction") == 100 + assert hnsw_config_loaded.get("ef_search") == 100 + assert hnsw_config_loaded.get("max_neighbors") == 16 + assert ef is not None + else: + coll = client.create_collection( + name="test_spann_config", + configuration=config, + ) + + # Verify configuration is preserved + loaded_config = load_collection_configuration_from_json( + coll._model.configuration_json + ) + if loaded_config and isinstance(loaded_config, dict): + spann_config_loaded = cast( + CreateSpannConfiguration, loaded_config.get("spann", {}) + ) + ef = loaded_config.get("embedding_function") + assert spann_config_loaded.get("space") == "cosine" + assert spann_config_loaded.get("ef_construction") == 100 + assert spann_config_loaded.get("ef_search") == 200 + assert spann_config_loaded.get("max_neighbors") == 10 + assert spann_config_loaded.get("search_nprobe") == 5 + assert spann_config_loaded.get("write_nprobe") == 10 + assert ef is not None + + +@pytest.mark.skipif(is_spann_disabled_mode, reason=skip_reason_spann_disabled) +def test_spann_configuration_persistence(client_factories: "ClientFactories") -> None: + """Test SPANN configuration persistence across client restarts""" + client = client_factories.create_client_from_system() + client.reset() + + # Create collection with specific SPANN configuration + spann_config: CreateSpannConfiguration = { + "space": "cosine", + "ef_construction": 100, + "max_neighbors": 10, + "search_nprobe": 5, + "write_nprobe": 10, + } + config: CreateCollectionConfiguration = { + "spann": spann_config, + "embedding_function": CustomEmbeddingFunction(dim=5), + } + + client.create_collection( + name="test_persist_spann_config", + configuration=config, + ) + + client2 = client_factories.create_client_from_system() + + coll = client2.get_collection( + name="test_persist_spann_config", + ) + + loaded_config = load_collection_configuration_from_json( + coll._model.configuration_json + ) + if loaded_config and isinstance(loaded_config, dict): + spann_config = cast(CreateSpannConfiguration, loaded_config.get("spann", {})) + ef = loaded_config.get("embedding_function") + assert spann_config.get("space") == "cosine" + assert spann_config.get("ef_construction") == 100 + assert spann_config.get("max_neighbors") == 10 + assert spann_config.get("search_nprobe") == 5 + assert spann_config.get("write_nprobe") == 10 + assert ef is not None + + +def test_exclusive_hnsw_spann_configuration(client: ClientAPI) -> None: + """Test that HNSW and SPANN configurations cannot both be specified""" + client.reset() + + # Attempt to create with both HNSW and SPANN configurations + hnsw_config: CreateHNSWConfiguration = { + "space": "cosine", + "ef_construction": 100, + } + spann_config: CreateSpannConfiguration = { + "space": "cosine", + "search_nprobe": 5, + } + + # This validation always runs and raises ValueError if both are provided, + # regardless of whether SPANN is generally allowed or not. + with pytest.raises(ValueError, match="hnsw and spann cannot both be provided"): + client.create_collection( + name="test_dual_config", + configuration={ + "hnsw": hnsw_config, + "spann": spann_config, + }, + ) + + +def test_spann_default_parameters(client: ClientAPI) -> None: + """Test the default values for SPANN parameters""" + client.reset() + + # Create with minimal SPANN configuration + spann_config: CreateSpannConfiguration = { + "space": "cosine", + } + config: CreateCollectionConfiguration = { + "spann": spann_config, + } + + if is_spann_disabled_mode: + coll = client.create_collection( + name="test_spann_defaults", + configuration=config, + ) + + # Verify configuration is preserved + loaded_config = load_collection_configuration_from_json( + coll._model.configuration_json + ) + if loaded_config and isinstance(loaded_config, dict): + hnsw_config_loaded = cast( + CreateHNSWConfiguration, loaded_config.get("hnsw", {}) + ) + assert hnsw_config_loaded.get("space") == "cosine" + assert hnsw_config_loaded.get("ef_construction") == 100 + assert hnsw_config_loaded.get("ef_search") == 100 + assert hnsw_config_loaded.get("max_neighbors") == 16 + + ef = loaded_config.get("embedding_function") + assert ef is not None + assert ef.name() == "default" + else: + coll = client.create_collection( + name="test_spann_defaults", + configuration=config, + ) + + # Verify default values are populated + loaded_config = load_collection_configuration_from_json( + coll._model.configuration_json + ) + if loaded_config and isinstance(loaded_config, dict): + spann_config_loaded = cast( + CreateSpannConfiguration, loaded_config.get("spann", {}) + ) + assert spann_config_loaded.get("space") == "cosine" + assert spann_config_loaded.get("ef_construction") == 200 + assert spann_config_loaded.get("max_neighbors") == 16 + assert spann_config_loaded.get("ef_search") == 200 + assert spann_config_loaded.get("search_nprobe") == 128 + assert spann_config_loaded.get("write_nprobe") == 128 + + ef = loaded_config.get("embedding_function") + assert ef is not None + assert ef.name() == "default" + + +def test_spann_json_serialization(client: ClientAPI) -> None: + """Test serializing and deserializing SPANN configuration to/from JSON""" + client.reset() + + # Create JSON configuration with SPANN config + config_json = """ + { + "spann": { + "space": "cosine", + "search_nprobe": 7, + "write_nprobe": 15, + "ef_construction": 200, + "ef_search": 150 + }, + "embedding_function": { + "type": "known", + "name": "custom_ef", + "config": { + "dim": 10 + } + } + } + """ + + # Load the configuration from JSON + collection_config = load_collection_configuration_from_json(json.loads(config_json)) + + # Convert to CreateCollectionConfiguration for collection creation + create_config: CreateCollectionConfiguration = {} + if collection_config.get("spann") is not None: + create_config["spann"] = cast( + CreateSpannConfiguration, collection_config.get("spann") + ) + if collection_config.get("embedding_function") is not None: + create_config["embedding_function"] = collection_config.get( + "embedding_function" + ) + + if is_spann_disabled_mode: + coll = client.create_collection( + name="test_spann_json", + configuration=create_config, + ) + + # Verify configuration is preserved + loaded_config = load_collection_configuration_from_json( + coll._model.configuration_json + ) + if loaded_config and isinstance(loaded_config, dict): + hnsw_config_loaded = cast( + CreateHNSWConfiguration, loaded_config.get("hnsw", {}) + ) + ef = loaded_config.get("embedding_function") + assert hnsw_config_loaded.get("space") == "cosine" + assert hnsw_config_loaded.get("ef_construction") == 100 + assert hnsw_config_loaded.get("ef_search") == 100 + assert hnsw_config_loaded.get("max_neighbors") == 16 + assert ef is not None + else: + # Create collection with the converted configuration + coll = client.create_collection( + name="test_spann_json", + configuration=create_config, + ) + + # Verify the configuration was preserved correctly + loaded_config = load_collection_configuration_from_json( + coll._model.configuration_json + ) + if loaded_config and isinstance(loaded_config, dict): + spann_config_loaded = cast( + CreateSpannConfiguration, loaded_config.get("spann", {}) + ) + assert spann_config_loaded.get("space") == "cosine" + assert spann_config_loaded.get("search_nprobe") == 7 + assert spann_config_loaded.get("write_nprobe") == 15 + assert spann_config_loaded.get("ef_construction") == 200 + assert spann_config_loaded.get("ef_search") == 150 + + +@pytest.mark.skipif(is_spann_disabled_mode, reason=skip_reason_spann_disabled) +def test_configuration_spann_updates(client: ClientAPI) -> None: + """Test updating SPANN collection configurations""" + client.reset() + + # Create initial collection with SPANN + initial_spann: CreateSpannConfiguration = { + "ef_search": 100, + "search_nprobe": 10, + "space": "cosine", + } + coll = client.create_collection( + name="test_spann_updates", + configuration={"spann": initial_spann}, + ) + + # Update SPANN configuration + update_spann: UpdateSpannConfiguration = { + "ef_search": 150, + "search_nprobe": 20, + } + update_config: UpdateCollectionConfiguration = { + "spann": update_spann, + } + coll.modify(configuration=update_config) + + # Verify updates were applied + loaded_config = coll.configuration_json + if loaded_config and isinstance(loaded_config, dict): + spann_config = loaded_config.get("spann", {}) + if isinstance(spann_config, dict): + assert spann_config.get("ef_search") == 150 + assert spann_config.get("search_nprobe") == 20 + # Original values should remain unchanged + assert spann_config.get("space") == "cosine" + + coll = client.get_collection("test_spann_updates") + loaded_config = coll.configuration_json + if loaded_config and isinstance(loaded_config, dict): + spann_config = loaded_config.get("spann", {}) + if isinstance(spann_config, dict): + assert spann_config.get("ef_search") == 150 + assert spann_config.get("search_nprobe") == 20 + assert spann_config.get("space") == "cosine" + + +@pytest.mark.skipif(is_spann_disabled_mode, reason=skip_reason_spann_disabled) +def test_spann_update_from_json(client: ClientAPI) -> None: + """Test updating SPANN configuration from JSON and applying it""" + client.reset() + + # Create initial collection with SPANN + initial_spann: CreateSpannConfiguration = { + "ef_search": 100, + "search_nprobe": 10, + "space": "cosine", + "ef_construction": 150, + "max_neighbors": 12, + "write_nprobe": 20, + } + coll = client.create_collection( + name="test_spann_json_update", + configuration={"spann": initial_spann}, + ) + + update_config = UpdateCollectionConfiguration( + spann=UpdateSpannConfiguration( + search_nprobe=15, + ef_search=200, + ) + ) + + # Apply the update + coll.modify(configuration=update_config) + + # Verify updates were applied + loaded_config = coll.configuration_json + if loaded_config and isinstance(loaded_config, dict): + spann_config = loaded_config.get("spann", {}) + if isinstance(spann_config, dict): + # Updated values + assert spann_config.get("ef_search") == 200 + assert spann_config.get("search_nprobe") == 15 + + # Unchanged values + assert spann_config.get("space") == "cosine" + assert spann_config.get("ef_construction") == 150 + assert spann_config.get("max_neighbors") == 12 + assert spann_config.get("write_nprobe") == 20 + + coll = client.get_collection("test_spann_json_update") + loaded_config = coll.configuration_json + if loaded_config and isinstance(loaded_config, dict): + spann_config = loaded_config.get("spann", {}) + if isinstance(spann_config, dict): + # Updated values + assert spann_config.get("ef_search") == 200 + assert spann_config.get("search_nprobe") == 15 + + # Unchanged values + assert spann_config.get("space") == "cosine" + assert spann_config.get("ef_construction") == 150 + assert spann_config.get("max_neighbors") == 12 + assert spann_config.get("write_nprobe") == 20 + + +def test_overwrite_spann_configuration() -> None: + """Test the overwrite_spann_configuration function directly""" + # Create original SPANN configuration + original_config: SpannConfiguration = { + "space": "cosine", + "search_nprobe": 10, + "write_nprobe": 20, + "ef_construction": 150, + "ef_search": 100, + "max_neighbors": 16, + } + + # Create update configuration with only a few fields + update_config: UpdateSpannConfiguration = { + "search_nprobe": 15, + "ef_search": 200, + } + + # Apply the update + updated_config = overwrite_spann_configuration(original_config, update_config) + + # Verify updated fields + assert updated_config.get("search_nprobe") == 15 + assert updated_config.get("ef_search") == 200 + + # Verify other fields remain unchanged + assert updated_config.get("space") == "cosine" + assert updated_config.get("write_nprobe") == 20 + assert updated_config.get("ef_construction") == 150 + assert updated_config.get("max_neighbors") == 16 + + +@pytest.mark.skipif(is_spann_disabled_mode, reason=skip_reason_spann_disabled) +def test_exclusive_update_hnsw_spann_configuration(client: ClientAPI) -> None: + """Test that HNSW and SPANN configurations cannot both be specified in an update""" + client.reset() + + # Create initial collection with HNSW + initial_hnsw: CreateHNSWConfiguration = { + "ef_search": 10, + "space": "cosine", + } + coll = client.create_collection( + name="test_exclusive_update", + configuration={"hnsw": initial_hnsw}, + ) + + # Try to update with both HNSW and SPANN + update_hnsw: UpdateHNSWConfiguration = { + "ef_search": 20, + } + update_spann: UpdateSpannConfiguration = { + "search_nprobe": 15, + } + update_config: UpdateCollectionConfiguration = { + "hnsw": update_hnsw, + "spann": update_spann, + } + + # This should raise a ValueError + with pytest.raises(ValueError): + coll.modify(configuration=update_config) + + +def test_default_collection_creation(client: ClientAPI) -> None: + """Test creating a collection with default values""" + client.reset() + + coll = client.create_collection(name="test_default_creation") + assert coll is not None + + assert coll.configuration_json is not None + config = load_collection_configuration_from_json(coll.configuration_json) + assert config is not None + hnsw_config = config.get("hnsw") + assert hnsw_config is not None + assert hnsw_config.get("space") == "l2" + assert hnsw_config.get("ef_construction") == 100 + assert hnsw_config.get("max_neighbors") == 16 + assert hnsw_config.get("ef_search") == 100 + # assert hnsw_config.get("batch_size") == 100 + assert hnsw_config.get("sync_threshold") == 1000 + + assert config.get("spann") is None + ef = config.get("embedding_function") + assert ef is not None + assert ef.name() == "default" + + +def test_invalid_configuration() -> None: + """Test that on an invalid configuration, an error is raised""" + invalid_config: Dict[str, Any] = { + "hnsw": { + "space": "l2", + "ef_construction": 100, + "ef_search": 100, + "max_neighbors": 16, + "resize_factor": 1.2, + "sync_threshold": 1000, + }, + "spann": None, + "embedding_function": { + "name": "custom_ef", + "type": "known", + "config": {}, + }, + } + with pytest.raises(ValueError): + load_collection_configuration_from_json(invalid_config) + + +def test_collection_load_with_invalid_configuration(client: ClientAPI) -> None: + """ + When an invalid confiugration is used, collection create, get, list_collections should all pass + Only when trying to use the collection should an error be reaised + """ + client.reset() + + # Create a collection with a valid configuration first + coll = client.create_collection(name="test_invalid_config") + + # Simulate an invalid configuration by directly modifying the collection model + # This mimics what would happen if a collection was created with invalid config + # and stored in the database + invalid_config_json = { + "embedding_function": { + "name": "custom_ef", + "type": "known", + "config": {}, + } + } + + invalid_collection = CollectionModel( + id=coll.id, + name="test_invalid_config_collection", + configuration_json=invalid_config_json, + serialized_schema=None, + metadata=None, + dimension=None, + tenant=coll.tenant, + database=coll.database, + ) + + assert invalid_collection is not None + assert invalid_collection.name == "test_invalid_config_collection" + assert invalid_collection.configuration_json == invalid_config_json + + coll._model = invalid_collection + + with pytest.raises(ValueError): + coll.add(ids=["1"], documents=["test"]) + + with pytest.raises(ValueError): + coll.query(query_texts=["test"], n_results=1) + + +def test_configuration_json_vs_configuration_property_consistency( + client: ClientAPI, +) -> None: + """Test that configuration_json and configuration properties are consistent""" + client.reset() + + config: CreateCollectionConfiguration = { + "embedding_function": CustomEmbeddingFunction(dim=8), + } + + coll = client.create_collection( + name="test_config_consistency", + configuration=config, + ) + + # Get both raw JSON and processed configuration + config_json = coll.configuration_json + config_processed = coll.configuration + + assert "embedding_function" in config_json + + # Verify embedding function consistency + ef_json = config_json.get("embedding_function") + ef_processed = config_processed.get("embedding_function") + assert ef_json is not None + assert ef_processed is not None + assert ef_json.get("type") == "known" + assert ef_json.get("name") == "custom_ef" + assert ef_processed.name() == "custom_ef" + assert ef_processed.get_config() == ef_json.get("config") + + +def test_default_configuration_json_vs_configuration_property_consistency( + client: ClientAPI, +) -> None: + """Test that default configuration_json and configuration properties are consistent""" + client.reset() + + # Create collection with default configuration + coll = client.create_collection(name="test_default_config_consistency") + + # Get both raw JSON and processed configuration + config_json = coll.configuration_json + config_processed = coll.configuration + + assert "embedding_function" in config_json + + # Verify default embedding function + ef_json = config_json.get("embedding_function") + ef_processed = config_processed.get("embedding_function") + assert ef_json is not None + assert ef_processed is not None + assert ef_json.get("type") == "known" + assert ef_json.get("name") == "default" + assert ef_processed.name() == "default" + + +def test_invalid_configuration_operations_succeed_until_embed( + client: ClientAPI, +) -> None: + """ + Test that invalid configurations allow list_collections, get_collection to succeed, + but fail when _embed is called (during add, query, upsert operations) + """ + client.reset() + + # Create a collection with valid configuration first + coll = client.create_collection(name="test_invalid_operations") + + # Create collections with various invalid configurations + # and verify which operations succeed vs fail + invalid_configs: List[Dict[str, Any]] = [ + # Missing embedding function config + { + "embedding_function": { + "name": "nonexistent_ef", + "type": "known", + "config": {}, + } + }, + # Malformed embedding function config + { + "embedding_function": { + "type": "known", + # Missing 'name' field + "config": {"dim": 3}, + } + }, + # HNSW and SPANN both present (invalid) + { + "hnsw": {"space": "l2"}, + "spann": {"space": "cosine"}, + "embedding_function": {"type": "legacy"}, + }, + ] + + for i, invalid_config in enumerate(invalid_configs): + # Simulate an invalid configuration by directly modifying the collection model + invalid_collection_model = CollectionModel( + id=coll.id, + name=f"test_invalid_config_{i}", + configuration_json=invalid_config, + serialized_schema=None, + metadata=None, + dimension=None, + tenant=coll.tenant, + database=coll.database, + ) + + coll._model = invalid_collection_model + + # These operations should succeed (they don't process configuration) + assert coll.id == invalid_collection_model.id + assert coll.name == f"test_invalid_config_{i}" + assert coll.configuration_json == invalid_config + + with pytest.raises(ValueError): + coll.configuration + + with pytest.raises(ValueError): + coll.add(ids=["1"], documents=["test"]) + + with pytest.raises(ValueError): + coll.query(query_texts=["test"], n_results=1) + + with pytest.raises(ValueError): + coll.upsert(ids=["1"], documents=["test"]) + + with pytest.raises(ValueError): + coll._embed(["test"]) + + +def test_get_collection_with_invalid_configuration(client: ClientAPI) -> None: + """ + Test that get_collection works even with invalid configurations, + but operations that require _embed fail + """ + client.reset() + + # Create a valid collection first + valid_coll = client.create_collection( + name="test_get_invalid", + configuration={"embedding_function": CustomEmbeddingFunction(dim=4)}, + ) + + # Simulate database corruption or invalid configuration + # by directly modifying the model's configuration + invalid_config = { + "embedding_function": { + "name": "nonexistent_function", + "type": "known", + "config": {"dim": 4}, + } + } + + # Update the collection's configuration to be invalid + valid_coll._model.configuration_json = invalid_config + + # get_collection-like operations should still work + assert valid_coll.name == "test_get_invalid" + assert valid_coll.id is not None + assert valid_coll.configuration_json == invalid_config + assert valid_coll.tenant is not None + assert valid_coll.database is not None + + # But operations requiring embedding should fail + with pytest.raises(ValueError): + valid_coll.add(ids=["test"], documents=["test doc"]) + + with pytest.raises(ValueError): + valid_coll.query(query_texts=["test"], n_results=1) + + with pytest.raises(ValueError): + valid_coll.upsert(ids=["test"], documents=["test doc"]) + + # Accessing configuration property should also fail + with pytest.raises(ValueError): + _ = valid_coll.configuration + + +def test_ef_no_config(client: ClientAPI) -> None: + """Test creating a collection with no EF in config.""" + client.reset() + coll = client.create_collection( + name="test_no_config", embedding_function=CustomEmbeddingFunction(dim=3) + ) + assert coll is not None + ef = coll.configuration.get("embedding_function") + assert ef is not None + assert ef.name() == "custom_ef" + assert ef.get_config() == {"dim": 3} + + coll = client.get_or_create_collection( + name="test_no_config", embedding_function=CustomEmbeddingFunction(dim=3) + ) + assert coll is not None + ef = coll.configuration.get("embedding_function") + assert ef is not None + assert ef.name() == "custom_ef" + assert ef.get_config() == {"dim": 3} + + coll = client.get_collection(name="test_no_config") + ef = coll.configuration.get("embedding_function") + assert ef is not None + assert ef.name() == "custom_ef" + assert ef.get_config() == {"dim": 3} + + +def test_ef_with_config_exists_no_ef(client: ClientAPI) -> None: + """Test creating a collection with EF in parameter, no EF in config.""" + client.reset() + coll = client.create_collection( + name="test_ef_with_config_exists_no_ef", + embedding_function=CustomEmbeddingFunction(dim=3), + configuration={"hnsw": {"space": "cosine"}}, + ) + assert coll is not None + ef = coll.configuration.get("embedding_function") + assert ef is not None + assert ef.name() == "custom_ef" + assert ef.get_config() == {"dim": 3} + + coll = client.get_or_create_collection( + name="test_ef_with_config_exists_no_ef", + embedding_function=CustomEmbeddingFunction(dim=3), + configuration={"hnsw": {"space": "cosine"}}, + ) + assert coll is not None + ef = coll.configuration.get("embedding_function") + assert ef is not None + assert ef.name() == "custom_ef" + assert ef.get_config() == {"dim": 3} + + coll = client.get_collection(name="test_ef_with_config_exists_no_ef") + ef = coll.configuration.get("embedding_function") + assert ef is not None + assert ef.name() == "custom_ef" + assert ef.get_config() == {"dim": 3} + + +def test_ef_with_config_exists_with_ef_valid(client: ClientAPI) -> None: + """Test creating a collection with EF in parameter, EF in config. They are the same.""" + client.reset() + coll = client.create_collection( + name="test_ef_with_config_exists_with_ef", + embedding_function=CustomEmbeddingFunction(dim=3), + configuration={ + "hnsw": {"space": "cosine"}, + "embedding_function": CustomEmbeddingFunction(dim=3), + }, + ) + assert coll is not None + ef = coll.configuration.get("embedding_function") + assert ef is not None + assert ef.name() == "custom_ef" + assert ef.get_config() == {"dim": 3} + + coll = client.get_or_create_collection( + name="test_ef_with_config_exists_with_ef", + embedding_function=CustomEmbeddingFunction(dim=3), + configuration={ + "hnsw": {"space": "cosine"}, + "embedding_function": CustomEmbeddingFunction(dim=3), + }, + ) + assert coll is not None + ef = coll.configuration.get("embedding_function") + assert ef is not None + assert ef.name() == "custom_ef" + assert ef.get_config() == {"dim": 3} + + coll = client.get_collection(name="test_ef_with_config_exists_with_ef") + ef = coll.configuration.get("embedding_function") + assert ef is not None + assert ef.name() == "custom_ef" + assert ef.get_config() == {"dim": 3} + + +def test_create_ef_with_config_exists_with_ef_invalid(client: ClientAPI) -> None: + """Test creating a collection with EF in parameter, EF in config. They are different.""" + client.reset() + with pytest.raises(ValueError): + client.create_collection( + name="test_ef_with_config_exists_with_ef", + embedding_function=CustomEmbeddingFunction(dim=3), + configuration={ + "hnsw": {"space": "cosine"}, + "embedding_function": CustomEmbeddingFunction2(dim=3), + }, + ) + + +def test_get_or_create_ef_with_config_exists_with_ef_invalid(client: ClientAPI) -> None: + """Test get_or_create with EF in parameter, EF in config. They are different.""" + client.reset() + with pytest.raises(ValueError): + client.get_or_create_collection( + name="test_ef_with_config_exists_with_ef", + embedding_function=CustomEmbeddingFunction(dim=3), + configuration={ + "hnsw": {"space": "cosine"}, + "embedding_function": CustomEmbeddingFunction2(dim=3), + }, + ) + + +def test_get_collection_ef_with_config_exists_with_ef_invalid( + client: ClientAPI, +) -> None: + """Test get_collection with EF in parameter, EF in config. They are different.""" + client.reset() + client.create_collection( + name="test_ef_with_config_exists_with_ef", + configuration={ + "hnsw": {"space": "cosine"}, + "embedding_function": CustomEmbeddingFunction2(dim=3), + }, + ) + with pytest.raises(ValueError): + client.get_collection( + name="test_ef_with_config_exists_with_ef", + embedding_function=CustomEmbeddingFunction(dim=3), + ) + + +def test_get_or_create_after_create_with_ef(client: ClientAPI) -> None: + """ + After creating a collection with an embedding function, + get_or_create should raise an error before and after retrieval, if they had provided + a different embedding function or if it differs from the persisted one. + """ + client.reset() + coll = client.create_collection( + name="test_get_or_create_after_create_with_ef", + embedding_function=CustomEmbeddingFunction(dim=3), + ) + assert coll is not None + ef = coll.configuration.get("embedding_function") + assert ef is not None + assert ef.name() == "custom_ef" + assert ef.get_config() == {"dim": 3} + + with pytest.raises(ValueError): + client.get_or_create_collection( + name="test_get_or_create_after_create_with_ef", + embedding_function=CustomEmbeddingFunction2(dim=3), + configuration={"embedding_function": CustomEmbeddingFunction(dim=3)}, + ) + + with pytest.raises(ValueError): + client.get_or_create_collection( + name="test_get_or_create_after_create_with_ef", + embedding_function=CustomEmbeddingFunction2(dim=3), + ) + + +@register_embedding_function +class DefaultSpaceCustomEmbeddingFunction(EmbeddingFunction[Embeddable]): + def __init__(self, model_name: str, dim: int = 3): + self._dim = dim + self._model_name = model_name + + def __call__(self, input: Embeddable) -> Embeddings: + return cast(Embeddings, np.array([[1.0] * self._dim], dtype=np.float32)) + + @staticmethod + def name() -> str: + return "default_space_custom_ef" + + def get_config(self) -> Dict[str, Any]: + return {"model_name": self._model_name, "dim": self._dim} + + @staticmethod + def build_from_config( + config: Dict[str, Any] + ) -> "DefaultSpaceCustomEmbeddingFunction": + return DefaultSpaceCustomEmbeddingFunction( + model_name=config["model_name"], dim=config["dim"] + ) + + def default_space(self) -> Space: + if self._model_name == "i_want_cosine": + return "cosine" + elif self._model_name == "i_want_l2": + return "l2" + elif self._model_name == "i_want_ip": + return "ip" + else: + return "cosine" + + def supported_spaces(self) -> List[Space]: + if self._model_name == "i_want_cosine": + return ["cosine"] + elif self._model_name == "i_want_l2": + return ["l2"] + elif self._model_name == "i_want_ip": + return ["ip"] + elif self._model_name == "i_want_anything": + return ["cosine", "l2", "ip"] + else: + return ["cosine", "l2", "ip"] + + +def test_default_space_custom_embedding_function_no_config(client: ClientAPI) -> None: + client.reset() + coll = client.create_collection( + name="test_default_space_custom_embedding_function", + embedding_function=DefaultSpaceCustomEmbeddingFunction( + model_name="i_want_cosine", dim=3 + ), + ) + assert coll is not None + ef = coll.configuration.get("embedding_function") + assert ef is not None + assert ef.name() == "default_space_custom_ef" + assert ef.get_config() == {"model_name": "i_want_cosine", "dim": 3} + assert ef.default_space() == "cosine" + assert ef.supported_spaces() == ["cosine"] + + if is_spann_disabled_mode: + hnsw_config = coll.configuration.get("hnsw") + assert hnsw_config is not None + assert hnsw_config.get("space") == "cosine" + else: + spann_config = coll.configuration.get("spann") + assert spann_config is not None + assert spann_config.get("space") == "cosine" + + coll = client.get_or_create_collection( + name="test_default_space_custom_embedding_function_l2", + embedding_function=DefaultSpaceCustomEmbeddingFunction( + model_name="i_want_l2", dim=3 + ), + ) + assert coll is not None + ef = coll.configuration.get("embedding_function") + assert ef is not None + assert ef.name() == "default_space_custom_ef" + assert ef.get_config() == {"model_name": "i_want_l2", "dim": 3} + assert ef.default_space() == "l2" + assert ef.supported_spaces() == ["l2"] + + if is_spann_disabled_mode: + hnsw_config = coll.configuration.get("hnsw") + assert hnsw_config is not None + assert hnsw_config.get("space") == "l2" + else: + spann_config = coll.configuration.get("spann") + assert spann_config is not None + assert spann_config.get("space") == "l2" + + coll = client.get_or_create_collection( + name="test_default_space_custom_embedding_function_ip", + embedding_function=DefaultSpaceCustomEmbeddingFunction( + model_name="i_want_ip", dim=3 + ), + ) + assert coll is not None + ef = coll.configuration.get("embedding_function") + assert ef is not None + assert ef.name() == "default_space_custom_ef" + assert ef.get_config() == {"model_name": "i_want_ip", "dim": 3} + assert ef.default_space() == "ip" + assert ef.supported_spaces() == ["ip"] + + if is_spann_disabled_mode: + hnsw_config = coll.configuration.get("hnsw") + assert hnsw_config is not None + assert hnsw_config.get("space") == "ip" + else: + spann_config = coll.configuration.get("spann") + assert spann_config is not None + assert spann_config.get("space") == "ip" + + coll = client.get_or_create_collection( + name="test_default_space_custom_embedding_function_anything", + embedding_function=DefaultSpaceCustomEmbeddingFunction( + model_name="i_want_anything", dim=3 + ), + ) + assert coll is not None + ef = coll.configuration.get("embedding_function") + assert ef is not None + assert ef.name() == "default_space_custom_ef" + assert ef.get_config() == {"model_name": "i_want_anything", "dim": 3} + assert ef.default_space() == "cosine" + assert ef.supported_spaces() == ["cosine", "l2", "ip"] + + if is_spann_disabled_mode: + hnsw_config = coll.configuration.get("hnsw") + assert hnsw_config is not None + assert hnsw_config.get("space") == "cosine" + else: + spann_config = coll.configuration.get("spann") + assert spann_config is not None + assert spann_config.get("space") == "cosine" + + +def test_default_space_custom_embedding_function_with_valid_config( + client: ClientAPI, +) -> None: + client.reset() + if is_spann_disabled_mode: + coll = client.create_collection( + name="test_default_space_custom_embedding_function_with_valid_config", + embedding_function=DefaultSpaceCustomEmbeddingFunction( + model_name="i_want_anything", dim=3 + ), + configuration={"hnsw": {"space": "l2"}}, + ) + else: + coll = client.create_collection( + name="test_default_space_custom_embedding_function_with_valid_config", + embedding_function=DefaultSpaceCustomEmbeddingFunction( + model_name="i_want_anything", dim=3 + ), + configuration={"spann": {"space": "l2"}}, + ) + + assert coll is not None + ef = coll.configuration.get("embedding_function") + assert ef is not None + assert ef.name() == "default_space_custom_ef" + assert ef.get_config() == {"model_name": "i_want_anything", "dim": 3} + assert ef.default_space() == "cosine" + assert ef.supported_spaces() == ["cosine", "l2", "ip"] + + if is_spann_disabled_mode: + hnsw_config = coll.configuration.get("hnsw") + assert hnsw_config is not None + assert hnsw_config.get("space") == "l2" + else: + spann_config = coll.configuration.get("spann") + assert spann_config is not None + assert spann_config.get("space") == "l2" + + +def test_default_space_custom_embedding_function_with_invalid_config( + client: ClientAPI, +) -> None: + client.reset() + with warnings.catch_warnings(record=True) as w: + warnings.simplefilter("always") + + if is_spann_disabled_mode: + coll = client.get_or_create_collection( + name="test_default_space_custom_embedding_function_with_invalid_config", + embedding_function=DefaultSpaceCustomEmbeddingFunction( + model_name="i_want_cosine", dim=3 + ), + configuration={"hnsw": {"space": "l2"}}, + ) + else: + coll = client.get_or_create_collection( + name="test_default_space_custom_embedding_function_with_invalid_config", + embedding_function=DefaultSpaceCustomEmbeddingFunction( + model_name="i_want_cosine", dim=3 + ), + configuration={"spann": {"space": "l2"}}, + ) + + assert len(w) > 0 + warning_messages = [str(warning.message) for warning in w] + assert any( + "space l2 is not supported" in msg.lower() for msg in warning_messages + ) + + assert coll is not None + ef = coll.configuration.get("embedding_function") + assert ef is not None + assert ef.name() == "default_space_custom_ef" + + if is_spann_disabled_mode: + hnsw_config = coll.configuration.get("hnsw") + assert hnsw_config is not None + assert hnsw_config.get("space") == "l2" + else: + spann_config = coll.configuration.get("spann") + assert spann_config is not None + assert spann_config.get("space") == "l2" + + +def test_default_space_custom_embedding_function_with_metadata( + client: ClientAPI, +) -> None: + client.reset() + coll = client.create_collection( + name="test_default_space_custom_embedding_function_with_metadata", + embedding_function=DefaultSpaceCustomEmbeddingFunction( + model_name="i_want_anything", dim=3 + ), + metadata={"hnsw:space": "ip"}, + ) + + assert coll is not None + ef = coll.configuration.get("embedding_function") + assert ef is not None + assert ef.name() == "default_space_custom_ef" + assert ef.get_config() == {"model_name": "i_want_anything", "dim": 3} + assert ef.default_space() == "cosine" + assert ef.supported_spaces() == ["cosine", "l2", "ip"] + + if is_spann_disabled_mode: + hnsw_config = coll.configuration.get("hnsw") + assert hnsw_config is not None + assert hnsw_config.get("space") == "ip" + else: + spann_config = coll.configuration.get("spann") + assert spann_config is not None + assert spann_config.get("space") == "ip" + + +def test_default_space_custom_embedding_function_with_invalid_metadata( + client: ClientAPI, +) -> None: + client.reset() + with warnings.catch_warnings(record=True) as w: + warnings.simplefilter("always") + + coll = client.create_collection( + name="test_default_space_custom_embedding_function_with_invalid_metadata", + embedding_function=DefaultSpaceCustomEmbeddingFunction( + model_name="i_want_cosine", dim=3 + ), + metadata={"hnsw:space": "l2"}, + ) + + assert len(w) > 0 + warning_messages = [str(warning.message) for warning in w] + assert any( + "space l2 is not supported" in msg.lower() for msg in warning_messages + ) + + assert coll is not None + ef = coll.configuration.get("embedding_function") + assert ef is not None + assert ef.name() == "default_space_custom_ef" + assert ef.get_config() == {"model_name": "i_want_cosine", "dim": 3} + assert ef.default_space() == "cosine" + assert ef.supported_spaces() == ["cosine"] + + if is_spann_disabled_mode: + hnsw_config = coll.configuration.get("hnsw") + assert hnsw_config is not None + assert hnsw_config.get("space") == "l2" + else: + spann_config = coll.configuration.get("spann") + assert spann_config is not None + assert spann_config.get("space") == "l2" + + +def test_default_space_custom_embedding_function_with_metadata_and_config( + client: ClientAPI, +) -> None: + client.reset() + coll = client.create_collection( + name="test_default_space_custom_embedding_function_with_metadata_and_config", + configuration={"hnsw": {"space": "ip"}}, + embedding_function=DefaultSpaceCustomEmbeddingFunction( + model_name="i_want_anything", dim=3 + ), + metadata={"hnsw:space": "l2"}, + ) + + assert coll is not None + ef = coll.configuration.get("embedding_function") + assert ef is not None + assert ef.name() == "default_space_custom_ef" + assert ef.get_config() == {"model_name": "i_want_anything", "dim": 3} + assert ef.default_space() == "cosine" + assert ef.supported_spaces() == ["cosine", "l2", "ip"] + + if is_spann_disabled_mode: + hnsw_config = coll.configuration.get("hnsw") + assert hnsw_config is not None + assert hnsw_config.get("space") == "ip" + else: + spann_config = coll.configuration.get("spann") + assert spann_config is not None + assert spann_config.get("space") == "ip" + + +class CustomEmbeddingFunctionQueryConfig(TypedDict): + task: str + + +@register_embedding_function +class CustomEmbeddingFunctionWithQueryConfig(EmbeddingFunction[Embeddable]): + def __init__( + self, + task: str, + model_name: str, + dim: int = 3, + query_config: Optional[CustomEmbeddingFunctionQueryConfig] = None, + ): + self._dim = dim + self._model_name = model_name + self._task = task + self._query_config = query_config + + def __call__(self, input: Embeddable) -> Embeddings: + return cast(Embeddings, np.array([[1.0] * self._dim], dtype=np.float32)) + + def embed_query(self, input: Embeddable) -> Embeddings: + if self._query_config is not None and self._query_config.get("task") == "query": + return cast(Embeddings, np.array([[2.0] * self._dim], dtype=np.float32)) + else: + return self.__call__(input) + + @staticmethod + def name() -> str: + return "custom_ef_with_query_config" + + def get_config(self) -> Dict[str, Any]: + return { + "model_name": self._model_name, + "dim": self._dim, + "task": self._task, + "query_config": self._query_config, + } + + @staticmethod + def build_from_config( + config: Dict[str, Any] + ) -> "CustomEmbeddingFunctionWithQueryConfig": + model_name = config.get("model_name") + dim = config.get("dim") + task = config.get("task") + query_config = config.get("query_config") + + if model_name is None or dim is None: + assert False, "This code should not be reached" + + return CustomEmbeddingFunctionWithQueryConfig( + model_name=model_name, dim=dim, task=task, query_config=query_config # type: ignore + ) + + def default_space(self) -> Space: + return "cosine" + + def supported_spaces(self) -> List[Space]: + return ["cosine"] + + +def test_custom_embedding_function_with_query_config(client: ClientAPI) -> None: + client.reset() + coll = client.create_collection( + name="test_custom_embedding_function_with_query_config", + embedding_function=CustomEmbeddingFunctionWithQueryConfig( + task="document", + model_name="i_want_anything", + dim=3, + query_config={"task": "query"}, + ), + ) + assert coll is not None + ef = coll.configuration.get("embedding_function") + assert ef is not None + assert ef.name() == "custom_ef_with_query_config" + assert ef.get_config() == { + "model_name": "i_want_anything", + "dim": 3, + "task": "document", + "query_config": {"task": "query"}, + } + assert ef.default_space() == "cosine" + assert ef.supported_spaces() == ["cosine"] + assert np.array_equal( + ef.embed_query(input="How many people in Berlin?"), + np.array([[2.0, 2.0, 2.0]], dtype=np.float32), + ) + + +def test_deserializing_custom_embedding_function_with_query_config_no_query_config( + client: ClientAPI, +) -> None: + json_string = """ + { + "embedding_function": { + "type": "known", + "name": "custom_ef_with_query_config", + "config": {"model_name": "i_want_anything", "dim": 3, "task": "document"} + } + } + """ + config = load_collection_configuration_from_json(json.loads(json_string)) + assert config is not None + assert config.get("embedding_function") is not None + ef = config.get("embedding_function") + assert ef is not None + assert ef.get_config() == { + "model_name": "i_want_anything", + "dim": 3, + "task": "document", + "query_config": None, + } + assert ef.default_space() == "cosine" + assert ef.supported_spaces() == ["cosine"] + assert np.array_equal( + ef.embed_query(input="How many people in Berlin?"), + np.array([[1.0, 1.0, 1.0]], dtype=np.float32), + ) diff --git a/python/user_packages/Python313/site-packages/chromadb/test/configurations/test_configurations.py b/python/user_packages/Python313/site-packages/chromadb/test/configurations/test_configurations.py new file mode 100644 index 0000000000000000000000000000000000000000..639b614d534a873b8719c2f67ffa140d507dae74 --- /dev/null +++ b/python/user_packages/Python313/site-packages/chromadb/test/configurations/test_configurations.py @@ -0,0 +1,110 @@ +from overrides import overrides +import pytest +from chromadb.api.configuration import ( + ConfigurationInternal, + ConfigurationDefinition, + InvalidConfigurationError, + StaticParameterError, + ConfigurationParameter, + HNSWConfiguration, +) + + +class TestConfiguration(ConfigurationInternal): + definitions = { + "static_str_value": ConfigurationDefinition( + name="static_str_value", + validator=lambda value: isinstance(value, str), + is_static=True, + default_value="default", + ), + "int_value": ConfigurationDefinition( + name="int_value", + validator=lambda value: isinstance(value, int), + is_static=False, + default_value=0, + ), + } + + @overrides + def configuration_validator(self) -> None: + pass + + +def test_default_values() -> None: + default_test_configuration = TestConfiguration() + assert default_test_configuration.get_parameter("static_str_value") is not None + assert ( + default_test_configuration.get_parameter("static_str_value").value + == TestConfiguration.definitions["static_str_value"].default_value + ) + assert default_test_configuration.get_parameter("static_str_value") is not None + assert ( + default_test_configuration.get_parameter("int_value").value + == TestConfiguration.definitions["int_value"].default_value + ) + + +def test_set_values() -> None: + test_configuration = TestConfiguration() + + with pytest.raises(StaticParameterError): + test_configuration.set_parameter("static_str_value", "new_value") + test_configuration.set_parameter("int_value", 1) + assert test_configuration.get_parameter("int_value").value == 1 + + +def test_get_invalid_parameter() -> None: + test_configuration = TestConfiguration() + with pytest.raises(ValueError): + test_configuration.get_parameter("invalid_name") + + +def test_validation() -> None: + valid_parameters = [ + ConfigurationParameter(name="static_str_value", value="valid_value"), + ConfigurationParameter(name="int_value", value=1), + ] + valid_test_configuration = TestConfiguration(parameters=valid_parameters) + assert ( + valid_test_configuration.get_parameter("static_str_value").value + == "valid_value" + ) + assert valid_test_configuration.get_parameter("int_value").value == 1 + + invalid_parameter_values = [ + ConfigurationParameter(name="static_str_value", value=1.0) + ] + with pytest.raises(ValueError): + TestConfiguration(parameters=invalid_parameter_values) + + invalid_parameter_names = [ + ConfigurationParameter(name="invalid_name", value="some_value") + ] + with pytest.raises(ValueError): + TestConfiguration(parameters=invalid_parameter_names) + + +def test_configuration_validation() -> None: + class FooConfiguration(ConfigurationInternal): + definitions = { + "foo": ConfigurationDefinition( + name="foo", + validator=lambda value: isinstance(value, str), + is_static=False, + default_value="default", + ), + } + + @overrides + def configuration_validator(self) -> None: + if self.parameter_map.get("foo") != "bar": + raise InvalidConfigurationError("foo must be 'bar'") + + with pytest.raises(ValueError, match="foo must be 'bar'"): + FooConfiguration(parameters=[ConfigurationParameter(name="foo", value="baz")]) + + +def test_hnsw_validation() -> None: + with pytest.raises(ValueError, match="must be less than or equal"): + HNSWConfiguration(batch_size=500, sync_threshold=100) diff --git a/python/user_packages/Python313/site-packages/chromadb/test/conftest.py b/python/user_packages/Python313/site-packages/chromadb/test/conftest.py new file mode 100644 index 0000000000000000000000000000000000000000..eec478af4a7f6a3b4a2c959f533711a82ebd759e --- /dev/null +++ b/python/user_packages/Python313/site-packages/chromadb/test/conftest.py @@ -0,0 +1,1244 @@ +import multiprocessing +import os +import socket +import subprocess +import tempfile +import time +from typing import ( + Any, + Generator, + Iterator, + List, + Optional, + Sequence, + Tuple, + Callable, + cast, +) +from uuid import UUID + +import hypothesis +import pytest +import uvicorn +from httpx import ConnectError +from typing_extensions import Protocol + +from chromadb.api.async_fastapi import AsyncFastAPI +from chromadb.api.fastapi import FastAPI +import chromadb.server.fastapi +from chromadb.api import ClientAPI, ServerAPI, BaseAPI +from chromadb.config import DEFAULT_DATABASE, Settings, System +from chromadb.ingest import Producer +from chromadb.types import SeqId, OperationRecord +from chromadb.api.client import Client as ClientCreator, AdminClient +from chromadb.api.async_client import ( + AsyncAdminClient, + AsyncClient as AsyncClientCreator, +) +from chromadb.utils.async_to_sync import async_class_to_sync +import logging +import sys +import numpy as np +from unittest.mock import MagicMock +from pytest import MonkeyPatch +from chromadb.api.types import Documents, Embeddings +import uuid + +logger = logging.getLogger(__name__) + +VALID_PRESETS = ["fast", "normal", "slow"] +CURRENT_PRESET = os.getenv("PROPERTY_TESTING_PRESET", "fast") +HYPOTHESIS_CI_REPRODUCE_ONLY = os.getenv("CHROMA_HYPOTHESIS_CI_REPRODUCE_ONLY") == "1" + +if CURRENT_PRESET not in VALID_PRESETS: + raise ValueError( + f"Invalid property testing preset: {CURRENT_PRESET}. Must be one of {VALID_PRESETS}." + ) + +base_hypothesis_settings: dict[str, Any] = { + "deadline": 90000, + "suppress_health_check": [ + hypothesis.HealthCheck.data_too_large, + hypothesis.HealthCheck.large_base_example, + hypothesis.HealthCheck.function_scoped_fixture, + ], + "verbosity": hypothesis.Verbosity.verbose, +} + +if HYPOTHESIS_CI_REPRODUCE_ONLY: + disabled_phases = {hypothesis.Phase.shrink} + explain_phase = getattr(hypothesis.Phase, "explain", None) + if explain_phase is not None: + disabled_phases.add(explain_phase) + + base_hypothesis_settings.update( + phases=tuple( + phase for phase in hypothesis.Phase if phase not in disabled_phases + ), + print_blob=True, + ) + +hypothesis.settings.register_profile("base", **base_hypothesis_settings) + +hypothesis.settings.register_profile( + "fast", hypothesis.settings.get_profile("base"), max_examples=50 +) +# Hypothesis's default max_examples is 100 +hypothesis.settings.register_profile( + "normal", hypothesis.settings.get_profile("base"), max_examples=100 +) +hypothesis.settings.register_profile( + "slow", + hypothesis.settings.get_profile("base"), + max_examples=500, + stateful_step_count=100, +) + +hypothesis.settings.load_profile(CURRENT_PRESET) + +# Check if we are running in a mode where SPANN is disabled +# (Rust bindings test OR Rust single-node integration test) +is_spann_disabled_mode = ( + os.getenv("CHROMA_RUST_BINDINGS_TEST_ONLY") == "1" + or os.getenv("CHROMA_INTEGRATION_TEST_ONLY") == "1" +) +skip_reason_spann_disabled = ( + "SPANN creation/modification disallowed in Rust bindings or integration test mode" +) +skip_reason_spann_enabled = ( + "SPANN creation/modification allowed in Rust bindings or integration test mode" +) + + +def reset(api: BaseAPI) -> None: + api.reset() + + +def override_hypothesis_profile( + fast: Optional[hypothesis.settings] = None, + normal: Optional[hypothesis.settings] = None, + slow: Optional[hypothesis.settings] = None, +) -> Optional[hypothesis.settings]: + """Override Hypothesis settings for specific profiles. + + For example, to override max_examples only when the current profile is 'fast': + + override_hypothesis_profile( + fast=hypothesis.settings(max_examples=50), + ) + + Settings will be merged with the default/active profile. + """ + + allowable_override_keys = [ + "deadline", + "max_examples", + "stateful_step_count", + "suppress_health_check", + ] + + override_profiles = { + "fast": fast, + "normal": normal, + "slow": slow, + } + + overriding_profile = override_profiles.get(CURRENT_PRESET) + + if overriding_profile is not None: + overridden_settings = { + key: value + for key, value in overriding_profile.__dict__.items() + if key in allowable_override_keys + } + + return hypothesis.settings(hypothesis.settings.default, **overridden_settings) + + return cast(hypothesis.settings, hypothesis.settings.default) + + +NOT_CLUSTER_ONLY = os.getenv("CHROMA_CLUSTER_TEST_ONLY") != "1" +MULTI_REGION_ENABLED = not NOT_CLUSTER_ONLY and os.getenv("MULTI_REGION") == "true" +MULTI_REGION_TOPOLOGY = "tilt-spanning" +DEFAULT_MCMR_DATABASE = f"{MULTI_REGION_TOPOLOGY}+{DEFAULT_DATABASE}" +COMPACTION_SLEEP = 120 + + +def skip_if_not_cluster() -> pytest.MarkDecorator: + return pytest.mark.skipif( + NOT_CLUSTER_ONLY, + reason="Requires Kubernetes to be running with a valid config", + ) + + +def generate_self_signed_certificate() -> None: + config_path = os.path.join( + os.path.dirname(os.path.abspath(__file__)), "openssl.cnf" + ) + print(f"Config path: {config_path}") # Debug print to verify path + if not os.path.exists(config_path): + raise FileNotFoundError(f"Config file not found at {config_path}") + subprocess.run( + [ + "openssl", + "req", + "-x509", + "-newkey", + "rsa:4096", + "-keyout", + "serverkey.pem", + "-out", + "servercert.pem", + "-days", + "365", + "-nodes", + "-subj", + "/CN=localhost", + "-config", + config_path, + ] + ) + + +def find_free_port() -> int: + with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s: + s.bind(("", 0)) + s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) + return s.getsockname()[1] # type: ignore + + +def _run_server( + port: int, + is_persistent: bool = False, + persist_directory: Optional[str] = None, + chroma_server_authn_provider: Optional[str] = None, + chroma_server_authn_credentials_file: Optional[str] = None, + chroma_server_authn_credentials: Optional[str] = None, + chroma_auth_token_transport_header: Optional[str] = None, + chroma_server_authz_provider: Optional[str] = None, + chroma_server_authz_config_file: Optional[str] = None, + chroma_server_ssl_certfile: Optional[str] = None, + chroma_server_ssl_keyfile: Optional[str] = None, + chroma_overwrite_singleton_tenant_database_access_from_auth: Optional[bool] = False, +) -> None: + """Run a Chroma server locally""" + if is_persistent and persist_directory: + settings = Settings( + chroma_api_impl="chromadb.api.segment.SegmentAPI", + chroma_sysdb_impl="chromadb.db.impl.sqlite.SqliteDB", + chroma_producer_impl="chromadb.db.impl.sqlite.SqliteDB", + chroma_consumer_impl="chromadb.db.impl.sqlite.SqliteDB", + chroma_segment_manager_impl="chromadb.segment.impl.manager.local.LocalSegmentManager", + is_persistent=is_persistent, + persist_directory=persist_directory, + allow_reset=True, + chroma_server_authn_provider=chroma_server_authn_provider, + chroma_server_authn_credentials_file=chroma_server_authn_credentials_file, + chroma_server_authn_credentials=chroma_server_authn_credentials, + chroma_auth_token_transport_header=chroma_auth_token_transport_header, + chroma_server_authz_provider=chroma_server_authz_provider, + chroma_server_authz_config_file=chroma_server_authz_config_file, + chroma_overwrite_singleton_tenant_database_access_from_auth=chroma_overwrite_singleton_tenant_database_access_from_auth, + ) + else: + settings = Settings( + chroma_api_impl="chromadb.api.segment.SegmentAPI", + chroma_sysdb_impl="chromadb.db.impl.sqlite.SqliteDB", + chroma_producer_impl="chromadb.db.impl.sqlite.SqliteDB", + chroma_consumer_impl="chromadb.db.impl.sqlite.SqliteDB", + chroma_segment_manager_impl="chromadb.segment.impl.manager.local.LocalSegmentManager", + is_persistent=False, + allow_reset=True, + chroma_server_authn_provider=chroma_server_authn_provider, + chroma_server_authn_credentials_file=chroma_server_authn_credentials_file, + chroma_server_authn_credentials=chroma_server_authn_credentials, + chroma_auth_token_transport_header=chroma_auth_token_transport_header, + chroma_server_authz_provider=chroma_server_authz_provider, + chroma_server_authz_config_file=chroma_server_authz_config_file, + chroma_overwrite_singleton_tenant_database_access_from_auth=chroma_overwrite_singleton_tenant_database_access_from_auth, + ) + server = chromadb.server.fastapi.FastAPI(settings) + uvicorn.run( + server.app(), + host="0.0.0.0", + port=port, + log_level="error", + timeout_keep_alive=30, + ssl_keyfile=chroma_server_ssl_keyfile, + ssl_certfile=chroma_server_ssl_certfile, + ) + + +def _await_server(api: ServerAPI, attempts: int = 0) -> None: + try: + api.heartbeat() + except ConnectError as e: + if attempts > 15: + raise e + else: + time.sleep(4) + _await_server(api, attempts + 1) + + +def _fastapi_fixture( + is_persistent: bool = False, + chroma_api_impl: str = "chromadb.api.fastapi.FastAPI", + chroma_server_authn_provider: Optional[str] = None, + chroma_client_auth_provider: Optional[str] = None, + chroma_server_authn_credentials_file: Optional[str] = None, + chroma_server_authn_credentials: Optional[str] = None, + chroma_client_auth_credentials: Optional[str] = None, + chroma_auth_token_transport_header: Optional[str] = None, + chroma_server_authz_provider: Optional[str] = None, + chroma_server_authz_config_file: Optional[str] = None, + chroma_server_ssl_certfile: Optional[str] = None, + chroma_server_ssl_keyfile: Optional[str] = None, + chroma_overwrite_singleton_tenant_database_access_from_auth: Optional[bool] = False, +) -> Generator[System, None, None]: + """Fixture generator that launches a server in a separate process, and yields a + fastapi client connect to it""" + + port = find_free_port() + ctx = multiprocessing.get_context("spawn") + args: Tuple[ + int, + bool, + Optional[str], + Optional[str], + Optional[str], + Optional[str], + Optional[str], + Optional[str], + Optional[str], + Optional[str], + Optional[str], + Optional[bool], + ] = ( + port, + False, + None, + chroma_server_authn_provider, + chroma_server_authn_credentials_file, + chroma_server_authn_credentials, + chroma_auth_token_transport_header, + chroma_server_authz_provider, + chroma_server_authz_config_file, + chroma_server_ssl_certfile, + chroma_server_ssl_keyfile, + chroma_overwrite_singleton_tenant_database_access_from_auth, + ) + + def run(args: Any) -> Generator[System, None, None]: + proc = ctx.Process(target=_run_server, args=args, daemon=True) + proc.start() + settings = Settings( + chroma_api_impl=chroma_api_impl, + chroma_server_host="localhost", + chroma_server_http_port=port, + allow_reset=True, + chroma_client_auth_provider=chroma_client_auth_provider, + chroma_client_auth_credentials=chroma_client_auth_credentials, + chroma_auth_token_transport_header=chroma_auth_token_transport_header, + chroma_server_ssl_verify=chroma_server_ssl_certfile, + chroma_server_ssl_enabled=True if chroma_server_ssl_certfile else False, + chroma_overwrite_singleton_tenant_database_access_from_auth=chroma_overwrite_singleton_tenant_database_access_from_auth, + ) + system = System(settings) + api = system.instance(ServerAPI) + system.start() + _await_server(api if isinstance(api, FastAPI) else async_class_to_sync(api)) + yield system + system.stop() + proc.kill() + proc.join() + + if is_persistent: + persist_directory = tempfile.TemporaryDirectory() + args = ( + port, + is_persistent, + persist_directory.name, + chroma_server_authn_provider, + chroma_server_authn_credentials_file, + chroma_server_authn_credentials, + chroma_auth_token_transport_header, + chroma_server_authz_provider, + chroma_server_authz_config_file, + chroma_server_ssl_certfile, + chroma_server_ssl_keyfile, + chroma_overwrite_singleton_tenant_database_access_from_auth, + ) + + yield from run(args) + + try: + persist_directory.cleanup() + + # (Older versions of Python throw NotADirectoryError sometimes instead of PermissionError) + # (when we drop support for Python < 3.10, we should use ignore_cleanup_errors=True with the context manager instead) + except (PermissionError, NotADirectoryError) as e: + # todo: what's holding onto directory contents on Windows? + if os.name == "nt": + pass + else: + raise e + + else: + yield from run(args) + + +def fastapi() -> Generator[System, None, None]: + return _fastapi_fixture(is_persistent=False) + + +def async_fastapi() -> Generator[System, None, None]: + return _fastapi_fixture( + is_persistent=False, + chroma_api_impl="chromadb.api.async_fastapi.AsyncFastAPI", + ) + + +def fastapi_persistent() -> Generator[System, None, None]: + return _fastapi_fixture(is_persistent=True) + + +def fastapi_ssl() -> Generator[System, None, None]: + generate_self_signed_certificate() + return _fastapi_fixture( + is_persistent=False, + chroma_server_ssl_certfile="./servercert.pem", + chroma_server_ssl_keyfile="./serverkey.pem", + ) + + +def _get_server_host_port_from_env() -> Tuple[str, int]: + """Get server host and port from CHROMA_SERVER_HOST environment variable. + + Returns: + Tuple of (host, port) from environment, or defaults (localhost, 8000) if not set. + """ + port = 8000 + host = "localhost" + + if os.getenv("CHROMA_SERVER_HOST"): + host = os.getenv("CHROMA_SERVER_HOST", "").split(":")[0] + port = int(os.getenv("CHROMA_SERVER_HOST", "").split(":")[1]) + + return host, port + + +@pytest.fixture() +def basic_http_client() -> Generator[System, None, None]: + host, port = _get_server_host_port_from_env() + + settings = Settings( + chroma_api_impl="chromadb.api.fastapi.FastAPI", + chroma_server_http_port=port, + chroma_server_host=host, + allow_reset=True, + ) + system = System(settings) + api = system.instance(ServerAPI) + _await_server(api) + system.start() + yield system + system.stop() + + +def fastapi_server_basic_auth_valid_cred_single_user() -> Generator[System, None, None]: + # This (and similar usage below) should use the delete_on_close parameter + # instead of delete=False, but it's only available in Python 3.12 and later. + # We must explicitly close the file before spawning a subprocess to avoid + # file locking issues on Windows. + with tempfile.NamedTemporaryFile("w", suffix=".htpasswd", delete=False) as f: + f.write("admin:$2y$05$e5sRb6NCcSH3YfbIxe1AGu2h5K7OOd982OXKmd8WyQ3DRQ4MvpnZS\n") + f.close() + + for item in _fastapi_fixture( + is_persistent=False, + chroma_server_authn_provider="chromadb.auth.basic_authn.BasicAuthenticationServerProvider", + chroma_server_authn_credentials_file=f.name, + chroma_client_auth_provider="chromadb.auth.basic_authn.BasicAuthClientProvider", + chroma_client_auth_credentials="admin:admin", + ): + yield item + + +def fastapi_server_basic_auth_valid_cred_multiple_users() -> Generator[ + System, None, None +]: + creds = { + "user": "$2y$10$kY9hn.Wlfcj7n1Cnjmy1kuIhEFIVBsfbNWLQ5ahoKmdc2HLA4oP6i", + "user2": "$2y$10$CymQ63tic/DRj8dD82915eoM4ke3d6RaNKU4dj4IVJlHyea0yeGDS", + "admin": "$2y$05$e5sRb6NCcSH3YfbIxe1AGu2h5K7OOd982OXKmd8WyQ3DRQ4MvpnZS", + } + with tempfile.NamedTemporaryFile("w", suffix=".htpasswd", delete=False) as f: + for user, cred in creds.items(): + f.write(f"{user}:{cred}\n") + f.close() + + for item in _fastapi_fixture( + is_persistent=False, + chroma_server_authn_provider="chromadb.auth.basic_authn.BasicAuthenticationServerProvider", + chroma_server_authn_credentials_file=f.name, + chroma_client_auth_provider="chromadb.auth.basic_authn.BasicAuthClientProvider", + chroma_client_auth_credentials="admin:admin", + ): + yield item + + +def fastapi_server_basic_auth_invalid_cred() -> Generator[System, None, None]: + with tempfile.NamedTemporaryFile("w", suffix=".htpasswd", delete=False) as f: + f.write("admin:$2y$05$e5sRb6NCcSH3YfbIxe1AGu2h5K7OOd982OXKmd8WyQ3DRQ4MvpnZS\n") + f.close() + + for item in _fastapi_fixture( + is_persistent=False, + chroma_server_authn_provider="chromadb.auth.basic_authn.BasicAuthenticationServerProvider", + chroma_server_authn_credentials_file=f.name, + chroma_client_auth_provider="chromadb.auth.basic_authn.BasicAuthClientProvider", + chroma_client_auth_credentials="admin:admin1", + ): + yield item + + +def fastapi_server_basic_authn_rbac_authz() -> Generator[System, None, None]: + with tempfile.NamedTemporaryFile( + "w", suffix=".htpasswd", delete=False + ) as server_authn_file: + server_authn_file.write( + "admin:$2y$05$e5sRb6NCcSH3YfbIxe1AGu2h5K7OOd982OXKmd8WyQ3DRQ4MvpnZS\n" + ) + server_authn_file.close() + + with tempfile.NamedTemporaryFile( + "w", suffix=".authz", delete=False + ) as server_authz_file: + server_authz_file.write( + """ +roles_mapping: + admin: + actions: + [ + "system:reset", + "tenant:create_tenant", + "tenant:get_tenant", + "db:create_database", + "db:get_database", + "db:list_collections", + "db:create_collection", + "db:get_or_create_collection", + "collection:get_collection", + "collection:delete_collection", + "collection:update_collection", + "collection:add", + "collection:delete", + "collection:get", + "collection:query", + "collection:peek", + "collection:update", + "collection:upsert", + "collection:count", + ] +users: +- id: admin + role: admin + """ + ) + server_authz_file.close() + + for item in _fastapi_fixture( + is_persistent=False, + chroma_client_auth_provider="chromadb.auth.basic_authn.BasicAuthClientProvider", + chroma_client_auth_credentials="admin:admin", + chroma_server_authn_provider="chromadb.auth.basic_authn.BasicAuthenticationServerProvider", + chroma_server_authn_credentials_file=server_authn_file.name, + chroma_server_authz_provider="chromadb.auth.simple_rbac_authz.SimpleRBACAuthorizationProvider", + chroma_server_authz_config_file=server_authz_file.name, + ): + yield item + + +def fastapi_fixture_admin_and_singleton_tenant_db_user( + singleton_database: str = "singleton_database", +) -> Generator[System, None, None]: + # Check if we should connect to existing server instead of spawning a new one + if os.getenv("CHROMA_SERVER_HOST") and not NOT_CLUSTER_ONLY: + # Connect to existing Tilt instance using the same pattern as basic_http_client + host, port = _get_server_host_port_from_env() + + settings = Settings( + chroma_api_impl="chromadb.api.fastapi.FastAPI", + chroma_server_host=host, + chroma_server_http_port=port, + allow_reset=True, + chroma_client_auth_provider="chromadb.auth.token_authn.TokenAuthClientProvider", + chroma_client_auth_credentials="admin-token", + # Don't overwrite tenant/database from auth when connecting to external Tilt + chroma_overwrite_singleton_tenant_database_access_from_auth=False, + ) + system = System(settings) + api = system.instance(ServerAPI) + _await_server(api) + system.start() + yield system + return + + # Original behavior: spawn isolated server + with tempfile.NamedTemporaryFile("w", suffix=".authn", delete=False) as f: + f.write( + f""" +users: + - id: admin + tokens: + - admin-token + - id: singleton_user + tenant: singleton_tenant + databases: + - {singleton_database} + tokens: + - singleton-token +""" + ) + f.close() + + for item in _fastapi_fixture( + is_persistent=False, + chroma_overwrite_singleton_tenant_database_access_from_auth=True, + chroma_client_auth_provider="chromadb.auth.token_authn.TokenAuthClientProvider", + chroma_client_auth_credentials="admin-token", + chroma_server_authn_provider="chromadb.auth.token_authn.TokenAuthenticationServerProvider", + chroma_server_authn_credentials_file=f.name, + ): + yield item + + +@pytest.fixture() +def integration() -> Generator[System, None, None]: + """Fixture generator for returning a client configured via environmenet + variables, intended for externally configured integration tests + """ + settings = Settings( + allow_reset=True, chroma_api_impl="chromadb.api.fastapi.FastAPI" + ) + system = System(settings) + system.start() + yield system + system.stop() + + +@pytest.fixture() +def async_integration() -> Generator[System, None, None]: + """Fixture generator for returning a client configured via environmenet + variables, intended for externally configured integration tests + """ + settings = Settings( + allow_reset=True, chroma_api_impl="chromadb.api.async_fastapi.AsyncFastAPI" + ) + system = System(settings) + system.start() + yield system + system.stop() + + +@pytest.fixture(scope="function") +def python_sqlite_ephemeral() -> Generator[System, None, None]: + """Fixture generator for segment-based API using in-memory Sqlite""" + settings = Settings( + chroma_api_impl="chromadb.api.segment.SegmentAPI", + chroma_sysdb_impl="chromadb.db.impl.sqlite.SqliteDB", + chroma_producer_impl="chromadb.db.impl.sqlite.SqliteDB", + chroma_consumer_impl="chromadb.db.impl.sqlite.SqliteDB", + chroma_segment_manager_impl="chromadb.segment.impl.manager.local.LocalSegmentManager", + is_persistent=False, + allow_reset=True, + ) + system = System(settings) + system.start() + yield system + system.stop() + + +@pytest.fixture(scope="function") +def python_sqlite_persistent() -> Generator[System, None, None]: + """Fixture generator for segment-based API using persistent Sqlite""" + save_path = tempfile.TemporaryDirectory() + settings = Settings( + chroma_api_impl="chromadb.api.segment.SegmentAPI", + chroma_sysdb_impl="chromadb.db.impl.sqlite.SqliteDB", + chroma_producer_impl="chromadb.db.impl.sqlite.SqliteDB", + chroma_consumer_impl="chromadb.db.impl.sqlite.SqliteDB", + chroma_segment_manager_impl="chromadb.segment.impl.manager.local.LocalSegmentManager", + allow_reset=True, + is_persistent=True, + persist_directory=save_path.name, + ) + system = System(settings) + system.start() + yield system + system.stop() + + try: + save_path.cleanup() + + # (Older versions of Python throw NotADirectoryError sometimes instead of PermissionError) + # (when we drop support for Python < 3.10, we should use ignore_cleanup_errors=True with the context manager instead) + except (PermissionError, NotADirectoryError) as e: + # todo: what's holding onto directory contents on Windows? + if os.name == "nt": + pass + else: + raise e + + +@pytest.fixture(scope="function") +def rust_sqlite_ephemeral() -> Generator[System, None, None]: + """Fixture generator for system using ephemeral Rust bindings""" + settings = Settings( + chroma_api_impl="chromadb.api.rust.RustBindingsAPI", + chroma_sysdb_impl="chromadb.db.impl.sqlite.SqliteDB", + chroma_producer_impl="chromadb.db.impl.sqlite.SqliteDB", + chroma_consumer_impl="chromadb.db.impl.sqlite.SqliteDB", + chroma_segment_manager_impl="chromadb.segment.impl.manager.local.LocalSegmentManager", + is_persistent=False, + allow_reset=True, + persist_directory="", + ) + system = System(settings) + system.start() + yield system + system.stop() + + +@pytest.fixture(scope="function") +def rust_sqlite_persistent() -> Generator[System, None, None]: + """Fixture generator for system using Rust bindings""" + save_path = tempfile.TemporaryDirectory() + settings = Settings( + chroma_api_impl="chromadb.api.rust.RustBindingsAPI", + chroma_sysdb_impl="chromadb.db.impl.sqlite.SqliteDB", + chroma_producer_impl="chromadb.db.impl.sqlite.SqliteDB", + chroma_consumer_impl="chromadb.db.impl.sqlite.SqliteDB", + chroma_segment_manager_impl="chromadb.segment.impl.manager.local.LocalSegmentManager", + is_persistent=True, + allow_reset=True, + persist_directory=save_path.name, + ) + system = System(settings) + system.start() + yield system + system.stop() + + +@pytest.fixture( + params=["rust_sqlite_ephemeral"] + if "CHROMA_RUST_BINDINGS_TEST_ONLY" in os.environ + else ["python_sqlite_ephemeral"] +) +def sqlite(request: pytest.FixtureRequest) -> Generator[System, None, None]: + return request.getfixturevalue(request.param) # type: ignore + + +@pytest.fixture( + params=["rust_sqlite_persistent"] + if "CHROMA_RUST_BINDINGS_TEST_ONLY" in os.environ + else ["python_sqlite_persistent"] +) +def sqlite_persistent(request: pytest.FixtureRequest) -> Generator[System, None, None]: + return request.getfixturevalue(request.param) # type: ignore + + +def filtered_fixture_names() -> List[str]: + fixtures = [ + "fastapi", + "async_fastapi", + "fastapi_persistent", + "sqlite_fixture", + "sqlite_persistent", + ] + + if "CHROMA_INTEGRATION_TEST" in os.environ: + fixtures.append("integration") + fixtures.append("async_integration") + if "CHROMA_INTEGRATION_TEST_ONLY" in os.environ: + fixtures = ["integration", "async_integration"] + if "CHROMA_CLUSTER_TEST_ONLY" in os.environ: + fixtures = ["basic_http_client"] + if "CHROMA_RUST_BINDINGS_TEST_ONLY" in os.environ: + fixtures = ["rust_sqlite_ephemeral", "rust_sqlite_persistent"] + return fixtures + + +def filtered_http_server_fixture_names() -> List[str]: + fixtures = [ + fixture + for fixture in filtered_fixture_names() + if fixture + not in [ + "python_sqlite_ephemeral", + "python_sqlite_persistent", + "rust_sqlite_ephemeral", + "rust_sqlite_persistent", + ] + ] + return fixtures + + +def system_fixtures_auth() -> List[Callable[[], Generator[System, None, None]]]: + fixtures = [ + fastapi_server_basic_auth_valid_cred_single_user, + fastapi_server_basic_auth_valid_cred_multiple_users, + ] + return fixtures + + +def system_fixtures_authn_rbac_authz() -> List[ + Callable[[], Generator[System, None, None]] +]: + fixtures = [fastapi_server_basic_authn_rbac_authz] + return fixtures + + +def system_fixtures_root_and_singleton_tenant_db_user() -> List[ + Callable[[], Generator[System, None, None]] +]: + fixtures = [fastapi_fixture_admin_and_singleton_tenant_db_user] + return fixtures + + +def system_fixtures_wrong_auth() -> List[Callable[[], Generator[System, None, None]]]: + fixtures = [fastapi_server_basic_auth_invalid_cred] + return fixtures + + +def system_fixtures_ssl() -> List[Callable[[], Generator[System, None, None]]]: + fixtures = [fastapi_ssl] + return fixtures + + +@pytest.fixture(scope="module", params=system_fixtures_wrong_auth()) +def system_wrong_auth( + request: pytest.FixtureRequest, +) -> Generator[ServerAPI, None, None]: + yield from request.param() + + +@pytest.fixture(scope="module", params=system_fixtures_authn_rbac_authz()) +def system_authn_rbac_authz( + request: pytest.FixtureRequest, +) -> Generator[ServerAPI, None, None]: + yield from request.param() + + +@pytest.fixture(params=filtered_http_server_fixture_names()) +def system_http_server( + request: pytest.FixtureRequest, +) -> Generator[ServerAPI, None, None]: + return request.getfixturevalue(request.param) # type: ignore + + +@pytest.fixture(scope="function", params=filtered_fixture_names()) +def system(request: pytest.FixtureRequest) -> Generator[ServerAPI, None, None]: + return request.getfixturevalue(request.param) # type: ignore + + +@pytest.fixture(scope="module", params=system_fixtures_ssl()) +def system_ssl(request: pytest.FixtureRequest) -> Generator[ServerAPI, None, None]: + yield from request.param() + + +@pytest.fixture(scope="module", params=system_fixtures_auth()) +def system_auth(request: pytest.FixtureRequest) -> Generator[ServerAPI, None, None]: + yield from request.param() + + +@async_class_to_sync +class AsyncClientCreatorSync(AsyncClientCreator): + pass + + +@async_class_to_sync +class AsyncAdminClientSync(AsyncAdminClient): + pass + + +@pytest.fixture(scope="function") +def api(system: System) -> Generator[ServerAPI, None, None]: + system.reset_state() + api = system.instance(ServerAPI) + + if isinstance(api, AsyncFastAPI): + transformed = async_class_to_sync(api) + yield transformed + else: + yield api + + +class ClientFactories: + """This allows consuming tests to be parameterized by async/sync versions of the client and papers over the async implementation. + If you don't need to manually construct clients, use the `client` fixture instead. + """ + + _system: System + # Need to track created clients so we can call .clear_system_cache() during teardown + _created_clients: List[ClientAPI] = [] + + def __init__(self, system: System): + self._system = system + + def create_client(self, *args: Any, **kwargs: Any) -> ClientCreator: + if kwargs.get("settings") is None: + kwargs["settings"] = self._system.settings + + if kwargs.get("database") is None and MULTI_REGION_ENABLED: + kwargs["database"] = DEFAULT_MCMR_DATABASE + + if ( + self._system.settings.chroma_api_impl + == "chromadb.api.async_fastapi.AsyncFastAPI" + ): + client = cast(ClientCreator, AsyncClientCreatorSync.create(*args, **kwargs)) + self._created_clients.append(client) + return client + + client = ClientCreator(*args, **kwargs) + self._created_clients.append(client) + return client + + def create_client_from_system(self) -> ClientCreator: + if ( + self._system.settings.chroma_api_impl + == "chromadb.api.async_fastapi.AsyncFastAPI" + ): + client = cast( + ClientCreator, AsyncClientCreatorSync.from_system_async(self._system) + ) + self._created_clients.append(client) + return client + + client = ClientCreator.from_system(self._system) + self._created_clients.append(client) + return client + + def create_admin_client(self, *args: Any, **kwargs: Any) -> AdminClient: + if ( + self._system.settings.chroma_api_impl + == "chromadb.api.async_fastapi.AsyncFastAPI" + ): + client = cast(AdminClient, AsyncAdminClientSync(*args, **kwargs)) + self._created_clients.append(client) # type: ignore + return client + + client = AdminClient(*args, **kwargs) + self._created_clients.append(client) # type: ignore + return client + + def create_admin_client_from_system(self) -> AdminClient: + if ( + self._system.settings.chroma_api_impl + == "chromadb.api.async_fastapi.AsyncFastAPI" + ): + client = cast(AdminClient, AsyncAdminClientSync.from_system(self._system)) + self._created_clients.append(client) # type: ignore + return client + + client = AdminClient.from_system(self._system) + self._created_clients.append(client) # type: ignore + return client + + +@pytest.fixture(scope="function") +def client_factories(system: System) -> Generator[ClientFactories, None, None]: + system.reset_state() + + factories = ClientFactories(system) + yield factories + + while len(factories._created_clients) > 0: + client = factories._created_clients.pop() + client.clear_system_cache() + del client + + +def get_topology_name(database_name: str) -> Optional[str]: + return database_name.split("+")[0] if len(database_name.split("+")) > 1 else None + + +def create_database(client: ClientAPI, database_name: str) -> None: + admin_settings = client.get_settings() + if admin_settings.chroma_api_impl == "chromadb.api.async_fastapi.AsyncFastAPI": + admin_settings.chroma_api_impl = "chromadb.api.fastapi.FastAPI" + admin = AdminClient(admin_settings) + admin.create_database(database_name) + + +def create_isolated_database(client: ClientAPI) -> None: + """Create an isolated database for a test and updates the client to use it.""" + database = "test_" + str(uuid.uuid4()) + topo_name = get_topology_name(client.database) + if topo_name is not None: + database = topo_name + "+" + database + create_database(client, database) + client.set_database(database) + + +@pytest.fixture(scope="function") +def client(system: System, database_name: str) -> Generator[ClientAPI, None, None]: + system.reset_state() + + if system.settings.chroma_api_impl == "chromadb.api.async_fastapi.AsyncFastAPI": + client = cast( + Any, + AsyncClientCreatorSync.from_system_async(system, database=database_name), + ) + else: + client = ClientCreator.from_system(system, database=database_name) + + yield client + client.clear_system_cache() + + +@pytest.fixture +def database_name(request: pytest.FixtureRequest) -> str: + return cast(str, request.param) + + +def pytest_generate_tests(metafunc: pytest.Metafunc) -> None: + """Parameterize database_name based on whether the test opted in to multi-region.""" + if "database_name" in metafunc.fixturenames: + params = [pytest.param(DEFAULT_DATABASE, id="classic")] + if MULTI_REGION_ENABLED and metafunc.definition.get_closest_marker( + "test_with_multi_region" + ): + params.append( + pytest.param( + DEFAULT_MCMR_DATABASE, + id="multi-region-db", + marks=pytest.mark.test_with_multi_region, + ) + ) + metafunc.parametrize("database_name", params, indirect=True) + + +def multi_region_test(test_func: Callable[..., Any]) -> Any: + """Opt-in decorator for multi-region testing. + + If MULTI_REGION_ENABLED: Test runs with MCMR database (tilt-spanning+default_database) + If not MULTI_REGION_ENABLED: Test runs with default database only + """ + return pytest.mark.test_with_multi_region(test_func) + + +# For backward compatibility, also provide test_with_multi_region +test_with_multi_region = multi_region_test + + +def pytest_itemcollected(item: pytest.Item) -> None: + """Modify test names to show database type""" + if hasattr(item, "iter_markers"): + for marker in item.iter_markers(): + if marker.name == "test_with_multi_region": + # Add multi-region suffix to test node ID + suffix = "[multi-region]" if MULTI_REGION_ENABLED else "[single-region]" + item._nodeid = f"{item._nodeid}{suffix}" + break + else: + # No multi-region marker, show single-region + item._nodeid = f"{item._nodeid}[single-region]" + + +@pytest.fixture(scope="function") +def http_client( + system_http_server: System, database_name: str +) -> Generator[ClientAPI, None, None]: + system_http_server.reset_state() + + if ( + system_http_server.settings.chroma_api_impl + == "chromadb.api.async_fastapi.AsyncFastAPI" + ): + client = cast( + Any, + AsyncClientCreatorSync.from_system_async( + system_http_server, database=database_name + ), + ) + yield client + client.clear_system_cache() + else: + client = ClientCreator.from_system(system_http_server, database=database_name) + yield client + client.clear_system_cache() + + +@pytest.fixture(scope="function") +def client_ssl(system_ssl: System) -> Generator[ClientAPI, None, None]: + system_ssl.reset_state() + client = ClientCreator.from_system(system_ssl) + yield client + client.clear_system_cache() + + +@pytest.fixture(scope="function") +def api_wrong_cred( + system_wrong_auth: System, +) -> Generator[ServerAPI, None, None]: + system_wrong_auth.reset_state() + api = system_wrong_auth.instance(ServerAPI) + yield api + + +@pytest.fixture(scope="function") +def api_with_authn_rbac_authz( + system_authn_rbac_authz: System, +) -> Generator[ServerAPI, None, None]: + system_authn_rbac_authz.reset_state() + api = system_authn_rbac_authz.instance(ServerAPI) + yield api + + +@pytest.fixture(scope="function") +def api_with_server_auth(system_auth: System) -> Generator[ServerAPI, None, None]: + _sys = system_auth + _sys.reset_state() + api = _sys.instance(ServerAPI) + yield api + + +# Producer / Consumer fixtures # + + +class ProducerFn(Protocol): + def __call__( + self, + producer: Producer, + collection_id: UUID, + embeddings: Iterator[OperationRecord], + n: int, + ) -> Tuple[Sequence[OperationRecord], Sequence[SeqId]]: ... + + +def produce_n_single( + producer: Producer, + collection_id: UUID, + embeddings: Iterator[OperationRecord], + n: int, +) -> Tuple[Sequence[OperationRecord], Sequence[SeqId]]: + submitted_embeddings = [] + seq_ids = [] + for _ in range(n): + e = next(embeddings) + seq_id = producer.submit_embedding(collection_id, e) + submitted_embeddings.append(e) + seq_ids.append(seq_id) + return submitted_embeddings, seq_ids + + +def produce_n_batch( + producer: Producer, + collection_id: UUID, + embeddings: Iterator[OperationRecord], + n: int, +) -> Tuple[Sequence[OperationRecord], Sequence[SeqId]]: + submitted_embeddings = [] + seq_ids: Sequence[SeqId] = [] + for _ in range(n): + e = next(embeddings) + submitted_embeddings.append(e) + seq_ids = producer.submit_embeddings(collection_id, submitted_embeddings) + return submitted_embeddings, seq_ids + + +def produce_fn_fixtures() -> List[ProducerFn]: + return [produce_n_single, produce_n_batch] + + +@pytest.fixture(scope="module", params=produce_fn_fixtures()) +def produce_fns( + request: pytest.FixtureRequest, +) -> Generator[ProducerFn, None, None]: + yield request.param + + +def pytest_configure(config: pytest.Config) -> None: + """Register custom markers""" + config.addinivalue_line("markers", "dual_database: run test with both databases") + config.addinivalue_line( + "markers", + "test_with_multi_region: run test with MCMR database when MULTI_REGION_ENABLED", + ) + + +def is_client_in_process(client: ClientAPI) -> bool: + """Returns True if the client is in-process (a SQLite client), False if it's out-of-process (a HTTP client).""" + return client.get_settings().chroma_server_http_port is None + + +@pytest.fixture(autouse=True) +def log_tests(request: pytest.FixtureRequest) -> Generator[None, None, None]: + """Automatically logs the start and end of each test.""" + test_name = request.node.name + logger.debug(f"Starting test: {test_name}") + + # Yield control back to the test, allowing it to execute + yield + + logger.debug(f"Finished test: {test_name}") + + +@pytest.fixture +def mock_embeddings() -> Callable[[Documents], Embeddings]: + """Return mock embeddings for testing""" + + def _mock_embeddings(input: Documents) -> Embeddings: + return [np.array([0.1, 0.2, 0.3], dtype=np.float32) for _ in input] + + return _mock_embeddings + + +@pytest.fixture +def mock_common_deps(monkeypatch: MonkeyPatch) -> MonkeyPatch: + """Mock common dependencies""" + # Create mock modules + mock_modules = { + "PIL": MagicMock(), + "torch": MagicMock(), + "openai": MagicMock(), + "cohere": MagicMock(), + "sentence_transformers": MagicMock(), + "ollama": MagicMock(), + "InstructorEmbedding": MagicMock(), + "voyageai": MagicMock(), + "text2vec": MagicMock(), + "open_clip": MagicMock(), + "boto3": MagicMock(), + } + + # Mock all modules at once using monkeypatch.setitem + monkeypatch.setattr(sys, "modules", dict(sys.modules, **mock_modules)) + + # Mock submodules and attributes + mock_attributes = { + "PIL.Image": MagicMock(), + "sentence_transformers.SentenceTransformer": MagicMock(), + "ollama.Client": MagicMock(), + "InstructorEmbedding.INSTRUCTOR": MagicMock(), + "voyageai.Client": MagicMock(), + "text2vec.SentenceModel": MagicMock(), + } + + # Setup OpenCLIP mock with specific behavior + mock_model = MagicMock() + mock_model.encode_text.return_value = np.array([[0.1, 0.2, 0.3]]) + mock_model.encode_image.return_value = np.array([[0.1, 0.2, 0.3]]) + mock_modules["open_clip"].create_model_and_transforms.return_value = ( + mock_model, + MagicMock(), + mock_model, + ) + + # Mock all attributes + for path, mock in mock_attributes.items(): + monkeypatch.setattr(path, mock, raising=False) + + return monkeypatch diff --git a/python/user_packages/Python313/site-packages/chromadb/test/data_loader/test_data_loader.py b/python/user_packages/Python313/site-packages/chromadb/test/data_loader/test_data_loader.py new file mode 100644 index 0000000000000000000000000000000000000000..10e4c69ccd8d36f1db18bb981dea592e78cae9a4 --- /dev/null +++ b/python/user_packages/Python313/site-packages/chromadb/test/data_loader/test_data_loader.py @@ -0,0 +1,122 @@ +from typing import Dict, Generator, List, Optional, Sequence, Union +import numpy as np +from numpy.typing import NDArray + +import pytest +import chromadb +from chromadb.api.types import URI, DataLoader, Documents, IDs, Image, URIs +from chromadb.api import ClientAPI +from chromadb.test.conftest import reset +from chromadb.test.ef.test_multimodal_ef import hashing_multimodal_ef + + +def encode_data(data: str) -> NDArray[np.uint8]: + return np.array(data.encode()) + + +class DefaultDataLoader(DataLoader[List[Optional[Image]]]): + def __call__(self, uris: Sequence[Optional[URI]]) -> List[Optional[Image]]: + # Convert each URI to a numpy array + return [None if uri is None else encode_data(uri) for uri in uris] + + +def record_set_with_uris(n: int = 3) -> Dict[str, Union[IDs, Documents, URIs]]: + return { + "ids": [f"{i}" for i in range(n)], + "documents": [f"document_{i}" for i in range(n)], + "uris": [f"uri_{i}" for i in range(n)], + } + + +@pytest.fixture() +def collection_with_data_loader( + client: ClientAPI, +) -> Generator[chromadb.Collection, None, None]: + reset(client) + collection = client.create_collection( + name="collection_with_data_loader", + data_loader=DefaultDataLoader(), + embedding_function=hashing_multimodal_ef(), + ) + yield collection + client.delete_collection(collection.name) + + +@pytest.fixture +def collection_without_data_loader( + client: ClientAPI, +) -> Generator[chromadb.Collection, None, None]: + reset(client) + collection = client.create_collection( + name="collection_without_data_loader", + embedding_function=hashing_multimodal_ef(), + ) + yield collection + client.delete_collection(collection.name) + + +def test_without_data_loader( + collection_without_data_loader: chromadb.Collection, + n_examples: int = 3, +) -> None: + record_set = record_set_with_uris(n=n_examples) + + # Can't embed data in URIs without a data loader + with pytest.raises(ValueError): + collection_without_data_loader.add( + ids=record_set["ids"], + uris=record_set["uris"], + ) + + # Can't get data from URIs without a data loader + with pytest.raises(ValueError): + collection_without_data_loader.get(include=["data"]) + + +def test_without_uris( + collection_with_data_loader: chromadb.Collection, n_examples: int = 3 +) -> None: + record_set = record_set_with_uris(n=n_examples) + + collection_with_data_loader.add( + ids=record_set["ids"], + documents=record_set["documents"], + ) + + get_result = collection_with_data_loader.get(include=["data"]) + + assert get_result["data"] is not None + for data in get_result["data"]: + assert data is None + + +def test_data_loader( + collection_with_data_loader: chromadb.Collection, n_examples: int = 3 +) -> None: + record_set = record_set_with_uris(n=n_examples) + + collection_with_data_loader.add( + ids=record_set["ids"], + uris=record_set["uris"], + ) + + # Get with "data" + get_result = collection_with_data_loader.get(include=["data"]) + + assert get_result["data"] is not None + for i, data in enumerate(get_result["data"]): + assert data is not None + assert data == encode_data(record_set["uris"][i]) + + # Query by URI + query_result = collection_with_data_loader.query( + query_uris=record_set["uris"], + n_results=len(record_set["uris"][0]), + include=["data", "uris"], + ) + + assert query_result["data"] is not None + for i, data in enumerate(query_result["data"][0]): + assert data is not None + assert query_result["uris"] is not None + assert data == encode_data(query_result["uris"][0][i]) diff --git a/python/user_packages/Python313/site-packages/chromadb/test/db/test_log_purge.py b/python/user_packages/Python313/site-packages/chromadb/test/db/test_log_purge.py new file mode 100644 index 0000000000000000000000000000000000000000..e2ffc0349cc0f7e4768b3c2b35ec4465b9600b34 --- /dev/null +++ b/python/user_packages/Python313/site-packages/chromadb/test/db/test_log_purge.py @@ -0,0 +1,50 @@ +from chromadb.api.client import Client +from chromadb.config import System +from chromadb.test.property import invariants + + +def test_log_purge(sqlite_persistent: System) -> None: + client = Client.from_system(sqlite_persistent) + + first_collection = client.create_collection( + "first_collection", metadata={"hnsw:sync_threshold": 10, "hnsw:batch_size": 10} + ) + second_collection = client.create_collection( + "second_collection", metadata={"hnsw:sync_threshold": 10, "hnsw:batch_size": 10} + ) + collections = [first_collection, second_collection] + + # (Does not trigger a purge) + for i in range(5): + first_collection.add(ids=str(i), embeddings=[i, i]) + + # (Should trigger a purge) + for i in range(100): + second_collection.add(ids=str(i), embeddings=[i, i]) + + # The purge of the second collection should not be blocked by the first + invariants.log_size_below_max(client._system, collections, True) + + +def test_log_purge_with_multiple_collections(sqlite_persistent: System) -> None: + client = Client.from_system(sqlite_persistent) + + first_collection = client.create_collection( + "first_collection", metadata={"hnsw:sync_threshold": 10, "hnsw:batch_size": 10} + ) + second_collection = client.create_collection( + "second_collection", metadata={"hnsw:sync_threshold": 10, "hnsw:batch_size": 10} + ) + collections = [first_collection, second_collection] + + # (Does not trigger a purge) + for i in range(15): + first_collection.add(ids=str(i), embeddings=[i, i]) + + # (Should trigger a purge) + for i in range(25): + second_collection.add(ids=str(i), embeddings=[i, i]) + + invariants.log_size_for_collections_match_expected( + client._system, collections, True + ) diff --git a/python/user_packages/Python313/site-packages/chromadb/test/distributed/README.md b/python/user_packages/Python313/site-packages/chromadb/test/distributed/README.md new file mode 100644 index 0000000000000000000000000000000000000000..112e13b66130243f0c3d5d15dc94e07ea4691630 --- /dev/null +++ b/python/user_packages/Python313/site-packages/chromadb/test/distributed/README.md @@ -0,0 +1,3 @@ +# This folder holds basic sanity checks for the distributed version of chromadb +# while it is in development. In the future, it may hold more extensive tests +# in tandem with the main test suite, targeted at the distributed version. diff --git a/python/user_packages/Python313/site-packages/chromadb/test/distributed/test_log_backpressure.py b/python/user_packages/Python313/site-packages/chromadb/test/distributed/test_log_backpressure.py new file mode 100644 index 0000000000000000000000000000000000000000..fa979f6a7d7b904f5266a5ba51cbd616b5c725e7 --- /dev/null +++ b/python/user_packages/Python313/site-packages/chromadb/test/distributed/test_log_backpressure.py @@ -0,0 +1,54 @@ +# Add up to 200k records until the log-is-full message is seen. + +import grpc +import math +import random +import time + +import numpy as np + +from chromadb.api import ClientAPI +from chromadb.proto.logservice_pb2 import SealLogRequest, MigrateLogRequest +from chromadb.proto.logservice_pb2_grpc import LogServiceStub +from chromadb.test.conftest import ( + reset, + skip_if_not_cluster, +) +from chromadb.test.property import invariants +from chromadb.test.utils.wait_for_version_increase import wait_for_version_increase + +RECORDS = 2000000 +BATCH_SIZE = 100 + +@skip_if_not_cluster() +def test_log_backpressure( + client: ClientAPI, +) -> None: + seed = time.time() + random.seed(seed) + print("Generating data with seed ", seed) + reset(client) + collection = client.create_collection( + name="test", + metadata={"hnsw:construction_ef": 128, "hnsw:search_ef": 128, "hnsw:M": 128}, + ) + + time.sleep(1) + + print('backpressuring for', collection.id) + + excepted = False + # Add RECORDS records, where each embedding has 3 dimensions randomly generated between 0 and 1 + for i in range(0, RECORDS, BATCH_SIZE): + ids = [] + embeddings = [] + ids.extend([str(x) for x in range(i, i + BATCH_SIZE)]) + embeddings.extend([np.random.rand(1, 3)[0] for x in range(i, i + BATCH_SIZE)]) + try: + collection.add(ids=ids, embeddings=embeddings) + except Exception as x: + print(f"Caught exception:\n{x}") + if 'log needs compaction before accepting more writes; please backoff exponentially and retry' in str(x): + excepted = True + break + assert excepted, "Expected an exception to be thrown." diff --git a/python/user_packages/Python313/site-packages/chromadb/test/distributed/test_repair_collection_log_offset.py b/python/user_packages/Python313/site-packages/chromadb/test/distributed/test_repair_collection_log_offset.py new file mode 100644 index 0000000000000000000000000000000000000000..a7f8a0b4417b90c0c2adb017413adc33a4ac1151 --- /dev/null +++ b/python/user_packages/Python313/site-packages/chromadb/test/distributed/test_repair_collection_log_offset.py @@ -0,0 +1,126 @@ +# Add some records, wait for compaction, then roll back the log offset. +# Poll the log for up to 240s to see if the offset gets repaired. + +import grpc +import random +import time +from typing import cast + +import numpy as np + +from chromadb.api import ClientAPI +from chromadb.proto.logservice_pb2 import ( + InspectLogStateRequest, + UpdateCollectionLogOffsetRequest, +) +from chromadb.proto.logservice_pb2_grpc import LogServiceStub +from chromadb.test.conftest import ( + multi_region_test, + reset, + skip_if_not_cluster, +) +from chromadb.test.utils.wait_for_version_increase import wait_for_version_increase + +RECORDS = 1000 +BATCH_SIZE = 100 +EXPECTED_REPAIRED_LOG_OFFSET = RECORDS + 1 +COMPACTION_ADDITIONAL_TIME_SECONDS = 120 +LOG_REPAIR_TIMEOUT_SECONDS = 240 +LOG_POLL_INTERVAL_SECONDS = 1 + + +def _inspect_collection_log_start( + log_service_stub: LogServiceStub, + database_name: str, + collection_id: str, +) -> int: + request = InspectLogStateRequest( + database_name=database_name, + collection_id=collection_id, + ) + response = log_service_stub.InspectLogState(request, timeout=60) + return int(response.start) + + +def _wait_for_collection_log_start( + log_service_stub: LogServiceStub, + database_name: str, + collection_id: str, + expected_start: int, +) -> None: + deadline = time.time() + LOG_REPAIR_TIMEOUT_SECONDS + last_start = None + while time.time() < deadline: + last_start = _inspect_collection_log_start( + log_service_stub, database_name, collection_id + ) + if last_start == expected_start: + return + time.sleep(LOG_POLL_INTERVAL_SECONDS) + + raise TimeoutError( + "Timed out waiting for collection log start " + f"database={database_name} collection_id={collection_id} " + f"expected={expected_start} last_seen={last_start}" + ) + + +@skip_if_not_cluster() +@multi_region_test +def test_repair_collection_log_offset( + client: ClientAPI, +) -> None: + seed = time.time() + random.seed(seed) + print("Generating data with seed ", seed) + reset(client) + + channel = grpc.insecure_channel("localhost:50054") + log_service_stub = LogServiceStub(channel) + database_name = str(client.database) + + collection = client.create_collection( + name="test_repair_collection_log_offset", + metadata={"hnsw:construction_ef": 128, "hnsw:search_ef": 128, "hnsw:M": 128}, + ) + print("collection_id =", collection.id) + + initial_version = cast(int, collection.get_model()["version"]) + + # Add RECORDS records, where each embedding has 3 dimensions randomly generated + # between 0 and 1. + for i in range(0, RECORDS, BATCH_SIZE): + ids = [] + embeddings = [] + ids.extend([str(x) for x in range(i, i + BATCH_SIZE)]) + embeddings.extend([np.random.rand(1, 3)[0] for x in range(i, i + BATCH_SIZE)]) + collection.add(ids=ids, embeddings=embeddings) + + wait_for_version_increase( + client, + collection.name, + initial_version, + COMPACTION_ADDITIONAL_TIME_SECONDS, + ) + + collection_id = str(collection.id) + _wait_for_collection_log_start( + log_service_stub, + database_name, + collection_id, + EXPECTED_REPAIRED_LOG_OFFSET, + ) + + request = UpdateCollectionLogOffsetRequest( + database_name=database_name, + collection_id=collection_id, + log_offset=1, + ) + log_service_stub.RollbackCollectionLogOffset(request, timeout=60) + + _wait_for_collection_log_start( + log_service_stub, + database_name, + collection_id, + EXPECTED_REPAIRED_LOG_OFFSET, + ) diff --git a/python/user_packages/Python313/site-packages/chromadb/test/distributed/test_reroute.py b/python/user_packages/Python313/site-packages/chromadb/test/distributed/test_reroute.py new file mode 100644 index 0000000000000000000000000000000000000000..04c1c8a974cc05205e2e1e9ea348e43d632e762d --- /dev/null +++ b/python/user_packages/Python313/site-packages/chromadb/test/distributed/test_reroute.py @@ -0,0 +1,74 @@ +from typing import Sequence +from chromadb.test.conftest import ( + reset, + skip_if_not_cluster, +) +from chromadb.api import ClientAPI +from kubernetes import client as k8s_client, config +import time + + +@skip_if_not_cluster() +def test_reroute( + client: ClientAPI, +) -> None: + reset(client) + collection = client.create_collection( + name="test", + metadata={"hnsw:construction_ef": 128, "hnsw:search_ef": 128, "hnsw:M": 128}, + ) + + ids = [str(i) for i in range(10)] + embeddings: list[Sequence[float]] = [ + [float(i), float(i), float(i)] for i in range(10) + ] + collection.add(ids=ids, embeddings=embeddings) + collection.query(query_embeddings=[embeddings[0]]) + + # Restart the query service using k8s api, in order to trigger a reroute + # of the query service + config.load_kube_config() + v1 = k8s_client.CoreV1Api() + # Find all pods with the label "app=query" + res = v1.list_namespaced_pod("chroma", label_selector="app=query-service") + assert len(res.items) > 0 + items = res.items + seen_ids = set() + + # Restart all the pods by deleting them + for item in items: + seen_ids.add(item.metadata.uid) + name = item.metadata.name + namespace = item.metadata.namespace + v1.delete_namespaced_pod(name, namespace) + + # Wait until we have len(seen_ids) pods running with new UIDs + timeout_secs = 10 + start_time = time.time() + while True: + res = v1.list_namespaced_pod("chroma", label_selector="app=query-service") + items = res.items + new_ids = set([item.metadata.uid for item in items]) + if len(new_ids) == len(seen_ids) and len(new_ids.intersection(seen_ids)) == 0: + break + if time.time() - start_time > timeout_secs: + assert False, "Timed out waiting for new pods to start" + time.sleep(1) + + # Wait for the query service to be ready, or timeout + while True: + res = v1.list_namespaced_pod("chroma", label_selector="app=query-service") + items = res.items + ready = True + for item in items: + if item.status.phase != "Running": + ready = False + break + if ready: + break + if time.time() - start_time > timeout_secs: + assert False, "Timed out waiting for new pods to be ready" + time.sleep(1) + + time.sleep(1) + collection.query(query_embeddings=[embeddings[0]]) diff --git a/python/user_packages/Python313/site-packages/chromadb/test/distributed/test_sanity.py b/python/user_packages/Python313/site-packages/chromadb/test/distributed/test_sanity.py new file mode 100644 index 0000000000000000000000000000000000000000..38ade43cabd5f63b8b8bbc28df3e309518bd300e --- /dev/null +++ b/python/user_packages/Python313/site-packages/chromadb/test/distributed/test_sanity.py @@ -0,0 +1,105 @@ +# This tests a very minimal of test_add in test_add.py as a example based test +# instead of a property based test. We can use the delta to get the property +# test working and then enable +import random +import time +from chromadb.api import ClientAPI +from chromadb.test.conftest import ( + multi_region_test, + reset, + skip_if_not_cluster, +) +from chromadb.test.property import invariants +from chromadb.test.utils.wait_for_version_increase import ( + wait_for_version_increase, + get_collection_version, +) +import numpy as np + + +@skip_if_not_cluster() +@multi_region_test +def test_add( + client: ClientAPI, +) -> None: + seed = time.time() + random.seed(seed) + print("Generating data with seed ", seed) + reset(client) + collection = client.create_collection( + name="test", + metadata={"hnsw:construction_ef": 128, "hnsw:search_ef": 128, "hnsw:M": 128}, + ) + + # Add 1000 records, where each embedding has 3 dimensions randomly generated + # between 0 and 1 + ids = [] + embeddings = [] + for i in range(1000): + ids.append(str(i)) + embeddings.append(np.random.rand(1, 3)[0]) + collection.add( + ids=[str(i)], + embeddings=[embeddings[-1]], + ) + + random_query = np.random.rand(1, 3)[0] + print("Generated data with seed ", seed) + + invariants.ann_accuracy( + collection, + { + "ids": ids, + "embeddings": embeddings, + "metadatas": None, + "documents": None, + }, + 10, + query_embeddings=[random_query], + ) + + +@skip_if_not_cluster() +@multi_region_test +def test_add_include_all_with_compaction_delay(client: ClientAPI) -> None: + seed = time.time() + random.seed(seed) + print("Generating data with seed ", seed) + reset(client) + collection = client.create_collection( + name="test_add_include_all_with_compaction_delay", + metadata={"hnsw:construction_ef": 128, "hnsw:search_ef": 128, "hnsw:M": 128}, + ) + initial_version = get_collection_version(client, collection.name) + + ids = [] + embeddings = [] + documents = [] + for i in range(1000): + ids.append(str(i)) + embeddings.append(np.random.rand(1, 3)[0]) + documents.append(f"document_{i}") + collection.add( + ids=[str(i)], + embeddings=[embeddings[-1]], + documents=[documents[-1]], + ) + + wait_for_version_increase(client, collection.name, initial_version, 120) + + random_query_1 = np.random.rand(1, 3)[0] + random_query_2 = np.random.rand(1, 3)[0] + print("Generated data with seed ", seed) + + # Query the collection with a random query + invariants.ann_accuracy( + collection, + { + "ids": ids, + "embeddings": embeddings, + "metadatas": None, + "documents": documents, + }, + 10, + query_embeddings=[random_query_1, random_query_2], + ) diff --git a/python/user_packages/Python313/site-packages/chromadb/test/distributed/test_statistics_wrapper.py b/python/user_packages/Python313/site-packages/chromadb/test/distributed/test_statistics_wrapper.py new file mode 100644 index 0000000000000000000000000000000000000000..cc83dad8fc4234d69ef768502b45a45f6b124a7b --- /dev/null +++ b/python/user_packages/Python313/site-packages/chromadb/test/distributed/test_statistics_wrapper.py @@ -0,0 +1,489 @@ +""" +Integration test for the Collection statistics wrapper methods +""" + +import json +import time +from typing import Any + +import pytest + +from chromadb.api.client import Client as ClientCreator +from chromadb.base_types import SparseVector +from chromadb.config import System +from chromadb.test.conftest import skip_if_not_cluster +from chromadb.test.utils.wait_for_version_increase import ( + get_collection_version, + wait_for_version_increase, +) +from chromadb.utils.statistics import ( + attach_statistics_function, + detach_statistics_function, + get_statistics, + get_statistics_fn_name, +) + +pytestmark = [skip_if_not_cluster()] + + +def test_statistics_wrapper(basic_http_client: System) -> None: + """Test the statistics wrapper methods on Collection""" + client = ClientCreator.from_system(basic_http_client) + client.reset() + + # Create a collection + collection = client.get_or_create_collection( + name="test_collection", + metadata={"description": "Test collection for statistics"}, + ) + + # Enable statistics + attached_fn, created = attach_statistics_function( + collection, "test_collection_statistics" + ) + assert attached_fn is not None + assert created is True + assert attached_fn.function_name == "statistics" + assert attached_fn.output_collection == "test_collection_statistics" + + initial_version = get_collection_version(client, collection.name) + + # Add some documents with metadata + collection.add( + ids=["doc1", "doc2", "doc3"], + documents=["test document 1", "test document 2", "test document 3"], + metadatas=[ + {"category": "A", "score": 10, "active": True}, + {"category": "B", "score": 10, "active": False}, + {"category": "A", "score": 20, "active": True}, + ], + ) + + # Wait for statistics to be computed + wait_for_version_increase(client, collection.name, initial_version) + time.sleep(60) + + # Get statistics + stats = get_statistics(collection, "test_collection_statistics") + print("\nStatistics output:") + print(json.dumps(stats, indent=2)) + + # Verify the structure + assert "statistics" in stats + assert "summary" in stats + + # Verify summary + assert stats["summary"]["total_count"] == 3 + + # Verify category statistics + assert "category" in stats["statistics"] + assert "A" in stats["statistics"]["category"] + assert "B" in stats["statistics"]["category"] + assert stats["statistics"]["category"]["A"]["count"] == 2 + assert stats["statistics"]["category"]["B"]["count"] == 1 + + # Verify score statistics + assert "score" in stats["statistics"] + assert "10" in stats["statistics"]["score"] + assert "20" in stats["statistics"]["score"] + assert stats["statistics"]["score"]["10"]["count"] == 2 + assert stats["statistics"]["score"]["20"]["count"] == 1 + + # Verify active statistics + assert "active" in stats["statistics"] + assert "true" in stats["statistics"]["active"] + assert "false" in stats["statistics"]["active"] + assert stats["statistics"]["active"]["true"]["count"] == 2 + assert stats["statistics"]["active"]["false"]["count"] == 1 + + # Test get_attached_function + stats_fn = collection.get_attached_function(get_statistics_fn_name(collection)) + assert stats_fn.function_name == "statistics" + + # Disable statistics (keep the collection) + success = detach_statistics_function(collection, delete_stats_collection=False) + assert success is True + + # Verify the statistics collection still exists + stats_collection = client.get_collection("test_collection_statistics") + assert stats_collection is not None + + +def test_backfill_statistics(basic_http_client: System) -> None: + """Test backfill statistics""" + client = ClientCreator.from_system(basic_http_client) + client.reset() + + collection = client.create_collection(name="my_collection") + + initial_version = get_collection_version(client, collection.name) + + # Add some documents with metadata + collection.add( + ids=["doc1", "doc2", "doc3"], + documents=["test document 1", "test document 2", "test document 3"], + metadatas=[ + {"category": "A", "score": 10, "active": True}, + {"category": "B", "score": 10, "active": False}, + {"category": "A", "score": 20, "active": True}, + ], + ) + + # Let this all be compacted + wait_for_version_increase(client, collection.name, initial_version) + initial_version = get_collection_version(client, collection.name) + + # Enable statistics + attached_fn, created = attach_statistics_function( + collection, "my_collection_statistics" + ) + assert created is True + assert attached_fn.function_name == "statistics" + assert attached_fn.output_collection == "my_collection_statistics" + + # Wait for statistics to be computed + wait_for_version_increase(client, collection.name, initial_version) + + stats = get_statistics(collection, "my_collection_statistics") + assert stats is not None + assert "statistics" in stats + assert "summary" in stats + + # Verify summary + assert stats["summary"]["total_count"] == 3 + + # Verify category statistics + assert "category" in stats["statistics"] + assert "A" in stats["statistics"]["category"] + assert "B" in stats["statistics"]["category"] + assert stats["statistics"]["category"]["A"]["count"] == 2 + assert stats["statistics"]["category"]["B"]["count"] == 1 + + # Verify score statistics + assert "score" in stats["statistics"] + assert "10" in stats["statistics"]["score"] + assert "20" in stats["statistics"]["score"] + assert stats["statistics"]["score"]["10"]["count"] == 2 + assert stats["statistics"]["score"]["20"]["count"] == 1 + + # Verify active statistics + assert "active" in stats["statistics"] + assert "true" in stats["statistics"]["active"] + assert "false" in stats["statistics"]["active"] + assert stats["statistics"]["active"]["true"]["count"] == 2 + assert stats["statistics"]["active"]["false"]["count"] == 1 + + # Disable statistics + success = detach_statistics_function(collection, delete_stats_collection=True) + assert success is True + + +def test_statistics_wrapper_custom_output_collection(basic_http_client: System) -> None: + """Test statistics with custom output collection name""" + client = ClientCreator.from_system(basic_http_client) + client.reset() + + collection = client.create_collection(name="my_collection") + + # Enable statistics with custom output collection name + attached_fn, created = attach_statistics_function( + collection, stats_collection_name="my_custom_stats" + ) + assert created is True + assert attached_fn.output_collection == "my_custom_stats" + + initial_version = get_collection_version(client, collection.name) + + # Add data + collection.add( + ids=["id1"], + documents=["doc1"], + metadatas=[{"key": "value"}], + ) + + wait_for_version_increase(client, collection.name, initial_version) + + # Get statistics + stats = get_statistics(collection, "my_custom_stats") + assert "statistics" in stats + assert "key" in stats["statistics"] + + # Disable and delete the custom collection + detach_statistics_function(collection, delete_stats_collection=True) + + +def test_statistics_wrapper_key_filter(basic_http_client: System) -> None: + """Test get_statistics with key filter parameter""" + client = ClientCreator.from_system(basic_http_client) + client.reset() + + collection = client.create_collection(name="key_filter_test") + + # Enable statistics + _, created = attach_statistics_function(collection, "key_filter_test_statistics") + assert created is True + + initial_version = get_collection_version(client, collection.name) + + # Add documents with multiple metadata keys + collection.add( + ids=["doc1", "doc2", "doc3"], + documents=["test document 1", "test document 2", "test document 3"], + metadatas=[ + {"category": "A", "score": 10, "active": True}, + {"category": "B", "score": 10, "active": False}, + {"category": "A", "score": 20, "active": True}, + ], + ) + + wait_for_version_increase(client, collection.name, initial_version) + time.sleep(60) + + # Get all statistics (no key filter) + all_stats = get_statistics(collection, "key_filter_test_statistics") + assert "category" in all_stats["statistics"] + assert "score" in all_stats["statistics"] + assert "active" in all_stats["statistics"] + + # Get statistics filtered by "category" key only + category_stats = get_statistics( + collection, "key_filter_test_statistics", keys=["category"] + ) + assert "category" in category_stats["statistics"] + assert "score" not in category_stats["statistics"] + assert "active" not in category_stats["statistics"] + assert category_stats["statistics"]["category"]["A"]["count"] == 2 + assert category_stats["statistics"]["category"]["B"]["count"] == 1 + # Summary should still be present when filtering by key + assert "summary" in category_stats + assert category_stats["summary"]["total_count"] == 3 + + # Get statistics filtered by "score" key only + score_stats = get_statistics( + collection, "key_filter_test_statistics", keys=["score"] + ) + assert "score" in score_stats["statistics"] + assert "category" not in score_stats["statistics"] + assert "active" not in score_stats["statistics"] + assert score_stats["statistics"]["score"]["10"]["count"] == 2 + assert score_stats["statistics"]["score"]["20"]["count"] == 1 + # Summary should still be present when filtering by key + assert "summary" in score_stats + assert score_stats["summary"]["total_count"] == 3 + + # Cleanup + detach_statistics_function(collection, delete_stats_collection=True) + + +def test_statistics_wrapper_key_filter_too_many_keys(basic_http_client: System) -> None: + """Test that get_statistics raises ValueError when more than 30 keys are provided""" + client = ClientCreator.from_system(basic_http_client) + client.reset() + + collection = client.create_collection(name="too_many_keys_test") + + # Enable statistics + attach_statistics_function(collection, "too_many_keys_test_statistics") + + # Generate more than 30 keys + too_many_keys = [f"key_{i}" for i in range(31)] + + # Should raise ValueError when more than 30 keys are provided + with pytest.raises(ValueError) as exc_info: + get_statistics(collection, "too_many_keys_test_statistics", keys=too_many_keys) + + assert "Too many keys provided: 31" in str(exc_info.value) + assert "Maximum allowed is 30" in str(exc_info.value) + + # Cleanup + detach_statistics_function(collection, delete_stats_collection=True) + + +# commenting out for now as waiting for query cache invalidateion slows down the test suite +def test_statistics_wrapper_incremental_updates(basic_http_client: System) -> None: + """Test that statistics are updated incrementally""" + client = ClientCreator.from_system(basic_http_client) + client.reset() + + collection = client.create_collection(name="incremental_test") + _, created = attach_statistics_function(collection, "incremental_test_statistics") + assert created is True + + initial_version = get_collection_version(client, collection.name) + + # Add initial batch + collection.add( + ids=["id1", "id2"], + documents=["doc1", "doc2"], + metadatas=[{"category": "A"}, {"category": "A"}], + ) + + wait_for_version_increase(client, collection.name, initial_version) + next_version = get_collection_version(client, collection.name) + + # Check initial statistics + stats = get_statistics(collection, "incremental_test_statistics") + assert stats["statistics"]["category"]["A"]["count"] == 2 + assert stats["summary"]["total_count"] == 2 + + # Add more data + collection.add( + ids=["id3", "id4"], + documents=["doc3", "doc4"], + metadatas=[{"category": "B"}, {"category": "A"}], + ) + + wait_for_version_increase(client, collection.name, next_version) + # TODO(tanujnay112): Remove this sleep once query cache invalidation is solidified + # or figure out a different testing harness where we don't have to wait for query cache invalidation + time.sleep(70) + + # Check updated statistics + stats = get_statistics(collection, "incremental_test_statistics") + assert stats["statistics"]["category"]["A"]["count"] == 3 + assert stats["statistics"]["category"]["B"]["count"] == 1 + assert stats["summary"]["total_count"] == 4 + + detach_statistics_function(collection, delete_stats_collection=True) + + +def test_sparse_vector_statistics(basic_http_client: System) -> None: + """Test statistics with sparse vector that includes labels""" + client = ClientCreator.from_system(basic_http_client) + client.reset() + + collection = client.create_collection(name="sparse_vector_test1") + + # Create sparse vectors with labels + sparse_vec1 = SparseVector( + indices=[100, 200, 300], + values=[1.0, 2.0, 3.0], + labels=["apple", "banana", "cherry"], + ) + sparse_vec2 = SparseVector( + indices=[100, 400], values=[1.5, 2.5], labels=["apple", "date"] + ) + sparse_vec3 = SparseVector( + indices=[200, 300], values=[2.0, 3.0], labels=["banana", "cherry"] + ) + + # Add data with sparse vectors + collection.add( + ids=["id1", "id2", "id3"], + documents=["doc1", "doc2", "doc3"], + metadatas=[ + {"category": "A", "vec": sparse_vec1}, + {"category": "B", "vec": sparse_vec2}, + {"category": "A", "vec": sparse_vec3}, + ], + ) + _, created = attach_statistics_function( + collection, "sparse_vector_test1_statistics" + ) + assert created is True + + initial_version = get_collection_version(client, collection.name) + + wait_for_version_increase(client, collection.name, initial_version) + + # Get statistics + stats = get_statistics(collection, "sparse_vector_test1_statistics") + print("\nSparse vector statistics output:") + print(json.dumps(stats, indent=2)) + + assert "statistics" in stats + assert "summary" in stats + assert stats["summary"]["total_count"] == 3 + + # Verify category statistics + assert "category" in stats["statistics"] + assert "A" in stats["statistics"]["category"] + assert "B" in stats["statistics"]["category"] + assert stats["statistics"]["category"]["A"]["count"] == 2 + assert stats["statistics"]["category"]["B"]["count"] == 1 + + # Verify sparse vector statistics use labels instead of hash IDs + assert "vec" in stats["statistics"] + assert "apple" in stats["statistics"]["vec"], "Should use label 'apple' not hash ID" + assert ( + "banana" in stats["statistics"]["vec"] + ), "Should use label 'banana' not hash ID" + assert ( + "cherry" in stats["statistics"]["vec"] + ), "Should use label 'cherry' not hash ID" + assert "date" in stats["statistics"]["vec"], "Should use label 'date' not hash ID" + + # Verify counts + assert stats["statistics"]["vec"]["apple"]["count"] == 2 # in id1 and id2 + assert stats["statistics"]["vec"]["banana"]["count"] == 2 # in id1 and id3 + assert stats["statistics"]["vec"]["cherry"]["count"] == 2 # in id1 and id3 + assert stats["statistics"]["vec"]["date"]["count"] == 1 # in id2 only + + +def test_statistics_high_cardinality(basic_http_client: System) -> None: + """Test statistics with high cardinality metadata""" + client = ClientCreator.from_system(basic_http_client) + client.reset() + + collection = client.create_collection(name="high_cardinality_test") + + # Generate 500 documents with 10 metadata fields each + num_docs = 500 + num_fields = 10 + ids = [f"id{i}" for i in range(num_docs)] + documents = [f"doc{i}" for i in range(num_docs)] + + metadatas: list[dict[str, Any]] = [] + for i in range(num_docs): + meta: dict[str, Any] = {} + for j in range(num_fields): + meta[f"field_{j}"] = f"value_{j}_{i}" + metadatas.append(meta) + + # Add in batches to avoid hitting request size limits + batch_size = 100 + initial_version = get_collection_version(client, collection.name) + + for i in range(0, num_docs, batch_size): + collection.add( + ids=ids[i : i + batch_size], + documents=documents[i : i + batch_size], + metadatas=metadatas[i : i + batch_size], # type: ignore[arg-type] + ) + + # Let all data be compacted + wait_for_version_increase(client, collection.name, initial_version) + initial_version = get_collection_version(client, collection.name) + + # Enable statistics + _, created = attach_statistics_function( + collection, "high_cardinality_test_statistics" + ) + assert created is True + + # Wait for statistics to be computed + wait_for_version_increase(client, collection.name, initial_version) + + # Get statistics + stats = get_statistics(collection, "high_cardinality_test_statistics") + + assert "statistics" in stats + + # Verify we have stats for all fields + for j in range(num_fields): + field_key = f"field_{j}" + assert field_key in stats["statistics"] + + field_stats = stats["statistics"][field_key] + assert len(field_stats) == num_docs + + # Verify each value has count 1 + for i in range(num_docs): + value = f"value_{j}_{i}" + assert value in field_stats + assert field_stats[value]["count"] == 1 + + # Verify total count + assert stats["summary"]["total_count"] == num_docs + + detach_statistics_function(collection, delete_stats_collection=True) diff --git a/python/user_packages/Python313/site-packages/chromadb/test/distributed/test_task_api.py b/python/user_packages/Python313/site-packages/chromadb/test/distributed/test_task_api.py new file mode 100644 index 0000000000000000000000000000000000000000..7a6ed6baea274192d664b3a17600a5c27fc18920 --- /dev/null +++ b/python/user_packages/Python313/site-packages/chromadb/test/distributed/test_task_api.py @@ -0,0 +1,592 @@ +""" +Integration test for Chroma's Task API + +Tests the task creation, execution, and removal functionality +for automatically processing collections. +""" + +import pytest +from chromadb.api.client import Client as ClientCreator +from chromadb.api.functions import ( + RECORD_COUNTER_FUNCTION, + STATISTICS_FUNCTION, + Function, +) +from chromadb.config import System +from chromadb.errors import ChromaError, NotFoundError +from chromadb.test.conftest import skip_if_not_cluster +from chromadb.test.utils.wait_for_version_increase import ( + get_collection_version, + wait_for_version_increase, +) +from time import sleep + +pytestmark = [skip_if_not_cluster()] + + +def test_count_function_attach_and_detach(basic_http_client: System) -> None: + """Test creating and removing a function with the record_counter operator""" + client = ClientCreator.from_system(basic_http_client) + client.reset() + + # Create a collection + collection = client.get_or_create_collection( + name="my_document", + metadata={"description": "Sample documents for task processing"}, + ) + + # Create a task that counts records in the collection + attached_fn, created = collection.attach_function( + name="count_my_docs", + function=RECORD_COUNTER_FUNCTION, + output_collection="my_documents_counts", + params=None, + ) + + # Verify task creation succeeded + assert attached_fn is not None + assert created is True + initial_version = get_collection_version(client, collection.name) + + # Add documents + collection.add( + ids=["doc_{}".format(i) for i in range(0, 300)], + documents=["test document"] * 300, + ) + + # Verify documents were added + assert collection.count() == 300 + + wait_for_version_increase(client, collection.name, initial_version) + # Give some time to invalidate the frontend query cache + sleep(60) + + result = client.get_collection("my_documents_counts").get("function_output") + assert result["metadatas"] is not None + assert result["metadatas"][0]["total_count"] == 300 + + # Remove the task + success = collection.detach_function( + attached_fn.name, + delete_output_collection=True, + ) + + # Verify task removal succeeded + assert success is True + + +def test_task_with_invalid_function(basic_http_client: System) -> None: + """Test that creating a task with an invalid function raises an error""" + client = ClientCreator.from_system(basic_http_client) + client.reset() + + collection = client.get_or_create_collection(name="test_invalid_function") + collection.add(ids=["id1"], documents=["test document"]) + + # Attempt to create task with non-existent function should raise ChromaError + with pytest.raises(ChromaError, match="function not found"): + collection.attach_function( + function=Function._NONEXISTENT_TEST_ONLY, + name="invalid_task", + output_collection="output_collection", + params=None, + ) + + +def test_attach_function_returns_function_name(basic_http_client: System) -> None: + """Test that attach_function and get_attached_function return function_name field instead of UUID""" + client = ClientCreator.from_system(basic_http_client) + client.reset() + + collection = client.create_collection(name="test_function_name") + collection.add(ids=["id1"], documents=["doc1"]) + + # Attach a function and verify function_name field in response + attached_fn, created = collection.attach_function( + function=RECORD_COUNTER_FUNCTION, + name="my_counter", + output_collection="output_collection", + params=None, + ) + + # Verify the attached function has function_name (not function_id UUID) + assert created is True + assert attached_fn.function_name == "record_counter" + assert attached_fn.name == "my_counter" + + # Get the attached function and verify function_name field is also present + retrieved_fn = collection.get_attached_function("my_counter") + assert retrieved_fn == attached_fn + + # Clean up + collection.detach_function(attached_fn.name, delete_output_collection=True) + + +def test_function_multiple_collections(basic_http_client: System) -> None: + """Test attaching functions on multiple collections""" + client = ClientCreator.from_system(basic_http_client) + client.reset() + + # Create first collection and task + collection1 = client.create_collection(name="collection_1") + collection1.add(ids=["id1", "id2"], documents=["doc1", "doc2"]) + + attached_fn1, created1 = collection1.attach_function( + function=RECORD_COUNTER_FUNCTION, + name="task_1", + output_collection="output_1", + params=None, + ) + + assert attached_fn1 is not None + assert created1 is True + + # Create second collection and task + collection2 = client.create_collection(name="collection_2") + collection2.add(ids=["id3", "id4"], documents=["doc3", "doc4"]) + + attached_fn2, created2 = collection2.attach_function( + function=RECORD_COUNTER_FUNCTION, + name="task_2", + output_collection="output_2", + params=None, + ) + + assert attached_fn2 is not None + assert created2 is True + + # Task IDs should be different + assert attached_fn1.id != attached_fn2.id + + # Clean up + assert ( + collection1.detach_function(attached_fn1.name, delete_output_collection=True) + is True + ) + assert ( + collection2.detach_function(attached_fn2.name, delete_output_collection=True) + is True + ) + + +def test_functions_one_attached_function_per_collection( + basic_http_client: System, +) -> None: + """Test that only one attached function is allowed per collection""" + client = ClientCreator.from_system(basic_http_client) + client.reset() + + # Create a single collection + collection = client.create_collection(name="single_task_collection") + collection.add(ids=["id1", "id2", "id3"], documents=["doc1", "doc2", "doc3"]) + + # Create first task on the collection + attached_fn1, created = collection.attach_function( + function=RECORD_COUNTER_FUNCTION, + name="task_1", + output_collection="output_1", + params=None, + ) + + assert attached_fn1 is not None + assert created is True + + # Attempt to create a second task with a different name should fail + # (only one attached function allowed per collection) + with pytest.raises( + ChromaError, + match="collection already has an attached function: name=task_1, function=record_counter, output_collection=output_1", + ): + collection.attach_function( + function=RECORD_COUNTER_FUNCTION, + name="task_2", + output_collection="output_2", + params=None, + ) + + # Attempt to create a task with the same name but different function_id should also fail + with pytest.raises( + ChromaError, + match=r"collection already has an attached function: name=task_1, function=record_counter, output_collection=output_1", + ): + collection.attach_function( + function=STATISTICS_FUNCTION, + name="task_1", + output_collection="output_different", # Different output collection + params=None, + ) + + # Detach the first function + assert ( + collection.detach_function(attached_fn1.name, delete_output_collection=True) + is True + ) + + # Now we should be able to attach a new function + attached_fn2, created2 = collection.attach_function( + function=RECORD_COUNTER_FUNCTION, + name="task_2", + output_collection="output_2", + params=None, + ) + + assert attached_fn2 is not None + assert created2 is True + assert attached_fn2.id != attached_fn1.id + + # Clean up + assert ( + collection.detach_function(attached_fn2.name, delete_output_collection=True) + is True + ) + + +def test_attach_function_with_invalid_params(basic_http_client: System) -> None: + """Test that attach_function with non-empty params raises an error""" + client = ClientCreator.from_system(basic_http_client) + client.reset() + + collection = client.create_collection(name="test_invalid_params") + collection.add(ids=["id1"], documents=["test document"]) + + # Attempt to create task with non-empty params should fail + # (no functions currently accept parameters) + with pytest.raises( + ChromaError, + match="params must be empty - no functions currently accept parameters", + ): + collection.attach_function( + name="invalid_params_task", + function=RECORD_COUNTER_FUNCTION, + output_collection="output_collection", + params={"some_key": "some_value"}, + ) + + +def test_attach_function_output_collection_already_exists( + basic_http_client: System, +) -> None: + """Test that attach_function fails when output collection name already exists""" + client = ClientCreator.from_system(basic_http_client) + client.reset() + + # Create a collection that will be used as input + input_collection = client.create_collection(name="input_collection") + input_collection.add(ids=["id1"], documents=["test document"]) + + # Create another collection with the name we want to use for output + client.create_collection(name="existing_output_collection") + + # Attempt to create task with output collection name that already exists + with pytest.raises( + ChromaError, + match=r"Output collection \[existing_output_collection\] already exists", + ): + input_collection.attach_function( + name="my_task", + function=RECORD_COUNTER_FUNCTION, + output_collection="existing_output_collection", + params=None, + ) + + +def test_function_remove_nonexistent(basic_http_client: System) -> None: + """Test removing a task that doesn't exist raises NotFoundError""" + client = ClientCreator.from_system(basic_http_client) + client.reset() + + collection = client.create_collection(name="test_collection") + collection.add(ids=["id1"], documents=["test"]) + attached_fn, _ = collection.attach_function( + function=RECORD_COUNTER_FUNCTION, + name="test_function", + output_collection="output_collection", + params=None, + ) + + collection.detach_function(attached_fn.name, delete_output_collection=True) + + # Trying to detach this function again should raise NotFoundError + with pytest.raises(NotFoundError, match="does not exist"): + collection.detach_function(attached_fn.name, delete_output_collection=True) + + +def test_attach_to_output_collection_fails(basic_http_client: System) -> None: + """Test that attaching a function to an output collection fails""" + client = ClientCreator.from_system(basic_http_client) + client.reset() + + # Create input collection + input_collection = client.create_collection(name="input_collection") + input_collection.add(ids=["id1"], documents=["test"]) + + _, _ = input_collection.attach_function( + name="test_function", + function=RECORD_COUNTER_FUNCTION, + output_collection="output_collection", + params=None, + ) + output_collection = client.get_collection(name="output_collection") + + with pytest.raises( + ChromaError, match="cannot attach function to an output collection" + ): + _ = output_collection.attach_function( + name="test_function_2", + function=RECORD_COUNTER_FUNCTION, + output_collection="output_collection_2", + params=None, + ) + + +def test_delete_output_collection_detaches_function(basic_http_client: System) -> None: + """Test that deleting an output collection also detaches the attached function""" + client = ClientCreator.from_system(basic_http_client) + client.reset() + + # Create input collection and attach a function + input_collection = client.create_collection(name="input_collection") + input_collection.add(ids=["id1"], documents=["test"]) + + attached_fn, created = input_collection.attach_function( + name="my_function", + function=RECORD_COUNTER_FUNCTION, + output_collection="output_collection", + params=None, + ) + assert attached_fn is not None + assert created is True + + # Delete the output collection directly + client.delete_collection("output_collection") + + # The attached function should now be gone - trying to get it should raise NotFoundError + with pytest.raises(NotFoundError): + input_collection.get_attached_function("my_function") + + +def test_delete_orphaned_output_collection(basic_http_client: System) -> None: + """Test that deleting an output collection from a recently detached function works""" + client = ClientCreator.from_system(basic_http_client) + client.reset() + + # Create input collection and attach a function + input_collection = client.create_collection(name="input_collection") + input_collection.add(ids=["id1"], documents=["test"]) + + attached_fn, created = input_collection.attach_function( + name="my_function", + function=RECORD_COUNTER_FUNCTION, + output_collection="output_collection", + params=None, + ) + assert attached_fn is not None + assert created is True + + input_collection.detach_function(attached_fn.name, delete_output_collection=False) + + # Delete the output collection directly + client.delete_collection("output_collection") + + # The attached function should still exist but be marked as detached + with pytest.raises(NotFoundError): + input_collection.get_attached_function("my_function") + + with pytest.raises(NotFoundError): + # Try to use the function - it should fail since it's detached + client.get_collection("output_collection") + + +def test_partial_attach_function_repair( + basic_http_client: System, +) -> None: + """Test creating and removing a function with the record_counter operator""" + client = ClientCreator.from_system(basic_http_client) + client.reset() + + # Create a collection + collection = client.get_or_create_collection( + name="my_document", + ) + + # Create a task that counts records in the collection + attached_fn, created = collection.attach_function( + name="count_my_docs", + function=RECORD_COUNTER_FUNCTION, + output_collection="my_documents_counts", + params=None, + ) + assert created is True + + # Verify task creation succeeded + assert attached_fn is not None + + collection2 = client.get_or_create_collection( + name="my_document2", + ) + + # Create a task that counts records in the collection + # This should fail + with pytest.raises( + ChromaError, match=r"Output collection \[my_documents_counts\] already exists" + ): + attached_fn, _ = collection2.attach_function( + name="count_my_docs", + function=RECORD_COUNTER_FUNCTION, + output_collection="my_documents_counts", + params=None, + ) + + # Detach the function + assert ( + collection.detach_function(attached_fn.name, delete_output_collection=True) + is True + ) + + # Create a task that counts records in the collection + attached_fn, created = collection2.attach_function( + name="count_my_docs", + function=RECORD_COUNTER_FUNCTION, + output_collection="my_documents_counts", + params=None, + ) + assert attached_fn is not None + assert created is True + + +def test_output_collection_created_with_schema(basic_http_client: System) -> None: + """Test that output collections are created with the source_attached_function_id in the schema""" + client = ClientCreator.from_system(basic_http_client) + client.reset() + + # Create input collection and attach a function + input_collection = client.create_collection(name="input_collection") + input_collection.add(ids=["id1"], documents=["test"]) + + attached_fn, created = input_collection.attach_function( + name="my_function", + function=RECORD_COUNTER_FUNCTION, + output_collection="output_collection", + params=None, + ) + assert attached_fn is not None + assert created is True + + # Get the output collection - it should exist + output_collection = client.get_collection(name="output_collection") + assert output_collection is not None + + # The source_attached_function_id is stored in the schema (not metadata) + # We can't directly access the schema from the client, but we verify the collection exists + # and the attached function orchestrator will use this field internally + assert "source_attached_function_id" in output_collection._model.pretty_schema() + + # Clean up + input_collection.detach_function(attached_fn.name, delete_output_collection=True) + + +def test_count_function_attach_and_detach_attach_attach( + basic_http_client: System, +) -> None: + """Test creating and removing a function with the record_counter operator""" + client = ClientCreator.from_system(basic_http_client) + client.reset() + + # Create a collection + collection = client.get_or_create_collection( + name="my_document", + metadata={"description": "Sample documents for task processing"}, + ) + + # Create a task that counts records in the collection + attached_fn, created = collection.attach_function( + name="count_my_docs", + function=RECORD_COUNTER_FUNCTION, + output_collection="my_documents_counts", + params=None, + ) + + # Verify task creation succeeded + assert created is True + assert attached_fn is not None + initial_version = get_collection_version(client, collection.name) + + # Add documents + collection.add( + ids=["doc_{}".format(i) for i in range(0, 300)], + documents=["test document"] * 300, + ) + + # Verify documents were added + assert collection.count() == 300 + + wait_for_version_increase(client, collection.name, initial_version) + # Give some time to invalidate the frontend query cache + sleep(60) + + result = client.get_collection("my_documents_counts").get("function_output") + assert result["metadatas"] is not None + assert result["metadatas"][0]["total_count"] == 300 + + # Remove the task + success = collection.detach_function( + attached_fn.name, delete_output_collection=True + ) + + # Verify task removal succeeded + assert success is True + + # Attach a function that counts records in the collection + attached_fn, created = collection.attach_function( + name="count_my_docs", + function=RECORD_COUNTER_FUNCTION, + output_collection="my_documents_counts", + params=None, + ) + assert attached_fn is not None + assert created is True + + # Attach a function that counts records in the collection + attached_fn, created = collection.attach_function( + name="count_my_docs", + function=RECORD_COUNTER_FUNCTION, + output_collection="my_documents_counts", + params=None, + ) + assert created is False + assert attached_fn is not None + + +def test_attach_function_idempotency(basic_http_client: System) -> None: + """Test that attach_function is idempotent - calling it twice with same params returns created=False""" + client = ClientCreator.from_system(basic_http_client) + client.reset() + + collection = client.create_collection(name="idempotency_test") + collection.add(ids=["id1"], documents=["test document"]) + + # First attach - should be newly created + attached_fn1, created1 = collection.attach_function( + name="my_function", + function=RECORD_COUNTER_FUNCTION, + output_collection="output_collection", + params=None, + ) + assert attached_fn1 is not None + assert created1 is True + + # Second attach with identical params - should be idempotent (created=False) + attached_fn2, created2 = collection.attach_function( + name="my_function", + function=RECORD_COUNTER_FUNCTION, + output_collection="output_collection", + params=None, + ) + assert attached_fn2 is not None + assert created2 is False + + # Both should return the same function ID + assert attached_fn1.id == attached_fn2.id + + # Clean up + collection.detach_function(attached_fn1.name, delete_output_collection=True) diff --git a/python/user_packages/Python313/site-packages/chromadb/test/ef/test_chroma_bm25_embedding_function.py b/python/user_packages/Python313/site-packages/chromadb/test/ef/test_chroma_bm25_embedding_function.py new file mode 100644 index 0000000000000000000000000000000000000000..6a73a9b99d7d9535178a08d006aaf39415033fec --- /dev/null +++ b/python/user_packages/Python313/site-packages/chromadb/test/ef/test_chroma_bm25_embedding_function.py @@ -0,0 +1,202 @@ +import math +from concurrent.futures import ThreadPoolExecutor, as_completed + +import pytest + +from chromadb import SparseVector +from chromadb.utils.embedding_functions.chroma_bm25_embedding_function import ( + DEFAULT_CHROMA_BM25_STOPWORDS, + ChromaBm25EmbeddingFunction, +) + + +def _is_sorted(values: list[int]) -> bool: + return all(values[i] >= values[i - 1] for i in range(1, len(values))) + + +def test_comprehensive_tokenization_matches_reference() -> None: + embedder = ChromaBm25EmbeddingFunction() + embedding = embedder( + [ + "Usain Bolt's top speed reached ~27.8 mph (44.72 km/h)", + ] + )[0] + + expected_indices = [ + 230246813, + 395514983, + 458027949, + 488165615, + 729632045, + 734978415, + 997512866, + 1114505193, + 1381820790, + 1501587190, + 1649421877, + 1837285388, + ] + expected_value = 1.6391153 + + assert embedding.indices == expected_indices + for value in embedding.values: + assert value == pytest.approx(expected_value, abs=1e-5) + + +def test_matches_rust_reference_values() -> None: + embedder = ChromaBm25EmbeddingFunction() + embedding = embedder( + [ + "The space-time continuum WARPS near massive objects...", + ] + )[0] + + expected_indices = [ + 90097469, + 519064992, + 737893654, + 1110755108, + 1950894484, + 2031641008, + 2058513491, + ] + expected_value = 1.660867 + + assert embedding.indices == expected_indices + for value in embedding.values: + assert value == pytest.approx(expected_value, abs=1e-5) + + +def test_generates_embeddings_for_multiple_documents() -> None: + embedder = ChromaBm25EmbeddingFunction() + texts = [ + "Usain Bolt's top speed reached ~27.8 mph (44.72 km/h)", + "The space-time continuum WARPS near massive objects...", + "BM25 is great for sparse retrieval tasks", + ] + + embeddings = embedder(texts) + + assert len(embeddings) == len(texts) + for embedding in embeddings: + assert embedding.indices + assert len(embedding.indices) == len(embedding.values) + assert _is_sorted(embedding.indices) + for value in embedding.values: + assert value > 0 + assert math.isfinite(value) + + +def test_embed_query_matches_call() -> None: + embedder = ChromaBm25EmbeddingFunction() + query = "retrieve BM25 docs" + + query_embedding = embedder.embed_query([query])[0] + doc_embedding = embedder([query])[0] + + assert query_embedding.indices == doc_embedding.indices + assert query_embedding.values == doc_embedding.values + + +def test_config_round_trip() -> None: + embedder = ChromaBm25EmbeddingFunction() + config = embedder.get_config() + + assert config["k"] == pytest.approx(1.2, abs=1e-9) + assert config["b"] == pytest.approx(0.75, abs=1e-9) + assert config["avg_doc_length"] == pytest.approx(256.0, abs=1e-9) + assert config["token_max_length"] == 40 + assert "stopwords" not in config + + custom_stopwords = DEFAULT_CHROMA_BM25_STOPWORDS[:10] + rebuilt = ChromaBm25EmbeddingFunction.build_from_config( + { + **config, + "stopwords": custom_stopwords, + } + ) + + rebuilt_config = rebuilt.get_config() + assert rebuilt_config["stopwords"] == custom_stopwords + assert rebuilt_config["token_max_length"] == config["token_max_length"] + assert rebuilt_config["k"] == pytest.approx(config["k"], abs=1e-9) + assert rebuilt_config["b"] == pytest.approx(config["b"], abs=1e-9) + assert rebuilt_config["avg_doc_length"] == pytest.approx( + config["avg_doc_length"], abs=1e-9 + ) + + +def test_validate_config_update_rejects_unknown_keys() -> None: + embedder = ChromaBm25EmbeddingFunction() + + with pytest.raises(ValueError): + embedder.validate_config_update(embedder.get_config(), {"unknown": 123}) + + +def test_validate_config_update_allows_known_keys() -> None: + embedder = ChromaBm25EmbeddingFunction() + + embedder.validate_config_update( + embedder.get_config(), {"k": 1.1, "stopwords": ["custom"]} + ) + + +def test_multithreaded_usage() -> None: + embedder = ChromaBm25EmbeddingFunction() + base_texts = [ + """The gravitational wave background from massive black hole binaries emit bursts of + gravitational waves at periapse. Such events may be directly resolvable in the Galactic + centre. However, if the star does not spiral in, the emitted GWs are not resolvable for + extra-galactic MBHs, but constitute a source of background noise. We estimate the power + spectrum of this extreme mass ratio burst background.""", + """Dynamics of planets in exoplanetary systems with multiple stars showing how the + gravitational interactions between the stars and planets affect the orbital stability + and long-term evolution of the planetary system architectures.""", + """Diurnal Thermal Tides in a Non-rotating atmosphere with realistic heating profiles + and temperature gradients that demonstrate the complex interplay between radiation + and atmospheric dynamics in planetary atmospheres.""", + """Intermittent turbulence, noise and waves in stellar atmospheres create complex + patterns of energy transport and momentum deposition that influence the structure + and evolution of stellar interiors and surfaces.""", + """Superconductivity in quantum materials and condensed matter physics systems + exhibiting novel quantum phenomena including topological phases, strongly correlated + electron systems, and exotic superconducting pairing mechanisms.""", + """Machine learning models require careful tuning of hyperparameters including learning + rates, regularization coefficients, and architectural choices that demonstrate the + complex interplay between optimization algorithms and model capacity.""", + """Natural language processing enables text understanding through sophisticated + algorithms that analyze semantic relationships, syntactic structures, and contextual + information to extract meaningful representations from unstructured textual data.""", + """Vector databases store high-dimensional embeddings efficiently using advanced + indexing techniques including approximate nearest neighbor search algorithms that + balance accuracy and computational efficiency for large-scale similarity search.""", + ] + texts = base_texts * 30 + + num_threads = 10 + + def process_single_text(text: str) -> SparseVector: + return embedder([text])[0] + + with ThreadPoolExecutor(max_workers=num_threads) as executor: + futures = [executor.submit(process_single_text, text) for text in texts] + all_results = [] + for future in as_completed(futures): + try: + embedding = future.result() + all_results.append(embedding) + except Exception as e: + pytest.fail( + f"Threading error detected: {type(e).__name__}: {e}. " + "This indicates the stemmer is not thread-safe when cached." + ) + + assert len(all_results) == len(texts) + + for embedding in all_results: + assert embedding.indices + assert len(embedding.indices) == len(embedding.values) + assert _is_sorted(embedding.indices) + for value in embedding.values: + assert value > 0 + assert math.isfinite(value) diff --git a/python/user_packages/Python313/site-packages/chromadb/test/ef/test_custom_ef.py b/python/user_packages/Python313/site-packages/chromadb/test/ef/test_custom_ef.py new file mode 100644 index 0000000000000000000000000000000000000000..c3290cdeb84c0c37d47f0e5f8e6758a6cec6b986 --- /dev/null +++ b/python/user_packages/Python313/site-packages/chromadb/test/ef/test_custom_ef.py @@ -0,0 +1,95 @@ +from chromadb.api.types import EmbeddingFunction, Embeddable, Embeddings +import numpy as np +from typing import cast, Any +from chromadb.utils.embedding_functions import ( + register_embedding_function, + known_embedding_functions, +) + + +class LegacyCustomEmbeddingFunction(EmbeddingFunction[Embeddable]): + def __call__(self, input: Embeddable) -> Embeddings: + return cast(Embeddings, np.array([1, 2, 3]).tolist()) + + +class CustomEmbeddingFunction(EmbeddingFunction[Embeddable]): + def __call__(self, input: Embeddable) -> Embeddings: + return cast(Embeddings, np.array([1, 2, 3]).tolist()) + + def __init__(self, *args: Any, **kwargs: Any) -> None: + pass + + @staticmethod + def name() -> str: + return "custom_embedding_function" + + @staticmethod + def build_from_config(config: dict[str, Any]) -> "CustomEmbeddingFunction": + return CustomEmbeddingFunction() + + def get_config(self) -> dict[str, Any]: + return {} + + +@register_embedding_function +class CustomEmbeddingFunctionWithRegistration(EmbeddingFunction[Embeddable]): + def __call__(self, input: Embeddable) -> Embeddings: + return cast(Embeddings, np.array([1, 2, 3]).tolist()) + + def __init__(self, *args: Any, **kwargs: Any) -> None: + pass + + @staticmethod + def name() -> str: + return "custom_embedding_function_with_registration" + + @staticmethod + def build_from_config( + config: dict[str, Any] + ) -> "CustomEmbeddingFunctionWithRegistration": + return CustomEmbeddingFunctionWithRegistration() + + def get_config(self) -> dict[str, Any]: + return {} + + +def test_legacy_custom_ef() -> None: + ef = LegacyCustomEmbeddingFunction() + result = ef(["test"]) + + # Check the structure: we expect a list with one NumPy array + assert isinstance(result, list), "Result should be a list" + assert len(result) == 1, "Result should contain exactly one element" + assert isinstance(result[0], np.ndarray), "Result element should be a NumPy array" + + # Compare the contents of the array + expected = np.array([1, 2, 3], dtype=np.float32) + assert np.array_equal( + result[0], expected + ), f"Arrays not equal: {result[0]} vs {expected}" + + +def test_custom_ef() -> None: + ef = CustomEmbeddingFunction() + result = ef(["test"]) + + # Same checks as above + assert isinstance(result, list), "Result should be a list" + assert len(result) == 1, "Result should contain exactly one element" + assert isinstance(result[0], np.ndarray), "Result element should be a NumPy array" + + expected = np.array([1, 2, 3], dtype=np.float32) + assert np.array_equal( + result[0], expected + ), f"Arrays not equal: {result[0]} vs {expected}" + + +def test_custom_ef_registration() -> None: + # check all 4 embedding functions for registration. + # LegacyCustomEmbeddingFunction should not be in known_embedding_functions + # CustomEmbeddingFunction should not be in known_embedding_functions + # CustomEmbeddingFunctionWithRegistration should be in known_embedding_functions + + assert "legacy_custom_embedding_function" not in known_embedding_functions + assert "custom_embedding_function" not in known_embedding_functions + assert "custom_embedding_function_with_registration" in known_embedding_functions diff --git a/python/user_packages/Python313/site-packages/chromadb/test/ef/test_default_ef.py b/python/user_packages/Python313/site-packages/chromadb/test/ef/test_default_ef.py new file mode 100644 index 0000000000000000000000000000000000000000..accedc6b5f373c16df2e4dfc36fa1b4f1ed4ce68 --- /dev/null +++ b/python/user_packages/Python313/site-packages/chromadb/test/ef/test_default_ef.py @@ -0,0 +1,90 @@ +import shutil +import os +from typing import List, Hashable + +import hypothesis.strategies as st +import onnxruntime +import pytest +from hypothesis import given, settings + +from chromadb.utils.embedding_functions.onnx_mini_lm_l6_v2 import ( + ONNXMiniLM_L6_V2, +) + +from chromadb.utils.embedding_functions.onnx_mini_lm_l6_v2 import _verify_sha256 + + +def unique_by(x: Hashable) -> Hashable: + return x + + +@settings(deadline=None) +@given( + providers=st.lists( + st.sampled_from(onnxruntime.get_all_providers()).filter( + lambda x: x not in onnxruntime.get_available_providers() + ), + unique_by=unique_by, + min_size=1, + ) +) +def test_unavailable_provider_multiple(providers: List[str]) -> None: + with pytest.raises(ValueError) as e: + ef = ONNXMiniLM_L6_V2(preferred_providers=providers) + ef(["test"]) + assert "Preferred providers must be subset of available providers" in str(e.value) + + +@given( + providers=st.lists( + st.sampled_from(onnxruntime.get_available_providers()), + min_size=1, + unique_by=unique_by, + ) +) +def test_available_provider(providers: List[str]) -> None: + ef = ONNXMiniLM_L6_V2(preferred_providers=providers) + ef(["test"]) + + +def test_warning_no_providers_supplied() -> None: + ef = ONNXMiniLM_L6_V2() + ef(["test"]) + + +@given( + providers=st.lists( + st.sampled_from(onnxruntime.get_available_providers()), + min_size=1, + ).filter(lambda x: len(x) > len(set(x))) +) +def test_provider_repeating(providers: List[str]) -> None: + with pytest.raises(ValueError) as e: + ef = ONNXMiniLM_L6_V2(preferred_providers=providers) + ef(["test"]) + assert "Preferred providers must be unique" in str(e.value) + + +def test_invalid_sha256() -> None: + ef = ONNXMiniLM_L6_V2() + shutil.rmtree(ef.DOWNLOAD_PATH) # clean up any existing models + with pytest.raises(ValueError) as e: + ef._MODEL_SHA256 = "invalid" + ef(["test"]) + assert "does not match expected SHA256 hash" in str(e.value) + + +def test_partial_download() -> None: + ef = ONNXMiniLM_L6_V2() + shutil.rmtree(ef.DOWNLOAD_PATH, ignore_errors=True) # clean up any existing models + os.makedirs(ef.DOWNLOAD_PATH, exist_ok=True) + path = os.path.join(ef.DOWNLOAD_PATH, ef.ARCHIVE_FILENAME) + with open(path, "wb") as f: # create invalid file to simulate partial download + f.write(b"invalid") + ef._download_model_if_not_exists() # re-download model + assert os.path.exists(path) + assert _verify_sha256( + str(os.path.join(ef.DOWNLOAD_PATH, ef.ARCHIVE_FILENAME)), + ef._MODEL_SHA256, + ) + assert len(ef(["test"])) == 1 diff --git a/python/user_packages/Python313/site-packages/chromadb/test/ef/test_ef.py b/python/user_packages/Python313/site-packages/chromadb/test/ef/test_ef.py new file mode 100644 index 0000000000000000000000000000000000000000..bd02a8e08218403b808fb6301d251a675df17cb5 --- /dev/null +++ b/python/user_packages/Python313/site-packages/chromadb/test/ef/test_ef.py @@ -0,0 +1,122 @@ +from chromadb.utils import embedding_functions +from chromadb.utils.embedding_functions import ( + EmbeddingFunction, + register_embedding_function, +) +from typing import Dict, Any +import pytest +from chromadb.api.types import ( + Embeddings, + Space, + Embeddable, + SparseEmbeddingFunction, +) +from chromadb.api.models.CollectionCommon import validation_context + + +def test_get_builtins_holds() -> None: + """ + Ensure that `get_builtins` is consistent after the ef migration. + + This test is intended to be temporary until the ef migration is complete as + these expected builtins are likely to grow as long as users add new + embedding functions. + + REMOVE ME ON THE NEXT EF ADDITION + """ + expected_builtins = { + "AmazonBedrockEmbeddingFunction", + "BasetenEmbeddingFunction", + "CloudflareWorkersAIEmbeddingFunction", + "CohereEmbeddingFunction", + "VoyageAIEmbeddingFunction", + "GoogleGenerativeAiEmbeddingFunction", + "GooglePalmEmbeddingFunction", + "GoogleVertexEmbeddingFunction", + "GoogleGeminiEmbeddingFunction", + "GoogleGenaiEmbeddingFunction", # Backward compatibility alias + "HuggingFaceEmbeddingFunction", + "HuggingFaceEmbeddingServer", + "InstructorEmbeddingFunction", + "JinaEmbeddingFunction", + "MistralEmbeddingFunction", + "MorphEmbeddingFunction", + "NomicEmbeddingFunction", + "ONNXMiniLM_L6_V2", + "OllamaEmbeddingFunction", + "OpenAIEmbeddingFunction", + "OpenCLIPEmbeddingFunction", + "RoboflowEmbeddingFunction", + "SentenceTransformerEmbeddingFunction", + "Text2VecEmbeddingFunction", + "ChromaLangchainEmbeddingFunction", + "TogetherAIEmbeddingFunction", + "DefaultEmbeddingFunction", + "HuggingFaceSparseEmbeddingFunction", + "FastembedSparseEmbeddingFunction", + "Bm25EmbeddingFunction", + "ChromaCloudQwenEmbeddingFunction", + "ChromaCloudSpladeEmbeddingFunction", + "ChromaBm25EmbeddingFunction", + "PerplexityEmbeddingFunction", + } + + assert expected_builtins == embedding_functions.get_builtins() + + +def test_default_ef_exists() -> None: + assert hasattr(embedding_functions, "DefaultEmbeddingFunction") + default_ef = embedding_functions.DefaultEmbeddingFunction() + + assert default_ef is not None + assert isinstance(default_ef, EmbeddingFunction) or isinstance( + default_ef, SparseEmbeddingFunction + ) + + +def test_ef_imports() -> None: + for ef in embedding_functions.get_builtins(): + # Langchain embedding function is a special snowflake + if ef == "ChromaLangchainEmbeddingFunction": + continue + assert hasattr(embedding_functions, ef) + assert isinstance(getattr(embedding_functions, ef), type) + assert issubclass( + getattr(embedding_functions, ef), EmbeddingFunction + ) or issubclass(getattr(embedding_functions, ef), SparseEmbeddingFunction) + + +@register_embedding_function +class CustomEmbeddingFunction(EmbeddingFunction[Embeddable]): + def __init__(self, dim: int = 3): + self._dim = dim + + @validation_context("custom_ef_call") + def __call__(self, input: Embeddable) -> Embeddings: + raise Exception("This is a test exception") + + @staticmethod + def name() -> str: + return "custom_ef" + + def get_config(self) -> Dict[str, Any]: + return {"dim": self._dim} + + @staticmethod + def build_from_config(config: Dict[str, Any]) -> "CustomEmbeddingFunction": + return CustomEmbeddingFunction(dim=config["dim"]) + + def default_space(self) -> Space: + return "cosine" + + +def test_validation_context_with_custom_ef() -> None: + custom_ef = CustomEmbeddingFunction() + + with pytest.raises(Exception) as excinfo: + custom_ef(["test data"]) + + original_msg = "This is a test exception" + expected_msg = f"{original_msg} in custom_ef_call." + assert str(excinfo.value) == expected_msg + assert excinfo.value.args == (expected_msg,) diff --git a/python/user_packages/Python313/site-packages/chromadb/test/ef/test_morph_ef.py b/python/user_packages/Python313/site-packages/chromadb/test/ef/test_morph_ef.py new file mode 100644 index 0000000000000000000000000000000000000000..6045b1a147e37b50feb2d5287ea8d0e245d4bf4a --- /dev/null +++ b/python/user_packages/Python313/site-packages/chromadb/test/ef/test_morph_ef.py @@ -0,0 +1,135 @@ +import os +import pytest +import numpy as np +from chromadb.utils.embedding_functions.morph_embedding_function import ( + MorphEmbeddingFunction, +) + + +def test_morph_embedding_function_with_api_key() -> None: + """Test Morph embedding function when API key is available.""" + if os.environ.get("MORPH_API_KEY") is None: + pytest.skip("MORPH_API_KEY not set") + + ef = MorphEmbeddingFunction( + model_name="morph-embedding-v2" + ) + + # Test with code snippets (Morph's specialty) + code_snippets = [ + "def hello_world():\n print('Hello, World!')", + "class Calculator:\n def add(self, a, b):\n return a + b" + ] + + embeddings = ef(code_snippets) + assert embeddings is not None + assert len(embeddings) == 2 + assert all(isinstance(emb, np.ndarray) for emb in embeddings) + assert all(len(emb) > 0 for emb in embeddings) + + +def test_morph_embedding_function_with_custom_parameters() -> None: + """Test Morph embedding function with custom parameters.""" + if os.environ.get("MORPH_API_KEY") is None: + pytest.skip("MORPH_API_KEY not set") + + ef = MorphEmbeddingFunction( + model_name="morph-embedding-v2", + api_base="https://api.morphllm.com/v1", + encoding_format="float", + api_key_env_var="MORPH_API_KEY" + ) + + # Test with a simple function + code_snippet = ["function add(a, b) { return a + b; }"] + + embeddings = ef(code_snippet) + assert embeddings is not None + assert len(embeddings) == 1 + assert isinstance(embeddings[0], np.ndarray) + assert len(embeddings[0]) > 0 + + +def test_morph_embedding_function_config_roundtrip() -> None: + """Test that Morph embedding function configuration can be saved and restored.""" + try: + import openai + except ImportError: + pytest.skip("openai package not installed") + + ef = MorphEmbeddingFunction( + model_name="morph-embedding-v2", + api_base="https://api.morphllm.com/v1", + encoding_format="float", + api_key_env_var="MORPH_API_KEY" + ) + + # Get configuration + config = ef.get_config() + + # Verify configuration contains expected keys + assert "model_name" in config + assert "api_base" in config + assert "encoding_format" in config + assert "api_key_env_var" in config + + # Verify values + assert config["model_name"] == "morph-embedding-v2" + assert config["api_base"] == "https://api.morphllm.com/v1" + assert config["encoding_format"] == "float" + assert config["api_key_env_var"] == "MORPH_API_KEY" + + # Test building from config + new_ef = MorphEmbeddingFunction.build_from_config(config) + new_config = new_ef.get_config() + + # Configurations should match + assert config == new_config + + +def test_morph_embedding_function_name() -> None: + """Test that Morph embedding function returns correct name.""" + assert MorphEmbeddingFunction.name() == "morph" + + +def test_morph_embedding_function_spaces() -> None: + """Test that Morph embedding function supports expected spaces.""" + try: + import openai + except ImportError: + pytest.skip("openai package not installed") + + ef = MorphEmbeddingFunction( + model_name="morph-embedding-v2", + api_key_env_var="MORPH_API_KEY" + ) + + # Test default space + assert ef.default_space() == "cosine" + + # Test supported spaces + supported_spaces = ef.supported_spaces() + assert "cosine" in supported_spaces + assert "l2" in supported_spaces + assert "ip" in supported_spaces + + +def test_morph_embedding_function_validate_config() -> None: + """Test that Morph embedding function validates configuration correctly.""" + # Valid configuration + valid_config = { + "model_name": "morph-embedding-v2", + "api_key_env_var": "MORPH_API_KEY" + } + + # This should not raise an exception + MorphEmbeddingFunction.validate_config(valid_config) + + # Invalid configuration (missing required fields) + invalid_config = { + "model_name": "morph-embedding-v2" + # Missing api_key_env_var + } + + with pytest.raises(Exception): + MorphEmbeddingFunction.validate_config(invalid_config) \ No newline at end of file diff --git a/python/user_packages/Python313/site-packages/chromadb/test/ef/test_multimodal_ef.py b/python/user_packages/Python313/site-packages/chromadb/test/ef/test_multimodal_ef.py new file mode 100644 index 0000000000000000000000000000000000000000..e34c14d87a76022dce552df1509a979b782ebfdf --- /dev/null +++ b/python/user_packages/Python313/site-packages/chromadb/test/ef/test_multimodal_ef.py @@ -0,0 +1,169 @@ +import os +from typing import Generator, cast +import numpy as np +import pytest +import chromadb +from chromadb.api.types import ( + Embeddable, + EmbeddingFunction, + Embeddings, + Image, + Document, +) +from chromadb.test.property.strategies import hashing_embedding_function +from chromadb.test.property.invariants import _exact_distances +from chromadb.config import Settings + + +# A 'standard' multimodal embedding function, which converts inputs to strings +# then hashes them to a fixed dimension. +class hashing_multimodal_ef(EmbeddingFunction[Embeddable]): + def __init__(self) -> None: + self._hef = hashing_embedding_function(dim=10, dtype=np.float64) + + def __call__(self, input: Embeddable) -> Embeddings: + to_texts = [str(i) for i in input] + embeddings = np.array(self._hef(to_texts)) + # Normalize the embeddings + # This is so we can generate random unit vectors and have them be close to the embeddings + embeddings /= np.linalg.norm(embeddings, axis=1, keepdims=True) # type: ignore[misc] + return cast(Embeddings, embeddings.tolist()) + + +def random_image() -> Image: + return np.random.randint(0, 255, size=(10, 10, 3), dtype=np.int64) + + +def random_document() -> Document: + return str(random_image()) + + +@pytest.fixture +def multimodal_collection( + default_ef: EmbeddingFunction[Embeddable] = hashing_multimodal_ef(), +) -> Generator[chromadb.Collection, None, None]: + settings = Settings() + if os.environ.get("CHROMA_INTEGRATION_TEST_ONLY"): + host = os.environ.get("CHROMA_SERVER_HOST", "localhost") + port = int(os.environ.get("CHROMA_SERVER_HTTP_PORT", 0)) + settings.chroma_api_impl = "chromadb.api.fastapi.FastAPI" + settings.chroma_server_http_port = port + settings.chroma_server_host = host + + client = chromadb.Client(settings=settings) + collection = client.create_collection( + name="multimodal_collection", embedding_function=default_ef + ) + yield collection + client.clear_system_cache() + + +# Test adding and querying of a multimodal collection consisting of images and documents +def test_multimodal( + multimodal_collection: chromadb.Collection, + default_ef: EmbeddingFunction[Embeddable] = hashing_multimodal_ef(), + n_examples: int = 10, + n_query_results: int = 3, +) -> None: + # Fix numpy's random seed for reproducibility + random_state = np.random.get_state() + np.random.seed(0) + + image_ids = [str(i) for i in range(n_examples)] + images = [random_image() for _ in range(n_examples)] + image_embeddings = default_ef(images) + + document_ids = [str(i) for i in range(n_examples, 2 * n_examples)] + documents = [random_document() for _ in range(n_examples)] + document_embeddings = default_ef(documents) + + # Trying to add a document and an image at the same time should fail + with pytest.raises( + ValueError, + # This error string may be in any order + match=r"Exactly one of (images|documents|uris)(?:, (images|documents|uris))?(?:, (images|documents|uris))? must be provided in add\.", + ): + multimodal_collection.add( + ids=image_ids[0], documents=documents[0], images=images[0] + ) + + # Add some documents + multimodal_collection.add(ids=document_ids, documents=documents) + # Add some images + multimodal_collection.add(ids=image_ids, images=images) + + # get() should return all the documents and images + # ids corresponding to images should not have documents + get_result = multimodal_collection.get(include=["documents"]) + assert len(get_result["ids"]) == len(document_ids) + len(image_ids) + for i, id in enumerate(get_result["ids"]): + assert id in document_ids or id in image_ids + assert get_result["documents"] is not None + if id in document_ids: + assert get_result["documents"][i] == documents[document_ids.index(id)] + if id in image_ids: + assert get_result["documents"][i] is None + + # Generate a random query image + query_image = random_image() + query_image_embedding = default_ef([query_image]) + + image_neighbor_indices, _ = _exact_distances( + query_image_embedding, image_embeddings + document_embeddings + ) + # Get the ids of the nearest neighbors + nearest_image_neighbor_ids = [ + image_ids[i] if i < n_examples else document_ids[i % n_examples] + for i in image_neighbor_indices[0][:n_query_results] + ] + + # Generate a random query document + query_document = random_document() + query_document_embedding = default_ef([query_document]) + document_neighbor_indices, _ = _exact_distances( + query_document_embedding, image_embeddings + document_embeddings + ) + nearest_document_neighbor_ids = [ + image_ids[i] if i < n_examples else document_ids[i % n_examples] + for i in document_neighbor_indices[0][:n_query_results] + ] + + # Querying with both images and documents should fail + with pytest.raises(ValueError): + multimodal_collection.query( + query_images=[query_image], query_texts=[query_document] + ) + + # Query with images + query_result = multimodal_collection.query( + query_images=[query_image], n_results=n_query_results, include=["documents"] + ) + + assert query_result["ids"][0] == nearest_image_neighbor_ids + + # Query with documents + query_result = multimodal_collection.query( + query_texts=[query_document], n_results=n_query_results, include=["documents"] + ) + + assert query_result["ids"][0] == nearest_document_neighbor_ids + np.random.set_state(random_state) + + +@pytest.mark.xfail +def test_multimodal_update_with_image( + multimodal_collection: chromadb.Collection, +) -> None: + # Updating an entry with an existing document should remove the documentß + + document = random_document() + image = random_image() + id = "0" + + multimodal_collection.add(ids=id, documents=document) + + multimodal_collection.update(ids=id, images=image) + + get_result = multimodal_collection.get(ids=id, include=["documents"]) + assert get_result["documents"] is not None + assert get_result["documents"][0] is None diff --git a/python/user_packages/Python313/site-packages/chromadb/test/ef/test_ollama_ef.py b/python/user_packages/Python313/site-packages/chromadb/test/ef/test_ollama_ef.py new file mode 100644 index 0000000000000000000000000000000000000000..9705497b6d79a76825b9abe547f6ab576ee74b5b --- /dev/null +++ b/python/user_packages/Python313/site-packages/chromadb/test/ef/test_ollama_ef.py @@ -0,0 +1,50 @@ +import pytest + +from chromadb.utils.embedding_functions.ollama_embedding_function import ( + OllamaEmbeddingFunction, +) + + +def test_ollama_default_model() -> None: + pytest.importorskip("ollama", reason="ollama not installed") + ef = OllamaEmbeddingFunction() + embeddings = ef(["Here is an article about llamas...", "this is another article"]) + assert embeddings is not None + assert len(embeddings) == 2 + assert all(len(e) == 384 for e in embeddings) + + +def test_ollama_unknown_model() -> None: + pytest.importorskip("ollama", reason="ollama not installed") + model_name = "unknown-model" + ef = OllamaEmbeddingFunction(model_name=model_name) + with pytest.raises(Exception) as e: + ef(["Here is an article about llamas...", "this is another article"]) + assert f'model "{model_name}" not found' in str(e.value) + + +def test_ollama_backward_compat() -> None: + pytest.importorskip("ollama", reason="ollama not installed") + ef = OllamaEmbeddingFunction(url="http://localhost:11434/api/embeddings") + embeddings = ef(["Here is an article about llamas...", "this is another article"]) + assert embeddings is not None + + +def test_wrong_url() -> None: + pytest.importorskip("ollama", reason="ollama not installed") + ef = OllamaEmbeddingFunction(url="http://localhost:11434/this_is_wrong") + with pytest.raises(Exception) as e: + ef(["Here is an article about llamas...", "this is another article"]) + assert "404" in str(e.value) + + +def test_ollama_ask_user_to_install() -> None: + try: + from ollama import Client # noqa: F401 + except ImportError: + pass + else: + pytest.skip("ollama python package is installed") + with pytest.raises(ValueError) as e: + OllamaEmbeddingFunction() + assert "The ollama python package is not installed" in str(e.value) diff --git a/python/user_packages/Python313/site-packages/chromadb/test/ef/test_onnx_mini_lm_l6_v2.py b/python/user_packages/Python313/site-packages/chromadb/test/ef/test_onnx_mini_lm_l6_v2.py new file mode 100644 index 0000000000000000000000000000000000000000..edee2fa2f16754641cab5d0d5502a5ec009bb538 --- /dev/null +++ b/python/user_packages/Python313/site-packages/chromadb/test/ef/test_onnx_mini_lm_l6_v2.py @@ -0,0 +1,204 @@ +import os +import tempfile +from typing import Dict, Any + +import numpy as np +from numpy.typing import NDArray +import pytest +import onnxruntime +from unittest.mock import patch, MagicMock + +from chromadb.utils.embedding_functions import ONNXMiniLM_L6_V2, EmbeddingFunction + + +class TestONNXMiniLM_L6_V2: + """Test suite for ONNXMiniLM_L6_V2 embedding function.""" + + def test_initialization(self) -> None: + """Test that the embedding function initializes correctly.""" + ef = ONNXMiniLM_L6_V2() + assert ef is not None + assert isinstance(ef, EmbeddingFunction) + + # Test with valid providers + available_providers = onnxruntime.get_available_providers() + if available_providers: + ef = ONNXMiniLM_L6_V2(preferred_providers=[available_providers[0]]) + assert ef is not None + + # Test with None providers + ef = ONNXMiniLM_L6_V2(preferred_providers=None) + assert ef is not None + + def test_embedding_shape_and_normalization(self) -> None: + """Test that embeddings have the correct shape and are normalized.""" + ef = ONNXMiniLM_L6_V2() + + # Test with a single document + docs = ["This is a test document"] + embeddings = ef(docs) + + # Check shape and type + assert isinstance(embeddings, list) + assert len(embeddings) == 1 + assert ( + len(embeddings[0]) == 384 + ) # MiniLM-L6-v2 produces 384-dimensional embeddings + + # Check normalization (for cosine similarity) + embedding_np = np.array(embeddings[0]) + norm = np.linalg.norm(embedding_np) + assert np.isclose(norm, 1.0, atol=1e-5) + + # Test with multiple documents + docs = ["First document", "Second document", "Third document"] + embeddings = ef(docs) + + # Check shape + assert len(embeddings) == 3 + assert all(len(emb) == 384 for emb in embeddings) + + def test_batch_processing(self) -> None: + """Test that the embedding function correctly processes batches.""" + ef = ONNXMiniLM_L6_V2() + + # Create a list of documents larger than the default batch size (32) + docs = [f"Document {i}" for i in range(40)] + + # Get embeddings + embeddings = ef(docs) + + # Check that all documents were processed + assert len(embeddings) == 40 + assert all(len(emb) == 384 for emb in embeddings) + + def test_config_serialization(self) -> None: + """Test that the embedding function can be serialized and deserialized.""" + # Create an embedding function with specific providers + available_providers = onnxruntime.get_available_providers() + providers = available_providers[:1] if available_providers else None + ef = ONNXMiniLM_L6_V2(preferred_providers=providers) + + # Get config + config = ef.get_config() + + # Check config + assert isinstance(config, dict) + assert "preferred_providers" in config + + # Build from config + ef2 = ONNXMiniLM_L6_V2.build_from_config(config) + + # Check that the new instance works + docs = ["Test document"] + embeddings = ef2(docs) + assert len(embeddings) == 1 + assert len(embeddings[0]) == 384 + + def test_max_tokens(self) -> None: + """Test the max_tokens method.""" + ef = ONNXMiniLM_L6_V2() + assert ef.max_tokens() == 256 # Default for this model + + @patch("httpx.stream") + def test_download_functionality(self, mock_stream: MagicMock) -> None: + """Test the model download functionality with mocking.""" + # Setup mock response + mock_response = MagicMock() + mock_response.raise_for_status.return_value = None + mock_response.headers.get.return_value = "1000" + mock_response.iter_bytes.return_value = [b"test data"] + mock_stream.return_value.__enter__.return_value = mock_response + + # Create a temporary directory for testing + with tempfile.TemporaryDirectory() as temp_dir: + # Patch the download path + with patch.object(ONNXMiniLM_L6_V2, "DOWNLOAD_PATH", temp_dir): + with patch( + "chromadb.utils.embedding_functions.onnx_mini_lm_l6_v2._verify_sha256", + return_value=True, + ): + ef = ONNXMiniLM_L6_V2() + # Call download method directly + ef._download( + url="https://test.url", + fname=os.path.join(temp_dir, "test_file"), + ) + + # Check that the file was created + assert os.path.exists(os.path.join(temp_dir, "test_file")) + + def test_validate_config(self) -> None: + """Test config validation.""" + ef = ONNXMiniLM_L6_V2() + + # Test validate_config + config: Dict[str, Any] = {"preferred_providers": ["CPUExecutionProvider"]} + ef.validate_config(config) # Should not raise + + # Test validate_config_update + old_config: Dict[str, Any] = {"preferred_providers": ["CPUExecutionProvider"]} + new_config: Dict[str, Any] = {"preferred_providers": ["CUDAExecutionProvider"]} + ef.validate_config_update(old_config, new_config) # Should not raise + + @pytest.mark.parametrize( + "input_text", + [ + "Short text", + "A longer text that contains multiple words and should be embedded properly", + "", # Empty string + "Special characters: !@#$%^&*()", + "Numbers: 1234567890", + "Unicode: 你好, こんにちは, 안녕하세요", + ], + ) + def test_various_inputs(self, input_text: str) -> None: + """Test the embedding function with various types of input text.""" + ef = ONNXMiniLM_L6_V2() + + # Get embeddings + embeddings = ef([input_text]) + + # Check that embeddings were generated + assert len(embeddings) == 1 + assert len(embeddings[0]) == 384 + + def test_consistency(self) -> None: + """Test that the embedding function produces consistent results.""" + ef = ONNXMiniLM_L6_V2() + + # Get embeddings for the same text twice + text = "This is a test document" + embeddings1 = ef([text]) + embeddings2 = ef([text]) + + # Check that the embeddings are the same + np.testing.assert_allclose(embeddings1[0], embeddings2[0]) + + def test_similar_texts_have_similar_embeddings(self) -> None: + """Test that similar texts have similar embeddings.""" + ef = ONNXMiniLM_L6_V2() + + # Get embeddings for similar texts + text1 = "The cat sat on the mat" + text2 = "A cat was sitting on a mat" + text3 = "Quantum physics is fascinating" + + embeddings = ef([text1, text2, text3]) + + # Calculate cosine similarities + def cosine_similarity(a: NDArray[np.float32], b: NDArray[np.float32]) -> float: + return float(np.dot(a, b) / (np.linalg.norm(a) * np.linalg.norm(b))) + + # Similar texts should have higher similarity + sim_1_2 = cosine_similarity( + np.array(embeddings[0], dtype=np.float32), + np.array(embeddings[1], dtype=np.float32), + ) + sim_1_3 = cosine_similarity( + np.array(embeddings[0], dtype=np.float32), + np.array(embeddings[2], dtype=np.float32), + ) + + # The similarity between text1 and text2 should be higher than between text1 and text3 + assert sim_1_2 > sim_1_3 diff --git a/python/user_packages/Python313/site-packages/chromadb/test/ef/test_openai_ef.py b/python/user_packages/Python313/site-packages/chromadb/test/ef/test_openai_ef.py new file mode 100644 index 0000000000000000000000000000000000000000..600613997adba65b27b73b2aaf778b065710ca76 --- /dev/null +++ b/python/user_packages/Python313/site-packages/chromadb/test/ef/test_openai_ef.py @@ -0,0 +1,38 @@ +import os + +import pytest + +from chromadb.utils.embedding_functions.openai_embedding_function import ( + OpenAIEmbeddingFunction, +) + + +def test_with_embedding_dimensions() -> None: + if os.environ.get("OPENAI_API_KEY") is None: + pytest.skip("OPENAI_API_KEY not set") + ef = OpenAIEmbeddingFunction( + api_key=os.environ["OPENAI_API_KEY"], + model_name="text-embedding-3-small", + dimensions=64, + ) + embeddings = ef(["hello world"]) + assert embeddings is not None + assert len(embeddings) == 1 + assert len(embeddings[0]) == 64 + + +def test_with_embedding_dimensions_not_working_with_old_model() -> None: + if os.environ.get("OPENAI_API_KEY") is None: + pytest.skip("OPENAI_API_KEY not set") + ef = OpenAIEmbeddingFunction(api_key=os.environ["OPENAI_API_KEY"], dimensions=64) + with pytest.raises( + Exception, match="This model does not support specifying dimensions" + ): + ef(["hello world"]) + + +def test_with_incorrect_api_key() -> None: + pytest.importorskip("openai", reason="openai not installed") + ef = OpenAIEmbeddingFunction(api_key="incorrect_api_key", dimensions=64) + with pytest.raises(Exception, match="Incorrect API key provided"): + ef(["hello world"]) diff --git a/python/user_packages/Python313/site-packages/chromadb/test/ef/test_voyageai_ef.py b/python/user_packages/Python313/site-packages/chromadb/test/ef/test_voyageai_ef.py new file mode 100644 index 0000000000000000000000000000000000000000..fbf1c615b183c5102936b15023b9bb518a289d34 --- /dev/null +++ b/python/user_packages/Python313/site-packages/chromadb/test/ef/test_voyageai_ef.py @@ -0,0 +1,19 @@ +import os +import pytest +from chromadb.utils.embedding_functions.voyageai_embedding_function import ( + VoyageAIEmbeddingFunction, +) + +voyageai = pytest.importorskip("voyageai", reason="voyageai not installed") + + +def test_with_embedding_dimensions() -> None: + if os.environ.get("CHROMA_VOYAGE_API_KEY") is None: + pytest.skip("CHROMA_VOYAGE_API_KEY not set") + ef = VoyageAIEmbeddingFunction( + api_key=os.environ["CHROMA_VOYAGE_API_KEY"] + ) + embeddings = ef(["hello world"]) + assert embeddings is not None + assert len(embeddings) == 1 + assert len(embeddings[0]) == 1536 diff --git a/python/user_packages/Python313/site-packages/chromadb/test/openssl.cnf b/python/user_packages/Python313/site-packages/chromadb/test/openssl.cnf new file mode 100644 index 0000000000000000000000000000000000000000..54e3c5bfdb1e88df66b3ae397427616d256bd8e5 --- /dev/null +++ b/python/user_packages/Python313/site-packages/chromadb/test/openssl.cnf @@ -0,0 +1,12 @@ +[req] +distinguished_name = req_distinguished_name +x509_extensions = usr_cert + +[req_distinguished_name] +CN = localhost + +[usr_cert] +subjectAltName = @alt_names + +[alt_names] +DNS.1 = localhost diff --git a/python/user_packages/Python313/site-packages/chromadb/test/property/invariants.py b/python/user_packages/Python313/site-packages/chromadb/test/property/invariants.py new file mode 100644 index 0000000000000000000000000000000000000000..9604ea457b7800176e828eb51fc78b5239b8cfd5 --- /dev/null +++ b/python/user_packages/Python313/site-packages/chromadb/test/property/invariants.py @@ -0,0 +1,621 @@ +import gc +import math +import os.path +from uuid import UUID +from contextlib import contextmanager + +from chromadb.api.segment import SegmentAPI +from chromadb.db.system import SysDB +from chromadb.ingest.impl.utils import create_topic_name + +from chromadb.config import System +from chromadb.db.base import get_sql +from chromadb.db.impl.sqlite import SqliteDB +from time import sleep +import psutil + +from chromadb.segment import SegmentType +from chromadb.test.property.strategies import NormalizedRecordSet, RecordSet +from typing import Callable, Optional, Tuple, Union, List, TypeVar, cast, Any, Dict +from typing_extensions import Literal +import numpy as np +import numpy.typing as npt +from chromadb.api import types, ClientAPI +from chromadb.api.models.Collection import Collection +from hypothesis import note +from hypothesis.errors import InvalidArgument +from pypika import Table, functions + +from chromadb.utils import distance_functions +from chromadb.execution.expression.plan import Search +from chromadb.execution.expression.operator import Knn, Select, Limit, Key + +T = TypeVar("T") + + +def wrap(value: Union[T, List[T]]) -> List[T]: + """Wrap a value in a list if it is not a list""" + if value is None: + raise InvalidArgument("value cannot be None") + elif isinstance(value, List): + return value + else: + return [value] + + +def wrap_all(record_set: RecordSet) -> NormalizedRecordSet: + """Ensure that an embedding set has lists for all its values""" + + embedding_list: Optional[types.Embeddings] + if record_set["embeddings"] is None: + embedding_list = None + elif isinstance(record_set["embeddings"], list): + assert record_set["embeddings"] is not None + if len(record_set["embeddings"]) > 0: + if all( + isinstance(embedding, list) for embedding in record_set["embeddings"] + ): + embedding_list = cast(types.Embeddings, record_set["embeddings"]) + elif all( + isinstance(embedding, np.ndarray) + for embedding in record_set["embeddings"] + ): + embedding_list = cast(types.Embeddings, record_set["embeddings"]) + else: + if all( + isinstance(e, (int, float, np.integer, np.floating)) + for e in record_set["embeddings"] + ): + embedding_list = cast(types.Embeddings, [record_set["embeddings"]]) + else: + raise InvalidArgument( + "an embedding must be a list of floats or ints" + ) + else: + embedding_list = cast(types.Embeddings, record_set["embeddings"]) + else: + raise InvalidArgument( + "embeddings must be a list of lists, a list of numpy arrays, a list of numbers, or None" + ) + + return NormalizedRecordSet( + ids=wrap(record_set["ids"]), + documents=wrap(record_set["documents"]) + if record_set["documents"] is not None + else None, + metadatas=wrap(record_set["metadatas"]) + if record_set["metadatas"] is not None + else None, + embeddings=embedding_list, + ) + + +def check_metadata( + expected: Optional[types.Metadata], got: Optional[types.Metadata] +) -> None: + assert (expected is None and got is None) or ( + expected is not None and got is not None + ) + if expected is not None and got is not None: + assert len(expected) == len(got) + for key, val in expected.items(): + assert key in got + if isinstance(expected[key], float) and isinstance(got[key], float): + assert abs(cast(float, expected[key]) - cast(float, got[key])) < 1e-6 + else: + assert expected[key] == got[key] + + +def count(collection: Collection, record_set: RecordSet) -> None: + """The given collection count is equal to the number of embeddings""" + count = collection.count() + normalized_record_set = wrap_all(record_set) + if count != len(normalized_record_set["ids"]): + print("count mismatch:", count, "=!", len(normalized_record_set["ids"])) + assert count == len(normalized_record_set["ids"]) + + +def _field_matches( + collection: Collection, + normalized_record_set: NormalizedRecordSet, + field_name: Union[ + Literal["documents"], Literal["metadatas"], Literal["embeddings"] + ], +) -> None: + """ + The actual embedding field is equal to the expected field + field_name: one of [documents, metadatas] + """ + result = collection.get(ids=normalized_record_set["ids"], include=[field_name]) # type: ignore[list-item] + # The test_out_of_order_ids test fails because of this in test_add.py + # Here we sort by the ids to match the input order + embedding_id_to_index = {id: i for i, id in enumerate(normalized_record_set["ids"])} + actual_field = result[field_name] + + if len(normalized_record_set["ids"]) == 0: + if field_name == "embeddings": + assert cast(npt.NDArray[Any], actual_field).size == 0 + else: + assert actual_field == [] + return + + # This assert should never happen, if we include metadatas/documents it will be + # [None, None..] if there is no metadata. It will not be just None. + assert actual_field is not None + sorted_field = sorted( + enumerate(actual_field), + key=lambda index_and_field_value: embedding_id_to_index[ + result["ids"][index_and_field_value[0]] + ], + ) + field_values = [field_value for _, field_value in sorted_field] + + expected_field = normalized_record_set[field_name] + if expected_field is None: + # Since an RecordSet is the user input, we need to convert the documents to + # a List since thats what the API returns -> none per entry + expected_field = [None] * len(normalized_record_set["ids"]) # type: ignore + if field_name == "embeddings": + assert np.allclose(np.array(field_values), np.array(expected_field)) + else: + assert len(field_values) == len(expected_field) + + for field_value, expected_field in zip(field_values, expected_field): + if isinstance(expected_field, dict): + check_metadata( + cast(types.Metadata, field_value), + cast(types.Metadata, expected_field), + ) + else: + assert field_value == expected_field + + +def ids_match(collection: Collection, record_set: RecordSet) -> None: + """The actual embedding ids is equal to the expected ids""" + normalized_record_set = wrap_all(record_set) + actual_ids = collection.get(ids=normalized_record_set["ids"], include=[])["ids"] + # The test_out_of_order_ids test fails because of this in test_add.py + # Here we sort the ids to match the input order + embedding_id_to_index = {id: i for i, id in enumerate(normalized_record_set["ids"])} + actual_ids = sorted(actual_ids, key=lambda id: embedding_id_to_index[id]) + assert actual_ids == normalized_record_set["ids"] + + +def metadatas_match(collection: Collection, record_set: RecordSet) -> None: + """The actual embedding metadata is equal to the expected metadata""" + normalized_record_set = wrap_all(record_set) + _field_matches(collection, normalized_record_set, "metadatas") + + +def documents_match(collection: Collection, record_set: RecordSet) -> None: + """The actual embedding documents is equal to the expected documents""" + normalized_record_set = wrap_all(record_set) + _field_matches(collection, normalized_record_set, "documents") + + +def embeddings_match(collection: Collection, record_set: RecordSet) -> None: + """The actual embedding documents is equal to the expected documents""" + normalized_record_set = wrap_all(record_set) + _field_matches(collection, normalized_record_set, "embeddings") + + +def no_duplicates(collection: Collection) -> None: + ids = collection.get()["ids"] + assert len(ids) == len(set(ids)) + + +def _exact_distances( + query: types.Embeddings, + targets: types.Embeddings, + distance_fn: Callable[ + [npt.ArrayLike, npt.ArrayLike], float + ] = distance_functions.l2, +) -> Tuple[List[List[int]], List[List[float]]]: + """Return the ordered indices and distances from each query to each target""" + np_query = np.array(query, dtype=np.float32) + np_targets = np.array(targets, dtype=np.float32) + + # Compute the distance between each query and each target, using the distance function + distances = np.apply_along_axis( + lambda query: np.apply_along_axis(distance_fn, 1, np_targets, query), + 1, + np_query, + ) + # Sort the distances and return the indices + return np.argsort(distances).tolist(), distances.tolist() + + +def fd_not_exceeding_threadpool_size(threadpool_size: int) -> None: + """ + Checks that the open file descriptors are not exceeding the threadpool size + works only for SegmentAPI + """ + current_process = psutil.Process() + open_files = current_process.open_files() + max_retries = 5 + retry_count = 0 + # we probably don't need the below but we keep it to avoid flaky tests. + while ( + len([p.path for p in open_files if "sqlite3" in p.path]) - 1 > threadpool_size + and retry_count < max_retries + ): + gc.collect() # GC to collect the orphaned TLS objects + open_files = current_process.open_files() + retry_count += 1 + sleep(1) + assert ( + len([p.path for p in open_files if "sqlite3" in p.path]) - 1 <= threadpool_size + ) + + +def get_space(collection: Collection): + # TODO: this is a hack to get the space + # We should update the tests to not pass space via metadata instead use collection + # configuration_json + space = None + metadata = collection.metadata or {} + if "hnsw:space" in metadata: + space = metadata["hnsw:space"] + if collection._model.configuration_json is None: + return space + if ( + "spann" in collection._model.configuration_json + and collection._model.configuration_json.get("spann") is not None + and "space" in collection._model.configuration_json.get("spann") + ): + space = collection._model.configuration_json.get("spann").get("space") + elif ( + "hnsw" in collection._model.configuration_json + and collection._model.configuration_json.get("hnsw") is not None + and "space" in collection._model.configuration_json.get("hnsw") + ): + if space is None: + space = collection._model.configuration_json.get("hnsw").get("space") + return space + + +def ann_accuracy( + collection: Collection, + record_set: RecordSet, + n_results: int = 1, + min_recall: float = 0.95, + embedding_function: Optional[types.EmbeddingFunction] = None, # type: ignore[type-arg] + query_indices: Optional[List[int]] = None, + query_embeddings: Optional[types.Embeddings] = None, + use_search: bool = False, +) -> None: + """Validate that the API performs nearest_neighbor searches correctly""" + normalized_record_set = wrap_all(record_set) + + if len(normalized_record_set["ids"]) == 0: + return # nothing to test here + + embeddings: Optional[types.Embeddings] = normalized_record_set["embeddings"] + have_embeddings = embeddings is not None and len(embeddings) > 0 + if not have_embeddings: + assert embedding_function is not None + assert normalized_record_set["documents"] is not None + assert isinstance(normalized_record_set["documents"], list) + # Compute the embeddings for the documents + embeddings = embedding_function(normalized_record_set["documents"]) + + space = get_space(collection) + if space is None: + distance_function = distance_functions.l2 + elif space == "cosine": + distance_function = distance_functions.cosine + elif space == "ip": + distance_function = distance_functions.ip + elif space == "l2": + distance_function = distance_functions.l2 + + accuracy_threshold = 1e-6 + assert embeddings is not None + # TODO: ip and cosine are numerically unstable in HNSW. + # The higher the dimensionality, the more noise is introduced, since each float element + # of the vector has noise added, which is then subsequently included in all normalization calculations. + # This means that higher dimensions will have more noise, and thus more error. + assert all(isinstance(e, (list, np.ndarray)) for e in embeddings) + dim = len(embeddings[0]) + accuracy_threshold = accuracy_threshold * math.pow(10, int(math.log10(dim))) + + # Perform exact distance computation + if query_embeddings is None: + query_embeddings = ( + embeddings + if query_indices is None + else [embeddings[i] for i in query_indices] + ) + query_documents = normalized_record_set["documents"] + if query_indices is not None and query_documents is not None: + query_documents = [query_documents[i] for i in query_indices] + + indices, distances = _exact_distances( + query_embeddings, embeddings, distance_fn=distance_function + ) + + if use_search: + # Use search API instead of query + search_requests = [] + for query_embedding in query_embeddings: + # Convert numpy array to list if needed + if isinstance(query_embedding, np.ndarray): + query_embedding_list = query_embedding.tolist() + else: + query_embedding_list = query_embedding + search = Search( + rank=Knn(query=query_embedding_list), + limit=Limit(limit=n_results), + ).select_all() + search_requests.append(search) + + # Call search API + search_results = collection.search( + searches=search_requests, + ) + + # Convert search results to query-like format + query_results = cast( + types.QueryResult, + { + "ids": search_results["ids"], + "distances": search_results[ + "scores" + ], # scores is distances in search API + "embeddings": search_results["embeddings"], + "documents": search_results["documents"], + "metadatas": search_results["metadatas"], + }, + ) + else: + query_results = collection.query( + query_embeddings=query_embeddings if have_embeddings else None, + query_texts=query_documents if not have_embeddings else None, + n_results=n_results, + include=["embeddings", "documents", "metadatas", "distances"], # type: ignore[list-item] + ) + + _query_results_are_correct_shape(query_results, n_results) + + # Assert fields are not None for type checking + assert query_results["ids"] is not None + assert query_results["distances"] is not None + assert query_results["embeddings"] is not None + assert query_results["documents"] is not None + assert query_results["metadatas"] is not None + + # Dict of ids to indices + id_to_index = {id: i for i, id in enumerate(normalized_record_set["ids"])} + missing = 0 + for i, (indices_i, distances_i) in enumerate(zip(indices, distances)): + expected_ids = np.array(normalized_record_set["ids"])[indices_i[:n_results]] + missing += len(set(expected_ids) - set(query_results["ids"][i])) + + # For each id in the query results, find the index in the embeddings set + # and assert that the embeddings are the same + for j, id in enumerate(query_results["ids"][i]): + # This may be because the true nth nearest neighbor didn't get returned by the ANN query + unexpected_id = id not in expected_ids + index = id_to_index[id] + + correct_distance = np.allclose( + distances_i[index], + query_results["distances"][i][j], + atol=accuracy_threshold, + ) + if unexpected_id: + # If the ID is unexpcted, but the distance is correct, then we + # have a duplicate in the data. In this case, we should not reduce recall. + if correct_distance: + missing -= 1 + else: + continue + else: + assert correct_distance + + assert np.allclose(embeddings[index], query_results["embeddings"][i][j]) + if normalized_record_set["documents"] is not None: + assert ( + normalized_record_set["documents"][index] + == query_results["documents"][i][j] + ) + if normalized_record_set["metadatas"] is not None: + check_metadata( + normalized_record_set["metadatas"][index], + query_results["metadatas"][i][j], + ) + + size = len(normalized_record_set["ids"]) + recall = (size - missing) / size + + try: + note( + f"# recall: {recall}, missing {missing} out of {size}, accuracy threshold {accuracy_threshold}" + ) + except InvalidArgument: + pass # it's ok if we're running outside hypothesis + + assert recall >= min_recall + + # Ensure that the query results are sorted by distance + for distance_result in query_results["distances"]: + assert np.allclose(np.sort(distance_result), distance_result) + + +def _query_results_are_correct_shape( + query_results: types.QueryResult, n_results: int +) -> None: + for result_type in ["distances", "embeddings", "documents", "metadatas"]: + assert query_results[result_type] is not None # type: ignore[literal-required] + assert all( + len(result) == n_results for result in query_results[result_type] # type: ignore[literal-required] + ) + + +def _total_embedding_queue_log_size(sqlite: SqliteDB) -> int: + t = Table("embeddings_queue") + q = sqlite.querybuilder().from_(t) + + with sqlite.tx() as cur: + sql, params = get_sql( + q.select(functions.Count(t.seq_id)), sqlite.parameter_format() + ) + result = cur.execute(sql, params) + return cast(int, result.fetchone()[0]) + + +def log_size_below_max( + system: System, collections: List[Collection], has_collection_mutated: bool +) -> None: + sqlite = system.instance(SqliteDB) + + # Ephemeral Rust client is using its own sqlite impl, which cannot be accessed from Python + if ( + not system.settings.is_persistent + and system.settings.chroma_api_impl == "chromadb.api.rust.RustBindingsAPI" + ): + return + + if has_collection_mutated: + # Must always keep one entry to avoid reusing seq_ids + assert _total_embedding_queue_log_size(sqlite) >= 1 + + # We purge per-collection as the sync_threshold is a per-collection setting + sync_threshold_sum = sum( + collection.metadata.get("hnsw:sync_threshold", 1000) + if collection.metadata is not None + else 1000 + for collection in collections + ) + batch_size_sum = sum( + collection.metadata.get("hnsw:batch_size", 100) + if collection.metadata is not None + else 100 + for collection in collections + ) + + limit = ( + sync_threshold_sum + if system.settings.chroma_api_impl == "chromadb.api.rust.RustBindingsAPI" + else sync_threshold_sum + batch_size_sum + ) + + # -1 is used because the queue is always at least 1 entry long, so deletion stops before the max ack'ed sequence ID. + # And for python impl if the batch_size != sync_threshold, the queue can have up to batch_size more entries. + assert _total_embedding_queue_log_size(sqlite) - 1 <= limit + else: + assert _total_embedding_queue_log_size(sqlite) == 0 + + +def _total_embedding_queue_log_size_per_collection( + system: System, + collections: List[Collection], +) -> Dict[UUID, int]: + sqlite = system.instance(SqliteDB) + t = Table("embeddings_queue") + q = sqlite.querybuilder().from_(t) + _tenant = system.settings.require("tenant_id") + _topic_namespace = system.settings.require("topic_namespace") + topic_mappings = { + create_topic_name(_tenant, _topic_namespace, collection.id): collection + for collection in collections + } + with sqlite.tx() as cur: + sql, params = get_sql( + q.select(t.topic, functions.Count(t.seq_id)).groupby("topic"), + sqlite.parameter_format(), + ) + result = cur.execute(sql, params) + out = {} + for res in result.fetchall(): + out[topic_mappings[res[0]].id] = res[1] + return out + + +def log_size_for_collections_match_expected( + system: System, collections: List[Collection], has_collection_mutated: bool +) -> None: + if system.settings.chroma_api_impl == "chromadb.api.rust.RustBindingsAPI": + # The rust impl does not use batch size + return + + sqlite = system.instance(SqliteDB) + + if has_collection_mutated: + # Must always keep one entry to avoid reusing seq_ids + assert _total_embedding_queue_log_size(sqlite) >= 1 + + batch_size_sum = { + collection.id: collection.metadata.get("hnsw:batch_size", 100) + if collection.metadata is not None + else 100 + for collection in collections + } + expected_sizes = { + collection.id: collection.count() % batch_size_sum[collection.id] + 1 + for collection in collections + } + + actual_sizes = _total_embedding_queue_log_size_per_collection( + system, collections + ) + assert set(actual_sizes.keys()) == set(expected_sizes.keys()) + assert all( + actual_sizes[collection.id] == expected_sizes[collection.id] + for collection in collections + ) + + else: + assert _total_embedding_queue_log_size(sqlite) == 0 + + +@contextmanager +def collection_deleted(client: ClientAPI, collection_name: str): + # Invariant checks before deletion + collection_names = [c.name for c in client.list_collections()] + assert collection_name in collection_names + collection = client.get_collection(collection_name) + segments = [] + if isinstance(client._server, SegmentAPI): # type: ignore + sysdb: SysDB = client._server._sysdb # type: ignore + segments = sysdb.get_segments(collection=collection.id) + segment_types = {} + should_have_hnsw = False + for segment in segments: + segment_types[segment["type"]] = True + if segment["type"] == SegmentType.HNSW_LOCAL_PERSISTED.value: + sync_threshold = ( + collection.metadata["hnsw:sync_threshold"] + if collection.metadata is not None + and "hnsw:sync_threshold" in collection.metadata + else 1000 + ) + if ( + collection.count() > sync_threshold + ): # we only check if vector segment dir exists if we've synced at least once + should_have_hnsw = True + assert os.path.exists( + os.path.join( + client.get_settings().persist_directory, str(segment["id"]) + ) + ) + if should_have_hnsw: + assert segment_types[SegmentType.HNSW_LOCAL_PERSISTED.value] + assert segment_types[SegmentType.SQLITE.value] + + yield + + # Invariant checks after deletion + collection_names = [c.name for c in client.list_collections()] + assert collection_name not in collection_names + if len(segments) > 0: + sysdb: SysDB = client._server._sysdb # type: ignore + segments_after = sysdb.get_segments(collection=collection.id) + assert len(segments_after) == 0 + for segment in segments: + if segment["type"] == SegmentType.HNSW_LOCAL_PERSISTED.value: + assert not os.path.exists( + os.path.join( + client.get_settings().persist_directory, str(segment["id"]) + ) + ) diff --git a/python/user_packages/Python313/site-packages/chromadb/test/property/strategies.py b/python/user_packages/Python313/site-packages/chromadb/test/property/strategies.py new file mode 100644 index 0000000000000000000000000000000000000000..46cf4d2f7316d20cda01eebc41fee27babc4a8de --- /dev/null +++ b/python/user_packages/Python313/site-packages/chromadb/test/property/strategies.py @@ -0,0 +1,1113 @@ +import hashlib +import hypothesis +import hypothesis.strategies as st +from typing import Any, Optional, List, Dict, Union, cast, Tuple +from typing_extensions import TypedDict +import uuid +import numpy as np +import numpy.typing as npt +import chromadb.api.types as types +import re +from hypothesis.strategies._internal.strategies import SearchStrategy +from chromadb.test.api.test_schema_e2e import ( + SimpleEmbeddingFunction, + DeterministicSparseEmbeddingFunction, +) +from chromadb.test.conftest import NOT_CLUSTER_ONLY +from dataclasses import dataclass +from chromadb.api.types import ( + Documents, + Embeddable, + EmbeddingFunction, + Embeddings, + Metadata, + Schema, + CollectionMetadata, + VectorIndexConfig, + SparseVectorIndexConfig, + StringInvertedIndexConfig, + IntInvertedIndexConfig, + FloatInvertedIndexConfig, + BoolInvertedIndexConfig, + HnswIndexConfig, + SpannIndexConfig, + Space, +) +from chromadb.types import LiteralValue, WhereOperator, LogicalOperator +from chromadb.test.conftest import is_spann_disabled_mode +from chromadb.api.collection_configuration import ( + CreateCollectionConfiguration, + CreateSpannConfiguration, + CreateHNSWConfiguration, +) +from chromadb.utils.embedding_functions import ( + register_embedding_function, +) + +# Set the random seed for reproducibility +np.random.seed(0) # unnecessary, hypothesis does this for us + +# See Hypothesis documentation for creating strategies at +# https://hypothesis.readthedocs.io/en/latest/data.html + +# NOTE: Because these strategies are used in state machines, we need to +# work around an issue with state machines, in which strategies that frequently +# are marked as invalid (i.e. through the use of `assume` or `.filter`) can cause the +# state machine tests to fail with an hypothesis.errors.Unsatisfiable. + +# Ultimately this is because the entire state machine is run as a single Hypothesis +# example, which ends up drawing from the same strategies an enormous number of times. +# Whenever a strategy marks itself as invalid, Hypothesis tries to start the entire +# state machine run over. See https://github.com/HypothesisWorks/hypothesis/issues/3618 + +# Because strategy generation is all interrelated, seemingly small changes (especially +# ones called early in a test) can have an outside effect. Generating lists with +# unique=True, or dictionaries with a min size seems especially bad. + +# Please make changes to these strategies incrementally, testing to make sure they don't +# start generating unsatisfiable examples. + +test_hnsw_config = { + "hnsw:construction_ef": 128, + "hnsw:search_ef": 128, + "hnsw:M": 128, +} + + +class _TruncatedReprDict(dict): # type: ignore[type-arg] + """Dict subclass that truncates its repr to avoid overwhelming output in hypothesis error messages.""" + + _REPR_MAX_LEN = 1000 + + def __repr__(self) -> str: + full = super().__repr__() + if len(full) <= self._REPR_MAX_LEN: + return full + return full[: self._REPR_MAX_LEN] + "...}" + + +class RecordSet(_TruncatedReprDict): + """ + A generated set of embeddings, ids, metadatas, and documents that + represent what a user would pass to the API. + """ + + ids: Union[types.ID, List[types.ID]] + embeddings: Optional[Union[types.Embeddings, types.Embedding]] + metadatas: Optional[Union[List[Optional[types.Metadata]], types.Metadata]] + documents: Optional[Union[List[types.Document], types.Document]] + + +class NormalizedRecordSet(_TruncatedReprDict): + """ + A RecordSet, with all fields normalized to lists. + """ + + ids: List[types.ID] + embeddings: Optional[types.Embeddings] + metadatas: Optional[List[Optional[types.Metadata]]] + documents: Optional[List[types.Document]] + + +class StateMachineRecordSet(_TruncatedReprDict): + """ + Represents the internal state of a state machine in hypothesis tests. + """ + + ids: List[types.ID] + embeddings: types.Embeddings + metadatas: List[Optional[types.Metadata]] + documents: List[Optional[types.Document]] + + +class Record(TypedDict): + """ + A single generated record. + """ + + id: types.ID + embedding: Optional[types.Embedding] + metadata: Optional[types.Metadata] + document: Optional[types.Document] + + +# TODO: support arbitrary text everywhere so we don't SQL-inject ourselves. +# TODO: support empty strings everywhere +sql_alphabet = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_" +safe_text = st.text(alphabet=sql_alphabet, min_size=1) +sql_alphabet_minus_underscore = ( + "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-" +) +safe_text_min_size_3 = st.text(alphabet=sql_alphabet_minus_underscore, min_size=3) +tenant_database_name = st.text(alphabet=sql_alphabet, min_size=3) + +tenant_database_name = tenant_database_name.filter(lambda s: not s.startswith("_") and not s.startswith("-") and not s.endswith('-') and not s.endswith('_')) + +# Workaround for FastAPI json encoding peculiarities +# https://github.com/tiangolo/fastapi/blob/8ac8d70d52bb0dd9eb55ba4e22d3e383943da05c/fastapi/encoders.py#L104 +safe_text = safe_text.filter(lambda s: not s.startswith("_sa")) +safe_text_min_size_3 = safe_text_min_size_3.filter(lambda s: not s.startswith("_sa")) + +safe_integers = st.integers( + min_value=-(2**31), max_value=2**31 - 1 +) # TODO: handle longs +# In distributed chroma, floats are 32 bit hence we need to +# restrict the generation to generate only 32 bit floats. +safe_floats = st.floats( + allow_infinity=False, + allow_nan=False, + allow_subnormal=False, + width=32, + min_value=-1e6, + max_value=1e6, +) # TODO: handle infinity and NAN + +safe_values: List[SearchStrategy[Union[int, float, str, bool]]] = [ + safe_text, + safe_integers, + safe_floats, + st.booleans(), +] + + +def one_or_both( + strategy_a: st.SearchStrategy[Any], strategy_b: st.SearchStrategy[Any] +) -> st.SearchStrategy[Any]: + return st.one_of( + st.tuples(strategy_a, strategy_b), + st.tuples(strategy_a, st.none()), + st.tuples(st.none(), strategy_b), + ) + + +# Temporarily generate only these to avoid SQL formatting issues. +legal_id_characters = ( + "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_./+" +) + +float_types = [np.float16, np.float32, np.float64] +int_types = [np.int16, np.int32, np.int64] # TODO: handle int types + + +@st.composite +def collection_name(draw: st.DrawFn) -> str: + _collection_name_re = re.compile(r"^[a-zA-Z][a-zA-Z0-9-]{1,60}[a-zA-Z0-9]$") + _ipv4_address_re = re.compile(r"^([0-9]{1,3}\.){3}[0-9]{1,3}$") + _two_periods_re = re.compile(r"\.\.") + + name: str = draw(st.from_regex(_collection_name_re)).strip() + hypothesis.assume(not _ipv4_address_re.match(name)) + hypothesis.assume(not _two_periods_re.search(name)) + + return name + + +collection_metadata = st.one_of( + st.none(), st.dictionaries(safe_text, st.one_of(*safe_values)) +) + + +# TODO: Use a hypothesis strategy while maintaining embedding uniqueness +# Or handle duplicate embeddings within a known epsilon +def create_embeddings( + dim: int, + count: int, + dtype: npt.DTypeLike, +) -> types.Embeddings: + embeddings: types.Embeddings = cast( + types.Embeddings, + ( + np.random.uniform( + low=-1.0, + high=1.0, + size=(count, dim), + ) + .astype(dtype) + .tolist() + ), + ) + + return embeddings + + +def create_embeddings_ndarray( + dim: int, + count: int, + dtype: npt.DTypeLike, +) -> np.typing.NDArray[Any]: + return np.random.uniform( + low=-1.0, + high=1.0, + size=(count, dim), + ).astype(dtype) + + +class hashing_embedding_function(types.EmbeddingFunction[Documents]): + def __init__(self, dim: int, dtype: npt.DTypeLike) -> None: + self.dim = dim + self.dtype = dtype + + def __call__(self, input: types.Documents) -> types.Embeddings: + # Hash the texts and convert to hex strings + hashed_texts = [ + list(hashlib.sha256(text.encode("utf-8")).hexdigest()) for text in input + ] + # Pad with repetition, or truncate the hex strings to the desired dimension + padded_texts = [ + text * (self.dim // len(text)) + text[: self.dim % len(text)] + for text in hashed_texts + ] + + # Convert the hex strings to dtype + embeddings: types.Embeddings = [ + np.array([int(char, 16) / 15.0 for char in text], dtype=self.dtype) + for text in padded_texts + ] + + return embeddings + + def __repr__(self) -> str: + return f"hashing_embedding_function(dim={self.dim}, dtype={self.dtype})" + + +class not_implemented_embedding_function(types.EmbeddingFunction[Documents]): + def __call__(self, input: Documents) -> Embeddings: + assert False, "This embedding function is not implemented" + + +def embedding_function_strategy( + dim: int, dtype: npt.DTypeLike +) -> st.SearchStrategy[types.EmbeddingFunction[Embeddable]]: + return st.just( + cast(EmbeddingFunction[Embeddable], hashing_embedding_function(dim, dtype)) + ) + + +@dataclass +class ExternalCollection: + """ + An external view of a collection. + + This strategy only contains information about a collection that a client of Chroma + sees -- that is, it contains none of Chroma's internal bookkeeping. It should + be used to test the API and client code. + """ + + name: str + metadata: Optional[types.Metadata] + embedding_function: Optional[types.EmbeddingFunction[Embeddable]] + + +@register_embedding_function +class SimpleIpEmbeddingFunction(SimpleEmbeddingFunction): + """Simple embedding function with ip space for persistence tests.""" + + def default_space(self) -> str: # type: ignore[override] + return "ip" + + +@st.composite +def vector_index_config_strategy(draw: st.DrawFn) -> VectorIndexConfig: + """Generate VectorIndexConfig with optional space, embedding_function, source_key, hnsw, spann.""" + space = None + embedding_function = None + source_key = None + hnsw = None + spann = None + + if draw(st.booleans()): + space = draw(st.sampled_from(["cosine", "l2", "ip"])) + + if draw(st.booleans()): + embedding_function = SimpleIpEmbeddingFunction( + dim=draw(st.integers(min_value=1, max_value=1000)) + ) + + if draw(st.booleans()): + source_key = draw(st.one_of(st.just("#document"), safe_text)) + + index_choice = draw(st.sampled_from(["hnsw", "spann", "none"])) + + if index_choice == "hnsw": + hnsw = HnswIndexConfig( + ef_construction=draw(st.integers(min_value=1, max_value=1000)) + if draw(st.booleans()) + else None, + max_neighbors=draw(st.integers(min_value=1, max_value=1000)) + if draw(st.booleans()) + else None, + ef_search=draw(st.integers(min_value=1, max_value=1000)) + if draw(st.booleans()) + else None, + sync_threshold=draw(st.integers(min_value=2, max_value=10000)) + if draw(st.booleans()) + else None, + resize_factor=draw(st.floats(min_value=1.0, max_value=5.0)) + if draw(st.booleans()) + else None, + ) + elif index_choice == "spann": + spann = SpannIndexConfig( + search_nprobe=draw(st.integers(min_value=1, max_value=128)) + if draw(st.booleans()) + else None, + write_nprobe=draw(st.integers(min_value=1, max_value=64)) + if draw(st.booleans()) + else None, + ef_construction=draw(st.integers(min_value=1, max_value=200)) + if draw(st.booleans()) + else None, + ef_search=draw(st.integers(min_value=1, max_value=200)) + if draw(st.booleans()) + else None, + max_neighbors=draw(st.integers(min_value=1, max_value=64)) + if draw(st.booleans()) + else None, + reassign_neighbor_count=draw(st.integers(min_value=1, max_value=64)) + if draw(st.booleans()) + else None, + split_threshold=draw(st.integers(min_value=50, max_value=200)) + if draw(st.booleans()) + else None, + merge_threshold=draw(st.integers(min_value=25, max_value=100)) + if draw(st.booleans()) + else None, + ) + + return VectorIndexConfig( + space=cast(Space, space), + embedding_function=embedding_function, + source_key=source_key, + hnsw=hnsw, + spann=spann, + ) + + +@st.composite +def sparse_vector_index_config_strategy(draw: st.DrawFn) -> SparseVectorIndexConfig: + """Generate SparseVectorIndexConfig with optional embedding_function, source_key, bm25.""" + embedding_function = None + source_key = None + bm25 = None + + if draw(st.booleans()): + embedding_function = DeterministicSparseEmbeddingFunction() + source_key = draw(st.one_of(st.just("#document"), safe_text)) + + if draw(st.booleans()): + bm25 = draw(st.booleans()) + + return SparseVectorIndexConfig( + embedding_function=embedding_function, + source_key=source_key, + bm25=bm25, + ) + + +@st.composite +def schema_strategy(draw: st.DrawFn) -> Optional[Schema]: + """Generate a Schema object with various create_index/delete_index operations.""" + if draw(st.booleans()): + return None + + schema = Schema() + + # Decide how many operations to perform + num_operations = draw(st.integers(min_value=0, max_value=5)) + sparse_index_created = False + + for _ in range(num_operations): + operation = draw(st.sampled_from(["create_index", "delete_index"])) + config_type = draw( + st.sampled_from( + [ + "string_inverted", + "int_inverted", + "float_inverted", + "bool_inverted", + "vector", + "sparse_vector", + ] + ) + ) + + # Decide if we're setting on a key or globally + use_key = draw(st.booleans()) + key = None + if use_key and config_type != "vector": + # Vector indexes can't be set on specific keys, only globally + key = draw(safe_text) + + if operation == "create_index": + if config_type == "string_inverted": + schema.create_index(config=StringInvertedIndexConfig(), key=key) + elif config_type == "int_inverted": + schema.create_index(config=IntInvertedIndexConfig(), key=key) + elif config_type == "float_inverted": + schema.create_index(config=FloatInvertedIndexConfig(), key=key) + elif config_type == "bool_inverted": + schema.create_index(config=BoolInvertedIndexConfig(), key=key) + elif config_type == "vector": + vector_config = draw(vector_index_config_strategy()) + schema.create_index(config=vector_config, key=None) + elif ( + config_type == "sparse_vector" + and not is_spann_disabled_mode + and not sparse_index_created + ): + sparse_config = draw(sparse_vector_index_config_strategy()) + # Sparse vector MUST have a key + if key is None: + key = draw(safe_text) + schema.create_index(config=sparse_config, key=key) + sparse_index_created = True + + elif operation == "delete_index": + if config_type == "string_inverted": + schema.delete_index(config=StringInvertedIndexConfig(), key=key) + elif config_type == "int_inverted": + schema.delete_index(config=IntInvertedIndexConfig(), key=key) + elif config_type == "float_inverted": + schema.delete_index(config=FloatInvertedIndexConfig(), key=key) + elif config_type == "bool_inverted": + schema.delete_index(config=BoolInvertedIndexConfig(), key=key) + # Vector, FTS, and sparse_vector deletion is not currently supported + + return schema + + +@st.composite +def metadata_with_hnsw_strategy(draw: st.DrawFn) -> Optional[CollectionMetadata]: + """Generate metadata with hnsw parameters.""" + metadata: CollectionMetadata = {} + + if draw(st.booleans()): + metadata["hnsw:space"] = draw(st.sampled_from(["cosine", "l2", "ip"])) + if draw(st.booleans()): + metadata["hnsw:construction_ef"] = draw( + st.integers(min_value=1, max_value=1000) + ) + if draw(st.booleans()): + metadata["hnsw:search_ef"] = draw(st.integers(min_value=1, max_value=1000)) + if draw(st.booleans()): + metadata["hnsw:M"] = draw(st.integers(min_value=1, max_value=1000)) + if draw(st.booleans()): + metadata["hnsw:resize_factor"] = draw(st.floats(min_value=1.0, max_value=5.0)) + if draw(st.booleans()): + metadata["hnsw:sync_threshold"] = draw( + st.integers(min_value=2, max_value=10000) + ) + + return metadata if metadata else None + + +@st.composite +def create_configuration_strategy( + draw: st.DrawFn, +) -> Optional[CreateCollectionConfiguration]: + """Generate CreateCollectionConfiguration with mutual exclusivity rules.""" + configuration: CreateCollectionConfiguration = {} + + # Optionally set embedding_function (independent) + if draw(st.booleans()): + configuration["embedding_function"] = SimpleIpEmbeddingFunction( + dim=draw(st.integers(min_value=1, max_value=1000)) + ) + + # Decide: set space only, OR set hnsw config, OR set spann config + config_choice = draw( + st.sampled_from( + ["space_only_hnsw", "space_only_spann", "hnsw", "spann", "none"] + ) + ) + + if config_choice == "space_only_hnsw": + configuration["hnsw"] = CreateHNSWConfiguration( + space=draw(st.sampled_from(["cosine", "l2", "ip"])) + ) + elif config_choice == "space_only_spann": + configuration["spann"] = CreateSpannConfiguration( + space=draw(st.sampled_from(["cosine", "l2", "ip"])) + ) + elif config_choice == "hnsw": + # Set hnsw config (optionally with space) + hnsw_config: CreateHNSWConfiguration = {} + if draw(st.booleans()): + hnsw_config["space"] = draw(st.sampled_from(["cosine", "l2", "ip"])) + hnsw_config["ef_construction"] = draw(st.integers(min_value=1, max_value=1000)) + hnsw_config["ef_search"] = draw(st.integers(min_value=1, max_value=1000)) + hnsw_config["max_neighbors"] = draw(st.integers(min_value=1, max_value=1000)) + hnsw_config["sync_threshold"] = draw(st.integers(min_value=2, max_value=10000)) + hnsw_config["resize_factor"] = draw(st.floats(min_value=1.0, max_value=5.0)) + configuration["hnsw"] = hnsw_config + elif config_choice == "spann": + # Set spann config (optionally with space) + spann_config: CreateSpannConfiguration = {} + if draw(st.booleans()): + spann_config["space"] = draw(st.sampled_from(["cosine", "l2", "ip"])) + spann_config["search_nprobe"] = draw(st.integers(min_value=1, max_value=128)) + spann_config["write_nprobe"] = draw(st.integers(min_value=1, max_value=64)) + spann_config["ef_construction"] = draw(st.integers(min_value=1, max_value=200)) + spann_config["ef_search"] = draw(st.integers(min_value=1, max_value=200)) + spann_config["max_neighbors"] = draw(st.integers(min_value=1, max_value=64)) + spann_config["reassign_neighbor_count"] = draw( + st.integers(min_value=1, max_value=64) + ) + spann_config["split_threshold"] = draw(st.integers(min_value=50, max_value=200)) + spann_config["merge_threshold"] = draw(st.integers(min_value=25, max_value=100)) + configuration["spann"] = spann_config + + return configuration if configuration else None + + +@dataclass +class CollectionInputCombination: + """ + Input tuple for collection creation tests. + """ + + metadata: Optional[CollectionMetadata] + configuration: Optional[CreateCollectionConfiguration] + schema: Optional[Schema] + schema_vector_info: Optional[Dict[str, Any]] + kind: str + + +def non_none_items(items: Dict[str, Any]) -> Dict[str, Any]: + return {k: v for k, v in items.items() if v is not None} + + +def vector_index_to_dict(config: VectorIndexConfig) -> Dict[str, Any]: + embedding_default_space: Optional[str] = None + if config.embedding_function is not None and hasattr( + config.embedding_function, "default_space" + ): + embedding_default_space = cast(str, config.embedding_function.default_space()) + + return { + "space": config.space, + "hnsw": config.hnsw.model_dump(exclude_none=True) if config.hnsw else None, + "spann": config.spann.model_dump(exclude_none=True) if config.spann else None, + "embedding_function_default_space": embedding_default_space, + } + + +@st.composite +def _schema_input_strategy( + draw: st.DrawFn, +) -> Tuple[Schema, Dict[str, Any]]: + schema = Schema() + vector_config = draw(vector_index_config_strategy()) + schema.create_index(config=vector_config, key=None) + return schema, vector_index_to_dict(vector_config) + + +@st.composite +def metadata_configuration_schema_strategy( + draw: st.DrawFn, +) -> CollectionInputCombination: + """ + Generate compatible combinations of metadata, configuration, and schema inputs. + """ + + choice = draw( + st.sampled_from( + [ + "none", + "metadata", + "configuration", + "metadata_configuration", + "schema", + ] + ) + ) + + metadata: Optional[CollectionMetadata] = None + configuration: Optional[CreateCollectionConfiguration] = None + schema: Optional[Schema] = None + schema_info: Optional[Dict[str, Any]] = None + + if choice in ("metadata", "metadata_configuration"): + metadata = draw( + metadata_with_hnsw_strategy().filter( + lambda value: value is not None and len(value) > 0 + ) + ) + + if choice in ("configuration", "metadata_configuration"): + configuration = draw( + create_configuration_strategy().filter( + lambda value: value is not None + and ( + (value.get("hnsw") is not None and len(value["hnsw"]) > 0) + or (value.get("spann") is not None and len(value["spann"]) > 0) + ) + ) + ) + + if choice == "schema": + schema, schema_info = draw(_schema_input_strategy()) + + return CollectionInputCombination( + metadata=metadata, + configuration=configuration, + schema=schema, + schema_vector_info=schema_info, + kind=choice, + ) + + +@dataclass +class Collection(ExternalCollection): + """ + An internal view of a collection. + + This strategy contains all the information Chroma uses internally to manage a + collection. It is a superset of ExternalCollection and should be used to test + internal Chroma logic. + """ + + id: uuid.UUID + dimension: int + dtype: npt.DTypeLike + known_metadata_keys: types.Metadata + known_document_keywords: List[str] + has_documents: bool = False + has_embeddings: bool = False + collection_config: Optional[CreateCollectionConfiguration] = None + + +@st.composite +def collections( + draw: st.DrawFn, + add_filterable_data: bool = False, + with_hnsw_params: bool = False, + has_embeddings: Optional[bool] = None, + has_documents: Optional[bool] = None, + with_persistent_hnsw_params: st.SearchStrategy[bool] = st.just(False), + max_hnsw_batch_size: int = 2000, + max_hnsw_sync_threshold: int = 2000, +) -> Collection: + """Strategy to generate a Collection object. If add_filterable_data is True, then known_metadata_keys and known_document_keywords will be populated with consistent data.""" + + assert not ((has_embeddings is False) and (has_documents is False)) + + name = draw(collection_name()) + metadata = draw(collection_metadata) + dimension = draw(st.integers(min_value=2, max_value=2048)) + dtype = draw(st.sampled_from(float_types)) + + use_persistent_hnsw_params = draw(with_persistent_hnsw_params) + + if use_persistent_hnsw_params and not with_hnsw_params: + raise ValueError( + "with_persistent_hnsw_params requires with_hnsw_params to be true" + ) + + if with_hnsw_params: + if metadata is None: + metadata = {} + metadata.update(test_hnsw_config) + if use_persistent_hnsw_params: + metadata["hnsw:sync_threshold"] = draw( + st.integers(min_value=3, max_value=max_hnsw_sync_threshold) + ) + metadata["hnsw:batch_size"] = draw( + st.integers( + min_value=3, + max_value=min( + [metadata["hnsw:sync_threshold"], max_hnsw_batch_size] + ), + ) + ) + # Sometimes, select a space at random + if draw(st.booleans()): + # TODO: pull the distance functions from a source of truth that lives not + # in tests once https://github.com/chroma-core/issues/issues/61 lands + metadata["hnsw:space"] = draw(st.sampled_from(["cosine", "l2", "ip"])) + + collection_config: Optional[CreateCollectionConfiguration] = None + # Generate a spann config if in spann mode + if not is_spann_disabled_mode: + # Use metadata["hnsw:space"] if it exists, otherwise default to "l2" + spann_space = metadata.get("hnsw:space", "l2") if metadata else "l2" + + spann_config: CreateSpannConfiguration = { + "space": spann_space, + "write_nprobe": 4, + "reassign_neighbor_count": 4, + } + collection_config = { + "spann": spann_config, + } + + known_metadata_keys: Dict[str, Union[int, str, float]] = {} + if add_filterable_data: + while len(known_metadata_keys) < 5: + key = draw(safe_text) + known_metadata_keys[key] = draw(st.one_of(*safe_values)) + + if has_documents is None: + has_documents = draw(st.booleans()) + assert has_documents is not None + # For cluster tests, we want to avoid generating documents and where_document + # clauses of length < 3. We also don't want them to contain certan special + # characters like _ and % that implicitly involve searching for a regex in sqlite. + if not NOT_CLUSTER_ONLY: + if has_documents and add_filterable_data: + known_document_keywords = draw( + st.lists(safe_text_min_size_3, min_size=5, max_size=5) + ) + else: + known_document_keywords = [] + else: + if has_documents and add_filterable_data: + known_document_keywords = draw(st.lists(safe_text, min_size=5, max_size=5)) + else: + known_document_keywords = [] + + if not has_documents: + has_embeddings = True + else: + if has_embeddings is None: + has_embeddings = draw(st.booleans()) + assert has_embeddings is not None + + embedding_function = draw(embedding_function_strategy(dimension, dtype)) + + return Collection( + id=uuid.uuid4(), + name=name, + metadata=metadata, + dimension=dimension, + dtype=dtype, + known_metadata_keys=known_metadata_keys, + has_documents=has_documents, + known_document_keywords=known_document_keywords, + has_embeddings=has_embeddings, + embedding_function=embedding_function, + collection_config=collection_config, + ) + + +@st.composite +def metadata( + draw: st.DrawFn, + collection: Collection, + min_size: int = 0, + max_size: Optional[int] = None, +) -> Optional[types.Metadata]: + """Strategy for generating metadata that could be a part of the given collection""" + # First draw a random dictionary. + metadata: types.Metadata = draw( + st.dictionaries( + safe_text, st.one_of(*safe_values), min_size=min_size, max_size=max_size + ) + ) + # Then, remove keys that overlap with the known keys for the coll + # to avoid type errors when comparing. + if collection.known_metadata_keys: + for key in collection.known_metadata_keys.keys(): + if key in metadata: + del metadata[key] # type: ignore + # Finally, add in some of the known keys for the collection + sampling_dict: Dict[str, st.SearchStrategy[Union[str, int, float]]] = { + k: st.just(v) + for k, v in collection.known_metadata_keys.items() + if isinstance(v, (str, int, float)) + } + metadata.update(draw(st.fixed_dictionaries({}, optional=sampling_dict))) # type: ignore + # We don't allow submitting empty metadata + if metadata == {}: + return None + return metadata + + +@st.composite +def document(draw: st.DrawFn, collection: Collection) -> types.Document: + """Strategy for generating documents that could be a part of the given collection""" + # For cluster tests, we want to avoid generating documents of length < 3. + # We also don't want them to contain certan special + # characters like _ and % that implicitly involve searching for a regex in sqlite. + if not NOT_CLUSTER_ONLY: + # Blacklist certain unicode characters that affect sqlite processing. + # For example, the null (/x00) character makes sqlite stop processing a string. + # Also, blacklist _ and % for cluster tests. + blacklist_categories = ("Cc", "Cs", "Pc", "Po") + if collection.known_document_keywords: + known_words_st = st.sampled_from(collection.known_document_keywords) + else: + known_words_st = st.text( + min_size=3, + alphabet=st.characters(blacklist_categories=blacklist_categories), # type: ignore + ) + + random_words_st = st.text( + min_size=3, alphabet=st.characters(blacklist_categories=blacklist_categories) # type: ignore + ) + words = draw(st.lists(st.one_of(known_words_st, random_words_st), min_size=1)) + return " ".join(words) + + # Blacklist certain unicode characters that affect sqlite processing. + # For example, the null (/x00) character makes sqlite stop processing a string. + blacklist_categories = ("Cc", "Cs") # type: ignore + if collection.known_document_keywords: + known_words_st = st.sampled_from(collection.known_document_keywords) + else: + known_words_st = st.text( + min_size=1, + alphabet=st.characters(blacklist_categories=blacklist_categories), # type: ignore + ) + + random_words_st = st.text( + min_size=1, alphabet=st.characters(blacklist_categories=blacklist_categories) # type: ignore + ) + words = draw(st.lists(st.one_of(known_words_st, random_words_st), min_size=1)) + return " ".join(words) + + +@st.composite +def recordsets( + draw: st.DrawFn, + collection_strategy: SearchStrategy[Collection] = collections(), + id_strategy: SearchStrategy[str] = safe_text, + min_size: int = 1, + max_size: int = 50, + # If num_unique_metadata is not None, then the number of metadata generations + # will be the size of the record set. If set, the number of metadata + # generations will be the value of num_unique_metadata. + num_unique_metadata: Optional[int] = None, + min_metadata_size: int = 0, + max_metadata_size: Optional[int] = None, +) -> RecordSet: + collection = draw(collection_strategy) + + ids = list( + draw(st.lists(id_strategy, min_size=min_size, max_size=max_size, unique=True)) + ) + + embeddings: Optional[Embeddings] = None + if collection.has_embeddings: + embeddings = create_embeddings(collection.dimension, len(ids), collection.dtype) + num_metadata = num_unique_metadata if num_unique_metadata is not None else len(ids) + generated_metadatas = draw( + st.lists( + metadata( + collection, min_size=min_metadata_size, max_size=max_metadata_size + ), + min_size=num_metadata, + max_size=num_metadata, + ) + ) + metadatas = [] + for i in range(len(ids)): + metadatas.append(generated_metadatas[i % len(generated_metadatas)]) + + documents: Optional[Documents] = None + if collection.has_documents: + documents = draw( + st.lists(document(collection), min_size=len(ids), max_size=len(ids)) + ) + + # in the case where we have a single record, sometimes exercise + # the code that handles individual values rather than lists. + # In this case, any field may be a list or a single value. + if len(ids) == 1: + single_id: Union[str, List[str]] = ids[0] if draw(st.booleans()) else ids + single_embedding = ( + embeddings[0] + if embeddings is not None and draw(st.booleans()) + else embeddings + ) + single_metadata: Union[Optional[Metadata], List[Optional[Metadata]]] = ( + metadatas[0] if draw(st.booleans()) else metadatas + ) + single_document = ( + documents[0] if documents is not None and draw(st.booleans()) else documents + ) + return RecordSet( + ids=single_id, + embeddings=single_embedding, + metadatas=single_metadata, + documents=single_document, + ) + return RecordSet( + ids=ids, + embeddings=embeddings, + metadatas=metadatas, + documents=documents, + ) + + +def opposite_value(value: LiteralValue) -> SearchStrategy[Any]: + """ + Returns a strategy that will generate all valid values except the input value - testing of $nin + """ + if isinstance(value, float): + return safe_floats.filter(lambda x: x != value) + elif isinstance(value, str): + return safe_text.filter(lambda x: x != value) + elif isinstance(value, bool): + return st.booleans().filter(lambda x: x != value) + elif isinstance(value, int): + return st.integers(min_value=-(2**31), max_value=2**31 - 1).filter( + lambda x: x != value + ) + else: + return st.from_type(type(value)).filter(lambda x: x != value) + + +@st.composite +def where_clause(draw: st.DrawFn, collection: Collection) -> types.Where: + """Generate a filter that could be used in a query against the given collection""" + + known_keys = sorted(collection.known_metadata_keys.keys()) + + key = draw(st.sampled_from(known_keys)) + value = collection.known_metadata_keys[key] + + legal_ops: List[Optional[str]] = [None] + + if isinstance(value, bool): + legal_ops.extend(["$eq", "$ne", "$in", "$nin"]) + elif isinstance(value, float): + legal_ops.extend(["$gt", "$lt", "$lte", "$gte"]) + elif isinstance(value, int): + legal_ops.extend(["$gt", "$lt", "$lte", "$gte", "$eq", "$ne", "$in", "$nin"]) + elif isinstance(value, str): + legal_ops.extend(["$eq", "$ne", "$in", "$nin"]) + else: + assert False, f"Unsupported type: {type(value)}" + + if isinstance(value, float): + # Add or subtract a small number to avoid floating point rounding errors + value = value + draw(st.sampled_from([1e-6, -1e-6])) + # Truncate to 32 bit + value = float(np.float32(value)) + + op: WhereOperator = draw(st.sampled_from(legal_ops)) + + if op is None: + return {key: value} + elif op == "$in": # type: ignore + if isinstance(value, str) and not value: + return {} + return {key: {op: [value, *[draw(opposite_value(value)) for _ in range(3)]]}} + elif op == "$nin": # type: ignore + if isinstance(value, str) and not value: + return {} + return {key: {op: [draw(opposite_value(value)) for _ in range(3)]}} + else: + return {key: {op: value}} # type: ignore + + +@st.composite +def where_doc_clause(draw: st.DrawFn, collection: Collection) -> types.WhereDocument: + """Generate a where_document filter that could be used against the given collection""" + # For cluster tests, we want to avoid generating where_document + # clauses of length < 3. We also don't want them to contain certan special + # characters like _ and % that implicitly involve searching for a regex in sqlite. + if not NOT_CLUSTER_ONLY: + if collection.known_document_keywords: + word = draw(st.sampled_from(collection.known_document_keywords)) + else: + word = draw(safe_text_min_size_3) + else: + if collection.known_document_keywords: + word = draw(st.sampled_from(collection.known_document_keywords)) + else: + word = draw(safe_text) + + # This is hacky, but the distributed system does not support $not_contains + # so we need to avoid generating these operators for now in that case. + # TODO: Remove this once the distributed system supports $not_contains + op = draw(st.sampled_from(["$contains", "$not_contains"])) + + if op == "$contains": + return {"$contains": word} + else: + assert op == "$not_contains" + return {"$not_contains": word} + + +def binary_operator_clause( + base_st: SearchStrategy[types.Where], +) -> SearchStrategy[types.Where]: + op: SearchStrategy[LogicalOperator] = st.sampled_from(["$and", "$or"]) + return st.dictionaries( + keys=op, + values=st.lists(base_st, max_size=2, min_size=2), + min_size=1, + max_size=1, + ) + + +def binary_document_operator_clause( + base_st: SearchStrategy[types.WhereDocument], +) -> SearchStrategy[types.WhereDocument]: + op: SearchStrategy[LogicalOperator] = st.sampled_from(["$and", "$or"]) + return st.dictionaries( + keys=op, + values=st.lists(base_st, max_size=2, min_size=2), + min_size=1, + max_size=1, + ) + + +@st.composite +def recursive_where_clause(draw: st.DrawFn, collection: Collection) -> types.Where: + base_st = where_clause(collection) + where: types.Where = draw(st.recursive(base_st, binary_operator_clause)) + return where + + +@st.composite +def recursive_where_doc_clause( + draw: st.DrawFn, collection: Collection +) -> types.WhereDocument: + base_st = where_doc_clause(collection) + where: types.WhereDocument = draw( + st.recursive(base_st, binary_document_operator_clause) + ) + return where + + +class Filter(TypedDict): + where: Optional[types.Where] + ids: Optional[Union[str, List[str]]] + where_document: Optional[types.WhereDocument] + + +@st.composite +def filters( + draw: st.DrawFn, + collection_st: st.SearchStrategy[Collection], + recordset_st: st.SearchStrategy[RecordSet], + include_all_ids: bool = False, +) -> Filter: + collection = draw(collection_st) + recordset = draw(recordset_st) + + where_clause = draw(st.one_of(st.none(), recursive_where_clause(collection))) + where_document_clause = draw( + st.one_of(st.none(), recursive_where_doc_clause(collection)) + ) + + ids: Optional[Union[List[types.ID], types.ID]] + # Record sets can be a value instead of a list of values if there is only one record + if isinstance(recordset["ids"], str): + ids = [recordset["ids"]] + else: + ids = recordset["ids"] + + if not include_all_ids: + ids = draw(st.one_of(st.none(), st.lists(st.sampled_from(ids), min_size=1))) + if ids is not None: + # Remove duplicates since hypothesis samples with replacement + ids = list(set(ids)) + + # Test both the single value list and the unwrapped single value case + if ids is not None and len(ids) == 1 and draw(st.booleans()): + ids = ids[0] + + return {"where": where_clause, "where_document": where_document_clause, "ids": ids} diff --git a/python/user_packages/Python313/site-packages/chromadb/test/property/test_add.py b/python/user_packages/Python313/site-packages/chromadb/test/property/test_add.py new file mode 100644 index 0000000000000000000000000000000000000000..098f2b48efa720642893af2edda212704805a27f --- /dev/null +++ b/python/user_packages/Python313/site-packages/chromadb/test/property/test_add.py @@ -0,0 +1,570 @@ +import uuid +from random import randint +from typing import cast, List, Any, Dict +import hypothesis +import numpy as np +import pytest +import hypothesis.strategies as st +from hypothesis import given, settings +from chromadb.api import ClientAPI +from chromadb.api.types import Embeddings, Metadatas +from chromadb.config import DEFAULT_DATABASE +from chromadb.test.conftest import ( + DEFAULT_MCMR_DATABASE, + MULTI_REGION_ENABLED, + NOT_CLUSTER_ONLY, + database_name, + override_hypothesis_profile, + create_isolated_database, + multi_region_test, +) +import chromadb.test.property.strategies as strategies +import chromadb.test.property.invariants as invariants +from chromadb.test.utils.wait_for_version_increase import wait_for_version_increase +from chromadb.utils.batch_utils import create_batches + +MIN_RECORDS_BETWEEN_COMPACTION_WAITS = 10 +SMALL_MAX_RECORDS = 250 +MEDIUM_MIN_RECORDS = 150 +MEDIUM_MAX_RECORDS = 300 +LARGE_MIN_RECORDS = 5_000 +LARGE_MAX_RECORDS = 15_000 + + +collection_st = st.shared(strategies.collections(with_hnsw_params=True), key="coll") + + +@given( + collection=collection_st, + record_set=strategies.recordsets(collection_st, min_size=1, max_size=5), +) +@settings( + deadline=None, + parent=override_hypothesis_profile( + normal=hypothesis.settings(max_examples=100), + fast=hypothesis.settings(max_examples=40), + ), + max_examples=2, +) +def test_add_miniscule( + client: ClientAPI, + collection: strategies.Collection, + record_set: strategies.RecordSet, +) -> None: + if ( + client.get_settings().chroma_api_impl + == "chromadb.api.async_fastapi.AsyncFastAPI" + ): + pytest.skip( + "TODO @jai, come back and debug why CI runners fail with async + sync" + ) + _test_add(client, collection, record_set, True, always_compact=not MULTI_REGION_ENABLED) + + +# Hypothesis tends to generate smaller values so we explicitly segregate the +# the tests into tiers, Small, Medium. Hypothesis struggles to generate large +# record sets so we explicitly create a large record set without using Hypothesis +@multi_region_test +@given( + collection=collection_st, + record_set=strategies.recordsets( + collection_st, min_size=1, max_size=SMALL_MAX_RECORDS + ), + should_compact=st.booleans(), +) +@settings( + deadline=None, + parent=override_hypothesis_profile( + normal=hypothesis.settings(max_examples=50), + fast=hypothesis.settings(max_examples=20), + ), +) +def test_add_small( + client: ClientAPI, + collection: strategies.Collection, + record_set: strategies.RecordSet, + should_compact: bool, +) -> None: + if ( + client.get_settings().chroma_api_impl + == "chromadb.api.async_fastapi.AsyncFastAPI" + ): + pytest.skip( + "TODO @jai, come back and debug why CI runners fail with async + sync" + ) + _test_add(client, collection, record_set, should_compact) + + +@multi_region_test +@given( + collection=collection_st, + record_set=strategies.recordsets( + collection_st, + min_size=MEDIUM_MIN_RECORDS, + max_size=MEDIUM_MAX_RECORDS, + num_unique_metadata=4, + min_metadata_size=1, + max_metadata_size=4, + ), + should_compact=st.booleans(), +) +@settings( + deadline=None, + parent=override_hypothesis_profile( + normal=hypothesis.settings(max_examples=3), + fast=hypothesis.settings(max_examples=1), + ), + suppress_health_check=[ + hypothesis.HealthCheck.too_slow, + hypothesis.HealthCheck.data_too_large, + hypothesis.HealthCheck.large_base_example, + hypothesis.HealthCheck.function_scoped_fixture, + ], +) +def test_add_medium( + client: ClientAPI, + collection: strategies.Collection, + record_set: strategies.RecordSet, + should_compact: bool, +) -> None: + if ( + client.get_settings().chroma_api_impl + == "chromadb.api.async_fastapi.AsyncFastAPI" + ): + pytest.skip( + "TODO @jai, come back and debug why CI runners fail with async + sync" + ) + # Cluster tests transmit their results over grpc, which has a payload limit + # This breaks the ann_accuracy invariant by default, since + # the vector reader returns a payload of dataset size. So we need to batch + # the queries in the ann_accuracy invariant + _test_add(client, collection, record_set, should_compact, batch_ann_accuracy=True) + + +def _test_add( + client: ClientAPI, + collection: strategies.Collection, + record_set: strategies.RecordSet, + should_compact: bool, + batch_ann_accuracy: bool = False, + always_compact: bool = False, +) -> None: + create_isolated_database(client) + + # TODO: Generative embedding functions + coll = client.create_collection( + name=collection.name, + metadata=collection.metadata, # type: ignore + embedding_function=collection.embedding_function, + configuration=collection.collection_config, + ) + initial_version = cast(int, coll.get_model()["version"]) + + normalized_record_set = invariants.wrap_all(record_set) + should_wait_for_compaction = not NOT_CLUSTER_ONLY and should_compact + current_version = initial_version + records_since_compaction_wait = 0 + has_waited_for_compaction = False + min_records_between_compaction_waits = max( + MIN_RECORDS_BETWEEN_COMPACTION_WAITS, len(normalized_record_set["ids"]) // 10 + ) + print(f"starting min_records_between_compaction_waits={min_records_between_compaction_waits}") + + # TODO: The type of add() is incorrect as it does not allow for metadatas + # like [{"a": 1}, None, {"a": 3}] + for batch in create_batches( + api=client, + ids=cast(List[str], normalized_record_set["ids"]), + embeddings=cast(Embeddings, normalized_record_set["embeddings"]), + metadatas=cast(Metadatas, normalized_record_set["metadatas"]), + documents=cast(List[str], normalized_record_set["documents"]), + ): + print('adding', len(batch[0])) + coll.add(*batch) + if should_wait_for_compaction: + print('should wait for compaction') + records_since_compaction_wait += len(batch[0]) + if records_since_compaction_wait >= min_records_between_compaction_waits: + print(f"records_since_compaction_wait = {records_since_compaction_wait}") + print(f"min_records_between_compaction_waits = {min_records_between_compaction_waits}") + print(f"waiting {records_since_compaction_wait} >= {min_records_between_compaction_waits}") + current_version = wait_for_version_increase( + client, collection.name, current_version + ) + records_since_compaction_wait = 0 + has_waited_for_compaction = True + + # test_add_miniscule still needs one forced wait, but only if we have not + # already waited after at least the minimum compaction-sized write. + if ( + not NOT_CLUSTER_ONLY + and always_compact + and not has_waited_for_compaction + and len(normalized_record_set["ids"]) > 0 + ): + print('final wait for compaction') + current_version = wait_for_version_increase( + client, collection.name, current_version + ) + + invariants.count(coll, cast(strategies.RecordSet, normalized_record_set)) + n_results = max(1, (len(normalized_record_set["ids"]) // 10)) + + if batch_ann_accuracy: + batch_size = 50 + for i in range(0, len(normalized_record_set["ids"]), batch_size): + invariants.ann_accuracy( + coll, + cast(strategies.RecordSet, normalized_record_set), + n_results=n_results, + embedding_function=collection.embedding_function, + query_indices=list( + range(i, min(i + batch_size, len(normalized_record_set["ids"]))) + ), + ) + else: + invariants.ann_accuracy( + coll, + cast(strategies.RecordSet, normalized_record_set), + n_results=n_results, + embedding_function=collection.embedding_function, + ) + + +# Hypothesis struggles to generate large record sets so we explicitly create +# a large record set +def create_large_recordset( + min_size: int = 45000, + max_size: int = 50000, +) -> strategies.RecordSet: + size = randint(min_size, max_size) + + ids = [str(uuid.uuid4()) for _ in range(size)] + metadatas = [{"some_key": f"{i}"} for i in range(size)] + documents = [f"Document {i}" for i in range(size)] + embeddings = [[1, 2, 3] for _ in range(size)] + record_set = strategies.RecordSet( + ids=ids, + embeddings=cast(Embeddings, embeddings), + metadatas=metadatas, + documents=documents, + ) + return record_set + + +@multi_region_test +@given(collection=collection_st, should_compact=st.booleans()) +@settings(deadline=None, max_examples=2) +def test_add_large( + client: ClientAPI, + collection: strategies.Collection, + should_compact: bool, +) -> None: + create_isolated_database(client) + + if ( + client.get_settings().chroma_api_impl + == "chromadb.api.async_fastapi.AsyncFastAPI" + ): + pytest.skip( + "TODO @jai, come back and debug why CI runners fail with async + sync" + ) + + record_set = create_large_recordset( + min_size=LARGE_MIN_RECORDS, + max_size=LARGE_MAX_RECORDS, + ) + coll = client.create_collection( + name=collection.name, + metadata=collection.metadata, # type: ignore + embedding_function=collection.embedding_function, + ) + normalized_record_set = invariants.wrap_all(record_set) + initial_version = cast(int, coll.get_model()["version"]) + + for batch in create_batches( + api=client, + ids=cast(List[str], record_set["ids"]), + embeddings=cast(Embeddings, record_set["embeddings"]), + metadatas=cast(Metadatas, record_set["metadatas"]), + documents=cast(List[str], record_set["documents"]), + ): + coll.add(*batch) + + if ( + not NOT_CLUSTER_ONLY + and should_compact + and len(normalized_record_set["ids"]) > 10 + ): + # Wait for the model to be updated, since the record set is larger, add some additional time + wait_for_version_increase( + client, collection.name, initial_version, additional_time=300 + ) + + invariants.count(coll, cast(strategies.RecordSet, normalized_record_set)) + + +@given(collection=collection_st) +@settings(deadline=None, max_examples=1) +def test_add_large_exceeding( + client: ClientAPI, + collection: strategies.Collection, +) -> None: + create_isolated_database(client) + + if ( + client.get_settings().chroma_api_impl + == "chromadb.api.async_fastapi.AsyncFastAPI" + ): + pytest.skip( + "TODO @jai, come back and debug why CI runners fail with async + sync" + ) + + record_set = create_large_recordset( + min_size=client.get_max_batch_size(), + max_size=client.get_max_batch_size() + + 100, # Exceed the max batch size by 100 records + ) + coll = client.create_collection( + name=collection.name, + metadata=collection.metadata, # type: ignore + embedding_function=collection.embedding_function, + ) + + with pytest.raises(Exception) as e: + coll.add(**record_set) # type: ignore[arg-type] + assert "batch size" in str(e.value) + + +# TODO: This test fails right now because the ids are not sorted by the input order +@pytest.mark.xfail( + reason="This is expected to fail right now. We should change the API to sort the \ + ids by input order." +) +def test_out_of_order_ids(client: ClientAPI) -> None: + if ( + client.get_settings().chroma_api_impl + == "chromadb.api.async_fastapi.AsyncFastAPI" + ): + pytest.skip( + "TODO @jai, come back and debug why CI runners fail with async + sync" + ) + ooo_ids = [ + "40", + "05", + "8", + "6", + "10", + "01", + "00", + "3", + "04", + "20", + "02", + "9", + "30", + "11", + "13", + "2", + "0", + "7", + "06", + "5", + "50", + "12", + "03", + "4", + "1", + ] + + coll = client.create_collection( + "test", + embedding_function=lambda input: [[1, 2, 3] for _ in input], # type: ignore + ) + embeddings: Embeddings = [np.array([1, 2, 3]) for _ in ooo_ids] + coll.add(ids=ooo_ids, embeddings=embeddings) + get_ids = coll.get(ids=ooo_ids)["ids"] + assert get_ids == ooo_ids + + +def test_add_partial(client: ClientAPI) -> None: + """Tests adding a record set with some of the fields set to None.""" + + create_isolated_database(client) + + if ( + client.get_settings().chroma_api_impl + == "chromadb.api.async_fastapi.AsyncFastAPI" + ): + pytest.skip( + "TODO @jai, come back and debug why CI runners fail with async + sync" + ) + + coll = client.create_collection("test") + # TODO: We need to clean up the api types to support this typing + coll.add( + ids=["1", "2", "3"], + # All embeddings must be provided, or else None - no partial lists allowed + embeddings=[[1, 2, 3], [1, 2, 3], [1, 2, 3]], # type: ignore + # Metadatas can always be partial + metadatas=[{"a": 1}, None, {"a": 3}], # type: ignore + # Documents are optional if embeddings are provided + documents=["a", "b", None], # type: ignore + ) + + results = coll.get() + assert results["ids"] == ["1", "2", "3"] + assert results["metadatas"] == [{"a": 1}, None, {"a": 3}] + assert results["documents"] == ["a", "b", None] + + +@pytest.mark.skipif( + NOT_CLUSTER_ONLY, + reason="GroupBy is only supported in distributed mode", +) +def test_search_group_by(client: ClientAPI) -> None: + """Test GroupBy with single key, multiple keys, and multiple ranking keys.""" + from chromadb.execution.expression.operator import GroupBy, MinK, Key + from chromadb.execution.expression.plan import Search + from chromadb.execution.expression import Knn + + create_isolated_database(client) + + coll = client.create_collection(name="test_group_by") + + # Test data: 12 records across 3 categories and 2 years + # Embeddings are designed so science docs are closest to query [1,0,0,0] + ids = [ + "sci_2023_1", + "sci_2023_2", + "sci_2024_1", + "sci_2024_2", + "tech_2023_1", + "tech_2023_2", + "tech_2024_1", + "tech_2024_2", + "arts_2023_1", + "arts_2023_2", + "arts_2024_1", + "arts_2024_2", + ] + embeddings = cast( + Embeddings, + [ + # Science - closest to [1,0,0,0] + [1.0, 0.0, 0.0, 0.0], # sci_2023_1: score ~0.0 + [0.9, 0.1, 0.0, 0.0], # sci_2023_2: score ~0.141 + [0.8, 0.2, 0.0, 0.0], # sci_2024_1: score ~0.283 + [0.7, 0.3, 0.0, 0.0], # sci_2024_2: score ~0.424 + # Tech - farther from [1,0,0,0] + [0.0, 1.0, 0.0, 0.0], # tech_2023_1: score ~1.414 + [0.0, 0.9, 0.1, 0.0], # tech_2023_2: score ~1.345 + [0.0, 0.8, 0.2, 0.0], # tech_2024_1: score ~1.281 + [0.0, 0.7, 0.3, 0.0], # tech_2024_2: score ~1.221 + # Arts - farther from [1,0,0,0] + [0.0, 0.0, 1.0, 0.0], # arts_2023_1: score ~1.414 + [0.0, 0.0, 0.9, 0.1], # arts_2023_2: score ~1.345 + [0.0, 0.0, 0.8, 0.2], # arts_2024_1: score ~1.281 + [0.0, 0.0, 0.7, 0.3], # arts_2024_2: score ~1.221 + ], + ) + metadatas: Metadatas = [ + {"category": "science", "year": 2023, "priority": 1}, + {"category": "science", "year": 2023, "priority": 2}, + {"category": "science", "year": 2024, "priority": 1}, + {"category": "science", "year": 2024, "priority": 3}, + {"category": "tech", "year": 2023, "priority": 2}, + {"category": "tech", "year": 2023, "priority": 1}, + {"category": "tech", "year": 2024, "priority": 1}, + {"category": "tech", "year": 2024, "priority": 2}, + {"category": "arts", "year": 2023, "priority": 3}, + {"category": "arts", "year": 2023, "priority": 1}, + {"category": "arts", "year": 2024, "priority": 2}, + {"category": "arts", "year": 2024, "priority": 1}, + ] + documents = [f"doc_{id}" for id in ids] + + coll.add( + ids=ids, + embeddings=embeddings, + metadatas=metadatas, + documents=documents, + ) + + query = [1.0, 0.0, 0.0, 0.0] + + # Test 1: Single key grouping - top 2 per category by score + # Expected: 2 best from each category (science, tech, arts) + # - science: sci_2023_1 (0.0), sci_2023_2 (0.141) + # - tech: tech_2024_2 (1.221), tech_2024_1 (1.281) + # - arts: arts_2024_2 (1.221), arts_2024_1 (1.281) + results1 = coll.search( + Search() + .rank(Knn(query=query, limit=12)) + .group_by(GroupBy(keys=Key("category"), aggregate=MinK(keys=Key.SCORE, k=2))) + .limit(12) + ) + assert results1["ids"] is not None + result1_ids = results1["ids"][0] + assert len(result1_ids) == 6 + expected1 = { + "sci_2023_1", + "sci_2023_2", + "tech_2024_2", + "tech_2024_1", + "arts_2024_2", + "arts_2024_1", + } + assert set(result1_ids) == expected1 + + # Test 2: Multiple key grouping - top 1 per (category, year) combination + # 6 groups: (science,2023), (science,2024), (tech,2023), (tech,2024), (arts,2023), (arts,2024) + results2 = coll.search( + Search() + .rank(Knn(query=query, limit=12)) + .group_by( + GroupBy( + keys=[Key("category"), Key("year")], + aggregate=MinK(keys=Key.SCORE, k=1), + ) + ) + .limit(12) + ) + assert results2["ids"] is not None + result2_ids = results2["ids"][0] + assert len(result2_ids) == 6 + expected2 = { + "sci_2023_1", + "sci_2024_1", + "tech_2023_2", + "tech_2024_2", + "arts_2023_2", + "arts_2024_2", + } + assert set(result2_ids) == expected2 + + # Test 3: Multiple ranking keys - priority first, then score as tiebreaker + # Top 2 per category, sorted by priority (ascending), then score (ascending) + results3 = coll.search( + Search() + .rank(Knn(query=query, limit=12)) + .group_by( + GroupBy( + keys=Key("category"), + aggregate=MinK(keys=[Key("priority"), Key.SCORE], k=2), + ) + ) + .limit(12) + ) + assert results3["ids"] is not None + result3_ids = results3["ids"][0] + assert len(result3_ids) == 6 + expected3 = { + "sci_2023_1", + "sci_2024_1", + "tech_2024_1", + "tech_2023_2", + "arts_2024_2", + "arts_2023_2", + } + assert set(result3_ids) == expected3 diff --git a/python/user_packages/Python313/site-packages/chromadb/test/property/test_add_gc.py b/python/user_packages/Python313/site-packages/chromadb/test/property/test_add_gc.py new file mode 100644 index 0000000000000000000000000000000000000000..f897febb553363a7b287b8e159f27451964b75c8 --- /dev/null +++ b/python/user_packages/Python313/site-packages/chromadb/test/property/test_add_gc.py @@ -0,0 +1,474 @@ +import datetime +import hashlib +import hmac +import selectors +import subprocess +import time +import urllib.error +import urllib.parse +import urllib.request +import xml.etree.ElementTree as ET +import uuid +from typing import Dict, List, Optional, Tuple, cast + +import pytest + +from chromadb.api import ClientAPI +from chromadb.api.models.Collection import Collection +from chromadb.api.types import Embeddings, Metadatas +from chromadb.test.conftest import MULTI_REGION_ENABLED +from chromadb.test.property.test_add_mcmr import ( + _create_isolated_database_mcmr, + _create_mcmr_clients, +) +from chromadb.test.utils.wait_for_version_increase import wait_for_version_increase +from chromadb.utils.batch_utils import create_batches + + +GC_NAMESPACES = ("chroma", "chroma2") +GC_POD_NAME = "garbage-collector-0" +MINIO_S3_ENDPOINT = "http://localhost:9000" +MINIO_BUCKETS = ("chroma-storage", "chroma-storage2") +MINIO_ACCESS_KEY = "minio" +MINIO_SECRET_KEY = "minio123" +MINIO_REGION = "us-east-1" +COMPACTION_ROUNDS = 3 +RECORDS_PER_ROUND = 25 +GC_HARD_DELETE_TIMEOUT_SECONDS = 240 +MINIO_OBJECT_APPEAR_TIMEOUT_SECONDS = 60 +MINIO_OBJECT_DELETE_TIMEOUT_SECONDS = 60 +MINIO_OBJECT_LIST_TIMEOUT_SECONDS = 30.0 + + +def _records_for_round( + round_index: int, +) -> Tuple[List[str], Embeddings, Metadatas, List[str]]: + ids = [ + f"round-{round_index}-record-{record_index}-{uuid.uuid4()}" + for record_index in range(RECORDS_PER_ROUND) + ] + embeddings = [ + [float(round_index), float(record_index), 1.0] + for record_index in range(RECORDS_PER_ROUND) + ] + metadatas = [ + {"round": round_index, "record": record_index} + for record_index in range(RECORDS_PER_ROUND) + ] + documents = [ + f"round {round_index} record {record_index}" + for record_index in range(RECORDS_PER_ROUND) + ] + return ids, cast(Embeddings, embeddings), cast(Metadatas, metadatas), documents + + +def _add_round(client: ClientAPI, collection: Collection, round_index: int) -> None: + ids, embeddings, metadatas, documents = _records_for_round(round_index) + for batch in create_batches( + api=client, + ids=ids, + embeddings=embeddings, + metadatas=metadatas, + documents=documents, + ): + collection.add(*batch) + + +def _start_gc_log_watchers() -> List[Tuple[str, subprocess.Popen]]: + watchers = [] + for namespace in GC_NAMESPACES: + try: + proc = subprocess.Popen( + [ + "kubectl", + "logs", + "-n", + namespace, + GC_POD_NAME, + "--tail=0", + "--follow", + ], + stdout=subprocess.PIPE, + stderr=subprocess.PIPE, + text=True, + bufsize=1, + ) + except FileNotFoundError: + pytest.skip("kubectl is required to watch garbage collector logs") + watchers.append((namespace, proc)) + return watchers + + +def _hard_delete_log_found(output: str, collection_uuid: str) -> bool: + offset = 0 + while True: + hard_delete_index = output.find("Hard deleting collections", offset) + if hard_delete_index == -1: + return False + if collection_uuid in output[hard_delete_index : hard_delete_index + 4096]: + return True + offset = hard_delete_index + len("Hard deleting collections") + + +def _wait_for_gc_hard_delete_log( + watchers: List[Tuple[str, subprocess.Popen]], + captured_stdout: Dict[str, List[str]], + collection_uuid: str, +) -> None: + selector = selectors.DefaultSelector() + try: + for namespace, proc in watchers: + if proc.stdout is None: + continue + selector.register(proc.stdout, selectors.EVENT_READ, namespace) + + deadline = time.monotonic() + GC_HARD_DELETE_TIMEOUT_SECONDS + while time.monotonic() < deadline and selector.get_map(): + timeout = min(1.0, max(0.0, deadline - time.monotonic())) + for key, _ in selector.select(timeout=timeout): + namespace = cast(str, key.data) + line = key.fileobj.readline() + if line == "": + selector.unregister(key.fileobj) + continue + captured_stdout[namespace].append(line) + if _hard_delete_log_found( + "".join(captured_stdout[namespace]), collection_uuid + ): + return + finally: + selector.close() + + +def _stop_gc_log_watchers( + watchers: List[Tuple[str, subprocess.Popen]], + captured_stdout: Dict[str, List[str]], +) -> Dict[str, str]: + captured_stderr = {} + for _, proc in watchers: + proc.terminate() + + for namespace, proc in watchers: + try: + stdout, stderr = proc.communicate(timeout=5) + except subprocess.TimeoutExpired: + proc.kill() + stdout, stderr = proc.communicate() + if stdout: + captured_stdout[namespace].append(stdout) + captured_stderr[namespace] = stderr + return captured_stderr + + +def _aws_quote(value: str) -> str: + return urllib.parse.quote(value, safe="-_.~") + + +def _signing_key(date_stamp: str) -> bytes: + date_key = hmac.new( + f"AWS4{MINIO_SECRET_KEY}".encode("utf-8"), + date_stamp.encode("utf-8"), + hashlib.sha256, + ).digest() + region_key = hmac.new( + date_key, MINIO_REGION.encode("utf-8"), hashlib.sha256 + ).digest() + service_key = hmac.new(region_key, b"s3", hashlib.sha256).digest() + return hmac.new(service_key, b"aws4_request", hashlib.sha256).digest() + + +def _minio_signed_get(bucket: str, query: Dict[str, str]) -> bytes: + endpoint = urllib.parse.urlparse(MINIO_S3_ENDPOINT) + now = datetime.datetime.now(datetime.timezone.utc) + amz_date = now.strftime("%Y%m%dT%H%M%SZ") + date_stamp = now.strftime("%Y%m%d") + payload_hash = hashlib.sha256(b"").hexdigest() + + path = f"/{bucket}" + canonical_uri = urllib.parse.quote(path, safe="/-_.~") + canonical_query = "&".join( + f"{_aws_quote(key)}={_aws_quote(value)}" for key, value in sorted(query.items()) + ) + canonical_headers = ( + f"host:{endpoint.netloc}\n" + f"x-amz-content-sha256:{payload_hash}\n" + f"x-amz-date:{amz_date}\n" + ) + signed_headers = "host;x-amz-content-sha256;x-amz-date" + canonical_request = "\n".join( + [ + "GET", + canonical_uri, + canonical_query, + canonical_headers, + signed_headers, + payload_hash, + ] + ) + + credential_scope = f"{date_stamp}/{MINIO_REGION}/s3/aws4_request" + string_to_sign = "\n".join( + [ + "AWS4-HMAC-SHA256", + amz_date, + credential_scope, + hashlib.sha256(canonical_request.encode("utf-8")).hexdigest(), + ] + ) + signature = hmac.new( + _signing_key(date_stamp), + string_to_sign.encode("utf-8"), + hashlib.sha256, + ).hexdigest() + authorization = ( + "AWS4-HMAC-SHA256 " + f"Credential={MINIO_ACCESS_KEY}/{credential_scope}, " + f"SignedHeaders={signed_headers}, Signature={signature}" + ) + + url = urllib.parse.urlunparse( + ( + endpoint.scheme, + endpoint.netloc, + path, + "", + canonical_query, + "", + ) + ) + request = urllib.request.Request( + url, + headers={ + "Authorization": authorization, + "x-amz-content-sha256": payload_hash, + "x-amz-date": amz_date, + }, + method="GET", + ) + try: + with urllib.request.urlopen( + request, timeout=MINIO_OBJECT_LIST_TIMEOUT_SECONDS + ) as response: + return response.read() + except urllib.error.HTTPError as e: + body = e.read().decode("utf-8", errors="replace") + pytest.fail( + "Failed to list MinIO objects from S3 API " + f"{MINIO_S3_ENDPOINT}/{bucket}: HTTP {e.code} {e.reason}; body={body!r}" + ) + except urllib.error.URLError as e: + pytest.fail( + "Failed to connect to MinIO S3 API " + f"{MINIO_S3_ENDPOINT}/{bucket}: {e}" + ) + + +def _xml_local_name(tag: str) -> str: + return tag.rsplit("}", 1)[-1] + + +def _child_text(element: ET.Element, name: str) -> Optional[str]: + for child in element: + if _xml_local_name(child.tag) == name: + return child.text + return None + + +def _is_collection_version_file_key(key: str, collection_uuid: str) -> bool: + return f"/collection/{collection_uuid}/versionfiles/" in key + + +def _list_minio_files_for_collection(bucket: str, collection_uuid: str) -> List[str]: + keys: List[str] = [] + continuation_token: Optional[str] = None + while True: + query = {"list-type": "2", "max-keys": "1000"} + if continuation_token is not None: + query["continuation-token"] = continuation_token + + body = _minio_signed_get(bucket, query) + root = ET.fromstring(body) + + for element in root.iter(): + if _xml_local_name(element.tag) != "Contents": + continue + key = _child_text(element, "Key") + if ( + key is not None + and collection_uuid in key + and not _is_collection_version_file_key(key, collection_uuid) + ): + keys.append(key) + + is_truncated = _child_text(root, "IsTruncated") == "true" + if not is_truncated: + break + continuation_token = _child_text(root, "NextContinuationToken") + if continuation_token is None: + pytest.fail( + "MinIO returned a truncated object listing without a continuation token" + ) + + return sorted(keys) + + +def _format_minio_file_sample(paths: List[str]) -> str: + sample_size = 50 + sample = paths[:sample_size] + suffix = ( + "" if len(paths) <= sample_size else f" ... and {len(paths) - sample_size} more" + ) + return f"{sample}{suffix}" + + +def _wait_for_minio_files_for_collection(collection_uuid: str) -> Dict[str, List[str]]: + deadline = time.monotonic() + MINIO_OBJECT_APPEAR_TIMEOUT_SECONDS + paths_by_bucket: Dict[str, List[str]] = {} + while True: + paths_by_bucket = { + bucket: _list_minio_files_for_collection(bucket, collection_uuid) + for bucket in MINIO_BUCKETS + } + if all(paths_by_bucket.values()): + return paths_by_bucket + if time.monotonic() >= deadline: + missing_buckets = [ + bucket for bucket, paths in paths_by_bucket.items() if not paths + ] + pytest.fail( + "Expected MinIO to contain non-version files for collection " + f"{collection_uuid} in every test bucket before deletion, " + f"but these buckets had none: {missing_buckets}. " + f"Found counts: " + f"{ {bucket: len(paths) for bucket, paths in paths_by_bucket.items()} }" + ) + time.sleep(1) + + +def _wait_for_minio_files_deleted(collection_uuid: str) -> None: + deadline = time.monotonic() + MINIO_OBJECT_DELETE_TIMEOUT_SECONDS + paths_by_bucket: Dict[str, List[str]] = {} + while True: + paths_by_bucket = { + bucket: _list_minio_files_for_collection(bucket, collection_uuid) + for bucket in MINIO_BUCKETS + } + if not any(paths_by_bucket.values()): + return + if time.monotonic() >= deadline: + remaining = { + bucket: paths for bucket, paths in paths_by_bucket.items() if paths + } + samples = { + bucket: _format_minio_file_sample(paths) + for bucket, paths in remaining.items() + } + pytest.fail( + "Expected non-version MinIO files for collection " + f"{collection_uuid} to be deleted from every test bucket, " + f"but found files in these buckets: " + f"{ {bucket: len(paths) for bucket, paths in remaining.items()} }. " + f"Samples: {samples}" + ) + time.sleep(1) + + +def round_robin(round_index, round_around): + return round_around[round_index % len(round_around)] + + +def _delete_collection_and_assert_gc_hard_delete( + client: ClientAPI, collection_name: str, collection_uuid: str +) -> None: + watchers = _start_gc_log_watchers() + captured_stdout = {namespace: [] for namespace in GC_NAMESPACES} + captured_stderr: Dict[str, str] = {} + try: + client.delete_collection(collection_name) + _wait_for_gc_hard_delete_log(watchers, captured_stdout, collection_uuid) + finally: + captured_stderr = _stop_gc_log_watchers(watchers, captured_stdout) + + stdout_by_namespace = { + namespace: "".join(lines) for namespace, lines in captured_stdout.items() + } + matching_namespaces = [ + namespace + for namespace, stdout in stdout_by_namespace.items() + if _hard_delete_log_found(stdout, collection_uuid) + ] + + for namespace, stdout in stdout_by_namespace.items(): + print(f"{namespace} GC stdout captured {len(stdout)} bytes") + for namespace, stderr in captured_stderr.items(): + if stderr: + print(f"{namespace} GC stderr: {stderr[-1000:]}") + + assert matching_namespaces, ( + "Expected garbage collector logs to hard delete collection " + f"{collection_uuid}. Captured stdout tails: " + f"{ {namespace: stdout[-2000:] for namespace, stdout in stdout_by_namespace.items()} }" + ) + + +@pytest.mark.skipif( + not MULTI_REGION_ENABLED, + reason="MCMR GC coverage requires a multi-region Kubernetes cluster", +) +def test_add_gc_hard_deletes_empty_mcmr_collection() -> None: + client1, client2 = _create_mcmr_clients() + _create_isolated_database_mcmr(client1, client2, "tilt-spanning") + + collection_name = f"test_add_gc_empty_{uuid.uuid4().hex}" + collection = client1.create_collection(name=collection_name) + client2.get_collection(name=collection_name) + + _delete_collection_and_assert_gc_hard_delete( + client1, collection_name, str(collection.id) + ) + + +@pytest.mark.skipif( + not MULTI_REGION_ENABLED, + reason="MCMR GC coverage requires a multi-region Kubernetes cluster", +) +@pytest.mark.skip_single_region +def test_add_gc_hard_deletes_mcmr_collection() -> None: + client1, client2 = _create_mcmr_clients() + _create_isolated_database_mcmr(client1, client2, "tilt-spanning") + clients = [client1, client2] + + collection_name = f"test_add_gc_{uuid.uuid4().hex}" + coll1 = client1.create_collection(name=collection_name) + coll2 = client2.get_collection(name=collection_name) + collection_uuid = str(coll1.id) + collections = [coll1, coll2] + + current_version1 = cast(int, coll1.get_model()["version"]) + current_version2 = cast(int, coll2.get_model()["version"]) + + for round_index in range(COMPACTION_ROUNDS): + writer_client = round_robin(round_index, clients) + writer_collection = round_robin(round_index, collections) + _add_round(writer_client, writer_collection, round_index) + + current_version1 = wait_for_version_increase( + client1, collection_name, current_version1 + ) + current_version2 = wait_for_version_increase( + client2, collection_name, current_version2 + ) + + minio_files_before_delete_by_bucket = _wait_for_minio_files_for_collection( + collection_uuid + ) + for bucket, paths in minio_files_before_delete_by_bucket.items(): + print( + f"MinIO bucket {bucket} contained {len(paths)} files for collection " + f"{collection_uuid} before deletion" + ) + + _delete_collection_and_assert_gc_hard_delete( + client1, collection_name, collection_uuid + ) + _wait_for_minio_files_deleted(collection_uuid) diff --git a/python/user_packages/Python313/site-packages/chromadb/test/property/test_add_mcmr.py b/python/user_packages/Python313/site-packages/chromadb/test/property/test_add_mcmr.py new file mode 100644 index 0000000000000000000000000000000000000000..8b84aa03584903923f3689a0c923592160d8fa91 --- /dev/null +++ b/python/user_packages/Python313/site-packages/chromadb/test/property/test_add_mcmr.py @@ -0,0 +1,338 @@ +import uuid +from random import randint +from typing import cast, List, Any, Dict, Tuple +import hypothesis +import pytest +import hypothesis.strategies as st +from hypothesis import given, settings +import chromadb +from chromadb.api import ClientAPI +from chromadb.api.types import Embeddings, Metadatas +from chromadb.test.conftest import ( + NOT_CLUSTER_ONLY, + override_hypothesis_profile, +) +import chromadb.test.property.strategies as strategies +import chromadb.test.property.invariants as invariants +from chromadb.test.utils.wait_for_version_increase import wait_for_version_increase +from chromadb.utils.batch_utils import create_batches +from chromadb.api.client import AdminClient +from chromadb.config import Settings + +MIN_RECORDS_BETWEEN_COMPACTION_WAITS = 10 + + +collection_st = st.shared(strategies.collections(with_hnsw_params=True), key="coll") + + +# Hypothesis tends to generate smaller values so we explicitly segregate the +# the tests into tiers, Small, Medium. Hypothesis struggles to generate large +# record sets so we explicitly create a large record set without using Hypothesis +@given( + collection=collection_st, + record_set=strategies.recordsets(collection_st, min_size=1, max_size=500), + should_compact=st.booleans(), +) +@settings( + deadline=None, + parent=override_hypothesis_profile( + normal=hypothesis.settings(max_examples=50), + fast=hypothesis.settings(max_examples=20), + ), +) +def test_add_small( + collection: strategies.Collection, + record_set: strategies.RecordSet, + should_compact: bool, +) -> None: + _test_add(collection, record_set, should_compact) + + +@given( + collection=collection_st, + record_set=strategies.recordsets( + collection_st, + min_size=250, + max_size=500, + num_unique_metadata=5, + min_metadata_size=1, + max_metadata_size=5, + ), + should_compact=st.booleans(), +) +@settings( + deadline=None, + parent=override_hypothesis_profile( + normal=hypothesis.settings(max_examples=5), + fast=hypothesis.settings(max_examples=2), + ), + suppress_health_check=[ + hypothesis.HealthCheck.too_slow, + hypothesis.HealthCheck.data_too_large, + hypothesis.HealthCheck.large_base_example, + hypothesis.HealthCheck.function_scoped_fixture, + ], +) +def test_add_medium( + collection: strategies.Collection, + record_set: strategies.RecordSet, + should_compact: bool, +) -> None: + # Cluster tests transmit their results over grpc, which has a payload limit + # This breaks the ann_accuracy invariant by default, since + # the vector reader returns a payload of dataset size. So we need to batch + # the queries in the ann_accuracy invariant + _test_add(collection, record_set, should_compact, batch_ann_accuracy=True) + + +def _create_mcmr_clients() -> Tuple[ClientAPI, ClientAPI]: + """Create two clients connected to different regions for MCMR testing. + + Returns: + A tuple of two ClientAPI instances connected to localhost:8000 and localhost:8001. + """ + settings1 = Settings(chroma_server_host=None, chroma_server_http_port=None) + settings2 = Settings(chroma_server_host=None, chroma_server_http_port=None) + client1 = chromadb.HttpClient(host="localhost", port=8000, settings=settings1) + client2 = chromadb.HttpClient(host="localhost", port=8001, settings=settings2) + return client1, client2 + + +def _create_isolated_database_mcmr( + client1: ClientAPI, + client2: ClientAPI, + topology: str, +) -> str: + """Create an isolated database for MCMR testing using the topology+database format. + + Args: + client1: The first client (region 1). + client2: The second client (region 2). + topology: The topology identifier for the test. + + Returns: + The database name in the format '{topology}+{database}'. + """ + admin_settings = client1.get_settings() + admin = AdminClient(admin_settings) + database = f"{topology}+test_{uuid.uuid4()}" + admin.create_database(database) + client1.set_database(database) + client2.set_database(database) + return database + + +def _test_add( + collection: strategies.Collection, + record_set: strategies.RecordSet, + should_compact: bool, + batch_ann_accuracy: bool = False, + topology: str = "tilt-spanning", +) -> None: + """Test adding records to a collection across multiple regions. + + Args: + collection: The collection configuration. + record_set: The records to add. + should_compact: Whether to wait for compaction. + batch_ann_accuracy: Whether to batch the ANN accuracy checks. + topology: Topology identifier for MCMR testing. + Creates two clients connected to localhost:8000 and localhost:8001. + """ + client1, client2 = _create_mcmr_clients() + _create_isolated_database_mcmr(client1, client2, topology) + + coll1 = client1.create_collection( + name=collection.name, + metadata=collection.metadata, # type: ignore + embedding_function=collection.embedding_function, + configuration=collection.collection_config, + ) + coll2 = client2.get_collection( + name=collection.name, + embedding_function=collection.embedding_function, + ) + + normalized_record_set = invariants.wrap_all(record_set) + should_wait_for_compaction = not NOT_CLUSTER_ONLY and should_compact + current_version1 = cast(int, coll1.get_model()["version"]) + current_version2 = cast(int, coll2.get_model()["version"]) + records_since_compaction_wait = 0 + min_records_between_compaction_waits = max( + MIN_RECORDS_BETWEEN_COMPACTION_WAITS, len(normalized_record_set["ids"]) // 10 + ) + print( + f"starting min_records_between_compaction_waits={min_records_between_compaction_waits}" + ) + + # TODO: The type of add() is incorrect as it does not allow for metadatas + # like [{"a": 1}, None, {"a": 3}] + batches = list( + create_batches( + api=client1, + ids=cast(List[str], normalized_record_set["ids"]), + embeddings=cast(Embeddings, normalized_record_set["embeddings"]), + metadatas=cast(Metadatas, normalized_record_set["metadatas"]), + documents=cast(List[str], normalized_record_set["documents"]), + ) + ) + for batch_index, batch in enumerate(batches): + print("adding", len(batch[0])) + if batch_index % 2 == 0: + coll1.add(*batch) + else: + coll2.add(*batch) + if should_wait_for_compaction: + print("should wait for compaction") + records_since_compaction_wait += len(batch[0]) + if records_since_compaction_wait >= min_records_between_compaction_waits: + print( + f"records_since_compaction_wait = {records_since_compaction_wait}" + ) + print( + f"min_records_between_compaction_waits = {min_records_between_compaction_waits}" + ) + print( + f"waiting {records_since_compaction_wait} >= {min_records_between_compaction_waits}" + ) + current_version1 = wait_for_version_increase( + client1, collection.name, current_version1 + ) + current_version2 = wait_for_version_increase( + client2, collection.name, current_version2 + ) + records_since_compaction_wait = 0 + + # Verify invariants on both collections to ensure cross-region replication works. + # Data is written via both coll1 and coll2, so checking both verifies that data + # written to region 1 appears in region 2 and vice versa. + n_results = max(1, (len(normalized_record_set["ids"]) // 10)) + for coll in (coll1, coll2): + invariants.count(coll, cast(strategies.RecordSet, normalized_record_set)) + if batch_ann_accuracy: + batch_size = 10 + for i in range(0, len(normalized_record_set["ids"]), batch_size): + invariants.ann_accuracy( + coll, + cast(strategies.RecordSet, normalized_record_set), + n_results=n_results, + embedding_function=collection.embedding_function, + query_indices=list( + range(i, min(i + batch_size, len(normalized_record_set["ids"]))) + ), + ) + else: + invariants.ann_accuracy( + coll, + cast(strategies.RecordSet, normalized_record_set), + n_results=n_results, + embedding_function=collection.embedding_function, + ) + + +# Hypothesis struggles to generate large record sets so we explicitly create +# a large record set +def create_large_recordset( + dimension: int, + min_size: int = 45000, + max_size: int = 50000, +) -> strategies.RecordSet: + size = randint(min_size, max_size) + + ids = [str(uuid.uuid4()) for _ in range(size)] + metadatas = [{"some_key": f"{i}"} for i in range(size)] + documents = [f"Document {i}" for i in range(size)] + embeddings = [[1.0] * dimension for _ in range(size)] + record_set: Dict[str, List[Any]] = { + "ids": ids, + "embeddings": cast(Embeddings, embeddings), + "metadatas": metadatas, + "documents": documents, + } + return cast(strategies.RecordSet, record_set) + + +@given(collection=collection_st, should_compact=st.booleans()) +@settings(deadline=None, max_examples=2) +def test_add_large( + collection: strategies.Collection, + should_compact: bool, +) -> None: + """Test adding large record sets to a collection across multiple regions. + + Args: + collection: The collection configuration. + should_compact: Whether to wait for compaction. + """ + topology = "tilt-spanning" + client1, client2 = _create_mcmr_clients() + _create_isolated_database_mcmr(client1, client2, topology) + + if ( + client1.get_settings().chroma_api_impl + == "chromadb.api.async_fastapi.AsyncFastAPI" + ): + pytest.skip( + "TODO @jai, come back and debug why CI runners fail with async + sync" + ) + + record_set = create_large_recordset( + dimension=collection.dimension, + min_size=10000, + max_size=20000, + ) + coll1 = client1.create_collection( + name=collection.name, + metadata=collection.metadata, # type: ignore + embedding_function=collection.embedding_function, + ) + coll2 = client2.get_collection( + name=collection.name, + embedding_function=collection.embedding_function, + ) + + normalized_record_set = invariants.wrap_all(record_set) + initial_version1 = cast(int, coll1.get_model()["version"]) + initial_version2 = cast(int, coll2.get_model()["version"]) + + batches = list( + create_batches( + api=client1, + ids=cast(List[str], record_set["ids"]), + embeddings=cast(Embeddings, record_set["embeddings"]), + metadatas=cast(Metadatas, record_set["metadatas"]), + documents=cast(List[str], record_set["documents"]), + ) + ) + for batch_index, batch in enumerate(batches): + if batch_index % 2 == 0: + coll1.add(*batch) + else: + coll2.add(*batch) + + if ( + not NOT_CLUSTER_ONLY + and should_compact + and len(normalized_record_set["ids"]) > 10 + ): + # Wait for the model to be updated in each region, since the record set is + # larger, add some additional time + wait_for_version_increase( + client1, collection.name, initial_version1, additional_time=300 + ) + wait_for_version_increase( + client2, collection.name, initial_version2, additional_time=300 + ) + + for coll in (coll1, coll2): + invariants.count(coll, cast(strategies.RecordSet, normalized_record_set)) + invariants.ids_match(coll, cast(strategies.RecordSet, normalized_record_set)) + invariants.metadatas_match( + coll, cast(strategies.RecordSet, normalized_record_set) + ) + invariants.documents_match( + coll, cast(strategies.RecordSet, normalized_record_set) + ) + invariants.embeddings_match( + coll, cast(strategies.RecordSet, normalized_record_set) + ) diff --git a/python/user_packages/Python313/site-packages/chromadb/test/property/test_base64_conversion.py b/python/user_packages/Python313/site-packages/chromadb/test/property/test_base64_conversion.py new file mode 100644 index 0000000000000000000000000000000000000000..a9b1f27b4564b4602a1616d54da1107f5d4f1e95 --- /dev/null +++ b/python/user_packages/Python313/site-packages/chromadb/test/property/test_base64_conversion.py @@ -0,0 +1,91 @@ +from hypothesis import given, strategies as st +from chromadb.api.types import ( + optional_embeddings_to_base64_strings, + optional_base64_strings_to_embeddings, +) +import numpy as np +import math + + +@given(st.lists(st.lists(st.integers(min_value=-128, max_value=127)))) +def test_base64_conversion_is_identity_i8(embeddings) -> None: # type: ignore + b64_strings = optional_embeddings_to_base64_strings(embeddings) + assert b64_strings is not None + assert len(b64_strings) == len(embeddings) + decoded_embeddings = optional_base64_strings_to_embeddings(b64_strings) + for orig, decoded in zip(embeddings, decoded_embeddings): # type: ignore + np.testing.assert_allclose(orig, decoded, rtol=1e-6) + + +@given(st.lists(st.lists(st.floats(width=16)))) +def test_base64_conversion_is_identity_f16(embeddings) -> None: # type: ignore + b64_strings = optional_embeddings_to_base64_strings(embeddings) + assert b64_strings is not None + assert len(b64_strings) == len(embeddings) + decoded_embeddings = optional_base64_strings_to_embeddings(b64_strings) + for orig, decoded in zip(embeddings, decoded_embeddings): # type: ignore + np.testing.assert_allclose(orig, decoded, rtol=1e-6) + + +@given(st.lists(st.lists(st.floats(width=32)))) +def test_base64_conversion_is_identity_f32(embeddings) -> None: # type: ignore + b64_strings = optional_embeddings_to_base64_strings(embeddings) + assert b64_strings is not None + assert len(b64_strings) == len(embeddings) + decoded_embeddings = optional_base64_strings_to_embeddings(b64_strings) + for orig, decoded in zip(embeddings, decoded_embeddings): # type: ignore + np.testing.assert_allclose(orig, decoded, rtol=1e-6) + + +@given(st.lists(st.lists(st.floats(width=64)))) +def test_base64_conversion_is_identity_f64(embeddings) -> None: # type: ignore + b64_strings = optional_embeddings_to_base64_strings(embeddings) + assert b64_strings is not None + assert len(b64_strings) == len(embeddings) + decoded_embeddings = optional_base64_strings_to_embeddings(b64_strings) + + expected_embeddings = [] + for embedding in embeddings: + expected_embedding = [] + for value in embedding: + if math.isnan(value): + expected_embedding.append(float("nan")) + elif value > np.finfo(np.float32).max: + expected_embedding.append(float("inf")) + elif value < np.finfo(np.float32).min: + expected_embedding.append(float("-inf")) + else: + f32_value = np.float32(value) + expected_embedding.append(float(f32_value)) + expected_embeddings.append(expected_embedding) + + for orig, decoded in zip(expected_embeddings, decoded_embeddings): # type: ignore + np.testing.assert_allclose(orig, decoded, rtol=1e-6) + + +@given(st.lists(st.lists(st.floats(width=32)))) +def test_base64_conversion_numpy_is_identity_f32(embeddings) -> None: # type: ignore + b64_strings = optional_embeddings_to_base64_strings( + [np.array(embedding, dtype=np.float32) for embedding in embeddings] + ) + assert b64_strings is not None + assert len(b64_strings) == len(embeddings) + decoded_embeddings = optional_base64_strings_to_embeddings(b64_strings) + + expected_embeddings = [] + for embedding in embeddings: + expected_embedding = [] + for value in embedding: + if math.isnan(value): + expected_embedding.append(float("nan")) + elif value > np.finfo(np.float32).max: + expected_embedding.append(float("inf")) + elif value < np.finfo(np.float32).min: + expected_embedding.append(float("-inf")) + else: + f32_value = np.float32(value) + expected_embedding.append(float(f32_value)) + expected_embeddings.append(expected_embedding) + + for orig, decoded in zip(expected_embeddings, decoded_embeddings): # type: ignore + np.testing.assert_allclose(orig, decoded, rtol=1e-6) diff --git a/python/user_packages/Python313/site-packages/chromadb/test/property/test_client_url.py b/python/user_packages/Python313/site-packages/chromadb/test/property/test_client_url.py new file mode 100644 index 0000000000000000000000000000000000000000..5c243e978c8252233d36ed0655638c9be6f6974f --- /dev/null +++ b/python/user_packages/Python313/site-packages/chromadb/test/property/test_client_url.py @@ -0,0 +1,134 @@ +from typing import Optional +from urllib.parse import urlparse + +import pytest +from hypothesis import given, strategies as st + +from chromadb.api.fastapi import FastAPI + + +def hostname_strategy() -> st.SearchStrategy[str]: + label = st.text( + alphabet=st.characters(min_codepoint=97, max_codepoint=122), + min_size=1, + max_size=63, + ) + return st.lists(label, min_size=1, max_size=3).map("-".join) + + +tld_list = ["com", "org", "net", "edu"] + + +def domain_strategy() -> st.SearchStrategy[str]: + label = st.text( + alphabet=st.characters(min_codepoint=97, max_codepoint=122), + min_size=1, + max_size=63, + ) + tld = st.sampled_from(tld_list) + return st.tuples(label, tld).map(".".join) + + +port_strategy = st.one_of(st.integers(min_value=1, max_value=65535), st.none()) + +ssl_enabled_strategy = st.booleans() + + +def url_path_strategy() -> st.SearchStrategy[str]: + path_segment = st.text( + alphabet=st.sampled_from("abcdefghijklmnopqrstuvwxyz/-_"), + min_size=1, + max_size=10, + ) + return ( + st.lists(path_segment, min_size=1, max_size=5) + .map("/".join) + .map(lambda x: "/" + x) + ) + + +def is_valid_url(url: str) -> bool: + try: + parsed = urlparse(url) + return all([parsed.scheme, parsed.netloc]) + except Exception: + return False + + +def generate_valid_domain_url() -> st.SearchStrategy[str]: + return st.builds( + lambda url_scheme, hostname, url_path: f"{url_scheme}{hostname}{url_path}", + url_scheme=st.sampled_from(["http://", "https://"]), + hostname=domain_strategy(), + url_path=url_path_strategy(), + ) + + +def generate_invalid_domain_url() -> st.SearchStrategy[str]: + return st.builds( + lambda url_scheme, hostname, url_path: f"{url_scheme}{hostname}{url_path}", + url_scheme=st.builds( + lambda scheme, suffix: f"{scheme}{suffix}", + scheme=st.text(max_size=10), + suffix=st.sampled_from(["://", ":///", ":////", ""]), + ), + hostname=domain_strategy(), + url_path=url_path_strategy(), + ) + + +host_or_domain_strategy = st.one_of( + generate_valid_domain_url(), domain_strategy(), st.sampled_from(["localhost"]) +) + + +@given( + hostname=host_or_domain_strategy, + port=port_strategy, + ssl_enabled=ssl_enabled_strategy, + default_api_path=st.sampled_from(["/api/v1", "/api/v2", None]), +) +def test_url_resolve( + hostname: str, + port: Optional[int], + ssl_enabled: bool, + default_api_path: Optional[str], +) -> None: + _url = FastAPI.resolve_url( + chroma_server_host=hostname, + chroma_server_http_port=port, + chroma_server_ssl_enabled=ssl_enabled, + default_api_path=default_api_path, + ) + assert is_valid_url(_url), f"Invalid URL: {_url}" + assert ( + _url.startswith("https") if ssl_enabled else _url.startswith("http") + ), f"Invalid URL: {_url} - SSL Enabled: {ssl_enabled}" + if hostname.startswith("http"): + assert ":" + str(port) not in _url, f"Port in URL not expected: {_url}" + else: + assert ":" + str(port) in _url, f"Port in URL expected: {_url}" + if default_api_path: + assert _url.endswith(default_api_path), f"Invalid URL: {_url}" + + +@given( + hostname=generate_invalid_domain_url(), + port=port_strategy, + ssl_enabled=ssl_enabled_strategy, + default_api_path=st.sampled_from(["/api/v1", "/api/v2", None]), +) +def test_resolve_invalid( + hostname: str, + port: Optional[int], + ssl_enabled: bool, + default_api_path: Optional[str], +) -> None: + with pytest.raises(ValueError) as e: + FastAPI.resolve_url( + chroma_server_host=hostname, + chroma_server_http_port=port, + chroma_server_ssl_enabled=ssl_enabled, + default_api_path=default_api_path, + ) + assert "Invalid URL" in str(e.value) diff --git a/python/user_packages/Python313/site-packages/chromadb/test/property/test_collections.py b/python/user_packages/Python313/site-packages/chromadb/test/property/test_collections.py new file mode 100644 index 0000000000000000000000000000000000000000..c1e4ed6ff0b8e4c19724e761ec809f9259b45148 --- /dev/null +++ b/python/user_packages/Python313/site-packages/chromadb/test/property/test_collections.py @@ -0,0 +1,340 @@ +import pytest +import logging +import hypothesis.strategies as st +from chromadb.test.property.invariants import check_metadata +import chromadb.test.property.strategies as strategies +from chromadb.api import ClientAPI +import chromadb.api.types as types +from hypothesis.stateful import ( + Bundle, + RuleBasedStateMachine, + rule, + initialize, + multiple, + consumes, + run_state_machine_as_test, + MultipleResults, +) +from chromadb.test.conftest import multi_region_test +import chromadb.test.property.invariants as invariants +from typing import Any, Dict, Mapping, Optional +import numpy +from chromadb.test.property.strategies import hashing_embedding_function + + +class CollectionStateMachine(RuleBasedStateMachine): + collections: Bundle[strategies.ExternalCollection] + _model: Dict[str, Optional[types.CollectionMetadata]] + + collections = Bundle("collections") + + def __init__(self, client: ClientAPI): + super().__init__() + self._model = {} + self.client = client + + @initialize() + def initialize(self) -> None: + self.client.reset() + self._model = {} + + @rule(target=collections, coll=strategies.collections()) + def create_coll( + self, coll: strategies.ExternalCollection + ) -> MultipleResults[strategies.ExternalCollection]: + # Metadata can either be None or a non-empty dict + if coll.name in self.model or ( + coll.metadata is not None and len(coll.metadata) == 0 + ): + with pytest.raises(Exception): + c = self.client.create_collection( + name=coll.name, + metadata=coll.metadata, # type: ignore[arg-type] + embedding_function=coll.embedding_function, + ) + return multiple() + + c = self.client.create_collection( + name=coll.name, + metadata=coll.metadata, # type: ignore[arg-type] + embedding_function=coll.embedding_function, + ) + self.set_model(coll.name, coll.metadata) # type: ignore[arg-type] + + assert c.name == coll.name + check_metadata(self.model[coll.name], c.metadata) + return multiple(coll) + + @rule(coll=collections) + def get_coll(self, coll: strategies.ExternalCollection) -> None: + if coll.name in self.model: + c = self.client.get_collection(name=coll.name) + assert c.name == coll.name + check_metadata(self.model[coll.name], c.metadata) + else: + with pytest.raises(Exception): + self.client.get_collection(name=coll.name) + + @rule(coll=consumes(collections)) + def delete_coll(self, coll: strategies.ExternalCollection) -> None: + if coll.name in self.model: + with invariants.collection_deleted(self.client, coll.name): + self.client.delete_collection(name=coll.name) + self.delete_from_model(coll.name) + else: + with pytest.raises(Exception): + self.client.delete_collection(name=coll.name) + + with pytest.raises(Exception): + self.client.get_collection(name=coll.name) + + @rule() + def list_collections(self) -> None: + colls = self.client.list_collections() + assert len(colls) == len(self.model) + for c in colls: + assert c.name in self.model + + # @rule for list_collections with limit and offset + @rule( + limit=st.integers(min_value=1, max_value=5), + offset=st.integers(min_value=0, max_value=5), + ) + def list_collections_with_limit_offset(self, limit: int, offset: int) -> None: + colls = self.client.list_collections(limit=limit, offset=offset) + total_collections = self.client.count_collections() + + # get all collections + all_colls = self.client.list_collections() + # manually slice the collections based on the given limit and offset + man_colls = all_colls[offset : offset + limit] + + # given limit and offset, make various assertions regarding the total number of collections + if limit + offset > total_collections: + assert len(colls) == max(total_collections - offset, 0) + # assert that our manually sliced collections are the same as the ones returned by the API + assert colls == man_colls + + else: + assert len(colls) == limit + + @rule( + target=collections, + new_metadata=st.one_of(st.none(), strategies.collection_metadata), + coll=st.one_of(consumes(collections), strategies.collections()), + ) + def get_or_create_coll( + self, + coll: strategies.ExternalCollection, + new_metadata: Optional[types.Metadata], + ) -> MultipleResults[strategies.ExternalCollection]: + # Cases for get_or_create + + # Case 0 + # new_metadata is none, coll is an existing collection + # get_or_create should return the existing collection with existing metadata + + # Case 1 + # new_metadata is none, coll is a new collection + # get_or_create should create a new collection with the metadata of None + + # Case 2 + # new_metadata is not none, coll is an existing collection + # get_or_create should return the existing collection with the original metadata + + # Case 3 + # new_metadata is not none, coll is a new collection + # get_or_create should create a new collection with the new metadata + + if new_metadata is not None and len(new_metadata) == 0: + with pytest.raises(Exception): + c = self.client.get_or_create_collection( + name=coll.name, + metadata=new_metadata, # type: ignore[arg-type] + embedding_function=coll.embedding_function, + ) + return multiple() + + # Update model + if coll.name not in self.model: + # Handles case 1 and 3 + coll.metadata = new_metadata + self.set_model(coll.name, coll.metadata) # type: ignore[arg-type] + + # Update API + c = self.client.get_or_create_collection( + name=coll.name, + metadata=new_metadata, # type: ignore[arg-type] + embedding_function=coll.embedding_function, + ) + + # Check that model and API are in sync + assert c.name == coll.name + check_metadata(self.model[coll.name], c.metadata) + return multiple(coll) + + @rule( + target=collections, + coll=consumes(collections), + new_metadata=strategies.collection_metadata, + new_name=st.one_of(st.none(), strategies.collection_name()), + ) + def modify_coll( + self, + coll: strategies.ExternalCollection, + new_metadata: types.Metadata, + new_name: Optional[str], + ) -> MultipleResults[strategies.ExternalCollection]: + if coll.name not in self.model: + with pytest.raises(Exception): + c = self.client.get_collection(name=coll.name) + return multiple() + + c = self.client.get_collection(name=coll.name) + _metadata: Optional[Mapping[str, Any]] = self.model[coll.name] + _name: str = coll.name + if new_metadata is not None: + # Can't set metadata to an empty dict + if len(new_metadata) == 0: + with pytest.raises(Exception): + c = self.client.get_or_create_collection( + name=coll.name, + metadata=new_metadata, # type: ignore[arg-type] + embedding_function=coll.embedding_function, + ) + return multiple() + + coll.metadata = new_metadata + _metadata = new_metadata + + if new_name is not None: + if new_name in self.model and new_name != coll.name: + with pytest.raises(Exception): + c.modify(metadata=new_metadata, name=new_name) # type: ignore[arg-type] + return multiple() + + self.delete_from_model(coll.name) + coll.name = new_name + _name = new_name + + self.set_model(_name, _metadata) # type: ignore[arg-type] + c.modify(metadata=_metadata, name=_name) # type: ignore[arg-type] + c = self.client.get_collection(name=coll.name) + + assert c.name == coll.name + check_metadata(self.model[coll.name], c.metadata) + return multiple(coll) + + def set_model( + self, + name: str, + metadata: Optional[types.CollectionMetadata], + ) -> None: + model = self.model + model[name] = metadata + + def delete_from_model(self, name: str) -> None: + model = self.model + del model[name] + + @property + def model(self) -> Dict[str, Optional[types.CollectionMetadata]]: + return self._model + + +@multi_region_test +def test_collections(caplog: pytest.LogCaptureFixture, client: ClientAPI) -> None: + caplog.set_level(logging.ERROR) + run_state_machine_as_test(lambda: CollectionStateMachine(client)) # type: ignore + + +# Below are tests that have failed in the past. If your test fails, please add +# it to protect against regressions in the test harness itself. If you need +# help doing so, talk to anton. + + +def test_previously_failing_one(client: ClientAPI) -> None: + state = CollectionStateMachine(client) + state.initialize() + # I don't know why the typechecker is red here. This code is correct and is + # pulled from the logs. + (v1,) = state.get_or_create_coll( # type: ignore[misc] + coll=strategies.ExternalCollection( + name="jjn2yjLW1zp2T", + metadata=None, + embedding_function=hashing_embedding_function(dtype=numpy.float32, dim=863), # type: ignore[arg-type] + ), + new_metadata=None, + ) + (v6,) = state.get_or_create_coll( # type: ignore[misc] + coll=strategies.ExternalCollection( + name="jjn2yjLW1zp2T", + metadata=None, + embedding_function=hashing_embedding_function(dtype=numpy.float32, dim=863), # type: ignore[arg-type] + ), + new_metadata=None, + ) + state.modify_coll( + coll=v1, new_metadata={"7": -1281, "fGe": -0.0, "K5j": "im"}, new_name=None + ) + state.modify_coll(coll=v6, new_metadata=None, new_name=None) + + +# https://github.com/chroma-core/chroma/commit/cf476d70f0cebb7c87cb30c7172ba74d6ea175cd#diff-e81868b665d149bb315d86890dea6fc6a9fc9fc9ea3089aa7728142b54f622c5R210 +def test_previously_failing_two(client: ClientAPI) -> None: + state = CollectionStateMachine(client) + state.initialize() + (v13,) = state.get_or_create_coll( # type: ignore[misc] + coll=strategies.ExternalCollection( + name="C1030", + metadata={}, + embedding_function=hashing_embedding_function(dim=2, dtype=numpy.float32), # type: ignore[arg-type] + ), + new_metadata=None, + ) + (v15,) = state.modify_coll( # type: ignore[misc] + coll=v13, + new_metadata={ + "0": "10", + "40": "0", + "p1nviWeL7fO": "qN", + "7b": "YS", + "VYWq4LEMWjCo": True, + }, + new_name="OF5F0MzbQg", + ) + state.get_or_create_coll( + coll=strategies.ExternalCollection( + name="VS0QGh", + metadata={ + "h": 5.681951615025145e-227, + "A1": 61126, + "uhUhLEEMfeC_kN": 2147483647, + "weF": "pSP", + "B3DSaP": False, + "6H533K": 1.192092896e-07, + }, + embedding_function=hashing_embedding_function( # type: ignore[arg-type] + dim=1915, dtype=numpy.float32 + ), + ), + new_metadata={ + "xVW09xUpDZA": 31734, + "g": 1.1, + "n1dUTalF-MY": -1000000.0, + "y": "G3EtXTZ", + "ugXZ_hK": 5494, + }, + ) + v17 = state.modify_coll( # noqa: F841 + coll=v15, new_metadata={"L35J2S": "K0l026"}, new_name="Ai1" + ) + v18 = state.get_or_create_coll(coll=v13, new_metadata=None) # noqa: F841 + state.get_or_create_coll( + coll=strategies.ExternalCollection( + name="VS0QGh", + metadata=None, + embedding_function=hashing_embedding_function(dim=326, dtype=numpy.float16), # type: ignore[arg-type] + ), + new_metadata=None, + ) diff --git a/python/user_packages/Python313/site-packages/chromadb/test/property/test_collections_with_database_tenant.py b/python/user_packages/Python313/site-packages/chromadb/test/property/test_collections_with_database_tenant.py new file mode 100644 index 0000000000000000000000000000000000000000..93eeda3701ecdf8e687013a4760099add486fceb --- /dev/null +++ b/python/user_packages/Python313/site-packages/chromadb/test/property/test_collections_with_database_tenant.py @@ -0,0 +1,178 @@ +import logging +from typing import Dict, Optional, Tuple +import pytest +from chromadb.api import AdminAPI +import chromadb.api.types as types +from chromadb.config import DEFAULT_TENANT +from chromadb.test.conftest import ( + ClientFactories, + DEFAULT_MCMR_DATABASE, + MULTI_REGION_TOPOLOGY, + multi_region_test, +) + +from chromadb.test.property.test_collections import CollectionStateMachine +from hypothesis.stateful import ( + Bundle, + rule, + initialize, + multiple, + run_state_machine_as_test, + MultipleResults, +) +import chromadb.test.property.strategies as strategies + +class TenantDatabaseCollectionStateMachine(CollectionStateMachine): + """A collection state machine test that includes tenant and database information, + and switches between them.""" + + tenants: Bundle # [str] + databases: Bundle # [Tuple[str, str]] # database to tenant it belongs to + tenant_to_database_to_model: Dict[ + str, Dict[str, Dict[str, Optional[types.CollectionMetadata]]] + ] + admin_client: AdminAPI + curr_tenant: str + curr_database: str + effective_default_database: str + uses_multi_region_database: bool + + tenants = Bundle("tenants") + databases = Bundle("databases") + + def __init__( + self, + client_factories: ClientFactories, + database_name: str, + ) -> None: + self.effective_default_database = database_name + self.uses_multi_region_database = database_name == DEFAULT_MCMR_DATABASE + client = client_factories.create_client(database=database_name) + super().__init__(client) + self.client = client + self.admin_client = client_factories.create_admin_client_from_system() + + @initialize() + def initialize(self) -> None: + self.client.reset() + self.tenant_to_database_to_model = {} + self.curr_tenant = DEFAULT_TENANT + self.curr_database = self.effective_default_database + self.client.set_tenant(DEFAULT_TENANT, self.effective_default_database) + self.set_tenant_model(self.curr_tenant, {}) + self.set_database_model_for_tenant(self.curr_tenant, self.curr_database, {}) + + @rule(target=tenants, name=strategies.tenant_database_name) + def create_tenant(self, name: str) -> MultipleResults: # [str]: + tenant = self.overwrite_tenant(name) + # Check if tenant already exists + if self.has_tenant(tenant): + with pytest.raises(Exception): + self.admin_client.create_tenant(tenant) + return multiple() + + self.admin_client.create_tenant(tenant) + # When we create a tenant, create a default database for it just for testing + # since the state machine could call collection operations before creating a + # database + self.admin_client.create_database( + self.effective_default_database, tenant=tenant + ) + self.set_tenant_model(tenant, {}) + self.set_database_model_for_tenant( + tenant, self.effective_default_database, {} + ) + return multiple(tenant) + + @rule(target=databases, name=strategies.tenant_database_name) + def create_database(self, name: str) -> MultipleResults: # [Tuple[str, str]]: + if self.uses_multi_region_database: + name = f"{MULTI_REGION_TOPOLOGY}+{name}" + database = self.overwrite_database(name) + tenant = self.overwrite_tenant(self.curr_tenant) + # If database already exists in current tenant, raise an error + if self.has_database_for_tenant(tenant, database): + with pytest.raises(Exception): + self.admin_client.create_database(name=database, tenant=tenant) + return multiple() + + self.admin_client.create_database(name=database, tenant=tenant) + self.set_database_model_for_tenant( + tenant=tenant, database=database, database_model={} + ) + return multiple((database, tenant)) + + @rule(database=databases) + def set_database_and_tenant(self, database: Tuple[str, str]) -> None: + # Get a database and switch to the database and the tenant it belongs to + database_name = database[0] + tenant_name = database[1] + self.set_api_tenant_database(tenant_name, database_name) + self.curr_database = database_name + self.curr_tenant = tenant_name + + @rule(tenant=tenants) + def set_tenant(self, tenant: str) -> None: + self.set_api_tenant_database(tenant, self.effective_default_database) + self.curr_tenant = tenant + self.curr_database = self.effective_default_database + + # These methods allow other tests, namely + # test_collections_with_database_tenant_override.py, to swap out the model + # without needing to do a bunch of pythonic cleverness to fake a dict which + # preteds to have every key. + def set_api_tenant_database(self, tenant: str, database: str) -> None: + self.client.set_tenant(tenant, database) + + # For calls to create_database, and create_tenant we may want to override the tenant and database + # This is a leaky abstraction that exists soley for the purpose of + # test_collections_with_database_tenant_override.py + def overwrite_tenant(self, tenant: str) -> str: + return tenant + + def overwrite_database(self, database: str) -> str: + return database + + def has_tenant(self, tenant: str) -> bool: + return tenant in self.tenant_to_database_to_model + + def get_tenant_model( + self, tenant: str + ) -> Dict[str, Dict[str, Optional[types.CollectionMetadata]]]: + return self.tenant_to_database_to_model[tenant] + + def set_tenant_model( + self, + tenant: str, + model: Dict[str, Dict[str, Optional[types.CollectionMetadata]]], + ) -> None: + self.tenant_to_database_to_model[tenant] = model + + def has_database_for_tenant(self, tenant: str, database: str) -> bool: + return database in self.tenant_to_database_to_model[tenant] + + def set_database_model_for_tenant( + self, + tenant: str, + database: str, + database_model: Dict[str, Optional[types.CollectionMetadata]], + ) -> None: + self.tenant_to_database_to_model[tenant][database] = database_model + + @property + def model(self) -> Dict[str, Optional[types.CollectionMetadata]]: + return self.tenant_to_database_to_model[self.curr_tenant][self.curr_database] + + +@multi_region_test +def test_collections( + caplog: pytest.LogCaptureFixture, + client_factories: ClientFactories, + database_name: str, +) -> None: + caplog.set_level(logging.ERROR) + run_state_machine_as_test( + lambda: TenantDatabaseCollectionStateMachine( + client_factories, database_name=database_name + ) + ) # type: ignore diff --git a/python/user_packages/Python313/site-packages/chromadb/test/property/test_collections_with_database_tenant_overwrite.py b/python/user_packages/Python313/site-packages/chromadb/test/property/test_collections_with_database_tenant_overwrite.py new file mode 100644 index 0000000000000000000000000000000000000000..9d83d83cd925a630bf442f5502bca198e3c06378 --- /dev/null +++ b/python/user_packages/Python313/site-packages/chromadb/test/property/test_collections_with_database_tenant_overwrite.py @@ -0,0 +1,260 @@ +from typing import Dict, Optional, Tuple +from overrides import overrides +from hypothesis.stateful import ( + initialize, + invariant, + rule, + run_state_machine_as_test, +) + +import uuid +import logging +import os +import pytest +from chromadb.api import AdminAPI, ServerAPI +from chromadb.api.client import AdminClient, Client +from chromadb.config import Settings, System +from chromadb.test.conftest import ( + ClientFactories, + DEFAULT_MCMR_DATABASE, + fastapi_fixture_admin_and_singleton_tenant_db_user, + MULTI_REGION_TOPOLOGY, + multi_region_test, + NOT_CLUSTER_ONLY, +) +from chromadb.test.property.test_collections_with_database_tenant import ( + TenantDatabaseCollectionStateMachine, +) +import chromadb.test.property.strategies as strategies +import numpy +import chromadb.api.types as types + +# See conftest.py +SINGLETON_TENANT = "singleton_tenant" +SINGLETON_DATABASE_NAME = "singleton_database" + + +def singleton_database_name(database_name: str) -> str: + if database_name == DEFAULT_MCMR_DATABASE: + return f"{MULTI_REGION_TOPOLOGY}+{SINGLETON_DATABASE_NAME}" + return SINGLETON_DATABASE_NAME + + +class SingletonTenantDatabaseCollectionStateMachine( + TenantDatabaseCollectionStateMachine +): + singleton_client: Client + singleton_admin_client: AdminAPI + root_client: Client + root_admin_client: AdminAPI + singleton_database: str + + def __init__( + self, + singleton_client: Client, + root_client: Client, + client_factories: ClientFactories, + database_name: str, + ) -> None: + super().__init__(client_factories, database_name=database_name) + self.root_client = root_client + self.root_admin_client = self.admin_client + + self.singleton_database = singleton_database_name(database_name) + self.singleton_client = singleton_client + self.singleton_admin_client = AdminClient.from_system(singleton_client._system) + + @initialize() + def initialize(self) -> None: + # Make sure we're back to the root client and admin client before + # doing reset/initialize things. + self.client = self.root_client + self.admin_client = self.root_admin_client + + super().initialize() + + self.root_admin_client.create_tenant(SINGLETON_TENANT) + self.root_admin_client.create_database( + self.singleton_database, SINGLETON_TENANT + ) + + self.set_tenant_model(SINGLETON_TENANT, {}) + self.set_database_model_for_tenant( + SINGLETON_TENANT, self.singleton_database, {} + ) + + @invariant() + def check_api_and_admin_client_are_in_sync(self) -> None: + if self.client == self.singleton_client: + assert self.admin_client == self.singleton_admin_client + else: + assert self.admin_client == self.root_admin_client + + @rule() + def change_clients(self) -> None: + if self.client == self.singleton_client: + self.client = self.root_client + self.admin_client = self.root_admin_client + # When switching back to root, restore the previous tenant/database context + from chromadb.config import DEFAULT_TENANT + + self.client.set_tenant(DEFAULT_TENANT, self.effective_default_database) + self.curr_tenant = DEFAULT_TENANT + self.curr_database = self.effective_default_database + else: + self.client = self.singleton_client + self.admin_client = self.singleton_admin_client + # Set to singleton tenant/database context and update state + self.client.set_tenant(SINGLETON_TENANT, self.singleton_database) + self.curr_tenant = SINGLETON_TENANT + self.curr_database = self.singleton_database + + @overrides + def set_api_tenant_database(self, tenant: str, database: str) -> None: + self.client.set_tenant(tenant, database) + + @overrides + def get_tenant_model( + self, tenant: str + ) -> Dict[str, Dict[str, Optional[types.CollectionMetadata]]]: + if self.client == self.singleton_client: + tenant = SINGLETON_TENANT + return self.tenant_to_database_to_model[tenant] + + @overrides + def set_tenant_model( + self, + tenant: str, + model: Dict[str, Dict[str, Optional[types.CollectionMetadata]]], + ) -> None: + if self.client == self.singleton_client: + # This never happens because we never actually issue a + # create_tenant call on singleton_tenant: + # thanks to the above overriding of get_tenant_model(), + # the underlying state machine test should always expect an error + # when it sends the request, so shouldn't try to update the model. + raise ValueError("trying to overwrite the model for singleton??") + self.tenant_to_database_to_model[tenant] = model + + @overrides + def set_database_model_for_tenant( + self, + tenant: str, + database: str, + database_model: Dict[str, Optional[types.CollectionMetadata]], + ) -> None: + if self.client == self.singleton_client: + # This never happens because we never actually issue a + # create_database call on (singleton_tenant, singleton_database): + # thanks to the above overriding of has_database_for_tenant(), + # the underlying state machine test should always expect an error + # when it sends the request, so shouldn't try to update the model. + raise ValueError("trying to overwrite the model for singleton??") + self.tenant_to_database_to_model[tenant][database] = database_model + + @overrides + def overwrite_database(self, database: str) -> str: + if self.client == self.singleton_client: + return self.singleton_database + return database + + @overrides + def overwrite_tenant(self, tenant: str) -> str: + if self.client == self.singleton_client: + return SINGLETON_TENANT + return tenant + + @property + def model(self) -> Dict[str, Optional[types.CollectionMetadata]]: + # Always use current tenant/database context + return self.tenant_to_database_to_model[self.curr_tenant][self.curr_database] + + +def _singleton_and_root_clients( + database_name: str, +) -> Tuple[Client, Client, ClientFactories]: + singleton_database = singleton_database_name(database_name) + api_fixture = fastapi_fixture_admin_and_singleton_tenant_db_user( + singleton_database=singleton_database + ) + sys: System = next(api_fixture) + sys.reset_state() + + # When connecting to external Tilt, also reset the server + if os.getenv("CHROMA_SERVER_HOST") and not NOT_CLUSTER_ONLY: + sys.instance(ServerAPI).reset() + + client_factories = ClientFactories(sys) + root_client = client_factories.create_client(database=database_name) + root_client.reset() + _root_admin_client = client_factories.create_admin_client_from_system() + + # This is a little awkward but we have to create the tenant and DB + # before we can instantiate a Client which connects to them. This also + # means we need to manually populate state in the state machine. + _root_admin_client.create_tenant(SINGLETON_TENANT) + _root_admin_client.create_database(singleton_database, SINGLETON_TENANT) + + singleton_settings = Settings(**dict(sys.settings)) + singleton_settings.chroma_client_auth_credentials = "singleton-token" + singleton_system = System(singleton_settings) + singleton_system.start() + singleton_client = Client.from_system( + singleton_system, tenant=SINGLETON_TENANT, database=singleton_database + ) + + return singleton_client, root_client, client_factories + + +@multi_region_test +def test_collections_with_tenant_database_overwrite( + caplog: pytest.LogCaptureFixture, + database_name: str, +) -> None: + caplog.set_level(logging.ERROR) + + singleton_client, root_client, client_factories = _singleton_and_root_clients( + database_name + ) + run_state_machine_as_test( + lambda: SingletonTenantDatabaseCollectionStateMachine( + singleton_client, root_client, client_factories, database_name + ) + ) # type: ignore + + +@multi_region_test +def test_repeat_failure( + caplog: pytest.LogCaptureFixture, + database_name: str, +) -> None: + caplog.set_level(logging.ERROR) + + singleton_client, root_client, client_factories = _singleton_and_root_clients( + database_name + ) + + state = SingletonTenantDatabaseCollectionStateMachine( + singleton_client, root_client, client_factories, database_name + ) + state.initialize() + state.check_api_and_admin_client_are_in_sync() + state.change_clients() + state.check_api_and_admin_client_are_in_sync() + state.create_coll( + coll=strategies.Collection( + name="A00", + metadata=None, + embedding_function=strategies.hashing_embedding_function( + dim=2, dtype=numpy.float16 # type: ignore + ), + id=uuid.UUID("c9bcb72f-92b1-4604-a8cb-084162dfe98b"), + dimension=2, + dtype=numpy.float16, + known_metadata_keys={}, + known_document_keywords=[], + has_documents=False, + has_embeddings=True, + ) + ) + state.teardown() # type: ignore diff --git a/python/user_packages/Python313/site-packages/chromadb/test/property/test_cross_version_persist.py b/python/user_packages/Python313/site-packages/chromadb/test/property/test_cross_version_persist.py new file mode 100644 index 0000000000000000000000000000000000000000..f7514309f52341d0f6d5aee0318b8d14c8e5ed2d --- /dev/null +++ b/python/user_packages/Python313/site-packages/chromadb/test/property/test_cross_version_persist.py @@ -0,0 +1,356 @@ +from multiprocessing.connection import Connection +import os +import shutil +import tempfile +from typing import Generator, List, Tuple, Dict, Any, Callable, Type +from hypothesis import given, settings +import hypothesis.strategies as st +import pytest +import json +from urllib import request +from chromadb import config +from chromadb.api.configuration import ( + ConfigurationParameter, + EmbeddingsQueueConfigurationInternal, +) +from chromadb.api.types import Documents, EmbeddingFunction, Embeddings +from chromadb.db.impl.sqlite import SqliteDB +from chromadb.ingest.impl.utils import trigger_vector_segments_max_seq_id_migration +from chromadb.segment import SegmentManager +from chromadb.segment.impl.manager.local import LocalSegmentManager +import chromadb.test.property.strategies as strategies +import chromadb.test.property.invariants as invariants +from packaging import version as packaging_version +import re +import multiprocessing +from chromadb.config import Settings +from chromadb.api.client import Client as ClientCreator +from chromadb.test.utils.cross_version import ( + switch_to_version, + install_version, + get_path_to_version_install, +) + +# Minimum persisted version we support, and other substantial change versions +# 0.4.1 is the first version with persistence +# 0.5.3 is the first version with the new API where the serverapi and client api return types and arguments differ +BASELINE_VERSIONS = ["0.4.1", "0.5.3"] +version_re = re.compile(r"^[0-9]+\.[0-9]+\.[0-9]+$") + +# Some modules do not work across versions, since we upgrade our support for them, and should be explicitly reimported in the subprocess +VERSIONED_MODULES = ["pydantic", "pydantic_settings", "numpy", "tokenizers"] + + +def versions() -> List[str]: + """Returns the pinned minimum version and the latest version of chromadb.""" + url = "https://pypi.org/pypi/chromadb/json" + data = json.load(request.urlopen(request.Request(url))) + releases = data["releases"] + versions = list(releases.keys()) + # Older versions on pypi contain "devXYZ" suffixes + versions = [v for v in versions if version_re.match(v)] + versions = [ + v + for v in versions + if not any(file.get("yanked", False) for file in releases.get(v, [])) + ] + versions.sort(key=packaging_version.Version) + return BASELINE_VERSIONS + [versions[-1]] + + +def _bool_to_int(metadata: Dict[str, Any]) -> Dict[str, Any]: + metadata.update((k, 1) for k, v in metadata.items() if v is True) + metadata.update((k, 0) for k, v in metadata.items() if v is False) + return metadata + + +def _patch_boolean_metadata( + collection: strategies.Collection, + embeddings: strategies.RecordSet, + settings: Settings, +) -> None: + # Since the old version does not support boolean value metadata, we will convert + # boolean value metadata to int + collection_metadata = collection.metadata + if collection_metadata is not None: + _bool_to_int(collection_metadata) # type: ignore + + if embeddings["metadatas"] is not None: + if isinstance(embeddings["metadatas"], list): + for metadata in embeddings["metadatas"]: + if metadata is not None and isinstance(metadata, dict): + _bool_to_int(metadata) + elif isinstance(embeddings["metadatas"], dict): + metadata = embeddings["metadatas"] + _bool_to_int(metadata) + + +def _patch_telemetry_client( + collection: strategies.Collection, + embeddings: strategies.RecordSet, + settings: Settings, +) -> None: + # chroma 0.4.14 added OpenTelemetry, distinct from ProductTelemetry. Before 0.4.14 + # ProductTelemetry was simply called Telemetry. + settings.chroma_telemetry_impl = "chromadb.telemetry.posthog.Posthog" + + +version_patches: List[ + Tuple[str, Callable[[strategies.Collection, strategies.RecordSet, Settings], None]] +] = [ + ("0.4.3", _patch_boolean_metadata), + ("0.4.14", _patch_telemetry_client), +] + + +def patch_for_version( + version: str, + collection: strategies.Collection, + embeddings: strategies.RecordSet, + settings: Settings, +) -> None: + """Override aspects of the collection and embeddings, before testing, to account for + breaking changes in old versions.""" + + for patch_version, patch in version_patches: + if packaging_version.Version(version) <= packaging_version.Version( + patch_version + ): + patch(collection, embeddings, settings) + + +def api_import_for_version(module: Any, version: str) -> Type: # type: ignore + if packaging_version.Version(version) <= packaging_version.Version("0.4.14"): + return module.api.API # type: ignore + return module.api.ServerAPI # type: ignore + + +def configurations(versions: List[str]) -> List[Tuple[str, Settings]]: + return [ + ( + version, + Settings( + chroma_api_impl="chromadb.api.rust.RustBindingsAPI" + if "CHROMA_RUST_BINDINGS_TEST_ONLY" in os.environ + else "chromadb.api.segment.SegmentAPI", + chroma_sysdb_impl="chromadb.db.impl.sqlite.SqliteDB", + chroma_producer_impl="chromadb.db.impl.sqlite.SqliteDB", + chroma_consumer_impl="chromadb.db.impl.sqlite.SqliteDB", + chroma_segment_manager_impl="chromadb.segment.impl.manager.local.LocalSegmentManager", + allow_reset=True, + is_persistent=True, + persist_directory=tempfile.mkdtemp(), + ), + ) + for version in versions + ] + + +test_old_versions = versions() +base_install_dir = tempfile.mkdtemp() + + +# This fixture is not shared with the rest of the tests because it is unique in how it +# installs the versions of chromadb +@pytest.fixture(scope="module", params=configurations(test_old_versions)) # type: ignore +def version_settings(request) -> Generator[Tuple[str, Settings], None, None]: + configuration = request.param + version = configuration[0] + + install_version(version, {}) + yield configuration + # Cleanup the installed version + path = get_path_to_version_install(version) + shutil.rmtree(path) + # Cleanup the persisted data + data_path = configuration[1].persist_directory + if os.path.exists(data_path): + shutil.rmtree(data_path, ignore_errors=True) + + +class not_implemented_ef(EmbeddingFunction[Documents]): + def __call__(self, input: Documents) -> Embeddings: + assert False, "Embedding function should not be called" + + def __init__(self, *args: Any, **kwargs: Any) -> None: + pass + + +def persist_generated_data_with_old_version( + version: str, + settings: Settings, + collection_strategy: strategies.Collection, + embeddings_strategy: strategies.RecordSet, + conn: Connection, +) -> None: + try: + old_module = switch_to_version(version, VERSIONED_MODULES) + # In 0.7.0 we switch to Rust client. The old versions are using the the python SegmentAPI client + if "CHROMA_RUST_BINDINGS_TEST_ONLY" in os.environ and packaging_version.Version( + version + ) < packaging_version.Version("0.7.0"): + settings.chroma_api_impl = "chromadb.api.segment.SegmentAPI" + system = old_module.config.System(settings) + api = system.instance(api_import_for_version(old_module, version)) + system.start() + + api.reset() + # In 0.5.4 we changed the API of the server api level to + # deal with collection models instead of collections + # in order to work with this we need to wrap the api in a client + # for versions greater than or equal to 0.5.4 + if packaging_version.Version(version) >= packaging_version.Version("0.5.4"): + api = old_module.api.client.Client.from_system(system) + coll = api.create_collection( + name=collection_strategy.name, + metadata=collection_strategy.metadata, + # In order to test old versions, we can't rely on the not_implemented function + embedding_function=not_implemented_ef(), + ) + coll.add(**embeddings_strategy) + + # Just use some basic checks for sanity and manual testing where you break the new + # version + + check_embeddings = invariants.wrap_all(embeddings_strategy) + # Check count + assert coll.count() == len(check_embeddings["embeddings"] or []) + # Check ids + result = coll.get() + actual_ids = result["ids"] + embedding_id_to_index = {id: i for i, id in enumerate(check_embeddings["ids"])} + actual_ids = sorted(actual_ids, key=lambda id: embedding_id_to_index[id]) + assert actual_ids == check_embeddings["ids"] + + # Leave writes on the queue to be processed by the next version's + # segment manager so we can test cross version serialization + # compatibility. + system.instance(LocalSegmentManager).stop() + coll.upsert(**embeddings_strategy) + + # Shutdown system + system.stop() + except Exception as e: + conn.send(e) + raise e + + +# Since we can't pickle the embedding function, we always generate record sets with embeddings +collection_st: st.SearchStrategy[strategies.Collection] = st.shared( + strategies.collections( + with_hnsw_params=True, + has_embeddings=True, + # By default, these are set to 2000, which makes it unlikely that index mutations will ever be fully flushed + max_hnsw_sync_threshold=10, + max_hnsw_batch_size=10, + with_persistent_hnsw_params=st.booleans(), + ), + key="coll", +) + + +@given( + collection_strategy=collection_st, + embeddings_strategy=strategies.recordsets(collection_st, max_size=200), +) +@settings(deadline=None) +def test_cycle_versions( + version_settings: Tuple[str, Settings], + collection_strategy: strategies.Collection, + embeddings_strategy: strategies.RecordSet, +) -> None: + # Test backwards compatibility + # For the current version, ensure that we can load a collection from + # the previous versions + version, settings = version_settings + # The strategies can generate metadatas of malformed inputs. Other tests + # will error check and cover these cases to make sure they error. Here we + # just convert them to valid values since the error cases are already tested + if embeddings_strategy["metadatas"] == {}: + embeddings_strategy["metadatas"] = None + if embeddings_strategy["metadatas"] is not None and isinstance( + embeddings_strategy["metadatas"], list + ): + embeddings_strategy["metadatas"] = [ + m if m is None or len(m) > 0 else None + for m in embeddings_strategy["metadatas"] + ] + + patch_for_version(version, collection_strategy, embeddings_strategy, settings) + + # Can't pickle a function, and we won't need them + collection_strategy.embedding_function = None + collection_strategy.known_metadata_keys = {} + + # Run the task in a separate process to avoid polluting the current process + # with the old version. Using spawn instead of fork to avoid sharing the + # current process memory which would cause the old version to be loaded + ctx = multiprocessing.get_context("spawn") + conn1, conn2 = multiprocessing.Pipe() + p = ctx.Process( + target=persist_generated_data_with_old_version, + args=(version, settings, collection_strategy, embeddings_strategy, conn2), + ) + p.start() + p.join() + + if conn1.poll(): + e = conn1.recv() + raise e + + p.close() + + # Switch to the current version (local working directory) and check the invariants + # are preserved for the collection + system = config.System(settings) + system.start() + client = ClientCreator.from_system(system) + coll = client.get_collection( + name=collection_strategy.name, + embedding_function=not_implemented_ef(), # type: ignore + ) + + embeddings_queue = system.instance(SqliteDB) + + # Automatic pruning should be disabled since embeddings_queue is non-empty + if packaging_version.Version(version) < packaging_version.Version( + "0.5.7" + ): # (automatic pruning is enabled by default in 0.5.7 and later) + assert ( + embeddings_queue.config.get_parameter("automatically_purge").value is False + ) + + # Update to True so log_size_below_max() invariant will pass + embeddings_queue.set_config( + EmbeddingsQueueConfigurationInternal( + [ConfigurationParameter("automatically_purge", True)] + ) + ) + + # Should be able to clean log immediately after updating + + # 07/29/24: the max_seq_id for vector segments was moved from the pickled metadata file to SQLite. + # Cleaning the log is dependent on vector segments migrating their max_seq_id from the pickled metadata file to SQLite. + # Vector segments migrate this field automatically on init, but at this point the segment has not been loaded yet. + if "CHROMA_RUST_BINDINGS_TEST_ONLY" in os.environ: + # Trigger log purge in Rust impl + invariants.count(coll, embeddings_strategy) + else: + trigger_vector_segments_max_seq_id_migration( + embeddings_queue, system.instance(SegmentManager) + ) + embeddings_queue.purge_log(coll.id) + invariants.log_size_below_max(system, [coll], True) + + # Should be able to add embeddings + coll.add(**embeddings_strategy) # type: ignore + + invariants.count(coll, embeddings_strategy) + invariants.metadatas_match(coll, embeddings_strategy) + invariants.documents_match(coll, embeddings_strategy) + invariants.ids_match(coll, embeddings_strategy) + invariants.ann_accuracy(coll, embeddings_strategy) + invariants.log_size_below_max(system, [coll], True) + + # Shutdown system + system.stop() diff --git a/python/user_packages/Python313/site-packages/chromadb/test/property/test_embeddings.py b/python/user_packages/Python313/site-packages/chromadb/test/property/test_embeddings.py new file mode 100644 index 0000000000000000000000000000000000000000..9279ca1a7e62ca029a831a269fe82b20a89527df --- /dev/null +++ b/python/user_packages/Python313/site-packages/chromadb/test/property/test_embeddings.py @@ -0,0 +1,1536 @@ +import hypothesis.stateful +import hypothesis.strategies +from overrides import overrides +import pytest +import logging +import hypothesis +import hypothesis.strategies as st +from hypothesis import given, settings, HealthCheck +from typing import Dict, Set, cast, Union, DefaultDict, Any, List +from dataclasses import dataclass +from chromadb.api.types import ( + ID, + Embeddings, + Include, + IDs, + validate_embeddings, + normalize_embeddings, +) +from chromadb.config import System +import chromadb.errors as errors +from chromadb.api import ClientAPI +from chromadb.api.models.Collection import Collection +import chromadb.test.property.strategies as strategies +from hypothesis.stateful import ( + Bundle, + RuleBasedStateMachine, + MultipleResults, + rule, + initialize, + precondition, + consumes, + run_state_machine_as_test, + multiple, + invariant, +) +from collections import defaultdict +import chromadb.test.property.invariants as invariants +from chromadb.test.conftest import ( + is_client_in_process, + NOT_CLUSTER_ONLY, + create_isolated_database, +) +import numpy as np +import uuid +from chromadb.test.utils.wait_for_version_increase import ( + wait_for_version_increase, + get_collection_version, +) + + +traces: DefaultDict[str, int] = defaultdict(lambda: 0) + + +VERSION_INCREASE_WAIT_TIME = 300 + + +def trace(key: str) -> None: + global traces + traces[key] += 1 + + +def print_traces() -> None: + global traces + for key, value in traces.items(): + print(f"{key}: {value}") + + +dtype_shared_st: st.SearchStrategy[Union[np.float16, np.float32, np.float64]] = ( + st.shared(st.sampled_from(strategies.float_types), key="dtype") +) + +dimension_shared_st: st.SearchStrategy[int] = st.shared( + st.integers(min_value=2, max_value=2048), key="dimension" +) + + +@dataclass +class EmbeddingStateMachineStates: + initialize = "initialize" + add_embeddings = "add_embeddings" + delete_by_ids = "delete_by_ids" + update_embeddings = "update_embeddings" + upsert_embeddings = "upsert_embeddings" + + +collection_st = st.shared(strategies.collections(with_hnsw_params=True), key="coll") + + +class EmbeddingStateMachineBase(RuleBasedStateMachine): + collection: Collection + embedding_ids: Bundle[ID] = Bundle("embedding_ids") + has_collection_mutated = False + + def __init__(self, client: ClientAPI, use_search: bool = False): + super().__init__() + self.client = client + self.use_search = use_search # New flag to use search API instead of query + self._rules_strategy = hypothesis.stateful.RuleStrategy(self) # type: ignore + + @initialize(collection=collection_st) # type: ignore + def initialize(self, collection: strategies.Collection): + self.collection = self.client.create_collection( + name=collection.name, + metadata=collection.metadata, # type: ignore[arg-type] + embedding_function=collection.embedding_function, + ) + self.embedding_function = collection.embedding_function + trace("init") + self.on_state_change(EmbeddingStateMachineStates.initialize) + + self.record_set_state = strategies.StateMachineRecordSet( + ids=[], metadatas=[], documents=[], embeddings=[] + ) + + @overrides + def teardown(self) -> None: + self.client.delete_collection(self.collection.name) + + @rule( + target=embedding_ids, + record_set=strategies.recordsets(collection_st), + ) + def add_embeddings(self, record_set: strategies.RecordSet) -> MultipleResults[ID]: + trace("add_embeddings") + self.on_state_change(EmbeddingStateMachineStates.add_embeddings) + + normalized_record_set: strategies.NormalizedRecordSet = invariants.wrap_all( + record_set + ) + + if len(normalized_record_set["ids"]) > 0: + trace("add_more_embeddings") + + intersection = set(normalized_record_set["ids"]).intersection( + self.record_set_state["ids"] + ) + if len(intersection) > 0: + # Partially apply the non-duplicative records to the state + new_ids = list(set(normalized_record_set["ids"]).difference(intersection)) + indices = [normalized_record_set["ids"].index(id) for id in new_ids] + filtered_record_set: strategies.NormalizedRecordSet = ( + strategies.NormalizedRecordSet( + ids=[normalized_record_set["ids"][i] for i in indices], + metadatas=[normalized_record_set["metadatas"][i] for i in indices] + if normalized_record_set["metadatas"] + else None, + documents=[normalized_record_set["documents"][i] for i in indices] + if normalized_record_set["documents"] + else None, + embeddings=[normalized_record_set["embeddings"][i] for i in indices] + if normalized_record_set["embeddings"] + else None, + ) + ) + self.collection.add(**normalized_record_set) # type: ignore[arg-type] + self._upsert_embeddings(cast(strategies.RecordSet, filtered_record_set)) + return multiple(*filtered_record_set["ids"]) + + else: + self.collection.add(**normalized_record_set) # type: ignore[arg-type] + self._upsert_embeddings(cast(strategies.RecordSet, normalized_record_set)) + return multiple(*normalized_record_set["ids"]) + + @rule(ids=st.lists(consumes(embedding_ids), min_size=1)) + def delete_by_ids(self, ids: IDs) -> None: + trace("remove embeddings") + self.on_state_change(EmbeddingStateMachineStates.delete_by_ids) + indices_to_remove = [self.record_set_state["ids"].index(id) for id in ids] + + self.collection.delete(ids=ids) + self._remove_embeddings(set(indices_to_remove)) + + # Removing the precondition causes the tests to frequently fail as "unsatisfiable" + # Using a value < 5 causes retries and lowers the number of valid samples + @precondition(lambda self: len(self.record_set_state["ids"]) >= 5) + @rule( + record_set=strategies.recordsets( + collection_strategy=collection_st, + id_strategy=embedding_ids, + min_size=1, + max_size=5, + ), + ) + def update_embeddings(self, record_set: strategies.RecordSet) -> None: + trace("update embeddings") + self.on_state_change(EmbeddingStateMachineStates.update_embeddings) + + self.collection.update(**record_set) # type: ignore[arg-type] + self._upsert_embeddings(record_set) + + # Using a value < 3 causes more retries and lowers the number of valid samples + @precondition(lambda self: len(self.record_set_state["ids"]) >= 3) + @rule( + record_set=strategies.recordsets( + collection_strategy=collection_st, + id_strategy=st.one_of(embedding_ids, strategies.safe_text), + min_size=1, + max_size=5, + ) + ) + def upsert_embeddings(self, record_set: strategies.RecordSet) -> None: + trace("upsert embeddings") + self.on_state_change(EmbeddingStateMachineStates.upsert_embeddings) + + self.collection.upsert(**record_set) # type: ignore[arg-type] + self._upsert_embeddings(record_set) + + @invariant() + def count(self) -> None: + invariants.count( + self.collection, cast(strategies.RecordSet, self.record_set_state) + ) + + @invariant() + def no_duplicates(self) -> None: + invariants.no_duplicates(self.collection) + + @invariant() + def ann_accuracy(self) -> None: + invariants.ann_accuracy( + collection=self.collection, + record_set=cast(strategies.RecordSet, self.record_set_state), + min_recall=0.95, + embedding_function=self.embedding_function, + use_search=self.use_search, # Pass the use_search flag to invariants + ) + + @invariant() + def fields_match(self) -> None: + if self._is_state_empty(): + # Check that the collection is empty + assert self.collection.count() == 0 + else: + # RecordSet is a superset of StateMachineRecordSet + record_set_state = cast(strategies.RecordSet, self.record_set_state) + + invariants.embeddings_match(self.collection, record_set_state) + invariants.metadatas_match(self.collection, record_set_state) + invariants.documents_match(self.collection, record_set_state) + + @precondition( + lambda self: is_client_in_process(self.client) + ) # (Can't check the log size on HTTP clients) + @invariant() + def log_size_below_max(self) -> None: + system: System = self.client._system # type: ignore + invariants.log_size_below_max( + system, [self.collection], self.has_collection_mutated + ) + + def _is_state_empty(self) -> bool: + for field in self.record_set_state.values(): + if field: + return False + return True + + def _upsert_embeddings(self, record_set: strategies.RecordSet) -> None: + normalized_record_set: strategies.NormalizedRecordSet = invariants.wrap_all( + record_set + ) + for idx, id in enumerate(normalized_record_set["ids"]): + # Update path + if id in self.record_set_state["ids"]: + target_idx = self.record_set_state["ids"].index(id) + if normalized_record_set["embeddings"] is not None: + self.record_set_state["embeddings"][target_idx] = ( + normalized_record_set["embeddings"][idx] + ) + else: + assert normalized_record_set["documents"] is not None + assert self.embedding_function is not None + self.record_set_state["embeddings"][target_idx] = ( + self.embedding_function( + [normalized_record_set["documents"][idx]] + )[0] + ) + if normalized_record_set["metadatas"] is not None: + # Sqlite merges the metadata, as opposed to old + # implementations which overwrites it + record_set_state = self.record_set_state["metadatas"][target_idx] + if record_set_state is not None: + record_set_state = cast( + Dict[str, Union[str, int, float]], record_set_state + ) + if normalized_record_set["metadatas"][idx] is not None: + record_set_state.update( + normalized_record_set["metadatas"][idx] # type: ignore[arg-type] + ) + else: + # None in the update metadata is a no-op + pass + else: + self.record_set_state["metadatas"][target_idx] = ( + normalized_record_set["metadatas"][idx] + ) + if normalized_record_set["documents"] is not None: + self.record_set_state["documents"][target_idx] = ( + normalized_record_set["documents"][idx] + ) + else: + # Add path + self.record_set_state["ids"].append(id) + if normalized_record_set["embeddings"] is not None: + self.record_set_state["embeddings"].append( + normalized_record_set["embeddings"][idx] + ) + else: + assert self.embedding_function is not None + assert normalized_record_set["documents"] is not None + self.record_set_state["embeddings"].append( + self.embedding_function( + [normalized_record_set["documents"][idx]] + )[0] + ) + if normalized_record_set["metadatas"] is not None: + self.record_set_state["metadatas"].append( + normalized_record_set["metadatas"][idx] + ) + else: + self.record_set_state["metadatas"].append(None) + if normalized_record_set["documents"] is not None: + self.record_set_state["documents"].append( + normalized_record_set["documents"][idx] + ) + else: + self.record_set_state["documents"].append(None) + + def _remove_embeddings(self, indices_to_remove: Set[int]) -> None: + indices_list = list(indices_to_remove) + indices_list.sort(reverse=True) + + for i in indices_list: + del self.record_set_state["ids"][i] + del self.record_set_state["embeddings"][i] + del self.record_set_state["metadatas"][i] + del self.record_set_state["documents"][i] + + def on_state_change(self, new_state: str) -> None: + if new_state != EmbeddingStateMachineStates.initialize: + self.has_collection_mutated = True + + +class EmbeddingStateMachine(EmbeddingStateMachineBase): + embedding_ids: Bundle[ID] = Bundle("embedding_ids") + + def __init__(self, client: ClientAPI, use_search: bool = False): + super().__init__(client, use_search) + + @initialize(collection=collection_st) # type: ignore + def initialize(self, collection: strategies.Collection): + super().initialize(collection) + print( + "[test_embeddings][initialize] Initialize collection id ", + self.collection._model["id"], + " hypothesis generated collection id ", + collection.id, + ) + self.log_operation_count = 0 + self.unique_ids_in_log: Set[ID] = set() + self.collection_version = self.collection.get_model()["version"] + + @precondition( + lambda self: ( + not NOT_CLUSTER_ONLY + and self.log_operation_count > 10 + and len(self.unique_ids_in_log) > 3 + ) + ) + @rule() + def wait_for_compaction(self) -> None: + current_version = get_collection_version(self.client, self.collection.name) + assert current_version >= self.collection_version # type: ignore[operator] + # This means that there was a compaction from the last time this was + # invoked. Ok to start all over again. + if current_version > self.collection_version: # type: ignore[operator] + print( + "[test_embeddings][wait_for_compaction] collection version has changed, so reset to 0" + ) + self.collection_version = current_version + # This is fine even if the log has some records right now + self.log_operation_count = 0 + self.unique_ids_in_log = set() + else: + print( + "[test_embeddings][wait_for_compaction] wait for version to increase from current version ", + current_version, + ) + new_version = wait_for_version_increase( + self.client, + self.collection.name, + current_version, + additional_time=VERSION_INCREASE_WAIT_TIME, + ) + # Everything got compacted. + self.log_operation_count = 0 + self.unique_ids_in_log = set() + self.collection_version = new_version + + @rule( + target=embedding_ids, + record_set=strategies.recordsets(collection_st), + ) + def add_embeddings(self, record_set: strategies.RecordSet) -> MultipleResults[ID]: + res = super().add_embeddings(record_set) + normalized_record_set: strategies.NormalizedRecordSet = invariants.wrap_all( + record_set + ) + print( + "[test_embeddings][add] Non Intersection ids ", + normalized_record_set["ids"], + " len ", + len(normalized_record_set["ids"]), + ) + self.log_operation_count += len(normalized_record_set["ids"]) + for id in normalized_record_set["ids"]: + if id not in self.unique_ids_in_log: + self.unique_ids_in_log.add(id) + return res # type: ignore[return-value] + + @rule(ids=st.lists(consumes(embedding_ids), min_size=1)) + def delete_by_ids(self, ids: IDs) -> None: + super().delete_by_ids(ids) + print("[test_embeddings][delete] ids ", ids, " len ", len(ids)) + self.log_operation_count += len(ids) + for id in ids: + if id in self.unique_ids_in_log: + self.unique_ids_in_log.remove(id) + + # Removing the precondition causes the tests to frequently fail as "unsatisfiable" + # Using a value < 5 causes retries and lowers the number of valid samples + @precondition(lambda self: len(self.record_set_state["ids"]) >= 5) + @rule( + record_set=strategies.recordsets( + collection_strategy=collection_st, + id_strategy=embedding_ids, + min_size=1, + max_size=5, + ), + ) + def update_embeddings(self, record_set: strategies.RecordSet) -> None: + super().update_embeddings(record_set) + print( + "[test_embeddings][update] ids ", + record_set["ids"], + " len ", + len(invariants.wrap(record_set["ids"])), + ) + self.log_operation_count += len(invariants.wrap(record_set["ids"])) + + # Using a value < 3 causes more retries and lowers the number of valid samples + @precondition(lambda self: len(self.record_set_state["ids"]) >= 3) + @rule( + record_set=strategies.recordsets( + collection_strategy=collection_st, + id_strategy=st.one_of(embedding_ids, strategies.safe_text), + min_size=1, + max_size=5, + ) + ) + def upsert_embeddings(self, record_set: strategies.RecordSet) -> None: + super().upsert_embeddings(record_set) + print( + "[test_embeddings][upsert] ids ", + record_set["ids"], + " len ", + len(invariants.wrap(record_set["ids"])), + ) + self.log_operation_count += len(invariants.wrap(record_set["ids"])) + for id in invariants.wrap(record_set["ids"]): + if id not in self.unique_ids_in_log: + self.unique_ids_in_log.add(id) + + +def test_embeddings_state(caplog: pytest.LogCaptureFixture, client: ClientAPI) -> None: + create_isolated_database(client) + caplog.set_level(logging.ERROR) + run_state_machine_as_test( + lambda: EmbeddingStateMachine(client), + settings=settings( + deadline=90000, suppress_health_check=[HealthCheck.filter_too_much] + ), + ) # type: ignore + print_traces() + + +@pytest.mark.skipif( + NOT_CLUSTER_ONLY, reason="Search API only available in distributed mode" +) +def test_embeddings_state_with_search( + caplog: pytest.LogCaptureFixture, client: ClientAPI +) -> None: + """Test embeddings state machine using search API instead of query.""" + create_isolated_database(client) + caplog.set_level(logging.ERROR) + run_state_machine_as_test( + lambda: EmbeddingStateMachine(client, use_search=True), + settings=settings( + deadline=90000, suppress_health_check=[HealthCheck.filter_too_much] + ), + ) # type: ignore + print_traces() + + +def test_add_then_delete_n_minus_1(client: ClientAPI) -> None: + create_isolated_database(client) + state = EmbeddingStateMachine(client) + state.initialize( + collection=strategies.Collection( + name="A00", + metadata={ + "hnsw:construction_ef": 128, + "hnsw:search_ef": 128, + "hnsw:M": 128, + }, + embedding_function=None, + id=uuid.uuid4(), + dimension=2, + dtype=np.float16, + known_metadata_keys={}, + known_document_keywords=[], + has_documents=False, + has_embeddings=True, + ) + ) + state.ann_accuracy() + state.count() + state.fields_match() + state.no_duplicates() + v1, v2, v3, v4, v5, v6 = state.add_embeddings( # type: ignore[misc] + record_set={ + "ids": ["0", "1", "2", "3", "4", "5"], + "embeddings": [ + [0.09765625, 0.430419921875], + [0.20556640625, 0.08978271484375], + [-0.1527099609375, 0.291748046875], + [-0.12481689453125, 0.78369140625], + [0.92724609375, -0.233154296875], + [0.92724609375, -0.233154296875], + ], + "metadatas": [None, None, None, None, None, None], + "documents": None, + } + ) + state.ann_accuracy() + state.count() + state.fields_match() + state.no_duplicates() + state.delete_by_ids(ids=[v1, v2, v3, v4, v5]) + if not NOT_CLUSTER_ONLY: + state.wait_for_compaction() + state.ann_accuracy() + state.count() + state.fields_match() + state.no_duplicates() + state.teardown() + + +def test_embeddings_flake1(client: ClientAPI) -> None: + create_isolated_database(client) + state = EmbeddingStateMachine(client) + state.initialize( + collection=strategies.Collection( + name="fOIBy", + metadata={ + "-7n": False, + "92WhVE_": "HtmY", + "J-sW": "RTip", + "wPGA8hY7uX": -171, + "4rA": "5KdoaYsUQ_EWStV4", + "hnsw:construction_ef": 128, + "hnsw:search_ef": 128, + "hnsw:M": 128, + }, + embedding_function=None, + id=uuid.UUID("ff006990-82c3-494b-97d5-cbb05092c861"), + dimension=664, + dtype=np.float16, + known_metadata_keys={}, + known_document_keywords=[], + has_documents=False, + has_embeddings=True, + ) + ) + state.ann_accuracy() + state.count() + state.fields_match() + state.no_duplicates() + ( + embedding_ids_0, + embedding_ids_1, + embedding_ids_2, + embedding_ids_3, + embedding_ids_4, + embedding_ids_5, + ) = state.add_embeddings( + record_set={ + "ids": ["kgaT4d", "C2h2YoNSgUqRyE-Tmxf3MT", "ODI-yO", "t", "b", "vC"], + "embeddings": [ + [0] * 664, + [0] * 664, + [0] * 664, + [0] * 664, + [0] * 664, + [0] * 664, + ], + "metadatas": [ + { + "s": False, + "d1wQJV-9": -2_021_928_494, + "hWf7gwQ": "5DkqA9o6", + "rbyHg": 0.0, + "Pe": 251, + "0r6qQ5XYxeq": -0.3333333432674408, + "PzXpiqB": "VT", + }, + None, + { + "hqTZ6Ok767eCSwyvGEuig8a": -659321220, + "TRGxN": -0.3333333432674408, + "1h8I": "E", + }, + {"ATRs": -0.3333333432674408, "KF0P": -23106}, + { + "PcFwu": -14169, + "PS": 0.0, + "WCgx": -13116, + "EQt": False, + "upcOfhu": -1.5, + "e": "vReD", + "U": -2147, + "zI4tO": True, + "MfHM7uU58tW_muctZf": -22, + "SvOy": 2.220446049250313e-16, + }, + { + "iuTAKznMg6IdUKxaPi": -58907, + "oy": "uDC", + "c0Zb3VTUktBu-uW": "OcywKhsi", + "6i": -42181, + "nn": 5.960464477539063e-08, + "bs": "-", + "om": -1000000.0, + "MXnpsEEE": True, + "Ful8JRj": -304752924, + "Hi7lrY": True, + }, + ], + "documents": None, + } + ) + state.ann_accuracy() + # recall: 1.0, missing 0 out of 6, accuracy threshold 1e-06 + state.count() + state.fields_match() + state.no_duplicates() + (embedding_ids_6,) = state.add_embeddings( + record_set={ + "ids": "ua", + "embeddings": [[0] * 664], + "metadatas": None, + "documents": None, + } + ) + state.ann_accuracy() + # recall: 1.0, missing 0 out of 7, accuracy threshold 1e-06 + state.count() + state.fields_match() + state.no_duplicates() + embedding_ids_7, embedding_ids_8 = state.add_embeddings( + record_set={ + "ids": ["K_", "yFsH"], + "embeddings": [[0] * 664, [0] * 664], + "metadatas": [ + None, + { + "RiaaN9MNpq": -634040344, + "g9Wx": True, + "uexOH": -2.220446049250313e-16, + "h2": True, + }, + ], + "documents": None, + } + ) + state.ann_accuracy() + # recall: 1.0, missing 0 out of 9, accuracy threshold 1e-06 + state.count() + state.fields_match() + state.no_duplicates() + state.upsert_embeddings( + record_set={ + "ids": ["SCeelWyLAWG_oHa", "lY", "3"], + "embeddings": [[0] * 664, [0] * 664, [0] * 664], + "metadatas": [ + { + "0ZbYq40P": 448094799, + "OT9sTxkM": 9.999999747378752e-06, + "-j": 158, + "rqsBEfrELJctJoVeLqtsPZp": -100, + "5M4": 64676, + "XFt": 227, + "ii": 168135.75, + "ly": True, + }, + {"Dy6": "q7LZUW"}, + { + "fP": "KuQG8m-T", + "APtmt": False, + "xKb6": -2_147_483_647, + "C": "xGw", + "G18V": False, + "s": True, + "c-": "k", + "G92n": -7024, + "YTTBWs31rbM_L_PQDSCu": False, + "xOGzFeG": True, + "gh7cuT_ruA3mn": 883101.75, + }, + ], + "documents": None, + } + ) + state.ann_accuracy() + # recall: 1.0, missing 0 out of 12, accuracy threshold 1e-06 + state.count() + state.fields_match() + state.no_duplicates() + state.upsert_embeddings( + record_set={ + "ids": [ + "O3m3-X1", + "ZNt2PF6M5_q", + "Ij0Yh6", + embedding_ids_1, + embedding_ids_7, + ], + "embeddings": [[0] * 664, [0] * 664, [0] * 664, [0] * 664, [0] * 664], + "metadatas": [ + { + "2fDAuv7": -46139, + "4Et": 19926, + "5hqGH60G-yZ6PWyM1B": False, + "OkMjjG": "34oWsr93EUl", + "yTk": 999999.0, + "wZvpmS5HbTAI": -9.999999747378752e-06, + "bvq": "Xc80e", + "zPhL": "e-QXuDdnxYMd", + }, + { + "WK": -9.999999747378752e-06, + "y": "g", + "GNZphPCKay88gsh3x_": 1.899999976158142, + }, + {"_zVO2i-N": -40, "tWHxo": False, "ltu_E_fg": "JDc", "9yGpik": -153}, + { + "otM8": "ZnQ3ALwA", + "EGeKm": 50, + "skf71O0UKT": True, + "S8Kc8-l95Rpc": True, + "4bGz1QmzbKVySN1yrXFl56CmDS08F": 1_284_815_517, + }, + None, + ], + "documents": None, + } + ) + state.ann_accuracy() + # recall: 1.0, missing 0 out of 15, accuracy threshold 1e-06 + state.count() + state.fields_match() + state.no_duplicates() + state.update_embeddings( + record_set={ + "ids": [ + embedding_ids_1, + embedding_ids_3, + embedding_ids_8, + embedding_ids_5, + embedding_ids_6, + ], + "embeddings": [[0] * 664, [0] * 664, [0] * 664, [0] * 664, [0] * 664], + "metadatas": [ + { + "hBFXAIA": False, + "Wx4dcB5": -35, + "8w": False, + "8": False, + "mwQ5": "c7", + "G9g2": "J", + "VY": True, + "VQGb_r-hzoA": -0.9999899864196777, + "M0lMig": True, + "F": True, + "J": 1.100000023841858, + "d": "R", + "DugrcoZv": False, + "45B": -2.0000100135803223, + "UG-sSV": False, + "cri4cT1G": -1_067_180_133, + "I": -4411, + "FqFWR__": False, + "4": -23, + "vwo4WERBljY3aWjWnqL": "xM0jUV4U2r", + "WF": "msuFYMwj_SXc", + }, + None, + {"m": -49054, "f4": 239658268, "Ut": False, "V_NVCw": "5"}, + {"VWuP": -9.999999747378752e-06, "7uF8": 127, "3": False}, + { + "a1": -6.103515625e-05, + "ML_Zl2Ir85KolESaX": False, + "iJvA": -1.5, + "O8o": 1_287_175_929, + "rMS": 200, + "0": -1000000.0, + "5AeE": 9.999999747378752e-06, + "2q": True, + }, + ], + "documents": None, + } + ) + state.ann_accuracy() + # recall: 1.0, missing 0 out of 15, accuracy threshold 1e-06 + state.count() + state.fields_match() + state.no_duplicates() + state.update_embeddings( + record_set={ + "ids": [embedding_ids_1, embedding_ids_2, embedding_ids_8, embedding_ids_3], + "embeddings": [[0] * 664, [0] * 664, [0] * 664, [0] * 664], + "metadatas": [ + {"Yx": "6T9tEEC84", "lGe5GMX": 3054}, + { + "UvsAljL5V5ELRv": True, + embedding_ids_3: False, + "yeLTrhAIq": 1.5, + "iP": -0.5, + }, + {"C": "Ri"}, + { + "pzHn2": -9.999999747378752e-06, + "YfdftMEd0C5ekByb7mhdb": 9735, + "LJCViu": 333447280, + "LT": True, + "5Y": False, + "OoVwE": False, + "vq": 1.899999976158142, + "8Wf6": False, + }, + ], + "documents": None, + } + ) + state.ann_accuracy() + # recall: 1.0, missing 0 out of 15, accuracy threshold 1e-06 + state.count() + state.fields_match() + state.no_duplicates() + state.update_embeddings( + record_set={ + "ids": [embedding_ids_5], + "embeddings": [[0] * 664], + "metadatas": { + "C1KbOOlKkzzLo9CGU2": -1_379_550_593, + "NH": "d", + "M": "ebEKOx", + "fpu77F70Icl": True, + "dz6fI-Gpp": True, + "qVVW": -63204, + "Qrcq645F": 296029.46875, + }, + "documents": None, + } + ) + state.ann_accuracy() + # recall: 1.0, missing 0 out of 15, accuracy threshold 1e-06 + state.count() + state.fields_match() + state.no_duplicates() + ( + embedding_ids_9, + embedding_ids_10, + embedding_ids_11, + embedding_ids_12, + ) = state.add_embeddings( + record_set={ + "ids": ["F7", "Rig1", "RXi", "_nC8-"], + "embeddings": [[0] * 664, [0] * 664, [0] * 664, [0] * 664], + "metadatas": [ + { + "FBtaPcQWV24v": -25365, + "ddLq1My3mbUL9I": 2019, + "fI": 908902.125, + "HLxuosT": False, + }, + {"ATUP1": -1.5}, + {"AhC": True, "wm9AwP": -0.9999899864196777}, + {"K": -33427}, + ], + "documents": None, + } + ) + state.ann_accuracy() + # recall: 1.0, missing 0 out of 19, accuracy threshold 1e-06 + state.count() + state.fields_match() + state.no_duplicates() + state.upsert_embeddings( + record_set={ + "ids": ["4GJ", "r", "Aunf5", embedding_ids_5], + "embeddings": [[0] * 664, [0] * 664, [0] * 664, [0] * 664], + "metadatas": [ + {"J8O0R8VGaY": True}, + { + "K2cCg": 5.960464477539063e-08, + "oObAcp": -2.0000100135803223, + "ax": "nK67g", + "afzp": 1000000.0, + "xnRCSPJUF4JZ2sKOIRDc": True, + "nBaQ6F1O38etVMhss2angu-": 158622.671875, + }, + { + "UwbDWM2_": 9.999999747378752e-06, + "3": -452142.625, + "nfoovt": 214128.375, + "elaMLbhEvW": 1.100000023841858, + "0": "iSNcMrT", + "UO": True, + "I": 176, + "3ssGS4rSKXsKqRPFTBGrRPPsu": 1000000.0, + "Gw": False, + "V": True, + }, + {"F": "tTw"}, + ], + "documents": None, + } + ) + state.ann_accuracy() + # recall: 1.0, missing 0 out of 22, accuracy threshold 1e-06 + state.count() + state.fields_match() + state.no_duplicates() + state.update_embeddings( + record_set={ + "ids": [embedding_ids_1, embedding_ids_9], + "embeddings": [[0] * 664, [0] * 664], + "metadatas": [ + { + "ei": -6.103515625e-05, + "_": "qscyRBC_", + "TP": "IXd", + "N0FG7Nta1": -745247.375, + "woD": 66, + "IV": "0L3xImGg", + "9N--JBl0uH_au_": -0.5, + "KVmhtcA": -9.999999747378752e-06, + "qr": False, + "NfL6": -0.9999899864196777, + "taIVpC": True, + "XJX": "l", + "5": 66, + "8YaEynJznB": True, + "k": -177, + "N": 671709.375, + "ebB": 53239, + "fJ": 65709.09375, + "QK8l3l4yP-": False, + "2": "cRl59jW_O", + "-XP899RRn": -999999.0, + "A9": 1.1754943508222875e-38, + "UlxNwmc": True, + "G": 128, + "1NoCd": False, + "WRn5cD": -175840.15625, + }, + { + "zAbCKkEvE4s": True, + "hnFN": "HExeVM0iM", + "Uc9": False, + "v": 1_759_514_963, + "X": False, + "W": 1.100000023841858, + }, + ], + "documents": None, + } + ) + state.ann_accuracy() + # recall: 1.0, missing 0 out of 22, accuracy threshold 1e-06 + state.count() + state.fields_match() + state.no_duplicates() + state.update_embeddings( + record_set={ + "ids": [embedding_ids_2], + "embeddings": [[0] * 664], + "metadatas": None, + "documents": None, + } + ) + state.ann_accuracy() + # recall: 1.0, missing 0 out of 22, accuracy threshold 1e-06 + state.count() + state.fields_match() + state.no_duplicates() + state.update_embeddings( + record_set={ + "ids": [ + embedding_ids_10, + embedding_ids_2, + embedding_ids_4, + embedding_ids_12, + embedding_ids_3, + ], + "embeddings": [[0] * 664, [0] * 664, [0] * 664, [0] * 664, [0] * 664], + "metadatas": [ + {"Y": "-iRt8"}, + {"55m28": "8MxYq", "krQsTFdqMhYjhF": False}, + None, + { + "9SnviLf": -6.103515625e-05, + "Y0Jw4pLTwr": -184, + "v3E": 6.103515625e-05, + "Fx3jsbcdqy": "VG7E7xm", + "H": 9071, + "-U": "1xXUHLklmIVSVgQd7EHUCu5wa", + "S": "kl6", + }, + { + "U": -12, + "Qfm_6duL": False, + "Sh0LkduZt5qsRJrF": "sB", + "8DM": -64114, + "MZ": "xtLNrNyRo2", + "lY": -922831.5, + "7": False, + }, + ], + "documents": None, + } + ) + state.ann_accuracy() + # recall: 1.0, missing 0 out of 22, accuracy threshold 1e-06 + state.count() + state.fields_match() + state.no_duplicates() + state.upsert_embeddings( + record_set={ + "ids": [embedding_ids_0, embedding_ids_7, "Oia", "iD", embedding_ids_5], + "embeddings": [[0] * 664, [0] * 664, [0] * 664, [0] * 664, [0] * 664], + "metadatas": [ + None, + { + "tVs": True, + "B": "4eK", + "zTR": True, + "bq6VslBBo2_12hgyKNPddxify34-np-": -22311, + "F7FcZpODwCTHg91o4mKTjBL": False, + "1Zjfys": -13897, + "lg3": -866314519, + }, + { + "1qr": "_TG-YhAQ", + "TKV": "Q", + "8tLu": 1000000.0, + "QHsxa": 1.100000023841858, + "F": True, + }, + { + "p": True, + "rR": "UepiV6K_", + "UDZ_uR": -1.5, + "fFG6cZvICaGc": True, + "unTbxz0qd2-AV1": -332950.25, + }, + { + "EXXVBZU": 2_147_483_647, + "tJMO": "C9OePg", + "4o": False, + "F8g8n": -999999.0, + "5": "aBY", + "hv3i": -48091, + }, + ], + "documents": None, + } + ) + state.ann_accuracy() + # recall: 1.0, missing 0 out of 24, accuracy threshold 1e-06 + state.count() + state.fields_match() + state.no_duplicates() + state.teardown() + + +def test_update_none(caplog: pytest.LogCaptureFixture, client: ClientAPI) -> None: + create_isolated_database(client) + state = EmbeddingStateMachine(client) + state.initialize( + collection=strategies.Collection( + name="A00", + metadata={ + "hnsw:construction_ef": 128, + "hnsw:search_ef": 128, + "hnsw:M": 128, + }, + embedding_function=None, + id=uuid.UUID("2fb0c945-b877-42ab-9417-bfe0f6b172af"), + dimension=2, + dtype=np.float16, + known_metadata_keys={}, + known_document_keywords=[], + has_documents=False, + has_embeddings=True, + ) + ) + state.ann_accuracy() + state.count() + state.fields_match() + state.no_duplicates() + v1, v2, v3, v4, v5 = state.add_embeddings( # type: ignore[misc] + record_set={ + "ids": ["0", "1", "2", "3", "4"], + "embeddings": [ + [0.09765625, 0.430419921875], + [0.20556640625, 0.08978271484375], + [-0.1527099609375, 0.291748046875], + [-0.12481689453125, 0.78369140625], + [0.92724609375, -0.233154296875], + ], + "metadatas": [None, None, None, None, None], + "documents": None, + } + ) + state.ann_accuracy() + state.count() + state.fields_match() + state.no_duplicates() + state.update_embeddings( + record_set={ + "ids": [v5], + "embeddings": [[0.58349609375, 0.05780029296875]], + "metadatas": [{v1: v1}], + "documents": None, + } + ) + state.ann_accuracy() + state.teardown() + + +def test_add_delete_add(client: ClientAPI) -> None: + create_isolated_database(client) + state = EmbeddingStateMachine(client) + state.initialize( + collection=strategies.Collection( + name="KR3cf", + metadata={ + "Ufmxsi3": 999999.0, + "bMMvvrqM4MKmp5CJB8A": 62921, + "-": True, + "37PNi": "Vkn", + "5KZfkpod3ND5soL_": True, + "KA4zcZL9lRN9": 142, + "Oc8G7ysXmE8lp4Hos_": "POQe8Unz1uJ", + "BI930U": 31, + "te": False, + "tyM": -0.5, + "R0ZiZ": True, + "m": True, + "IOw": -25725, + "hnsw:construction_ef": 128, + "hnsw:search_ef": 128, + "hnsw:M": 128, + }, + embedding_function=None, + id=uuid.UUID("284b6e99-b19e-49b2-96a4-a2a93a95447d"), + dimension=3, + dtype=np.float32, + known_metadata_keys={}, + known_document_keywords=[], + has_documents=False, + has_embeddings=True, + ) + ) + state.ann_accuracy() + state.count() + state.fields_match() + state.no_duplicates() + embeddings = state.add_embeddings( + record_set={ + "ids": ["255", "l", "3-", "i", "Nk", "9yPvT"], + "embeddings": [ + [1.2, 2.3, 1.5], + [4.5, 6.0, 2], + [1, 2, 3], + [4, 5, 6], + [8.9, 9.0, 7], + [4.5, 6.0, 5.6], + ], + "metadatas": None, + "documents": None, + } + ) + i = 0 + emb_list = {} + for embedding in embeddings: + emb_list[i] = embedding + i += 1 + state.ann_accuracy() + state.count() + state.fields_match() + state.no_duplicates() + state.upsert_embeddings( + record_set={ + "ids": [ + emb_list[0], + emb_list[4], + "KWcDaHUVD6MxEiJ", + emb_list[5], + "PdlP1d6w", + ], + "embeddings": [[1, 23, 4], [3, 5, 9], [9, 3, 5], [3, 9, 8], [1, 5, 4]], + "documents": None, + "metadatas": None, + } + ) + state.ann_accuracy() + state.count() + state.fields_match() + state.no_duplicates() + if not NOT_CLUSTER_ONLY: + state.wait_for_compaction() + state.ann_accuracy() + state.count() + state.fields_match() + state.no_duplicates() + state.upsert_embeddings( + record_set={ + "ids": ["TpjiboLSuYWBJDbRW1zeNmC", emb_list[0], emb_list[4]], + "embeddings": [[4, 6, 7], [7, 9, 3], [1, 3, 6]], + "metadatas": None, + "documents": None, + } + ) + state.ann_accuracy() + state.count() + state.fields_match() + state.no_duplicates() + state.delete_by_ids( + ids=[emb_list[2], emb_list[1], emb_list[5], emb_list[4], emb_list[3]] + ) + state.ann_accuracy() + state.count() + state.fields_match() + state.no_duplicates() + embeddings = state.add_embeddings( + record_set={ + "ids": ["o", "D3V84", "Rt", "TDwlc9C8_evn", emb_list[1]], + "embeddings": [ + [9, 5.4, 3.22], + [1.33, 3.44, 5.66], + [9.90, 9.8, 1.3], + [9.7, 5.6, 4.5], + [3.4, 5.6, 9.65], + ], + "documents": None, + "metadatas": None, + } + ) + i = 6 + for embedding in embeddings: + emb_list[i] = embedding + i += 1 + state.ann_accuracy() + state.count() + state.fields_match() + if not NOT_CLUSTER_ONLY: + state.wait_for_compaction() + + +def test_multi_add(client: ClientAPI) -> None: + create_isolated_database(client) + coll = client.create_collection(name="foo") + coll.add(ids=["a"], embeddings=[[0.0]]) # type: ignore[arg-type] + assert coll.count() == 1 + + # after the sqlite refactor - add silently ignores duplicates, no exception is raised + # partial adds are supported - i.e we will add whatever we can in the request + coll.add(ids=["a"], embeddings=[[0.0]]) # type: ignore[arg-type] + + assert coll.count() == 1 + + results = coll.get() + assert results["ids"] == ["a"] + + coll.delete(ids=["a"]) + assert coll.count() == 0 + + +def test_dup_add(client: ClientAPI) -> None: + create_isolated_database(client) + coll = client.create_collection(name="foo") + with pytest.raises(errors.DuplicateIDError): + coll.add(ids=["a", "a"], embeddings=[[0.0], [1.1]]) # type: ignore[arg-type] + with pytest.raises(errors.DuplicateIDError): + coll.upsert(ids=["a", "a"], embeddings=[[0.0], [1.1]]) # type: ignore[arg-type] + + +def test_query_without_add(client: ClientAPI) -> None: + create_isolated_database(client) + coll = client.create_collection(name="foo") + fields: Include = ["documents", "metadatas", "embeddings", "distances"] # type: ignore[list-item] + N = np.random.randint(1, 2000) + K = np.random.randint(1, 100) + query_embeddings = np.random.random((N, K)).tolist() + results = coll.query( + query_embeddings=cast(Embeddings, query_embeddings), include=fields + ) + for field in fields: + field_results = results[field] # type: ignore[literal-required] + assert field_results is not None + assert all([len(result) == 0 for result in field_results]) + + +def test_get_non_existent(client: ClientAPI) -> None: + create_isolated_database(client) + coll = client.create_collection(name="foo") + result = coll.get(ids=["a"], include=["documents", "metadatas", "embeddings"]) # type: ignore[list-item] + assert len(result["ids"]) == 0 + assert len(result["metadatas"]) == 0 # type: ignore[arg-type] + assert len(result["documents"]) == 0 # type: ignore[arg-type] + assert len(result["embeddings"]) == 0 # type: ignore[arg-type] + + +# TODO: Use SQL escaping correctly internally +@pytest.mark.xfail(reason="We don't properly escape SQL internally, causing problems") +def test_escape_chars_in_ids(client: ClientAPI) -> None: + create_isolated_database(client) + id = "\x1f" + coll = client.create_collection(name="foo") + coll.add(ids=[id], embeddings=[[0.0]]) # type: ignore[arg-type] + assert coll.count() == 1 + coll.delete(ids=[id]) + assert coll.count() == 0 + + +def test_delete_empty_fails(client: ClientAPI) -> None: + create_isolated_database(client) + coll = client.create_collection(name="foo") + with pytest.raises(ValueError): + coll.delete() + + +@pytest.mark.parametrize( + "kwargs", + [ + {"ids": ["foo"]}, + {"where": {"foo": "bar"}}, + {"where_document": {"$contains": "bar"}}, + {"ids": ["foo"], "where": {"foo": "bar"}}, + {"ids": ["foo"], "where_document": {"$contains": "bar"}}, + { + "ids": ["foo"], + "where": {"foo": "bar"}, + "where_document": {"$contains": "bar"}, + }, + ], +) +def test_delete_success(client: ClientAPI, kwargs: Any) -> None: + create_isolated_database(client) + coll = client.create_collection(name="foo") + # Should not raise + result = coll.delete(**kwargs) + assert isinstance(result, dict) + assert "deleted" in result + assert result["deleted"] >= 0 + + +@given(supported_types=st.sampled_from([np.float32, np.int32, np.int64, int, float])) +def test_autocasting_validate_embeddings_for_compatible_types( + supported_types: List[Any], +) -> None: + embds = strategies.create_embeddings(10, 10, supported_types) + validated_embeddings = validate_embeddings( + cast( + Embeddings, + normalize_embeddings(embds), + ) + ) + assert all( + [ + isinstance(value, np.ndarray) + and ( + value.dtype == np.float32 + or value.dtype == np.float64 + or value.dtype == np.int32 + or value.dtype == np.int64 + ) + for value in validated_embeddings + ] + ) + + +@given(supported_types=st.sampled_from([np.float32, np.int32, np.int64, int, float])) +def test_autocasting_validate_embeddings_with_ndarray( + supported_types: List[Any], +) -> None: + embds = strategies.create_embeddings_ndarray(10, 10, supported_types) + validated_embeddings = validate_embeddings( + cast(Embeddings, normalize_embeddings(embds)) + ) + assert all( + [ + isinstance(value, np.ndarray) + and ( + value.dtype == np.float32 + or value.dtype == np.float64 + or value.dtype == np.int32 + or value.dtype == np.int64 + ) + for value in validated_embeddings + ] + ) + + +@given(unsupported_types=st.sampled_from([str, bool])) +def test_autocasting_validate_embeddings_incompatible_types( + unsupported_types: List[Any], +) -> None: + embds = strategies.create_embeddings(10, 10, unsupported_types) + with pytest.raises(ValueError) as e: + validate_embeddings(cast(Embeddings, normalize_embeddings(embds))) + + assert ( + "Expected embeddings to be a list of floats or ints, a list of lists, a numpy array, or a list of numpy arrays, got " + in str(e.value) + ) + + +def test_0dim_embedding_validation() -> None: + embds: Embeddings = [np.array([])] + with pytest.raises(ValueError) as e: + validate_embeddings(embds) + assert ( + "Expected each embedding in the embeddings to be a 1-dimensional numpy array with at least 1 int/float value. Got a 1-dimensional numpy array with no values at pos" + in str(e) + ) + + +def test_no_op_compaction(client: ClientAPI) -> None: + create_isolated_database(client) + coll = client.create_collection(name="noop") + initial_version = get_collection_version(client, coll.name) + for batch in range(0, 5000, 100): + coll.delete(ids=[str(i) for i in range(batch, batch + 100)]) + if not NOT_CLUSTER_ONLY: + wait_for_version_increase( + client, coll.name, initial_version, VERSION_INCREASE_WAIT_TIME + ) + + +def test_add_then_purge(client: ClientAPI) -> None: + create_isolated_database(client) + record_count = 5000 + batch_count = 100 + coll = client.create_collection(name="add_then_purge") + witness_version = get_collection_version(client, coll.name) + + # Add records and wait for compaction + for batch in range(0, record_count, batch_count): + record_id_vals = [i for i in range(batch, batch + batch_count)] + record_ids = [str(i) for i in record_id_vals] + coll.add( + ids=record_ids, embeddings=[[2 * i, 2 * i + 1] for i in record_id_vals] + ) + if not NOT_CLUSTER_ONLY: + wait_for_version_increase( + client, coll.name, witness_version, VERSION_INCREASE_WAIT_TIME + ) + + # Purge records and wait for compaction + witness_version = get_collection_version(client, coll.name) + for batch in range(0, record_count, batch_count): + record_id_vals = [i for i in range(batch, batch + batch_count)] + record_ids = [str(i) for i in record_id_vals] + coll.delete(ids=record_ids) + if not NOT_CLUSTER_ONLY: + wait_for_version_increase( + client, coll.name, witness_version, VERSION_INCREASE_WAIT_TIME + ) + + # There should be no records left + assert len(coll.get()["ids"]) == 0 + + +def test_encompassing_delete(client: ClientAPI) -> None: + create_isolated_database(client) + col = client.create_collection("encompassing_delete") + initial_version = get_collection_version(client, col.name) + + id_start = 0 + # Add and then Delete 6 records + ids = [str(i) for i in range(id_start, id_start + 6)] + embeddings = [[i * 1.0, i * 1.0] for i in range(id_start, id_start + 6)] + id_start = id_start + 6 + + col.add(ids=ids, embeddings=embeddings) # type: ignore[arg-type] + col.delete(ids=ids) + + if not NOT_CLUSTER_ONLY: + wait_for_version_increase( + client, col.name, initial_version, VERSION_INCREASE_WAIT_TIME + ) + initial_version = get_collection_version(client, col.name) + + # Add and then delete and then add 16 + len_to_add = 16 + ids = [str(i) for i in range(id_start, id_start + len_to_add)] + embeddings = [[i * 1.0, i * 1.0] for i in range(id_start, id_start + len_to_add)] + + col.add(ids=ids, embeddings=embeddings) # type: ignore[arg-type] + col.delete(ids=ids) + col.add(ids=ids, embeddings=embeddings) # type: ignore[arg-type] + + if not NOT_CLUSTER_ONLY: + wait_for_version_increase( + client, col.name, initial_version, VERSION_INCREASE_WAIT_TIME + ) + + # Ensure we can get all + get_results = col.get() + assert len(get_results["ids"]) == len_to_add + for id in ids: + assert id in get_results["ids"] diff --git a/python/user_packages/Python313/site-packages/chromadb/test/property/test_filtering.py b/python/user_packages/Python313/site-packages/chromadb/test/property/test_filtering.py new file mode 100644 index 0000000000000000000000000000000000000000..2f62d28356cef12beae50ebc0cf0bd5093c0754d --- /dev/null +++ b/python/user_packages/Python313/site-packages/chromadb/test/property/test_filtering.py @@ -0,0 +1,839 @@ +from typing import Any, Dict, List, Optional, cast +import uuid +from hypothesis import example, given, settings, HealthCheck +import pytest +from typing import cast +from chromadb.api import ClientAPI +from chromadb.test.property import invariants +from chromadb.api.types import ( + Document, + Documents, + Embedding, + Embeddings, + GetResult, + IDs, + Metadata, + Metadatas, + Where, + WhereDocument, +) +from chromadb.test.conftest import reset, NOT_CLUSTER_ONLY +import chromadb.test.property.strategies as strategies +import hypothesis.strategies as st +from chromadb.execution.expression.plan import Search +from chromadb.execution.expression.operator import Knn, In, Key, Eq, And, Or, Contains, NotContains +import logging +from chromadb.test.utils.wait_for_version_increase import wait_for_version_increase +import numpy as np +from chromadb.api.models.Collection import Collection +from chromadb.execution.expression.operator import Where as WhereExpr + + +def _filter_where_clause(clause: Where, metadata: Optional[Metadata]) -> bool: + """Return true if the where clause is true for the given metadata map""" + metadata = metadata or dict() + key, expr = list(clause.items())[0] + + # Handle the shorthand for equal: {key: val} where val is a simple value + if ( + isinstance(expr, str) + or isinstance(expr, bool) + or isinstance(expr, int) + or isinstance(expr, float) + ): + return _filter_where_clause({key: {"$eq": expr}}, metadata) # type: ignore[dict-item] + + # expr is a list of clauses + if key == "$and": + assert isinstance(expr, list) + return all(_filter_where_clause(clause, metadata) for clause in expr) + + if key == "$or": + assert isinstance(expr, list) + return any(_filter_where_clause(clause, metadata) for clause in expr) + + # expr is an operator expression + assert isinstance(expr, dict) + op, val = list(expr.items())[0] + assert isinstance(metadata, dict) + if op == "$eq": + return key in metadata and metadata[key] == val + elif op == "$ne": + return key not in metadata or metadata[key] != val + elif op == "$in": + return key in metadata and metadata[key] in val # type: ignore[operator] + elif op == "$nin": + return key not in metadata or metadata[key] not in val # type: ignore[operator] + + # The following conditions only make sense for numeric values + assert ( + key not in metadata + or isinstance(metadata[key], int) + or isinstance(metadata[key], float) + ) + assert isinstance(val, int) or isinstance(val, float) + if op == "$gt": + return key in metadata and metadata[key] > val + elif op == "$gte": + return key in metadata and metadata[key] >= val + elif op == "$lt": + return key in metadata and metadata[key] < val + elif op == "$lte": + return key in metadata and metadata[key] <= val + else: + raise ValueError("Unknown operator: {}".format(key)) + + +def _filter_where_doc_clause(clause: WhereDocument, doc: Document) -> bool: + key, expr = list(clause.items())[0] + + if key == "$and": + assert isinstance(expr, list) + return all(_filter_where_doc_clause(clause, doc) for clause in expr) + if key == "$or": + assert isinstance(expr, list) + return any(_filter_where_doc_clause(clause, doc) for clause in expr) + + # Simple $contains clause + assert isinstance(expr, str) + if key == "$contains": + if not doc: + return False + return expr in doc + elif key == "$not_contains": + if not doc: + return True + return expr not in doc + else: + raise ValueError("Unknown operator: {}".format(key)) + + +EMPTY_DICT: Dict[Any, Any] = {} +EMPTY_STRING: str = "" + + +def _filter_embedding_set( + record_set: strategies.RecordSet, filter: strategies.Filter +) -> IDs: + """Return IDs from the embedding set that match the given filter object + If none match, return an empty list + """ + + normalized_record_set = invariants.wrap_all(record_set) + ids = set(normalized_record_set["ids"]) + + filter_ids = filter["ids"] + + if filter_ids is not None: + filter_ids = invariants.wrap(filter_ids) + assert filter_ids is not None + # If the filter ids is an empty list then we treat that as get all + if len(filter_ids) != 0: + ids = ids.intersection(filter_ids) + + for i in range(len(normalized_record_set["ids"])): + if filter["where"]: + metadatas: Metadatas + if isinstance(normalized_record_set["metadatas"], list): + metadatas = normalized_record_set["metadatas"] # type: ignore[assignment] + else: + metadatas = [EMPTY_DICT] * len(normalized_record_set["ids"]) + filter_where: Where = filter["where"] + if not _filter_where_clause(filter_where, metadatas[i]): + ids.discard(normalized_record_set["ids"][i]) + + if filter["where_document"]: + documents = normalized_record_set["documents"] or [EMPTY_STRING] * len( + normalized_record_set["ids"] + ) + if not _filter_where_doc_clause(filter["where_document"], documents[i]): + ids.discard(normalized_record_set["ids"][i]) + + return list(ids) + + +class LegacyWhereWrapper(WhereExpr): + """ + Wraps old-style where/where_document dicts for testing. + Converts where_document to use #document field and combines with where using $and. + """ + def __init__(self, where: Optional[Where] = None, where_document: Optional[WhereDocument] = None): + self.where = where + self.where_document = where_document + + def _convert_where_document(self, where_doc: WhereDocument) -> Dict[str, Any]: + """Convert where_document filters to use #document field.""" + if not where_doc: + return {} + + # Handle logical operators recursively + if "$and" in where_doc: + and_clauses = where_doc["$and"] + if isinstance(and_clauses, list): + return {"$and": [self._convert_where_document(clause) for clause in and_clauses]} + elif "$or" in where_doc: + or_clauses = where_doc["$or"] + if isinstance(or_clauses, list): + return {"$or": [self._convert_where_document(clause) for clause in or_clauses]} + + # Handle document operators - convert to #document field + if "$contains" in where_doc: + return {"#document": {"$contains": where_doc["$contains"]}} + elif "$not_contains" in where_doc: + return {"#document": {"$not_contains": where_doc["$not_contains"]}} + + if "$regex" in where_doc: + return {"#document": {"$regex": where_doc["$regex"]}} + elif "$not_regex" in where_doc: + return {"#document": {"$not_regex": where_doc["$not_regex"]}} + + # Cast to dict for return + return cast(Dict[str, Any], where_doc) + + def to_dict(self) -> Dict[str, Any]: + # Combine where and where_document into a single where clause + combined_where = None + + # Build list of conditions to AND together + conditions = [] + + if self.where: + conditions.append(self.where) + + if self.where_document: + # Convert where_document to use #document field + converted_doc_filter = self._convert_where_document(self.where_document) + if converted_doc_filter: + conditions.append(converted_doc_filter) + + # Combine conditions with $and if needed + if len(conditions) == 1: + combined_where = conditions[0] + elif len(conditions) > 1: + combined_where = {"$and": conditions} + + # Return the combined where clause directly + if combined_where: + return combined_where + return {} + + +def _search_with_filter( + collection: Collection, + filter: strategies.Filter, + query_embedding: Optional[Embedding] = None, + n_results: int = 10 +) -> List[str]: + """Use the search API to retrieve results with filters - test helper function.""" + # Build Search object + search = Search() + + # Add KNN if embedding provided + if query_embedding is not None: + search = search.rank(Knn(query=query_embedding)) # type: ignore[arg-type] + + # Add filters using the LegacyWhereWrapper + if filter.get("where") or filter.get("where_document") or filter.get("ids"): + # Convert ids to list if it's a string + ids_val = filter.get("ids") + if isinstance(ids_val, str): + ids_val = [ids_val] + + # Build the where clause + where_expr = None + + # Add legacy where/where_document if present + if filter.get("where") or filter.get("where_document"): + wrapper = LegacyWhereWrapper( + where=filter.get("where"), + where_document=filter.get("where_document"), + ) + if wrapper.to_dict(): # Only use if it has content + where_expr = wrapper + + # Add ID filter if present + if ids_val: + id_expr = Key.ID.is_in(ids_val) + if where_expr: + where_expr = where_expr & id_expr # type: ignore[assignment] + else: + where_expr = id_expr + + # Apply the where clause if we have one + if where_expr: + search = search.where(where_expr) + + # Set limit and select only IDs + search = search.limit(n_results).select("id") + + # Execute search and return IDs + result = collection.search(search) + return result["ids"][0] if result["ids"] else [] + + +collection_st = st.shared( + strategies.collections(add_filterable_data=True, with_hnsw_params=True), + key="coll", +) +recordset_st = st.shared( + strategies.recordsets(collection_st, max_size=1000), key="recordset" +) + + +@settings( + deadline=90000, + suppress_health_check=[ + HealthCheck.function_scoped_fixture, + HealthCheck.large_base_example, + HealthCheck.filter_too_much, + ], +) # type: ignore +@given( + collection=collection_st, + record_set=recordset_st, + filters=st.lists(strategies.filters(collection_st, recordset_st), min_size=1), + should_compact=st.booleans(), +) +def test_filterable_metadata_get( + caplog, + client: ClientAPI, + collection: strategies.Collection, + record_set, + filters, + should_compact: bool, +) -> None: + caplog.set_level(logging.ERROR) + + reset(client) + coll = client.create_collection( + name=collection.name, + metadata=collection.metadata, # type: ignore + embedding_function=collection.embedding_function, + ) + + initial_version = coll.get_model()["version"] + + coll.add(**record_set) + + if not NOT_CLUSTER_ONLY: + # Only wait for compaction if the size of the collection is + # some minimal size + if should_compact and len(invariants.wrap(record_set["ids"])) > 10: + # Wait for the model to be updated + wait_for_version_increase(client, collection.name, initial_version) # type: ignore + + for filter in filters: + result_ids = coll.get(**filter)["ids"] + expected_ids = _filter_embedding_set(record_set, filter) + assert sorted(result_ids) == sorted(expected_ids) + + +@pytest.mark.skipif( + NOT_CLUSTER_ONLY, + reason="Search API only available in distributed mode" +) +@settings( + deadline=90000, + suppress_health_check=[ + HealthCheck.function_scoped_fixture, + HealthCheck.large_base_example, + HealthCheck.filter_too_much, + ], +) # type: ignore +@given( + collection=collection_st, + record_set=recordset_st, + filters=st.lists(strategies.filters(collection_st, recordset_st), min_size=1), + should_compact=st.booleans(), +) +def test_filterable_metadata_search( + caplog, + client: ClientAPI, + collection: strategies.Collection, + record_set, + filters, + should_compact: bool, +) -> None: + """Test metadata filtering using search API endpoint.""" + caplog.set_level(logging.ERROR) + + reset(client) + coll = client.create_collection( + name=collection.name, + metadata=collection.metadata, # type: ignore + embedding_function=collection.embedding_function, + ) + + initial_version = coll.get_model()["version"] + coll.add(**record_set) + + if should_compact and len(invariants.wrap(record_set["ids"])) > 10: + wait_for_version_increase(client, collection.name, initial_version) # type: ignore + + for filter in filters: + # Use search API instead of get + result_ids = _search_with_filter(coll, filter, n_results=1000) + expected_ids = _filter_embedding_set(record_set, filter) + assert sorted(result_ids) == sorted(expected_ids) + + +@settings( + deadline=90000, + suppress_health_check=[ + HealthCheck.function_scoped_fixture, + HealthCheck.large_base_example, + HealthCheck.filter_too_much, + ], +) # type: ignore +@given( + collection=collection_st, + record_set=recordset_st, + filters=st.lists(strategies.filters(collection_st, recordset_st), min_size=1), + limit=st.integers(min_value=1, max_value=10), + offset=st.integers(min_value=0, max_value=10), + should_compact=st.booleans(), +) +# Repro of a former off-by-one error in distributed Chroma. Fixed in https://github.com/chroma-core/chroma/pull/3489. +@example( + collection=strategies.Collection( + name="test", + metadata={"test": "test"}, + embedding_function=None, + id=uuid.uuid4(), + dimension=2, + dtype="float32", + known_metadata_keys={}, + known_document_keywords=[], + ), + record_set=strategies.RecordSet( + ids=[str(i) for i in range(11)], + embeddings=[np.random.rand(2).tolist() for _ in range(11)], + metadatas=[{"test": "test"} for _ in range(11)], + documents=None, + ), + filters=[ + strategies.Filter( + { + "where_document": {"$not_contains": "foo"}, + "ids": None, + "where": None, + } + ) + ], + limit=10, + offset=10, + should_compact=True, +) +def test_filterable_metadata_get_limit_offset( + caplog, + client: ClientAPI, + collection: strategies.Collection, + record_set, + filters, + limit, + offset, + should_compact: bool, +) -> None: + caplog.set_level(logging.ERROR) + + reset(client) + coll = client.create_collection( + name=collection.name, + metadata=collection.metadata, # type: ignore + embedding_function=collection.embedding_function, + ) + + initial_version = coll.get_model()["version"] + + coll.add(**record_set) + + if not NOT_CLUSTER_ONLY: + # Only wait for compaction if the size of the collection is + # some minimal size + if should_compact and len(invariants.wrap(record_set["ids"])) > 10: + # Wait for the model to be updated + wait_for_version_increase(client, collection.name, initial_version) # type: ignore + + for filter in filters: + # add limit and offset to filter + filter["limit"] = limit + filter["offset"] = offset + result_ids = coll.get(**filter)["ids"] + expected_ids = _filter_embedding_set(record_set, filter) + if len(expected_ids) > 0: + collection_ids = coll.get(ids=expected_ids)["ids"] + offset_id_order = {id: index for index, id in enumerate(collection_ids)} + assert ( + result_ids + == sorted(expected_ids, key=lambda id: offset_id_order[id])[ + offset : offset + limit + ] + ) + + +@settings( + deadline=90000, + suppress_health_check=[ + HealthCheck.function_scoped_fixture, + HealthCheck.large_base_example, + HealthCheck.filter_too_much, + ], +) +@given( + collection=collection_st, + record_set=recordset_st, + filters=st.lists( + strategies.filters(collection_st, recordset_st, include_all_ids=True), + min_size=1, + ), + should_compact=st.booleans(), + data=st.data(), +) +def test_filterable_metadata_query( + caplog: pytest.LogCaptureFixture, + client: ClientAPI, + collection: strategies.Collection, + record_set: strategies.RecordSet, + filters: List[strategies.Filter], + should_compact: bool, + data: st.DataObject, +) -> None: + caplog.set_level(logging.ERROR) + + reset(client) + coll = client.create_collection( + name=collection.name, + metadata=collection.metadata, # type: ignore + embedding_function=collection.embedding_function, + ) + initial_version = coll.get_model()["version"] + normalized_record_set = invariants.wrap_all(record_set) + + coll.add(**record_set) # type: ignore[arg-type] + + if not NOT_CLUSTER_ONLY: + # Only wait for compaction if the size of the collection is + # some minimal size + if should_compact and len(invariants.wrap(record_set["ids"])) > 10: + # Wait for the model to be updated + wait_for_version_increase(client, collection.name, initial_version) # type: ignore + + total_count = len(normalized_record_set["ids"]) + # Pick a random vector using Hypothesis data + random_query: Embedding + + query_index = data.draw(st.integers(min_value=0, max_value=total_count - 1)) + if collection.has_embeddings: + assert normalized_record_set["embeddings"] is not None + assert all(isinstance(e, list) for e in normalized_record_set["embeddings"]) + # Use data.draw to select index + random_query = normalized_record_set["embeddings"][query_index] + else: + assert isinstance(normalized_record_set["documents"], list) + assert collection.embedding_function is not None + # Use data.draw to select index + random_query = collection.embedding_function( + [normalized_record_set["documents"][query_index]] + )[0] + for filter in filters: + result_ids = set( + coll.query( + query_embeddings=random_query, + n_results=total_count, + where=filter["where"], + where_document=filter["where_document"], + )["ids"][0] + ) + expected_ids = set( + _filter_embedding_set( + cast(strategies.RecordSet, normalized_record_set), filter + ) + ) + assert len(result_ids.intersection(expected_ids)) == len(result_ids) + + +@pytest.mark.skipif( + NOT_CLUSTER_ONLY, + reason="Search API only available in distributed mode" +) +@settings( + deadline=90000, + suppress_health_check=[ + HealthCheck.function_scoped_fixture, + HealthCheck.large_base_example, + HealthCheck.filter_too_much, + ], +) +@given( + collection=collection_st, + record_set=recordset_st, + filters=st.lists( + strategies.filters(collection_st, recordset_st, include_all_ids=True), + min_size=1, + ), + should_compact=st.booleans(), + data=st.data(), +) +def test_filterable_metadata_query_via_search( + caplog: pytest.LogCaptureFixture, + client: ClientAPI, + collection: strategies.Collection, + record_set: strategies.RecordSet, + filters: List[strategies.Filter], + should_compact: bool, + data: st.DataObject, +) -> None: + """Test query-like filtering using search API endpoint.""" + caplog.set_level(logging.ERROR) + + reset(client) + coll = client.create_collection( + name=collection.name, + metadata=collection.metadata, # type: ignore + embedding_function=collection.embedding_function, + ) + + initial_version = coll.get_model()["version"] + normalized_record_set = invariants.wrap_all(record_set) + coll.add(**record_set) # type: ignore[arg-type] + + if should_compact and len(invariants.wrap(record_set["ids"])) > 10: + wait_for_version_increase(client, collection.name, initial_version) # type: ignore + + total_count = len(normalized_record_set["ids"]) + + # Pick a random query embedding + query_index = data.draw(st.integers(min_value=0, max_value=total_count - 1)) + if collection.has_embeddings: + assert normalized_record_set["embeddings"] is not None + random_query = normalized_record_set["embeddings"][query_index] + else: + assert isinstance(normalized_record_set["documents"], list) + assert collection.embedding_function is not None + random_query = collection.embedding_function( + [normalized_record_set["documents"][query_index]] + )[0] + + for filter in filters: + # Use search API with query embedding + result_ids = set(_search_with_filter( + coll, + filter, + query_embedding=random_query, + n_results=total_count + )) + expected_ids = set( + _filter_embedding_set( + cast(strategies.RecordSet, normalized_record_set), filter + ) + ) + assert len(result_ids.intersection(expected_ids)) == len(result_ids) + + +def test_empty_filter(client: ClientAPI) -> None: + """Test that a filter where no document matches returns an empty result""" + reset(client) + coll = client.create_collection(name="test") + + test_ids: IDs = ["1", "2", "3"] + test_embeddings: Embeddings = [np.array([1, 1]), np.array([2, 2]), np.array([3, 3])] + test_query_embedding: Embedding = np.array([1, 2]) + test_query_embeddings: Embeddings = [test_query_embedding, test_query_embedding] + + coll.add(ids=test_ids, embeddings=test_embeddings) + + res = coll.query( + query_embeddings=test_query_embedding, + where={"q": {"$eq": 4}}, # type: ignore[dict-item] + n_results=3, + include=["embeddings", "distances", "metadatas"], + ) + assert res["ids"] == [[]] + if res["embeddings"] is not None: + assert cast(np.ndarray, res["embeddings"][0]).size == 0 # type: ignore + assert res["distances"] == [[]] + assert res["metadatas"] == [[]] + assert set(res["included"]) == set(["embeddings", "distances", "metadatas"]) + + res = coll.query( + query_embeddings=test_query_embeddings, + where={"test": "yes"}, + n_results=3, + ) + assert res["ids"] == [[], []] + assert res["embeddings"] is None + assert res["distances"] == [[], []] + assert res["metadatas"] == [[], []] + assert set(res["included"]) == set(["metadatas", "documents", "distances"]) + + +def test_boolean_metadata(client: ClientAPI) -> None: + """Test that metadata with boolean values is correctly filtered""" + reset(client) + coll = client.create_collection(name="test") + + test_ids: IDs = ["1", "2", "3"] + test_embeddings: Embeddings = [np.array([1, 1]), np.array([2, 2]), np.array([3, 3])] + test_metadatas: Metadatas = [{"test": True}, {"test": False}, {"test": True}] + + coll.add(ids=test_ids, embeddings=test_embeddings, metadatas=test_metadatas) + + res = coll.get(where={"test": True}) + + assert res["ids"] == ["1", "3"] + + +def test_get_empty(client: ClientAPI) -> None: + """Tests that calling get() with empty filters returns nothing""" + + reset(client) + coll = client.create_collection(name="test") + + test_ids: IDs = ["1", "2", "3"] + test_embeddings: Embeddings = [np.array([1, 1]), np.array([2, 2]), np.array([3, 3])] + test_metadatas: Metadatas = [{"test": 10}, {"test": 20}, {"test": 30}] + + def check_empty_res(res: GetResult) -> None: + assert len(res["ids"]) == 0 + assert res["embeddings"] is not None + assert len(res["embeddings"]) == 0 + assert res["documents"] is not None + assert len(res["documents"]) == 0 + assert res["metadatas"] is not None + + coll.add(ids=test_ids, embeddings=test_embeddings, metadatas=test_metadatas) + + res = coll.get(ids=["nope"], include=["embeddings", "metadatas", "documents"]) + check_empty_res(res) + res = coll.get( + include=["embeddings", "metadatas", "documents"], where={"test": 100} + ) + check_empty_res(res) + + +@settings( + deadline=90000, + suppress_health_check=[ + HealthCheck.function_scoped_fixture, + HealthCheck.large_base_example, + ], +) +@given( + collection=collection_st, + record_set=recordset_st, + n_results_st=st.integers(min_value=1, max_value=100), + should_compact=st.booleans(), + data=st.data(), +) +def test_query_ids_filter_property( + caplog: pytest.LogCaptureFixture, + client: ClientAPI, + collection: strategies.Collection, + record_set: strategies.RecordSet, + n_results_st: int, + should_compact: bool, + data: st.DataObject, +) -> None: + """Property test for querying with only the ids filter.""" + if ( + client.get_settings().chroma_api_impl + == "chromadb.api.async_fastapi.AsyncFastAPI" + ): + pytest.skip( + "Skipping test for async client due to potential resource/timeout issues" + ) + caplog.set_level(logging.ERROR) + reset(client) + coll = client.create_collection( + name=collection.name, + metadata=collection.metadata, # type: ignore + embedding_function=collection.embedding_function, + ) + initial_version = coll.get_model()["version"] + normalized_record_set = invariants.wrap_all(record_set) + + if len(normalized_record_set["ids"]) == 0: + # Cannot add empty record set + return + + coll.add(**record_set) # type: ignore[arg-type] + + if not NOT_CLUSTER_ONLY: + if should_compact and len(normalized_record_set["ids"]) > 10: + wait_for_version_increase(client, collection.name, initial_version) # type: ignore + + total_count = len(normalized_record_set["ids"]) + n_results = min(n_results_st, total_count) + + # Generate a random subset of ids to filter on using Hypothesis data + ids_to_query = data.draw( + st.lists( + st.sampled_from(normalized_record_set["ids"]), + min_size=0, + max_size=total_count, + unique=True, + ) + ) + + # Pick a random query vector using Hypothesis data + random_query: Embedding + query_index = data.draw(st.integers(min_value=0, max_value=total_count - 1)) + if collection.has_embeddings: + assert normalized_record_set["embeddings"] is not None + assert all(isinstance(e, list) for e in normalized_record_set["embeddings"]) + # Use data.draw to select index + random_query = normalized_record_set["embeddings"][query_index] + else: + assert isinstance(normalized_record_set["documents"], list) + assert collection.embedding_function is not None + # Use data.draw to select index + random_query = collection.embedding_function( + [normalized_record_set["documents"][query_index]] + )[0] + + # Perform the query with only the ids filter + result = coll.query( + query_embeddings=[random_query], + ids=ids_to_query, + n_results=n_results, + ) + + result_ids = set(result["ids"][0]) + filter_ids_set = set(ids_to_query) + + # The core assertion: all returned IDs must be within the filter set + assert result_ids.issubset(filter_ids_set) + + # Also check that the number of results is reasonable + assert len(result_ids) <= n_results + assert len(result_ids) <= len(filter_ids_set) + + +def test_regex(client: ClientAPI) -> None: + """Tests that regex works""" + + reset(client) + coll = client.create_collection(name="test") + + test_ids: IDs = ["1", "2", "3"] + test_documents: Documents = ["cat", "Cat", "CAT"] + test_embeddings: Embeddings = [np.array([1, 1]), np.array([2, 2]), np.array([3, 3])] + test_metadatas: Metadatas = [{"test": 10}, {"test": 20}, {"test": 30}] + + coll.add( + ids=test_ids, + documents=test_documents, + embeddings=test_embeddings, + metadatas=test_metadatas, + ) + + res = coll.get(where_document={"$regex": "cat"}) + assert res["ids"] == ["1"] + + res = coll.get(where_document={"$regex": "(?i)cat"}) + assert sorted(res["ids"]) == ["1", "2", "3"] + + res = coll.get( + where={"test": {"$ne": 10}}, where_document={"$regex": "(?i)c(?-i)at"} # type: ignore[dict-item] + ) + assert res["ids"] == ["2"] diff --git a/python/user_packages/Python313/site-packages/chromadb/test/property/test_fork.py b/python/user_packages/Python313/site-packages/chromadb/test/property/test_fork.py new file mode 100644 index 0000000000000000000000000000000000000000..c78659813191720dc01e55430ae9eed2b6766cf9 --- /dev/null +++ b/python/user_packages/Python313/site-packages/chromadb/test/property/test_fork.py @@ -0,0 +1,194 @@ +import chromadb +import chromadb.test.property.invariants as invariants +import chromadb.test.property.strategies as strategies +import copy +import hypothesis.strategies as hyst +import logging +import pytest + +from chromadb.api.models.Collection import Collection +from chromadb.test.conftest import ( + reset, + skip_if_not_cluster, +) +from hypothesis.stateful import ( + Bundle, + RuleBasedStateMachine, + rule, + initialize, + multiple, + consumes, + run_state_machine_as_test, + MultipleResults, +) +from overrides import overrides +from typing import Dict, cast, Union, Tuple, Set + +collection_st = hyst.shared(strategies.collections(with_hnsw_params=True), key="source") + + +class ForkStateMachine(RuleBasedStateMachine): + updated_collections: Bundle[ + Tuple[Collection, strategies.StateMachineRecordSet] + ] = Bundle("changing_collections") + forked_collections: Bundle[ + Tuple[Collection, strategies.StateMachineRecordSet] + ] = Bundle("collections") + collection_names: Set[str] + + def __init__(self, client: chromadb.api.ClientAPI): + super().__init__() + self.client = client + self.collection_names = set() + + @initialize(collection=collection_st, target=updated_collections) + def initialize( + self, collection: strategies.Collection + ) -> Tuple[Collection, strategies.StateMachineRecordSet]: + source = self.client.create_collection( + name=collection.name, + metadata=collection.metadata, # type: ignore[arg-type] + embedding_function=collection.embedding_function, + ) + self.collection_names.add(source.name) + return source, strategies.StateMachineRecordSet( + ids=[], metadatas=[], documents=[], embeddings=[] + ) + + @overrides + def teardown(self) -> None: + reset(self.client) + + @rule( + source=consumes(updated_collections), + new_name=strategies.collection_name(), + target=forked_collections, + ) + def fork( + self, source: Tuple[Collection, strategies.StateMachineRecordSet], new_name: str + ) -> MultipleResults[Tuple[Collection, strategies.StateMachineRecordSet]]: + collection, record_set = source + if new_name in self.collection_names: + with pytest.raises(Exception): + collection.fork(new_name) + return multiple(source) + + target = collection.fork(new_name) + self.collection_names.add(target.name) + return multiple(source, (target, copy.deepcopy(record_set))) + + @rule( + cursor=consumes(forked_collections), + delta=strategies.recordsets(collection_st), + target=updated_collections, + ) + def upsert( + self, + cursor: Tuple[Collection, strategies.StateMachineRecordSet], + delta: strategies.RecordSet, + ) -> Tuple[Collection, strategies.StateMachineRecordSet]: + collection, record_set_state = cursor + normalized_delta: strategies.NormalizedRecordSet = invariants.wrap_all(delta) + collection.upsert(**normalized_delta) # type: ignore[arg-type] + for idx, id in enumerate(normalized_delta["ids"]): + if id in record_set_state["ids"]: + target_idx = record_set_state["ids"].index(id) + if normalized_delta["embeddings"] is not None: + record_set_state["embeddings"][target_idx] = normalized_delta[ + "embeddings" + ][idx] + else: + assert normalized_delta["documents"] is not None + assert collection._embedding_function is not None + record_set_state["embeddings"][ + target_idx + ] = collection._embedding_function( + [normalized_delta["documents"][idx]] + )[ + 0 + ] + if normalized_delta["metadatas"] is not None: + record_set_state_metadata = cast( + Dict[str, Union[str, int, float]], + record_set_state["metadatas"][target_idx], + ) + if record_set_state_metadata is not None: + if normalized_delta["metadatas"][idx] is not None: + record_set_state_metadata.update( + normalized_delta["metadatas"][idx] # type: ignore[arg-type] + ) + else: + record_set_state["metadatas"][target_idx] = normalized_delta[ + "metadatas" + ][idx] + if normalized_delta["documents"] is not None: + record_set_state["documents"][target_idx] = normalized_delta[ + "documents" + ][idx] + else: + record_set_state["ids"].append(id) + if normalized_delta["embeddings"] is not None: + record_set_state["embeddings"].append( + normalized_delta["embeddings"][idx] + ) + else: + assert collection._embedding_function is not None + assert normalized_delta["documents"] is not None + record_set_state["embeddings"].append( + collection._embedding_function( + [normalized_delta["documents"][idx]] + )[0] + ) + if normalized_delta["metadatas"] is not None: + record_set_state["metadatas"].append( + normalized_delta["metadatas"][idx] + ) + else: + record_set_state["metadatas"].append(None) + if normalized_delta["documents"] is not None: + record_set_state["documents"].append( + normalized_delta["documents"][idx] + ) + else: + record_set_state["documents"].append(None) + return collection, record_set_state + + @rule( + cursor=consumes(forked_collections), + target=updated_collections, + ) + def delete( + self, cursor: Tuple[Collection, strategies.StateMachineRecordSet] + ) -> Tuple[Collection, strategies.StateMachineRecordSet]: + collection, record_set_state = cursor + boundary = len(record_set_state["ids"]) // 10 + if boundary == 0: + return collection, record_set_state + ids_to_delete = record_set_state["ids"][:boundary] + collection.delete(ids_to_delete) + record_set_state["ids"] = record_set_state["ids"][boundary:] + record_set_state["embeddings"] = record_set_state["embeddings"][boundary:] + record_set_state["metadatas"] = record_set_state["metadatas"][boundary:] + record_set_state["documents"] = record_set_state["documents"][boundary:] + return collection, record_set_state + + @rule( + cursor=forked_collections, + ) + def verify( + self, cursor: Tuple[Collection, strategies.StateMachineRecordSet] + ) -> None: + collection, record_set_state = cursor + if len(record_set_state["ids"]) == 0: + assert collection.count() == 0 + else: + record_set = cast(strategies.RecordSet, record_set_state) + invariants.embeddings_match(collection, record_set) + invariants.metadatas_match(collection, record_set) + invariants.documents_match(collection, record_set) + + +@skip_if_not_cluster() +def test_fork(caplog: pytest.LogCaptureFixture, client: chromadb.api.ClientAPI) -> None: + caplog.set_level(logging.ERROR) + run_state_machine_as_test(lambda: ForkStateMachine(client)) # type: ignore diff --git a/python/user_packages/Python313/site-packages/chromadb/test/property/test_persist.py b/python/user_packages/Python313/site-packages/chromadb/test/property/test_persist.py new file mode 100644 index 0000000000000000000000000000000000000000..973cd1e35e936fbfbac0e6ce03497d6cbf74ef9c --- /dev/null +++ b/python/user_packages/Python313/site-packages/chromadb/test/property/test_persist.py @@ -0,0 +1,725 @@ +import logging +import multiprocessing +from multiprocessing.connection import Connection +import multiprocessing.context +import time +from typing import Generator, Callable, List, Tuple, cast +from uuid import UUID +from hypothesis import given +import hypothesis.strategies as st +import pytest +import chromadb +from chromadb.api import ClientAPI, ServerAPI +from chromadb.config import Settings, System +from chromadb.segment import VectorReader +from chromadb.segment.impl.manager.local import LocalSegmentManager +import chromadb.test.property.strategies as strategies +import chromadb.test.property.invariants as invariants +from chromadb.test.property.strategies import hashing_embedding_function +from chromadb.test.property.test_embeddings import ( + EmbeddingStateMachineStates, + trace, + EmbeddingStateMachineBase, +) +from hypothesis.stateful import ( + run_state_machine_as_test, + rule, + precondition, + initialize, + MultipleResults, +) +import os +from chromadb.api.client import Client as ClientCreator +from chromadb.utils.embedding_functions import DefaultEmbeddingFunction +import numpy as np +import tempfile + +CreatePersistAPI = Callable[[], ServerAPI] + +configurations = ( + [ + Settings( + chroma_api_impl="chromadb.api.rust.RustBindingsAPI", + chroma_sysdb_impl="chromadb.db.impl.sqlite.SqliteDB", + chroma_producer_impl="chromadb.db.impl.sqlite.SqliteDB", + chroma_consumer_impl="chromadb.db.impl.sqlite.SqliteDB", + chroma_segment_manager_impl="chromadb.segment.impl.manager.local.LocalSegmentManager", + allow_reset=True, + is_persistent=True, + persist_directory=tempfile.mkdtemp(), + ) + ] + if "CHROMA_RUST_BINDINGS_TEST_ONLY" in os.environ + else [ + Settings( + chroma_api_impl="chromadb.api.segment.SegmentAPI", + chroma_sysdb_impl="chromadb.db.impl.sqlite.SqliteDB", + chroma_producer_impl="chromadb.db.impl.sqlite.SqliteDB", + chroma_consumer_impl="chromadb.db.impl.sqlite.SqliteDB", + chroma_segment_manager_impl="chromadb.segment.impl.manager.local.LocalSegmentManager", + allow_reset=True, + is_persistent=True, + persist_directory=tempfile.mkdtemp(), + ), + ] +) + + +@pytest.fixture(scope="module", params=configurations) +def settings(request: pytest.FixtureRequest) -> Generator[Settings, None, None]: + yield request.param + + +collection_st = st.shared( + strategies.collections( + with_hnsw_params=True, + with_persistent_hnsw_params=st.just(True), + # Makes it more likely to find persist-related bugs (by default these are set to 2000). + # Lower values make it more likely that a test will trigger a persist to disk. + max_hnsw_batch_size=10, + max_hnsw_sync_threshold=10, + ), + key="coll", +) + + +@st.composite +def collection_and_recordset_strategy( + draw: st.DrawFn, +) -> Tuple[strategies.Collection, strategies.RecordSet]: + collection = draw( + strategies.collections( + with_hnsw_params=True, + with_persistent_hnsw_params=st.just(True), + # Makes it more likely to find persist-related bugs (by default these are set to 2000). + max_hnsw_batch_size=10, + max_hnsw_sync_threshold=10, + ) + ) + recordset = draw(strategies.recordsets(st.just(collection))) + return collection, recordset + + +@given( + collection_and_recordset_strategies=st.lists( + collection_and_recordset_strategy(), + min_size=1, + unique_by=(lambda x: x[0].name, lambda x: x[0].name), + ) +) +def test_persist( + settings: Settings, + collection_and_recordset_strategies: List[ + Tuple[strategies.Collection, strategies.RecordSet] + ], +) -> None: + system_1 = System(settings) + system_1.start() + client_1 = ClientCreator.from_system(system_1) + + client_1.reset() + for ( + collection_strategy, + recordset_strategy, + ) in collection_and_recordset_strategies: + coll = client_1.create_collection( + name=collection_strategy.name, + metadata=collection_strategy.metadata, # type: ignore[arg-type] + embedding_function=collection_strategy.embedding_function, + ) + + coll.add(**recordset_strategy) # type: ignore[arg-type] + + invariants.count(coll, recordset_strategy) + invariants.metadatas_match(coll, recordset_strategy) + invariants.documents_match(coll, recordset_strategy) + invariants.ids_match(coll, recordset_strategy) + invariants.ann_accuracy( + coll, + recordset_strategy, + embedding_function=collection_strategy.embedding_function, + ) + + system_1.stop() + del client_1 + del system_1 + + system_2 = System(settings) + system_2.start() + client_2 = ClientCreator.from_system(system_2) + + for ( + collection_strategy, + recordset_strategy, + ) in collection_and_recordset_strategies: + coll = client_2.get_collection( + name=collection_strategy.name, + embedding_function=collection_strategy.embedding_function, + ) + invariants.count(coll, recordset_strategy) + invariants.metadatas_match(coll, recordset_strategy) + invariants.documents_match(coll, recordset_strategy) + invariants.ids_match(coll, recordset_strategy) + invariants.ann_accuracy( + coll, + recordset_strategy, + embedding_function=collection_strategy.embedding_function, + ) + + system_2.stop() + del client_2 + del system_2 + + +def test_sync_threshold(settings: Settings) -> None: + system = System(settings) + system.start() + client = ClientCreator.from_system(system) + + collection = client.create_collection( + name="test", metadata={"hnsw:batch_size": 3, "hnsw:sync_threshold": 3} + ) + + manager = system.instance(LocalSegmentManager) + segment = manager.get_segment(collection.id, VectorReader) + + def get_index_last_modified_at() -> float: + # Time resolution on Windows can be up to 10ms + time.sleep(0.1) + try: + return os.path.getmtime(segment._get_metadata_file()) # type: ignore[attr-defined] + except FileNotFoundError: + return -1 + + last_modified_at = get_index_last_modified_at() + + collection.add(ids=["1", "2"], embeddings=[[1.0], [2.0]]) # type: ignore[arg-type] + + # Should not have yet persisted + assert get_index_last_modified_at() == last_modified_at + last_modified_at = get_index_last_modified_at() + + # Now there's 3 additions, and the sync threshold is 3... + collection.add(ids=["3"], embeddings=[[3.0]]) # type: ignore[arg-type] + + # ...so it should have persisted + assert get_index_last_modified_at() > last_modified_at + last_modified_at = get_index_last_modified_at() + + # The same thing should happen with upserts + collection.upsert(ids=["1", "2", "3"], embeddings=[[1.0], [2.0], [3.0]]) # type: ignore[arg-type] + + # Should have persisted + assert get_index_last_modified_at() > last_modified_at + last_modified_at = get_index_last_modified_at() + + # Mixed usage should also trigger persistence + collection.add(ids=["4"], embeddings=[[4.0]]) # type: ignore[arg-type] + collection.upsert(ids=["1", "2"], embeddings=[[1.0], [2.0]]) # type: ignore[arg-type] + + # Should have persisted + assert get_index_last_modified_at() > last_modified_at + last_modified_at = get_index_last_modified_at() + + # Invalid updates should also trigger persistence + collection.add(ids=["5"], embeddings=[[5.0]]) # type: ignore[arg-type] + collection.add(ids=["1", "2"], embeddings=[[1.0], [2.0]]) # type: ignore[arg-type] + + # Should have persisted + assert get_index_last_modified_at() > last_modified_at + last_modified_at = get_index_last_modified_at() + + +def load_and_check( + settings: Settings, + collection_name: str, + record_set: strategies.RecordSet, + conn: Connection, +) -> None: + try: + system = System(settings) + system.start() + client = ClientCreator.from_system(system) + + coll = client.get_collection( + name=collection_name, + embedding_function=strategies.not_implemented_embedding_function(), # type: ignore[arg-type] + ) + invariants.count(coll, record_set) + invariants.metadatas_match(coll, record_set) + invariants.documents_match(coll, record_set) + invariants.ids_match(coll, record_set) + invariants.ann_accuracy(coll, record_set) + + system.stop() + except Exception as e: + conn.send(e) + raise e + + +def get_multiprocessing_context(): # type: ignore[no-untyped-def] + try: + # Run the invariants in a new process to bypass any shared state/caching (which would defeat the purpose of the test) + # (forkserver is used because it's much faster than spawn—it will spawn a new, minimal singleton process and then fork that singleton) + ctx = multiprocessing.get_context("forkserver") + # This is like running `import chromadb` in the single process that is forked rather than importing it in each forked process. + # Gives a ~3x speedup since importing chromadb is fairly expensive. + ctx.set_forkserver_preload(["chromadb"]) + return ctx + except Exception: + # forkserver/fork is not available on Windows + return multiprocessing.get_context("spawn") + + +class PersistEmbeddingsStateMachineStates(EmbeddingStateMachineStates): + persist = "persist" + + +MIN_STATE_CHANGES_BEFORE_PERSIST = 5 + + +class PersistEmbeddingsStateMachine(EmbeddingStateMachineBase): + def __init__(self, client: ClientAPI, settings: Settings): + self.client = client + self.settings = settings + self.min_state_changes_left_before_persisting = MIN_STATE_CHANGES_BEFORE_PERSIST + self.client.reset() + super().__init__(self.client) + + @initialize(collection=collection_st) # type: ignore + def initialize(self, collection: strategies.Collection): + self.client.reset() + self.collection = self.client.create_collection( + name=collection.name, + metadata=collection.metadata, # type: ignore[arg-type] + embedding_function=collection.embedding_function, + ) + self.embedding_function = collection.embedding_function + trace("init") + self.on_state_change(EmbeddingStateMachineStates.initialize) + + self.record_set_state = strategies.StateMachineRecordSet( + ids=[], metadatas=[], documents=[], embeddings=[] + ) + + @precondition( + lambda self: len(self.record_set_state["ids"]) >= 1 + and self.min_state_changes_left_before_persisting <= 0 + ) + @rule() + def persist(self) -> None: + self.on_state_change(PersistEmbeddingsStateMachineStates.persist) + collection_name = self.collection.name + conn1, conn2 = multiprocessing.Pipe() + ctx = get_multiprocessing_context() # type: ignore[no-untyped-call] + p = ctx.Process( + target=load_and_check, + args=(self.settings, collection_name, self.record_set_state, conn2), + ) + p.start() + p.join() + + if conn1.poll(): + e = conn1.recv() + raise e + + p.close() + + def on_state_change(self, new_state: str) -> None: + super().on_state_change(new_state) + if new_state == PersistEmbeddingsStateMachineStates.persist: + self.min_state_changes_left_before_persisting = ( + MIN_STATE_CHANGES_BEFORE_PERSIST + ) + else: + self.min_state_changes_left_before_persisting -= 1 + + def teardown(self) -> None: + self.client.reset() + + +def test_persist_embeddings_state( + caplog: pytest.LogCaptureFixture, settings: Settings +) -> None: + caplog.set_level(logging.ERROR) + client = chromadb.Client(settings) + run_state_machine_as_test( + lambda: PersistEmbeddingsStateMachine(settings=settings, client=client), + ) # type: ignore + + +def test_delete_less_than_k( + caplog: pytest.LogCaptureFixture, settings: Settings +) -> None: + client = chromadb.Client(settings) + state = PersistEmbeddingsStateMachine(settings=settings, client=client) + state.initialize( + collection=strategies.Collection( + name="A00", + metadata={ + "hnsw:construction_ef": 128, + "hnsw:search_ef": 128, + "hnsw:M": 128, + "hnsw:sync_threshold": 3, + "hnsw:batch_size": 3, + }, + embedding_function=None, + id=UUID("2d3eddc7-2314-45f4-a951-47a9a8e099d2"), + dimension=2, + dtype=np.float16, + known_metadata_keys={}, + known_document_keywords=[], + has_documents=False, + has_embeddings=True, + ) + ) + state.ann_accuracy() + state.count() + state.fields_match() + state.log_size_below_max() + state.no_duplicates() + (embedding_ids_0,) = state.add_embeddings(record_set={"ids": ["0"], "embeddings": [[0.09765625, 0.430419921875]], "metadatas": [None], "documents": None}) # type: ignore + state.ann_accuracy() + # recall: 1.0, missing 0 out of 1, accuracy threshold 1e-06 + state.count() + state.fields_match() + state.log_size_below_max() + state.no_duplicates() + embedding_ids_1, embedding_ids_2 = state.add_embeddings(record_set={"ids": ["1", "2"], "embeddings": [[0.20556640625, 0.08978271484375], [-0.1527099609375, 0.291748046875]], "metadatas": [None, None], "documents": None}) # type: ignore + state.ann_accuracy() + # recall: 1.0, missing 0 out of 3, accuracy threshold 1e-06 + state.count() + state.fields_match() + state.log_size_below_max() + state.no_duplicates() + state.delete_by_ids(ids=[embedding_ids_2]) + state.ann_accuracy() + state.teardown() + + +# Ideally this scenario would be exercised by Hypothesis, but most runs don't seem to trigger this particular state. +def test_delete_add_after_persist(settings: Settings) -> None: + client = chromadb.Client(settings) + state = PersistEmbeddingsStateMachine(settings=settings, client=client) + + state.initialize( + collection=strategies.Collection( + name="A00", + metadata={ + "hnsw:construction_ef": 128, + "hnsw:search_ef": 128, + "hnsw:M": 128, + # Important: both batch_size and sync_threshold are 3 + "hnsw:batch_size": 3, + "hnsw:sync_threshold": 3, + }, + embedding_function=DefaultEmbeddingFunction(), # type: ignore[arg-type] + id=UUID("0851f751-2f11-4424-ab23-4ae97074887a"), + dimension=2, + dtype=None, + known_metadata_keys={}, + known_document_keywords=[], + has_documents=False, + has_embeddings=True, + ) + ) + + state.add_embeddings( + record_set={ + # Add 3 records to hit the batch_size and sync_threshold + "ids": ["0", "1", "2"], + "embeddings": [[0, 0], [0, 0], [0, 0]], + "metadatas": [None, None, None], + "documents": None, + } + ) + + # Delete and then re-add record + state.delete_by_ids(ids=["0"]) + state.add_embeddings( + record_set={ + "ids": ["0"], + "embeddings": [[1, 1]], + "metadatas": [None], + "documents": None, + } + ) + + # At this point, the changes above are not fully persisted + state.fields_match() + + +def test_batch_size_less_than_sync_with_duplicate_adds_results_in_skipped_seq_ids( + caplog: pytest.LogCaptureFixture, settings: Settings +) -> None: + # NOTE(hammadb) this test was autogenerate by hypothesis and added here to ensure that the test is run + # in the future. It tests a case where the max seq id was incorrect in response to the same + # id being added multiple times in a bathc. + client = chromadb.Client(settings) + state = PersistEmbeddingsStateMachine(settings=settings, client=client) + state.initialize( + collection=strategies.Collection( + name="JqzMs4pPm14c", + metadata={ + "hnsw:construction_ef": 128, + "hnsw:search_ef": 128, + "hnsw:M": 128, + "hnsw:sync_threshold": 9, + "hnsw:batch_size": 7, + }, + embedding_function=hashing_embedding_function(dim=92, dtype=np.float64), # type: ignore[arg-type] + id=UUID("45c5c816-0a90-4293-8d01-4325ff860040"), + dimension=92, + dtype=np.float64, + known_metadata_keys={}, + known_document_keywords=[], + has_documents=False, + has_embeddings=True, + ) + ) + state.ann_accuracy() + state.count() + state.fields_match() + state.log_size_below_max() + state.no_duplicates() + ( + embedding_ids_0, + embedding_ids_1, + embedding_ids_2, + embedding_ids_3, + embedding_ids_4, + embedding_ids_5, + embedding_ids_6, + ) = cast( + MultipleResults[str], + state.add_embeddings( + record_set={ + "ids": ["N", "e8r6", "4", "Yao", "qFjA2c", "jHCv", "2"], + "embeddings": [ + [0.0, 0.0, 0.0], + [1.0, 1.0, 1.0], + [2.0, 2.0, 2.0], + [3.0, 3.0, 3.0], + [4.0, 4.0, 4.0], + [5.0, 5.0, 5.0], + [6.0, 6.0, 6.0], + ], + "metadatas": None, + "documents": None, + } + ), + ) + state.ann_accuracy() + # recall: 1.0, missing 0 out of 7, accuracy threshold 1e-06 + state.count() + state.fields_match() + state.log_size_below_max() + state.no_duplicates() + + print("\n\n") + (_) = state.add_embeddings( + record_set={ + "ids": ["MVu393QTc"], + "embeddings": [[7.0, 7.0, 7.0]], + "metadatas": None, + "documents": None, + } + ) + state.ann_accuracy() + # recall: 1.0, missing 0 out of 8, accuracy threshold 1e-06 + state.count() + state.fields_match() + state.log_size_below_max() + state.no_duplicates() + + ( + _, + _, + _, + _, + embedding_ids_12, + _, + _, + _, + _, + embedding_ids_17, + embedding_ids_18, + _, + _, + _, + embedding_ids_22, + _, + _, + ) = cast( + MultipleResults[str], + state.add_embeddings( + record_set={ + "ids": [ + "CyF0Mk-", + "q_Fwu", + "2D2sQSFogDgPLkcfT", + "SrwuQHQ6w4f51qWr2enLPQw8uKYs1", + "G", + "wdzt", + "5W", + "8tpsn", + "fJbV7z", + "5", + "V", + "1iFkoJX", + "Zw4u", + "Fc", + "7", + "vEEwrP", + "Yf", + ], + "embeddings": [ + [8.0, 8.0, 8.0], + [9.0, 9.0, 9.0], + [10.0, 10.0, 10.0], + [11.0, 11.0, 11.0], + [12.0, 12.0, 12.0], + [13.0, 13.0, 13.0], + [14.0, 14.0, 14.0], + [15.0, 15.0, 15.0], + [16.0, 16.0, 16.0], + [17.0, 17.0, 17.0], + [18.0, 18.0, 18.0], + [19.0, 19.0, 19.0], + [20.0, 20.0, 20.0], + [21.0, 21.0, 21.0], + [22.0, 22.0, 22.0], + [23.0, 23.0, 23.0], + [24.0, 24.0, 24.0], + ], + "metadatas": None, + "documents": None, + } + ), + ) + state.ann_accuracy() + state.count() + state.fields_match() + state.log_size_below_max() + state.no_duplicates() + + state.add_embeddings( + record_set={ + "ids": ["0", "df_RWhR0HelOcv"], + "embeddings": [[25.0, 25.0, 25.0], [26.0, 26.0, 26.0]], + "metadatas": [None, None], + "documents": None, + } + ) + state.ann_accuracy() + state.count() + state.fields_match() + state.log_size_below_max() + state.no_duplicates() + + state.add_embeddings( + record_set={ + "ids": ["3R", "9_", "44u", "3B", "MZCXZDS", "Uelx"], + "embeddings": [ + [27.0, 27.0, 27.0], + [28.0, 28.0, 28.0], + [29.0, 29.0, 29.0], + [30.0, 30.0, 30.0], + [31.0, 31.0, 31.0], + [32.0, 32.0, 32.0], + ], + "metadatas": None, + "documents": None, + } + ) + state.ann_accuracy() + state.count() + state.fields_match() + state.log_size_below_max() + state.no_duplicates() + state.persist() + state.ann_accuracy() + state.count() + state.fields_match() + state.log_size_below_max() + state.no_duplicates() + + state.add_embeddings( + record_set={ + "ids": "YlVm", + "embeddings": [[33.0, 33.0, 33.0]], + "metadatas": None, + "documents": None, + } + ) + state.ann_accuracy() + # recall: 1.0, missing 0 out of 34, accuracy threshold 1e-06 + state.count() + state.fields_match() + state.log_size_below_max() + state.no_duplicates() + + state.add_embeddings( + record_set={ + "ids": ["Rk1", "TPL"], + "embeddings": [[34.0, 34.0, 34.0], [35.0, 35.0, 35.0]], + "metadatas": [None, None], + "documents": None, + } + ) + state.ann_accuracy() + # recall: 1.0, missing 0 out of 36, accuracy threshold 1e-06 + state.count() + state.fields_match() + state.log_size_below_max() + state.no_duplicates() + + state.add_embeddings( + record_set={ + "ids": [ + "CyF0Mk-", + "q_Fwu", + "2D2sQSFogDgPLkcfT", + "SrwuQHQ6w4f51qWr2enLPQw8uKYs1", + embedding_ids_12, + "wdzt", + "5W", + "8tpsn", + "fJbV7z", + embedding_ids_17, + embedding_ids_18, + "1iFkoJX", + "Zw4u", + "Fc", + embedding_ids_22, + "vEEwrP", + "Yf", + ], + "embeddings": [ + [8.0, 8.0, 8.0], + [9.0, 9.0, 9.0], + [10.0, 10.0, 10.0], + [11.0, 11.0, 11.0], + [12.0, 12.0, 12.0], + [13.0, 13.0, 13.0], + [14.0, 14.0, 14.0], + [15.0, 15.0, 15.0], + [16.0, 16.0, 16.0], + [17.0, 17.0, 17.0], + [18.0, 18.0, 18.0], + [19.0, 19.0, 19.0], + [20.0, 20.0, 20.0], + [21.0, 21.0, 21.0], + [22.0, 22.0, 22.0], + [23.0, 23.0, 23.0], + [24.0, 24.0, 24.0], + ], + "metadatas": None, + "documents": None, + } + ) + state.ann_accuracy() + state.count() + state.fields_match() + state.log_size_below_max() + state.teardown() diff --git a/python/user_packages/Python313/site-packages/chromadb/test/property/test_restart_persist.py b/python/user_packages/Python313/site-packages/chromadb/test/property/test_restart_persist.py new file mode 100644 index 0000000000000000000000000000000000000000..4d343d2c650afccf490bcae89747ed962bdd9ae1 --- /dev/null +++ b/python/user_packages/Python313/site-packages/chromadb/test/property/test_restart_persist.py @@ -0,0 +1,86 @@ +from overrides import overrides +from chromadb.api.client import Client +from chromadb.config import System +import hypothesis.strategies as st +from hypothesis.stateful import ( + rule, + run_state_machine_as_test, + initialize, +) + +from chromadb.test.property.test_embeddings import ( + EmbeddingStateMachineBase, + EmbeddingStateMachineStates, + trace, +) +import chromadb.test.property.strategies as strategies +import os + + +collection_persistent_st = st.shared( + strategies.collections( + with_hnsw_params=True, + with_persistent_hnsw_params=st.just(True), + # Makes it more likely to find persist-related bugs (by default these are set to 2000). + max_hnsw_batch_size=10, + max_hnsw_sync_threshold=10, + ), + key="coll_persistent", +) + + +# This machine shares a lot of similarity with the machine in chromadb/test/property/test_persist.py. +# However, test_persist.py tests correctness under complete process isolation and therefore can only check invariants on a new system--whereas this machine does not have full process isolation between systems/clients but after a restart continues to exercise the state machine with the newly-created system. +class RestartablePersistedEmbeddingStateMachine(EmbeddingStateMachineBase): + system: System + + def __init__(self, system: System) -> None: + self.system = system + client = Client.from_system(system) + super().__init__(client) + + @initialize(collection=collection_persistent_st) # type: ignore + @overrides + def initialize(self, collection: strategies.Collection): + self.client.reset() + + self.collection = self.client.create_collection( + name=collection.name, + metadata=collection.metadata, # type: ignore + embedding_function=collection.embedding_function, + ) + self.embedding_function = collection.embedding_function + trace("init") + self.on_state_change(EmbeddingStateMachineStates.initialize) + + self.record_set_state = strategies.StateMachineRecordSet( + ids=[], metadatas=[], documents=[], embeddings=[] + ) + + @rule() + def restart_system(self) -> None: + # Simulates restarting chromadb + self.system.stop() + self.system = System(self.system.settings) + self.system.start() + self.client.clear_system_cache() + self.client = Client.from_system(self.system) + self.collection = self.client.get_collection( + self.collection.name, embedding_function=self.embedding_function + ) + + @overrides + def teardown(self) -> None: + super().teardown() + # Need to manually stop the system to cleanup resources because we may have created a new system (above rule). + # Normally, we wouldn't have to worry about this as the system from the fixture is shared between state machine runs. + # (This helps avoid a "too many open files" error.) + self.system.stop() + + +def test_restart_persisted_client(sqlite_persistent: System) -> None: + # TODO: This test is broken for rust bindings and should be fixed + if sqlite_persistent.settings.chroma_api_impl != "chromadb.api.rust.RustBindingsAPI": + run_state_machine_as_test( + lambda: RestartablePersistedEmbeddingStateMachine(sqlite_persistent), + ) # type: ignore diff --git a/python/user_packages/Python313/site-packages/chromadb/test/property/test_schema.py b/python/user_packages/Python313/site-packages/chromadb/test/property/test_schema.py new file mode 100644 index 0000000000000000000000000000000000000000..5d10eac38b084324fadd7779abc73f7f3dddab88 --- /dev/null +++ b/python/user_packages/Python313/site-packages/chromadb/test/property/test_schema.py @@ -0,0 +1,787 @@ +import math +from typing import Any, Dict, Optional, Set, Tuple, cast + +from hypothesis import given + +from chromadb.api import ClientAPI +from chromadb.api.collection_configuration import CreateCollectionConfiguration +from chromadb.api.types import ( + CollectionMetadata, + EMBEDDING_KEY, + Schema, +) +from chromadb.test.property import strategies +from chromadb.test.property.invariants import check_metadata +from chromadb.test.conftest import ( + is_spann_disabled_mode, + multi_region_test, + reset, +) + + +HNSW_METADATA_TO_CONFIG: Dict[str, str] = { + "hnsw:space": "space", + "hnsw:construction_ef": "ef_construction", + "hnsw:search_ef": "ef_search", + "hnsw:M": "max_neighbors", + "hnsw:sync_threshold": "sync_threshold", + "hnsw:resize_factor": "resize_factor", +} + +HNSW_FIELDS = [ + "space", + "ef_construction", + "ef_search", + "max_neighbors", + "sync_threshold", + "resize_factor", +] + +HNSW_DEFAULTS: Dict[str, Any] = { + "space": "l2", + "ef_construction": 100, + "ef_search": 100, + "max_neighbors": 16, + "sync_threshold": 1000, + "resize_factor": 1.2, +} + +SPANN_FIELDS = [ + "space", + "search_nprobe", + "write_nprobe", + "ef_construction", + "ef_search", + "max_neighbors", + "reassign_neighbor_count", + "split_threshold", + "merge_threshold", +] + +SPANN_DEFAULTS: Dict[str, Any] = { + "space": "l2", + "search_nprobe": 64, + "write_nprobe": 32, + "ef_construction": 200, + "ef_search": 200, + "max_neighbors": 64, + "reassign_neighbor_count": 64, + "split_threshold": 50, + "merge_threshold": 25, +} + + +def _extract_vector_configs_from_schema( + schema: Schema, +) -> Tuple[Dict[str, Any], Dict[str, Any]]: + defaults_float = schema.defaults.float_list + assert defaults_float is not None + defaults_vi = defaults_float.vector_index + assert defaults_vi is not None + + embedding_float = schema.keys[EMBEDDING_KEY].float_list + assert embedding_float is not None + embedding_vi = embedding_float.vector_index + assert embedding_vi is not None + + return ( + strategies.vector_index_to_dict(defaults_vi.config), + strategies.vector_index_to_dict(embedding_vi.config), + ) + + +def _compute_expected_config_spann( + metadata: Optional[CollectionMetadata], + configuration: Optional[CreateCollectionConfiguration], + schema_vector_index_config: Optional[Dict[str, Any]], +) -> Dict[str, Any]: + # start off creating default spann config, we slowly modify it to much whatever prop test provides + expected = SPANN_DEFAULTS.copy() + space_set = False + # theres some edge cases where space is set in hnsw config and in metadata + # in this case, we check if the space set by config is not the default, and if so, we don't try to get use the one from metadata + # essentially if either metadata or hnsw config provides a non-default space, we use that one, with config hnsw taking priority over metadata + should_try_metadata = True + + if configuration: + spann_cfg = configuration.get("spann") + if spann_cfg: + spann_cfg_dict = cast(Dict[str, Any], spann_cfg) + # update expected with whatever prop test provides + expected.update(strategies.non_none_items(spann_cfg_dict)) + # if space is set in spann, this now takes priority over all else + if spann_cfg_dict.get("space") is not None: + expected["space"] = spann_cfg_dict["space"] + space_set = True + should_try_metadata = False + hnsw_cfg = configuration.get("hnsw") + if hnsw_cfg: + hnsw_cfg_dict = cast(Dict[str, Any], hnsw_cfg) + hnsw_non_none = strategies.non_none_items(hnsw_cfg_dict) + for key, value in hnsw_non_none.items(): + if value is not None and value != HNSW_DEFAULTS[key]: + # if any hnsw config is not the default, we do not use metadata at all, this is used + # heres a sample case where this is needed: hnsw doesnt set space (so l2 by default), but sets ef_construction, metadata sets space to ip + # in this case, they were aware of hnsw config, and chose not to set space in it. therefore the config takes priority over metadata + should_try_metadata = False + # when SPANN is active and HNSW config is provided, use space from hnsw config + if hnsw_cfg_dict.get("space") is not None and not space_set: + # if the space set by config is not the default, don't try to get use the one from metadata + if hnsw_cfg_dict.get("space") != HNSW_DEFAULTS["space"]: + should_try_metadata = False + expected["space"] = hnsw_cfg_dict["space"] + space_set = True + + if schema_vector_index_config: + if schema_vector_index_config.get("space") is not None: + expected["space"] = schema_vector_index_config["space"] + space_set = True + if schema_vector_index_config.get("spann"): + spann_schema = strategies.non_none_items( + schema_vector_index_config["spann"] + ) + expected.update(spann_schema) + + if ( + metadata + and metadata.get("hnsw:space") is not None + and metadata.get("hnsw:space") != SPANN_DEFAULTS["space"] + and should_try_metadata + ): + expected["space"] = metadata["hnsw:space"] + space_set = True + + if ( + schema_vector_index_config + and schema_vector_index_config.get("embedding_function_default_space") + is not None + and schema_vector_index_config.get("embedding_function_default_space") + != SPANN_DEFAULTS["space"] + and not space_set + ): + expected["space"] = schema_vector_index_config[ + "embedding_function_default_space" + ] + space_set = True + + if ( + not space_set + and configuration + and configuration.get("embedding_function") is not None + ): + ef = configuration["embedding_function"] + if hasattr(ef, "default_space"): + expected["space"] = cast(Any, ef).default_space() + + return expected + + +def _compute_expected_config_hnsw( + metadata: Optional[CollectionMetadata], + configuration: Optional[CreateCollectionConfiguration], + schema_vector_index_config: Optional[Dict[str, Any]], +) -> Dict[str, Any]: + expected = HNSW_DEFAULTS.copy() + space_set = False + configured_hnsw_keys: Set[str] = set() + should_try_metadata = True + + if configuration: + hnsw_cfg_raw = configuration.get("hnsw") + if hnsw_cfg_raw is not None: + hnsw_dict: Dict[str, Any] = cast(Dict[str, Any], hnsw_cfg_raw) + hnsw_non_none = strategies.non_none_items(hnsw_dict) + expected.update(hnsw_non_none) + for key, value in hnsw_non_none.items(): + # if any hnsw config is not the default, we do not use metadata at all + if value is not None and value != HNSW_DEFAULTS[key]: + should_try_metadata = False + configured_hnsw_keys.update(hnsw_non_none.keys()) + if hnsw_non_none.get("space") is not None and not space_set: + if hnsw_non_none.get("space") != HNSW_DEFAULTS["space"]: + should_try_metadata = False + space_set = True + spann_cfg_raw = configuration.get("spann") + if spann_cfg_raw is not None: + spann_dict: Dict[str, Any] = cast(Dict[str, Any], spann_cfg_raw) + if spann_dict.get("space") is not None and not space_set: + expected["space"] = spann_dict["space"] + space_set = True + should_try_metadata = False + + if should_try_metadata and metadata: + for key, cfg_key in HNSW_METADATA_TO_CONFIG.items(): + if metadata.get(key) is None: + continue + if cfg_key == "space": + expected[cfg_key] = metadata[key] + space_set = True + configured_hnsw_keys.add(cfg_key) + continue + if cfg_key not in configured_hnsw_keys: + expected[cfg_key] = metadata[key] + configured_hnsw_keys.add(cfg_key) + + if schema_vector_index_config: + if schema_vector_index_config.get("space") is not None: + expected["space"] = schema_vector_index_config["space"] + space_set = True + if schema_vector_index_config.get("hnsw"): + expected.update( + strategies.non_none_items(schema_vector_index_config["hnsw"]) + ) + elif schema_vector_index_config.get("spann"): + # Schema provided SPANN configuration while HNSW is active; ignore. + pass + + if ( + schema_vector_index_config + and schema_vector_index_config.get("embedding_function_default_space") + is not None + and not space_set + ): + expected["space"] = schema_vector_index_config[ + "embedding_function_default_space" + ] + space_set = True + + if ( + not space_set + and configuration + and configuration.get("embedding_function") is not None + ): + ef = configuration["embedding_function"] + if hasattr(ef, "default_space"): + expected["space"] = cast(Any, ef).default_space() + + return expected + + +def _compute_expected_config( + spann_active: bool, + metadata: Optional[CollectionMetadata], + configuration: Optional[CreateCollectionConfiguration], + schema_vector_index_config: Optional[Dict[str, Any]], +) -> Dict[str, Any]: + """ + some assumptions/assertions: + 1. we are not testing failure paths. any config built is/should be valid. invalid cases can be tested separately or in e2e tests + ex: if configuration is set, schema is not set. if schema is set, configuration is not set. both hnsw and spann cannot be set at the same time in config or schema + """ + if spann_active: + return _compute_expected_config_spann( + metadata, configuration, schema_vector_index_config + ) + else: + return _compute_expected_config_hnsw( + metadata, configuration, schema_vector_index_config + ) + + +def _assert_config_values( + actual: Dict[str, Any], + expected: Dict[str, Any], + spann_active: bool, +) -> None: + fields = SPANN_FIELDS if spann_active else HNSW_FIELDS + for field in fields: + actual_value = actual.get(field) + expected_value = expected[field] + # Use approximate equality for floating-point values + if isinstance(actual_value, float) and isinstance(expected_value, float): + assert math.isclose( + actual_value, expected_value, rel_tol=1e-9, abs_tol=1e-9 + ), f"{field} mismatch: expected {expected_value}, got {actual_value}" + else: + assert ( + actual_value == expected_value + ), f"{field} mismatch: expected {expected_value}, got {actual_value}" + + +def _assert_schema_values( + vector_info: Dict[str, Any], + expected: Dict[str, Any], + spann_active: bool, +) -> None: + assert vector_info["space"] == expected["space"] + if spann_active: + spann_cfg = cast(Optional[Dict[str, Any]], vector_info["spann"]) + assert spann_cfg is not None + for field in SPANN_FIELDS: + if field == "space": + continue + actual_value = spann_cfg.get(field) + expected_value = expected[field] + # Use approximate equality for floating-point values + if isinstance(actual_value, float) and isinstance(expected_value, float): + assert math.isclose( + actual_value, expected_value, rel_tol=1e-9, abs_tol=1e-9 + ), f"{field} mismatch: expected {expected_value}, got {actual_value}" + else: + assert ( + actual_value == expected_value + ), f"{field} mismatch: expected {expected_value}, got {actual_value}" + else: + hnsw_cfg = cast(Optional[Dict[str, Any]], vector_info["hnsw"]) + assert hnsw_cfg is not None + for field in HNSW_FIELDS: + if field == "space": + continue + actual_value = hnsw_cfg.get(field) + expected_value = expected[field] + # Use approximate equality for floating-point values + if isinstance(actual_value, float) and isinstance(expected_value, float): + assert math.isclose( + actual_value, expected_value, rel_tol=1e-9, abs_tol=1e-9 + ), f"{field} mismatch: expected {expected_value}, got {actual_value}" + else: + assert ( + actual_value == expected_value + ), f"{field} mismatch: expected {expected_value}, got {actual_value}" + + +def _get_default_schema_indexes() -> Dict[str, Dict[str, Any]]: + """ + Get expected index states for default schema (when schema=None). + Based on Schema._initialize_defaults() and _initialize_keys(). + """ + return { + "defaults": { + "string_inverted": {"enabled": True}, + "int_inverted": {"enabled": True}, + "float_inverted": {"enabled": True}, + "bool_inverted": {"enabled": True}, + "sparse_vector": {"enabled": False}, + "fts_index": {"enabled": False}, + "vector_index": {"enabled": False}, + }, + "#document": { + "string_inverted": {"enabled": False}, + "fts_index": {"enabled": True}, + }, + "#embedding": { + "vector_index": {"enabled": True}, + }, + } + + +def _extract_expected_schema_indexes( + schema: Schema, +) -> Dict[str, Dict[str, Any]]: + """ + Extract expected index states from input schema. + Returns a dict mapping key -> index_type -> enabled/config info. + """ + expected: Dict[str, Dict[str, Any]] = {} + + # Check defaults + if schema.defaults.string and schema.defaults.string.string_inverted_index: + if "defaults" not in expected: + expected["defaults"] = {} + expected["defaults"]["string_inverted"] = { + "enabled": schema.defaults.string.string_inverted_index.enabled, + } + + if schema.defaults.int_value and schema.defaults.int_value.int_inverted_index: + if "defaults" not in expected: + expected["defaults"] = {} + expected["defaults"]["int_inverted"] = { + "enabled": schema.defaults.int_value.int_inverted_index.enabled, + } + + if schema.defaults.float_value and schema.defaults.float_value.float_inverted_index: + if "defaults" not in expected: + expected["defaults"] = {} + expected["defaults"]["float_inverted"] = { + "enabled": schema.defaults.float_value.float_inverted_index.enabled, + } + + if schema.defaults.boolean and schema.defaults.boolean.bool_inverted_index: + if "defaults" not in expected: + expected["defaults"] = {} + expected["defaults"]["bool_inverted"] = { + "enabled": schema.defaults.boolean.bool_inverted_index.enabled, + } + + if ( + schema.defaults.sparse_vector + and schema.defaults.sparse_vector.sparse_vector_index + ): + if "defaults" not in expected: + expected["defaults"] = {} + expected["defaults"]["sparse_vector"] = { + "enabled": schema.defaults.sparse_vector.sparse_vector_index.enabled, + "config": schema.defaults.sparse_vector.sparse_vector_index.config, + } + + # Check per-key indexes + for key, value_types in schema.keys.items(): + if key in (EMBEDDING_KEY, "#document"): + # Skip special keys - they're handled by vector index test + continue + + key_expected: Dict[str, Any] = {} + + if value_types.string and value_types.string.string_inverted_index: + key_expected["string_inverted"] = { + "enabled": value_types.string.string_inverted_index.enabled, + } + + if value_types.int_value and value_types.int_value.int_inverted_index: + key_expected["int_inverted"] = { + "enabled": value_types.int_value.int_inverted_index.enabled, + } + + if value_types.float_value and value_types.float_value.float_inverted_index: + key_expected["float_inverted"] = { + "enabled": value_types.float_value.float_inverted_index.enabled, + } + + if value_types.boolean and value_types.boolean.bool_inverted_index: + key_expected["bool_inverted"] = { + "enabled": value_types.boolean.bool_inverted_index.enabled, + } + + if value_types.sparse_vector and value_types.sparse_vector.sparse_vector_index: + key_expected["sparse_vector"] = { + "enabled": value_types.sparse_vector.sparse_vector_index.enabled, + "config": value_types.sparse_vector.sparse_vector_index.config, + } + + if key_expected: + expected[key] = key_expected + + return expected + + +def _assert_schema_indexes( + actual_schema: Schema, + expected_indexes: Dict[str, Dict[str, Any]], +) -> None: + """Assert that the actual schema matches expected index states.""" + + # Check defaults + if "defaults" in expected_indexes: + defaults_expected = expected_indexes["defaults"] + defaults_actual = actual_schema.defaults + + if "string_inverted" in defaults_expected: + expected_enabled = defaults_expected["string_inverted"]["enabled"] + actual_string = defaults_actual.string + if actual_string and actual_string.string_inverted_index: + assert ( + actual_string.string_inverted_index.enabled == expected_enabled + ), f"defaults string_inverted enabled mismatch: expected {expected_enabled}, got {actual_string.string_inverted_index.enabled}" + else: + # If not explicitly set, defaults should be enabled + assert expected_enabled, "defaults string_inverted should be enabled" + + if "int_inverted" in defaults_expected: + expected_enabled = defaults_expected["int_inverted"]["enabled"] + actual_int = defaults_actual.int_value + if actual_int and actual_int.int_inverted_index: + assert ( + actual_int.int_inverted_index.enabled == expected_enabled + ), f"defaults int_inverted enabled mismatch: expected {expected_enabled}, got {actual_int.int_inverted_index.enabled}" + else: + assert expected_enabled, "defaults int_inverted should be enabled" + + if "float_inverted" in defaults_expected: + expected_enabled = defaults_expected["float_inverted"]["enabled"] + actual_float = defaults_actual.float_value + if actual_float and actual_float.float_inverted_index: + assert ( + actual_float.float_inverted_index.enabled == expected_enabled + ), f"defaults float_inverted enabled mismatch: expected {expected_enabled}, got {actual_float.float_inverted_index.enabled}" + else: + assert expected_enabled, "defaults float_inverted should be enabled" + + if "bool_inverted" in defaults_expected: + expected_enabled = defaults_expected["bool_inverted"]["enabled"] + actual_bool = defaults_actual.boolean + if actual_bool and actual_bool.bool_inverted_index: + assert ( + actual_bool.bool_inverted_index.enabled == expected_enabled + ), f"defaults bool_inverted enabled mismatch: expected {expected_enabled}, got {actual_bool.bool_inverted_index.enabled}" + else: + assert expected_enabled, "defaults bool_inverted should be enabled" + + if "sparse_vector" in defaults_expected: + expected_enabled = defaults_expected["sparse_vector"]["enabled"] + actual_sparse = defaults_actual.sparse_vector + assert actual_sparse is not None, "defaults sparse_vector should exist" + assert ( + actual_sparse.sparse_vector_index is not None + ), "defaults sparse_vector_index should exist" + assert ( + actual_sparse.sparse_vector_index.enabled == expected_enabled + ), f"defaults sparse_vector enabled mismatch: expected {expected_enabled}, got {actual_sparse.sparse_vector_index.enabled}" + # Validate config fields if config is provided in expected + if "config" in defaults_expected["sparse_vector"]: + expected_config = defaults_expected["sparse_vector"]["config"] + actual_config = actual_sparse.sparse_vector_index.config + if expected_config.bm25 is not None: + assert ( + actual_config.bm25 == expected_config.bm25 + ), f"defaults sparse_vector bm25 mismatch: expected {expected_config.bm25}, got {actual_config.bm25}" + if expected_config.source_key is not None: + assert ( + actual_config.source_key == expected_config.source_key + ), f"defaults sparse_vector source_key mismatch: expected {expected_config.source_key}, got {actual_config.source_key}" + + if "fts_index" in defaults_expected: + expected_enabled = defaults_expected["fts_index"]["enabled"] + actual_string = defaults_actual.string + assert actual_string is not None, "defaults string should exist" + assert ( + actual_string.fts_index is not None + ), "defaults fts_index should exist" + assert ( + actual_string.fts_index.enabled == expected_enabled + ), f"defaults fts_index enabled mismatch: expected {expected_enabled}, got {actual_string.fts_index.enabled}" + + if "vector_index" in defaults_expected: + expected_enabled = defaults_expected["vector_index"]["enabled"] + actual_float_list = defaults_actual.float_list + assert actual_float_list is not None, "defaults float_list should exist" + assert ( + actual_float_list.vector_index is not None + ), "defaults vector_index should exist" + assert ( + actual_float_list.vector_index.enabled == expected_enabled + ), f"defaults vector_index enabled mismatch: expected {expected_enabled}, got {actual_float_list.vector_index.enabled}" + + # Check per-key indexes + for key, key_expected in expected_indexes.items(): + if key == "defaults": + continue + + assert key in actual_schema.keys, f"Expected key '{key}' not found in schema" + actual_value_types = actual_schema.keys[key] + + if "string_inverted" in key_expected: + expected_enabled = key_expected["string_inverted"]["enabled"] + actual_string = actual_value_types.string + assert actual_string is not None, f"Key '{key}' string should exist" + assert ( + actual_string.string_inverted_index is not None + ), f"Key '{key}' string_inverted_index should exist" + assert ( + actual_string.string_inverted_index.enabled == expected_enabled + ), f"Key '{key}' string_inverted enabled mismatch: expected {expected_enabled}, got {actual_string.string_inverted_index.enabled}" + + if "int_inverted" in key_expected: + expected_enabled = key_expected["int_inverted"]["enabled"] + actual_int = actual_value_types.int_value + assert actual_int is not None, f"Key '{key}' int_value should exist" + assert ( + actual_int.int_inverted_index is not None + ), f"Key '{key}' int_inverted_index should exist" + assert ( + actual_int.int_inverted_index.enabled == expected_enabled + ), f"Key '{key}' int_inverted enabled mismatch: expected {expected_enabled}, got {actual_int.int_inverted_index.enabled}" + + if "float_inverted" in key_expected: + expected_enabled = key_expected["float_inverted"]["enabled"] + actual_float = actual_value_types.float_value + assert actual_float is not None, f"Key '{key}' float_value should exist" + assert ( + actual_float.float_inverted_index is not None + ), f"Key '{key}' float_inverted_index should exist" + assert ( + actual_float.float_inverted_index.enabled == expected_enabled + ), f"Key '{key}' float_inverted enabled mismatch: expected {expected_enabled}, got {actual_float.float_inverted_index.enabled}" + + if "bool_inverted" in key_expected: + expected_enabled = key_expected["bool_inverted"]["enabled"] + actual_bool = actual_value_types.boolean + assert actual_bool is not None, f"Key '{key}' boolean should exist" + assert ( + actual_bool.bool_inverted_index is not None + ), f"Key '{key}' bool_inverted_index should exist" + assert ( + actual_bool.bool_inverted_index.enabled == expected_enabled + ), f"Key '{key}' bool_inverted enabled mismatch: expected {expected_enabled}, got {actual_bool.bool_inverted_index.enabled}" + + if "sparse_vector" in key_expected: + expected_enabled = key_expected["sparse_vector"]["enabled"] + expected_config = key_expected["sparse_vector"]["config"] + actual_sparse = actual_value_types.sparse_vector + assert actual_sparse is not None, f"Key '{key}' sparse_vector should exist" + assert ( + actual_sparse.sparse_vector_index is not None + ), f"Key '{key}' sparse_vector_index should exist" + assert ( + actual_sparse.sparse_vector_index.enabled == expected_enabled + ), f"Key '{key}' sparse_vector enabled mismatch: expected {expected_enabled}, got {actual_sparse.sparse_vector_index.enabled}" + # Validate config fields match + actual_config = actual_sparse.sparse_vector_index.config + if expected_config.bm25 is not None: + assert ( + actual_config.bm25 == expected_config.bm25 + ), f"Key '{key}' sparse_vector bm25 mismatch: expected {expected_config.bm25}, got {actual_config.bm25}" + if expected_config.source_key is not None: + assert ( + actual_config.source_key == expected_config.source_key + ), f"Key '{key}' sparse_vector source_key mismatch: expected {expected_config.source_key}, got {actual_config.source_key}" + + if "fts_index" in key_expected: + expected_enabled = key_expected["fts_index"]["enabled"] + actual_string = actual_value_types.string + assert actual_string is not None, f"Key '{key}' string should exist" + assert ( + actual_string.fts_index is not None + ), f"Key '{key}' fts_index should exist" + assert ( + actual_string.fts_index.enabled == expected_enabled + ), f"Key '{key}' fts_index enabled mismatch: expected {expected_enabled}, got {actual_string.fts_index.enabled}" + + if "vector_index" in key_expected: + expected_enabled = key_expected["vector_index"]["enabled"] + actual_float_list = actual_value_types.float_list + assert actual_float_list is not None, f"Key '{key}' float_list should exist" + assert ( + actual_float_list.vector_index is not None + ), f"Key '{key}' vector_index should exist" + assert ( + actual_float_list.vector_index.enabled == expected_enabled + ), f"Key '{key}' vector_index enabled mismatch: expected {expected_enabled}, got {actual_float_list.vector_index.enabled}" + + +@multi_region_test +@given( + name=strategies.collection_name(), + optional_fields=strategies.metadata_configuration_schema_strategy(), +) +def test_vector_index_configuration_create_collection( + client: ClientAPI, + name: str, + optional_fields: strategies.CollectionInputCombination, +) -> None: + metadata = optional_fields.metadata + configuration = optional_fields.configuration + schema = optional_fields.schema + + reset(client) + collection = client.create_collection( + name=name, + metadata=metadata, + configuration=configuration, + schema=schema, + ) + + if metadata is None: + assert collection.metadata in (None, {}) + else: + check_metadata(metadata, collection.metadata) + + coll_config = collection.configuration + spann_active = not is_spann_disabled_mode + active_key = "spann" if spann_active else "hnsw" + inactive_key = "hnsw" if spann_active else "spann" + + active_block = coll_config.get(active_key) + inactive_block = coll_config.get(inactive_key) + + assert active_block is not None, f"{active_key} configuration missing" + assert inactive_block in ( + None, + {}, + ), f"{inactive_key} configuration should be absent" + + expected = _compute_expected_config( + spann_active=spann_active, + metadata=metadata, + configuration=configuration, + schema_vector_index_config=optional_fields.schema_vector_info, + ) + + _assert_config_values(cast(Dict[str, Any], active_block), expected, spann_active) + + # Check embedding function name if one was provided + if configuration and configuration.get("embedding_function") is not None: + ef = configuration["embedding_function"] + if ef is not None: + coll_ef = coll_config.get("embedding_function") + if coll_ef is not None: + ef_config = coll_ef.get_config() + if ef_config and ef_config.get("type") == "known": + assert hasattr( + ef, "name" + ), "embedding function should have name method" + assert ef_config.get("name") == ef.name(), ( + f"embedding function name mismatch: " + f"expected {ef.name()}, got {ef_config.get('name')}" + ) + + schema_result = collection.schema + assert schema_result is not None + defaults_cfg, embedding_cfg = _extract_vector_configs_from_schema(schema_result) + + if spann_active: + assert defaults_cfg["hnsw"] is None + assert embedding_cfg["hnsw"] is None + assert defaults_cfg["spann"] is not None + assert embedding_cfg["spann"] is not None + else: + assert defaults_cfg["spann"] is None + assert embedding_cfg["spann"] is None + assert defaults_cfg["hnsw"] is not None + assert embedding_cfg["hnsw"] is not None + + _assert_schema_values(defaults_cfg, expected, spann_active) + _assert_schema_values(embedding_cfg, expected, spann_active) + + # Check embedding function name in schema if one was provided + if configuration and configuration.get("embedding_function") is not None: + ef = configuration["embedding_function"] + if ef is not None: + # Check defaults vector index + defaults_ef = schema_result.defaults.float_list.vector_index.config.embedding_function # type: ignore[union-attr] + if defaults_ef is not None and hasattr(defaults_ef, "name"): + assert defaults_ef.name() == ef.name(), ( + f"defaults embedding function name mismatch: " + f"expected {ef.name()}, got {defaults_ef.name()}" + ) + # Check embedding key vector index + embedding_ef = schema_result.keys[EMBEDDING_KEY].float_list.vector_index.config.embedding_function # type: ignore[union-attr] + if embedding_ef is not None and hasattr(embedding_ef, "name"): + assert embedding_ef.name() == ef.name(), ( + f"embedding key embedding function name mismatch: " + f"expected {ef.name()}, got {embedding_ef.name()}" + ) + + +@multi_region_test +@given( + name=strategies.collection_name(), + schema=strategies.schema_strategy(), +) +def test_schema_create_and_get_collection( + client: ClientAPI, + name: str, + schema: Optional[Schema], +) -> None: + """ + Test that schema-only components (inverted indexes, sparse vector indexes) + are correctly created and persisted when creating a collection. + """ + reset(client) + + if schema is None: + expected_indexes = _get_default_schema_indexes() + else: + expected_indexes = _extract_expected_schema_indexes(schema) + + collection = client.create_collection(name=name, schema=schema) + + # Get the returned schema + schema_result = collection.schema + assert schema_result is not None, "Schema should not be None" + + _assert_schema_indexes(schema_result, expected_indexes) + + collection = client.get_collection(name) + schema_result = collection.schema + assert schema_result is not None, "Schema should not be None" + _assert_schema_indexes(schema_result, expected_indexes) diff --git a/python/user_packages/Python313/site-packages/chromadb/test/stress/test_many_collections.py b/python/user_packages/Python313/site-packages/chromadb/test/stress/test_many_collections.py new file mode 100644 index 0000000000000000000000000000000000000000..aad219b187a8a31821721db04061a03ab1d58867 --- /dev/null +++ b/python/user_packages/Python313/site-packages/chromadb/test/stress/test_many_collections.py @@ -0,0 +1,40 @@ +from typing import List +import numpy as np + +from chromadb.api import ServerAPI +from chromadb.api.models.Collection import Collection +from chromadb.test.conftest import multi_region_test + + +@multi_region_test +def test_many_collections(client: ServerAPI) -> None: + """Test that we can create a large number of collections and that the system + # remains responsive.""" + client.reset() + + N = 10 + D = 10 + + metadata = None + if client.get_settings().is_persistent: + metadata = {"hnsw:batch_size": 3, "hnsw:sync_threshold": 3} + else: + # We only want to test persistent configurations in this way, since the main + # point is to test the file handle limit + return + + # NOTE(rescrv): 10k collections blows memory, 7.5k gives 25% headroom + num_collections = 7500 + collections: List[Collection] = [] + for i in range(num_collections): + new_collection = client.create_collection( + f"test_collection_{i}", + metadata=metadata, + ) + collections.append(new_collection) + + # Add a few embeddings to each collection + data = np.random.rand(N, D).tolist() + ids = [f"test_id_{i}" for i in range(N)] + for i in range(num_collections): + collections[i].add(ids, data) diff --git a/python/user_packages/Python313/site-packages/chromadb/test/test_api.py b/python/user_packages/Python313/site-packages/chromadb/test/test_api.py new file mode 100644 index 0000000000000000000000000000000000000000..33e931acc3dc2d59b4d27dd530da3ad05b094ab3 --- /dev/null +++ b/python/user_packages/Python313/site-packages/chromadb/test/test_api.py @@ -0,0 +1,4023 @@ +# type: ignore +import os +import shutil +import sys +import tempfile +import traceback +from datetime import datetime, timedelta +from typing import Any + +import httpx +import numpy as np +import pytest + +import chromadb +import chromadb.server.fastapi +from chromadb.api.fastapi import FastAPI +from chromadb.api.types import ( + Document, + EmbeddingFunction, + QueryResult, + TYPE_KEY, + SPARSE_VECTOR_TYPE_VALUE, +) +from chromadb.config import Settings +from chromadb.errors import ( + ChromaError, + NotFoundError, + InvalidArgumentError, +) +from chromadb.utils.embedding_functions import DefaultEmbeddingFunction + + +@pytest.fixture +def persist_dir(): + return tempfile.mkdtemp() + + +@pytest.fixture +def local_persist_api(persist_dir): + client = chromadb.Client( + Settings( + chroma_api_impl="chromadb.api.segment.SegmentAPI", + chroma_sysdb_impl="chromadb.db.impl.sqlite.SqliteDB", + chroma_producer_impl="chromadb.db.impl.sqlite.SqliteDB", + chroma_consumer_impl="chromadb.db.impl.sqlite.SqliteDB", + chroma_segment_manager_impl="chromadb.segment.impl.manager.local.LocalSegmentManager", + allow_reset=True, + is_persistent=True, + persist_directory=persist_dir, + ), + ) + yield client + client.clear_system_cache() + if os.path.exists(persist_dir): + shutil.rmtree(persist_dir, ignore_errors=True) + + +# https://docs.pytest.org/en/6.2.x/fixture.html#fixtures-can-be-requested-more-than-once-per-test-return-values-are-cached +@pytest.fixture +def local_persist_api_cache_bust(persist_dir): + client = chromadb.Client( + Settings( + chroma_api_impl="chromadb.api.segment.SegmentAPI", + chroma_sysdb_impl="chromadb.db.impl.sqlite.SqliteDB", + chroma_producer_impl="chromadb.db.impl.sqlite.SqliteDB", + chroma_consumer_impl="chromadb.db.impl.sqlite.SqliteDB", + chroma_segment_manager_impl="chromadb.segment.impl.manager.local.LocalSegmentManager", + allow_reset=True, + is_persistent=True, + persist_directory=persist_dir, + ), + ) + yield client + client.clear_system_cache() + if os.path.exists(persist_dir): + shutil.rmtree(persist_dir, ignore_errors=True) + + +def approx_equal(a, b, tolerance=1e-6) -> bool: + return abs(a - b) < tolerance + + +def vector_approx_equal(a, b, tolerance: float = 1e-6) -> bool: + if len(a) != len(b): + return False + return all([approx_equal(a, b, tolerance) for a, b in zip(a, b)]) + + +@pytest.mark.parametrize("api_fixture", [local_persist_api]) +def test_persist_index_loading(api_fixture, request): + client = request.getfixturevalue("local_persist_api") + client.reset() + collection = client.create_collection("test") + collection.add(ids="id1", documents="hello") + + api2 = request.getfixturevalue("local_persist_api_cache_bust") + collection = api2.get_collection("test") + + includes = ["embeddings", "documents", "metadatas", "distances"] + nn = collection.query( + query_texts="hello", + n_results=1, + include=["embeddings", "documents", "metadatas", "distances"], + ) + for key in nn.keys(): + if (key in includes) or (key == "ids"): + assert len(nn[key]) == 1 + elif key == "included": + assert set(nn[key]) == set(includes) + else: + assert nn[key] is None + + +@pytest.mark.parametrize("api_fixture", [local_persist_api]) +def test_persist_index_loading_embedding_function(api_fixture, request): + class TestEF(EmbeddingFunction[Document]): + def __call__(self, input): + return [np.array([1, 2, 3]) for _ in range(len(input))] + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + def name(self) -> str: + return "test" + + def build_from_config(self, config: dict[str, Any]) -> None: + pass + + def get_config(self) -> dict[str, Any]: + return {} + + client = request.getfixturevalue("local_persist_api") + client.reset() + collection = client.create_collection("test", embedding_function=TestEF()) + collection.add(ids="id1", documents="hello") + + client2 = request.getfixturevalue("local_persist_api_cache_bust") + collection = client2.get_collection("test", embedding_function=TestEF()) + + includes = ["embeddings", "documents", "metadatas", "distances"] + nn = collection.query( + query_texts="hello", + n_results=1, + include=includes, + ) + for key in nn.keys(): + if (key in includes) or (key == "ids"): + assert len(nn[key]) == 1 + elif key == "included": + assert set(nn[key]) == set(includes) + else: + assert nn[key] is None + + +@pytest.mark.parametrize("api_fixture", [local_persist_api]) +def test_persist_index_get_or_create_embedding_function(api_fixture, request): + class TestEF(EmbeddingFunction[Document]): + def __call__(self, input): + return [np.array([1, 2, 3]) for _ in range(len(input))] + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + def name(self) -> str: + return "test" + + def build_from_config(self, config: dict[str, Any]) -> None: + pass + + def get_config(self) -> dict[str, Any]: + return {} + + api = request.getfixturevalue("local_persist_api") + api.reset() + collection = api.get_or_create_collection("test", embedding_function=TestEF()) + collection.add(ids="id1", documents="hello") + + api2 = request.getfixturevalue("local_persist_api_cache_bust") + collection = api2.get_or_create_collection("test", embedding_function=TestEF()) + + includes = ["embeddings", "documents", "metadatas", "distances"] + nn = collection.query( + query_texts="hello", + n_results=1, + include=includes, + ) + + for key in nn.keys(): + if (key in includes) or (key == "ids"): + assert len(nn[key]) == 1 + elif key == "included": + assert set(nn[key]) == set(includes) + else: + assert nn[key] is None + + assert nn["ids"] == [["id1"]] + assert nn["embeddings"][0][0].tolist() == [1, 2, 3] + assert nn["documents"] == [["hello"]] + assert nn["distances"] == [[0]] + + +@pytest.mark.parametrize("api_fixture", [local_persist_api]) +def test_persist(api_fixture, request): + client = request.getfixturevalue(api_fixture.__name__) + + client.reset() + + collection = client.create_collection("testspace") + + collection.add(**batch_records) + + assert collection.count() == 2 + + client = request.getfixturevalue(api_fixture.__name__) + collection = client.get_collection("testspace") + assert collection.count() == 2 + + client.delete_collection("testspace") + + client = request.getfixturevalue(api_fixture.__name__) + assert client.list_collections() == [] + + +def test_heartbeat(client): + heartbeat_ns = client.heartbeat() + assert isinstance(heartbeat_ns, int) + + heartbeat_s = heartbeat_ns // 10**9 + heartbeat = datetime.fromtimestamp(heartbeat_s) + assert heartbeat > datetime.now() - timedelta(seconds=10) + + +def test_max_batch_size(client): + batch_size = client.get_max_batch_size() + assert batch_size > 0 + + +def test_supports_base64_encoding(client): + if not isinstance(client, FastAPI): + pytest.skip("Not a FastAPI instance") + + client.reset() + + supports_base64_encoding = client.supports_base64_encoding() + assert supports_base64_encoding is True + + +def test_supports_base64_encoding_legacy(client): + if not isinstance(client, FastAPI): + pytest.skip("Not a FastAPI instance") + + client.reset() + + # legacy server does not give back supports_base64_encoding + client.pre_flight_checks = { + "max_batch_size": 100, + } + + assert client.supports_base64_encoding() is False + assert client.get_max_batch_size() == 100 + + +def test_pre_flight_checks(client): + if not isinstance(client, FastAPI): + pytest.skip("Not a FastAPI instance") + + resp = httpx.get(f"{client._api_url}/pre-flight-checks") + assert resp.status_code == 200 + assert resp.json() is not None + assert "max_batch_size" in resp.json().keys() + assert "supports_base64_encoding" in resp.json().keys() + + +batch_records = { + "embeddings": [[1.1, 2.3, 3.2], [1.2, 2.24, 3.2]], + "ids": ["https://example.com/1", "https://example.com/2"], +} + + +def test_add(client): + client.reset() + + collection = client.create_collection("testspace") + + collection.add(**batch_records) + + assert collection.count() == 2 + + +def test_collection_add_with_invalid_collection_throws(client): + client.reset() + collection = client.create_collection("test") + client.delete_collection("test") + + with pytest.raises(NotFoundError, match=r"Collection .* does not exist"): + collection.add(**batch_records) + + +def test_get_or_create(client): + client.reset() + + collection = client.create_collection("testspace") + + collection.add(**batch_records) + + assert collection.count() == 2 + + with pytest.raises(Exception): + collection = client.create_collection("testspace") + + collection = client.get_or_create_collection("testspace") + + assert collection.count() == 2 + + +minimal_records = { + "embeddings": [[1.1, 2.3, 3.2], [1.2, 2.24, 3.2]], + "ids": ["https://example.com/1", "https://example.com/2"], +} + + +def test_add_minimal(client): + client.reset() + + collection = client.create_collection("testspace") + + collection.add(**minimal_records) + + assert collection.count() == 2 + + +def test_get_from_db(client): + client.reset() + collection = client.create_collection("testspace") + collection.add(**batch_records) + includes = ["embeddings", "documents", "metadatas"] + records = collection.get(include=includes) + for key in records.keys(): + if (key in includes) or (key == "ids"): + assert len(records[key]) == 2 + elif key == "included": + assert set(records[key]) == set(includes) + else: + assert records[key] is None + + +def test_collection_get_with_invalid_collection_throws(client): + client.reset() + collection = client.create_collection("test") + client.delete_collection("test") + + with pytest.raises(NotFoundError, match=r"Collection .* does not exist"): + collection.get() + + +def test_reset_db(client): + client.reset() + + collection = client.create_collection("testspace") + collection.add(**batch_records) + assert collection.count() == 2 + + client.reset() + assert len(client.list_collections()) == 0 + + +def test_get_nearest_neighbors(client): + client.reset() + collection = client.create_collection("testspace") + collection.add(**batch_records) + + includes = ["embeddings", "documents", "metadatas", "distances"] + nn = collection.query( + query_embeddings=[1.1, 2.3, 3.2], + n_results=1, + include=includes, + ) + for key in nn.keys(): + if (key in includes) or (key == "ids"): + assert len(nn[key]) == 1 + elif key == "included": + assert set(nn[key]) == set(includes) + else: + assert nn[key] is None + + nn = collection.query( + query_embeddings=[[1.1, 2.3, 3.2]], + n_results=1, + include=includes, + ) + for key in nn.keys(): + if (key in includes) or (key == "ids"): + assert len(nn[key]) == 1 + elif key == "included": + assert set(nn[key]) == set(includes) + else: + assert nn[key] is None + + nn = collection.query( + query_embeddings=[[1.1, 2.3, 3.2], [0.1, 2.3, 4.5]], + n_results=1, + include=includes, + ) + for key in nn.keys(): + if (key in includes) or (key == "ids"): + assert len(nn[key]) == 2 + elif key == "included": + assert set(nn[key]) == set(includes) + else: + assert nn[key] is None + + +def test_delete(client): + client.reset() + collection = client.create_collection("testspace") + collection.add(**batch_records) + assert collection.count() == 2 + + with pytest.raises(Exception): + collection.delete() + + +def test_delete_returns_delete_result(client): + client.reset() + collection = client.create_collection("testspace") + collection.add(**batch_records) + assert collection.count() == 2 + result = collection.delete(ids=batch_records["ids"]) + assert isinstance(result, dict) + assert "deleted" in result + assert result["deleted"] >= 0 + + +def test_delete_with_limit(client): + client.reset() + collection = client.create_collection( + "testspace", + metadata={"hnsw:space": "l2"}, + ) + collection.add( + ids=["id1", "id2", "id3", "id4", "id5"], + embeddings=[[1, 0, 0], [0, 1, 0], [0, 0, 1], [1, 1, 0], [0, 1, 1]], + metadatas=[ + {"category": "a"}, + {"category": "a"}, + {"category": "a"}, + {"category": "b"}, + {"category": "b"}, + ], + ) + assert collection.count() == 5 + + # Delete at most 2 records matching category=a (there are 3 total) + result = collection.delete(where={"category": "a"}, limit=2) + assert result["deleted"] == 2 + assert collection.count() == 3 + + +def test_delete_with_limit_zero_is_noop(client): + client.reset() + collection = client.create_collection( + "testspace", + metadata={"hnsw:space": "l2"}, + ) + collection.add( + ids=["id1", "id2"], + embeddings=[[1, 0, 0], [0, 1, 0]], + metadatas=[{"category": "a"}, {"category": "a"}], + ) + assert collection.count() == 2 + result = collection.delete(where={"category": "a"}, limit=0) + assert result["deleted"] == 0 + assert collection.count() == 2 + + +def test_delete_with_limit_requires_where(client): + client.reset() + collection = client.create_collection("testspace") + collection.add(**batch_records) + with pytest.raises(ValueError, match="limit can only be specified"): + collection.delete(ids=["id1"], limit=5) + + +def test_delete_with_index(client): + client.reset() + collection = client.create_collection("testspace") + collection.add(**batch_records) + assert collection.count() == 2 + collection.query(query_embeddings=[[1.1, 2.3, 3.2]], n_results=1) + + +def test_collection_delete_with_invalid_collection_throws(client): + client.reset() + collection = client.create_collection("test") + client.delete_collection("test") + + with pytest.raises(NotFoundError, match=r"Collection .* does not exist"): + collection.delete(ids=["id1"]) + + +def test_count(client): + client.reset() + collection = client.create_collection("testspace") + assert collection.count() == 0 + collection.add(**batch_records) + assert collection.count() == 2 + + +def test_collection_count_with_invalid_collection_throws(client): + client.reset() + collection = client.create_collection("test") + client.delete_collection("test") + + with pytest.raises(NotFoundError, match=r"Collection .* does not exist"): + collection.count() + + +def test_modify(client): + client.reset() + collection = client.create_collection("testspace") + collection.modify(name="testspace2") + + # collection name is modify + assert collection.name == "testspace2" + + +def test_collection_modify_with_invalid_collection_throws(client): + client.reset() + collection = client.create_collection("test") + client.delete_collection("test") + + with pytest.raises(NotFoundError, match=r"Collection .* does not exist"): + collection.modify(name="test2") + + +def test_modify_error_on_existing_name(client): + client.reset() + + client.create_collection("testspace") + c2 = client.create_collection("testspace2") + + with pytest.raises(Exception): + c2.modify(name="testspace") + + +def test_modify_warn_on_DF_change(client, caplog): + client.reset() + + collection = client.create_collection("testspace") + + with pytest.raises(Exception, match="not supported"): + collection.modify(metadata={"hnsw:space": "cosine"}) + + +def test_metadata_cru(client): + client.reset() + metadata_a = {"a": 1, "b": 2} + # Test create metadata + collection = client.create_collection("testspace", metadata=metadata_a) + assert collection.metadata is not None + assert collection.metadata["a"] == 1 + assert collection.metadata["b"] == 2 + + # Test get metadata + collection = client.get_collection("testspace") + assert collection.metadata is not None + assert collection.metadata["a"] == 1 + assert collection.metadata["b"] == 2 + + # Test modify metadata + collection.modify(metadata={"a": 2, "c": 3}) + assert collection.metadata["a"] == 2 + assert collection.metadata["c"] == 3 + assert "b" not in collection.metadata + + # Test get after modify metadata + collection = client.get_collection("testspace") + assert collection.metadata is not None + assert collection.metadata["a"] == 2 + assert collection.metadata["c"] == 3 + assert "b" not in collection.metadata + + # Test name exists get_or_create_metadata + collection = client.get_or_create_collection("testspace") + assert collection.metadata is not None + assert collection.metadata["a"] == 2 + assert collection.metadata["c"] == 3 + + # Test name exists create metadata + collection = client.get_or_create_collection("testspace2") + assert collection.metadata is None + + # Test list collections + collections = client.list_collections() + for collection in collections: + if collection.name == "testspace": + assert collection.metadata is not None + assert collection.metadata["a"] == 2 + assert collection.metadata["c"] == 3 + elif collection.name == "testspace2": + assert collection.metadata is None + + +def test_increment_index_on(client): + client.reset() + collection = client.create_collection("testspace") + collection.add(**batch_records) + assert collection.count() == 2 + + includes = ["embeddings", "documents", "metadatas", "distances"] + # increment index + nn = collection.query( + query_embeddings=[[1.1, 2.3, 3.2]], + n_results=1, + include=includes, + ) + for key in nn.keys(): + if (key in includes) or (key == "ids"): + assert len(nn[key]) == 1 + elif key == "included": + assert set(nn[key]) == set(includes) + else: + assert nn[key] is None + + +def test_add_a_collection(client): + client.reset() + client.create_collection("testspace") + + # get collection does not throw an error + collection = client.get_collection("testspace") + assert collection.name == "testspace" + + # get collection should throw an error if collection does not exist + with pytest.raises(Exception): + collection = client.get_collection("testspace2") + + +def test_get_collection_by_id(client): + import uuid + + client.reset() + collection = client.create_collection("testspace", metadata={"key": "value"}) + collection_id = collection.id + + retrieved = client.get_collection_by_id(collection_id) + assert retrieved.name == "testspace" + assert retrieved.id == collection_id + assert retrieved.metadata == {"key": "value"} + + with pytest.raises(NotFoundError): + client.get_collection_by_id(uuid.uuid4()) + + +def test_error_includes_trace_id(http_client): + http_client.reset() + + with pytest.raises(ChromaError) as error: + http_client.get_collection("testspace2") + + assert error.value.trace_id is not None + + +def test_list_collections(client): + client.reset() + client.create_collection("testspace") + client.create_collection("testspace2") + + # get collection does not throw an error + collections = client.list_collections() + assert len(collections) == 2 + + +def test_reset(client): + client.reset() + client.create_collection("testspace") + client.create_collection("testspace2") + + # get collection does not throw an error + collections = client.list_collections() + assert len(collections) == 2 + + client.reset() + collections = client.list_collections() + assert len(collections) == 0 + + +def test_peek(client): + client.reset() + collection = client.create_collection("testspace") + collection.add(**batch_records) + assert collection.count() == 2 + + # peek + peek = collection.peek() + print(peek) + for key in peek.keys(): + if key in ["embeddings", "documents", "metadatas"] or key == "ids": + assert len(peek[key]) == 2 + elif key == "included": + assert set(peek[key]) == set(["embeddings", "metadatas", "documents"]) + else: + assert peek[key] is None + + +def test_collection_peek_with_invalid_collection_throws(client): + client.reset() + collection = client.create_collection("test") + client.delete_collection("test") + + with pytest.raises(NotFoundError, match=r"Collection .* does not exist"): + collection.peek() + + +def test_collection_query_with_invalid_collection_throws(client): + client.reset() + collection = client.create_collection("test") + client.delete_collection("test") + + with pytest.raises(NotFoundError, match=r"Collection .* does not exist"): + collection.query(query_texts=["test"]) + + +def test_collection_update_with_invalid_collection_throws(client): + client.reset() + collection = client.create_collection("test") + client.delete_collection("test") + + with pytest.raises(NotFoundError, match=r"Collection .* does not exist"): + collection.update(ids=["id1"], documents=["test"]) + + +# TEST METADATA AND METADATA FILTERING +# region + +metadata_records = { + "embeddings": [[1.1, 2.3, 3.2], [1.2, 2.24, 3.2]], + "ids": ["id1", "id2"], + "metadatas": [ + {"int_value": 1, "string_value": "one", "float_value": 1.001}, + {"int_value": 2}, + ], +} + + +def test_metadata_add_get_int_float(client): + client.reset() + collection = client.create_collection("test_int") + collection.add(**metadata_records) + + items = collection.get(ids=["id1", "id2"]) + assert items["metadatas"][0]["int_value"] == 1 + assert items["metadatas"][0]["float_value"] == 1.001 + assert items["metadatas"][1]["int_value"] == 2 + assert isinstance(items["metadatas"][0]["int_value"], int) + assert isinstance(items["metadatas"][0]["float_value"], float) + + +def test_metadata_add_query_int_float(client): + client.reset() + collection = client.create_collection("test_int") + collection.add(**metadata_records) + + items: QueryResult = collection.query( + query_embeddings=[[1.1, 2.3, 3.2]], n_results=1 + ) + assert items["metadatas"] is not None + assert items["metadatas"][0][0]["int_value"] == 1 + assert items["metadatas"][0][0]["float_value"] == 1.001 + assert isinstance(items["metadatas"][0][0]["int_value"], int) + assert isinstance(items["metadatas"][0][0]["float_value"], float) + + +def test_metadata_get_where_string(client): + client.reset() + collection = client.create_collection("test_int") + collection.add(**metadata_records) + + items = collection.get(where={"string_value": "one"}) + assert items["metadatas"][0]["int_value"] == 1 + assert items["metadatas"][0]["string_value"] == "one" + + +def test_metadata_get_where_int(client): + client.reset() + collection = client.create_collection("test_int") + collection.add(**metadata_records) + + items = collection.get(where={"int_value": 1}) + assert items["metadatas"][0]["int_value"] == 1 + assert items["metadatas"][0]["string_value"] == "one" + + +def test_metadata_get_where_float(client): + client.reset() + collection = client.create_collection("test_int") + collection.add(**metadata_records) + + items = collection.get(where={"float_value": 1.001}) + assert items["metadatas"][0]["int_value"] == 1 + assert items["metadatas"][0]["string_value"] == "one" + assert items["metadatas"][0]["float_value"] == 1.001 + + +def test_metadata_update_get_int_float(client): + client.reset() + collection = client.create_collection("test_int") + collection.add(**metadata_records) + + collection.update( + ids=["id1"], + metadatas=[{"int_value": 2, "string_value": "two", "float_value": 2.002}], + ) + items = collection.get(ids=["id1"]) + assert items["metadatas"][0]["int_value"] == 2 + assert items["metadatas"][0]["string_value"] == "two" + assert items["metadatas"][0]["float_value"] == 2.002 + + +bad_metadata_records = { + "embeddings": [[1.1, 2.3, 3.2], [1.2, 2.24, 3.2]], + "ids": ["id1", "id2"], + "metadatas": [{"value": {"nested": "5"}}, {"value": [1, 2, 3]}], +} + + +def test_metadata_validation_add(client): + client.reset() + collection = client.create_collection("test_metadata_validation") + with pytest.raises(ValueError, match="metadata"): + collection.add(**bad_metadata_records) + + +def test_metadata_validation_update(client): + client.reset() + collection = client.create_collection("test_metadata_validation") + collection.add(**metadata_records) + with pytest.raises(ValueError, match="metadata"): + collection.update(ids=["id1"], metadatas={"value": {"nested": "5"}}) + + +def test_where_validation_get(client): + client.reset() + collection = client.create_collection("test_where_validation") + with pytest.raises(ValueError, match="where"): + collection.get(where={"value": {"nested": "5"}}) + + +def test_where_validation_query(client): + client.reset() + collection = client.create_collection("test_where_validation") + with pytest.raises(ValueError, match="where"): + collection.query(query_embeddings=[0, 0, 0], where={"value": {"nested": "5"}}) + + +operator_records = { + "embeddings": [[1.1, 2.3, 3.2], [1.2, 2.24, 3.2]], + "ids": ["id1", "id2"], + "metadatas": [ + {"int_value": 1, "string_value": "one", "float_value": 1.001}, + {"int_value": 2, "float_value": 2.002, "string_value": "two"}, + ], +} + + +def test_where_lt(client): + client.reset() + collection = client.create_collection("test_where_lt") + collection.add(**operator_records) + items = collection.get(where={"int_value": {"$lt": 2}}) + assert len(items["metadatas"]) == 1 + + +def test_where_lte(client): + client.reset() + collection = client.create_collection("test_where_lte") + collection.add(**operator_records) + items = collection.get(where={"int_value": {"$lte": 2.0}}) + assert len(items["metadatas"]) == 2 + + +def test_where_gt(client): + client.reset() + collection = client.create_collection("test_where_lte") + collection.add(**operator_records) + items = collection.get(where={"float_value": {"$gt": -1.4}}) + assert len(items["metadatas"]) == 2 + + +def test_where_gte(client): + client.reset() + collection = client.create_collection("test_where_lte") + collection.add(**operator_records) + items = collection.get(where={"float_value": {"$gte": 2.002}}) + assert len(items["metadatas"]) == 1 + + +def test_where_ne_string(client): + client.reset() + collection = client.create_collection("test_where_lte") + collection.add(**operator_records) + items = collection.get(where={"string_value": {"$ne": "two"}}) + assert len(items["metadatas"]) == 1 + + +def test_where_ne_eq_number(client): + client.reset() + collection = client.create_collection("test_where_lte") + collection.add(**operator_records) + items = collection.get(where={"int_value": {"$ne": 1}}) + assert len(items["metadatas"]) == 1 + items = collection.get(where={"float_value": {"$eq": 2.002}}) + assert len(items["metadatas"]) == 1 + + +def test_where_valid_operators(client): + client.reset() + collection = client.create_collection("test_where_valid_operators") + collection.add(**operator_records) + with pytest.raises(ValueError): + collection.get(where={"int_value": {"$invalid": 2}}) + + with pytest.raises(ValueError): + collection.get(where={"int_value": {"$lt": "2"}}) + + with pytest.raises(ValueError): + collection.get(where={"int_value": {"$lt": 2, "$gt": 1}}) + + # Test invalid $and, $or + with pytest.raises(ValueError): + collection.get(where={"$and": {"int_value": {"$lt": 2}}}) + + with pytest.raises(ValueError): + collection.get( + where={"int_value": {"$lt": 2}, "$or": {"int_value": {"$gt": 1}}} + ) + + with pytest.raises(ValueError): + collection.get( + where={"$gt": [{"int_value": {"$lt": 2}}, {"int_value": {"$gt": 1}}]} + ) + + with pytest.raises(ValueError): + collection.get(where={"$or": [{"int_value": {"$lt": 2}}]}) + + with pytest.raises(ValueError): + collection.get(where={"$or": []}) + + # $contains on a metadata key is now valid (array contains). + # But a bare $contains at the top level (no field key) is still invalid. + with pytest.raises(ValueError): + collection.get(where={"$contains": "test"}) + + +# TODO: Define the dimensionality of these embeddingds in terms of the default record +bad_dimensionality_records = { + "embeddings": [[1.1, 2.3, 3.2, 4.5], [1.2, 2.24, 3.2, 4.5]], + "ids": ["id1", "id2"], +} + +bad_dimensionality_query = { + "query_embeddings": [[1.1, 2.3, 3.2, 4.5], [1.2, 2.24, 3.2, 4.5]], +} + +bad_number_of_results_query = { + "query_embeddings": [[1.1, 2.3, 3.2], [1.2, 2.24, 3.2]], + "n_results": 100, +} + + +def test_dimensionality_validation_add(client): + client.reset() + collection = client.create_collection("test_dimensionality_validation") + collection.add(**minimal_records) + + with pytest.raises(Exception) as e: + collection.add(**bad_dimensionality_records) + assert "dimension" in str(e.value) + + +def test_dimensionality_validation_query(client): + client.reset() + collection = client.create_collection("test_dimensionality_validation_query") + collection.add(**minimal_records) + + with pytest.raises(Exception) as e: + collection.query(**bad_dimensionality_query) + assert "dimension" in str(e.value) + + +def test_query_document_valid_operators(client): + client.reset() + collection = client.create_collection("test_where_valid_operators") + collection.add(**operator_records) + with pytest.raises(ValueError, match="where document"): + collection.get(where_document={"$lt": {"$nested": 2}}) + + with pytest.raises(ValueError, match="where document"): + collection.query(query_embeddings=[0, 0, 0], where_document={"$contains": 2}) + + with pytest.raises(ValueError, match="where document"): + collection.get(where_document={"$contains": []}) + + # Test invalid $contains + with pytest.raises(ValueError, match="where document"): + collection.get(where_document={"$contains": {"text": "hello"}}) + + # Test invalid $not_contains + with pytest.raises(ValueError, match="where document"): + collection.get(where_document={"$not_contains": {"text": "hello"}}) + + # Test invalid $and, $or + with pytest.raises(ValueError): + collection.get(where_document={"$and": {"$unsupported": "doc"}}) + + with pytest.raises(ValueError): + collection.get( + where_document={"$or": [{"$unsupported": "doc"}, {"$unsupported": "doc"}]} + ) + + with pytest.raises(ValueError): + collection.get(where_document={"$or": [{"$contains": "doc"}]}) + + with pytest.raises(ValueError): + collection.get(where_document={"$or": []}) + + with pytest.raises(ValueError): + collection.get( + where_document={ + "$or": [{"$and": [{"$contains": "doc"}]}, {"$contains": "doc"}] + } + ) + + +contains_records = { + "embeddings": [[1.1, 2.3, 3.2], [1.2, 2.24, 3.2]], + "documents": ["this is doc1 and it's great!", "doc2 is also great!"], + "ids": ["id1", "id2"], + "metadatas": [ + {"int_value": 1, "string_value": "one", "float_value": 1.001}, + {"int_value": 2, "float_value": 2.002, "string_value": "two"}, + ], +} + + +def test_get_where_document(client): + client.reset() + collection = client.create_collection("test_get_where_document") + collection.add(**contains_records) + + items = collection.get(where_document={"$contains": "doc1"}) + assert len(items["metadatas"]) == 1 + + items = collection.get(where_document={"$contains": "great"}) + assert len(items["metadatas"]) == 2 + + items = collection.get(where_document={"$contains": "bad"}) + assert len(items["metadatas"]) == 0 + + +def test_query_where_document(client): + client.reset() + collection = client.create_collection("test_query_where_document") + collection.add(**contains_records) + + items = collection.query( + query_embeddings=[1, 0, 0], where_document={"$contains": "doc1"}, n_results=1 + ) + assert len(items["metadatas"][0]) == 1 + + items = collection.query( + query_embeddings=[0, 0, 0], where_document={"$contains": "great"}, n_results=2 + ) + assert len(items["metadatas"][0]) == 2 + + with pytest.raises(Exception) as e: + items = collection.query( + query_embeddings=[0, 0, 0], where_document={"$contains": "bad"}, n_results=1 + ) + assert "datapoints" in str(e.value) + + +def test_delete_where_document(client): + client.reset() + collection = client.create_collection("test_delete_where_document") + collection.add(**contains_records) + + collection.delete(where_document={"$contains": "doc1"}) + assert collection.count() == 1 + + collection.delete(where_document={"$contains": "bad"}) + assert collection.count() == 1 + + collection.delete(where_document={"$contains": "great"}) + assert collection.count() == 0 + + +logical_operator_records = { + "embeddings": [ + [1.1, 2.3, 3.2], + [1.2, 2.24, 3.2], + [1.3, 2.25, 3.2], + [1.4, 2.26, 3.2], + ], + "ids": ["id1", "id2", "id3", "id4"], + "metadatas": [ + {"int_value": 1, "string_value": "one", "float_value": 1.001, "is": "doc"}, + {"int_value": 2, "float_value": 2.002, "string_value": "two", "is": "doc"}, + {"int_value": 3, "float_value": 3.003, "string_value": "three", "is": "doc"}, + {"int_value": 4, "float_value": 4.004, "string_value": "four", "is": "doc"}, + ], + "documents": [ + "this document is first and great", + "this document is second and great", + "this document is third and great", + "this document is fourth and great", + ], +} + + +def test_where_logical_operators(client): + client.reset() + collection = client.create_collection("test_logical_operators") + collection.add(**logical_operator_records) + + items = collection.get( + where={ + "$and": [ + {"$or": [{"int_value": {"$gte": 3}}, {"float_value": {"$lt": 1.9}}]}, + {"is": "doc"}, + ] + } + ) + assert len(items["metadatas"]) == 3 + + items = collection.get( + where={ + "$or": [ + { + "$and": [ + {"int_value": {"$eq": 3}}, + {"string_value": {"$eq": "three"}}, + ] + }, + { + "$and": [ + {"int_value": {"$eq": 4}}, + {"string_value": {"$eq": "four"}}, + ] + }, + ] + } + ) + assert len(items["metadatas"]) == 2 + + items = collection.get( + where={ + "$and": [ + { + "$or": [ + {"int_value": {"$eq": 1}}, + {"string_value": {"$eq": "two"}}, + ] + }, + { + "$or": [ + {"int_value": {"$eq": 2}}, + {"string_value": {"$eq": "one"}}, + ] + }, + ] + } + ) + assert len(items["metadatas"]) == 2 + + +def test_where_document_logical_operators(client): + client.reset() + collection = client.create_collection("test_document_logical_operators") + collection.add(**logical_operator_records) + + items = collection.get( + where_document={ + "$and": [ + {"$contains": "first"}, + {"$contains": "doc"}, + ] + } + ) + assert len(items["metadatas"]) == 1 + + items = collection.get( + where_document={ + "$or": [ + {"$contains": "first"}, + {"$contains": "second"}, + ] + } + ) + assert len(items["metadatas"]) == 2 + + items = collection.get( + where_document={ + "$or": [ + {"$contains": "first"}, + {"$contains": "second"}, + ] + }, + where={ + "int_value": {"$ne": 2}, + }, + ) + assert len(items["metadatas"]) == 1 + + +# endregion + +records = { + "embeddings": [[0, 0, 0], [1.2, 2.24, 3.2]], + "ids": ["id1", "id2"], + "metadatas": [ + {"int_value": 1, "string_value": "one", "float_value": 1.001}, + {"int_value": 2}, + ], + "documents": ["this document is first", "this document is second"], +} + + +def test_query_include(client): + client.reset() + collection = client.create_collection("test_query_include") + collection.add(**records) + + include = ["metadatas", "documents", "distances"] + items = collection.query( + query_embeddings=[0, 0, 0], + include=include, + n_results=1, + ) + assert items["embeddings"] is None + assert items["ids"][0][0] == "id1" + assert items["metadatas"][0][0]["int_value"] == 1 + assert set(items["included"]) == set(include) + + include = ["embeddings", "documents", "distances"] + items = collection.query( + query_embeddings=[0, 0, 0], + include=include, + n_results=1, + ) + assert items["metadatas"] is None + assert items["ids"][0][0] == "id1" + assert set(items["included"]) == set(include) + + items = collection.query( + query_embeddings=[[0, 0, 0], [1, 2, 1.2]], + include=[], + n_results=2, + ) + assert items["documents"] is None + assert items["metadatas"] is None + assert items["embeddings"] is None + assert items["distances"] is None + assert items["ids"][0][0] == "id1" + assert items["ids"][0][1] == "id2" + + +def test_get_include(client): + client.reset() + collection = client.create_collection("test_get_include") + collection.add(**records) + + include = ["metadatas", "documents"] + items = collection.get(include=include, where={"int_value": 1}) + assert items["embeddings"] is None + assert items["ids"][0] == "id1" + assert items["metadatas"][0]["int_value"] == 1 + assert items["documents"][0] == "this document is first" + assert set(items["included"]) == set(include) + + include = ["embeddings", "documents"] + items = collection.get(include=include) + assert items["metadatas"] is None + assert items["ids"][0] == "id1" + assert approx_equal(items["embeddings"][1][0], 1.2) + assert set(items["included"]) == set(include) + + items = collection.get(include=[]) + assert items["documents"] is None + assert items["metadatas"] is None + assert items["embeddings"] is None + assert items["ids"][0] == "id1" + assert items["included"] == [] + + with pytest.raises(ValueError, match="include"): + items = collection.get(include=["metadatas", "undefined"]) + + with pytest.raises(ValueError, match="include"): + items = collection.get(include=None) + + +# make sure query results are returned in the right order + + +def test_query_order(client): + client.reset() + collection = client.create_collection("test_query_order") + collection.add(**records) + + items = collection.query( + query_embeddings=[1.2, 2.24, 3.2], + include=["metadatas", "documents", "distances"], + n_results=2, + ) + + assert items["documents"][0][0] == "this document is second" + assert items["documents"][0][1] == "this document is first" + + +# test to make sure add, get, delete error on invalid id input + + +def test_invalid_id(client): + client.reset() + collection = client.create_collection("test_invalid_id") + # Add with non-string id + with pytest.raises(ValueError) as e: + collection.add(embeddings=[0, 0, 0], ids=[1], metadatas=[{}]) + assert "ID" in str(e.value) + + # Get with non-list id + with pytest.raises(ValueError) as e: + collection.get(ids=1) + assert "ID" in str(e.value) + + # Delete with malformed ids + with pytest.raises(ValueError) as e: + collection.delete(ids=["valid", 0]) + assert "ID" in str(e.value) + + +def test_index_params(client): + EPS = 1e-12 + # first standard add + client.reset() + collection = client.create_collection(name="test_index_params") + collection.add(**records) + items = collection.query( + query_embeddings=[0.6, 1.12, 1.6], + n_results=1, + ) + assert items["distances"][0][0] > 4 + + # cosine + client.reset() + collection = client.create_collection( + name="test_index_params", + metadata={"hnsw:space": "cosine", "hnsw:construction_ef": 20, "hnsw:M": 5}, + ) + collection.add(**records) + items = collection.query( + query_embeddings=[0.6, 1.12, 1.6], + n_results=1, + ) + assert items["distances"][0][0] > 0 - EPS + assert items["distances"][0][0] < 1 + EPS + + # ip + client.reset() + collection = client.create_collection( + name="test_index_params", metadata={"hnsw:space": "ip"} + ) + collection.add(**records) + items = collection.query( + query_embeddings=[0.6, 1.12, 1.6], + n_results=1, + ) + assert items["distances"][0][0] < -5 + + +def test_invalid_index_params(client): + client.reset() + + with pytest.raises(InvalidArgumentError): + collection = client.create_collection( + name="test_index_params", metadata={"hnsw:space": "foobar"} + ) + collection.add(**records) + + +def test_persist_index_loading_params(client, request): + client = request.getfixturevalue("local_persist_api") + client.reset() + collection = client.create_collection( + "test", + metadata={"hnsw:space": "ip"}, + ) + collection.add(ids="id1", documents="hello") + + api2 = request.getfixturevalue("local_persist_api_cache_bust") + collection = api2.get_collection( + "test", + ) + + assert collection.metadata["hnsw:space"] == "ip" + includes = ["embeddings", "documents", "metadatas", "distances"] + nn = collection.query( + query_texts="hello", + n_results=1, + include=includes, + ) + for key in nn.keys(): + if (key in includes) or (key == "ids"): + assert len(nn[key]) == 1 + elif key == "included": + assert set(nn[key]) == set(includes) + else: + assert nn[key] is None + + +def test_add_large(client): + client.reset() + + collection = client.create_collection("testspace") + + # Test adding a large number of records + large_records = np.random.rand(2000, 512).astype(np.float32).tolist() + + collection.add( + embeddings=large_records, + ids=[f"http://example.com/{i}" for i in range(len(large_records))], + ) + + assert collection.count() == len(large_records) + + +# test get_version +def test_get_version(client): + client.reset() + version = client.get_version() + + # assert version matches the pattern x.y.z + import re + + assert re.match(r"\d+\.\d+\.\d+", version) + + +# test delete_collection +def test_delete_collection(client): + client.reset() + collection = client.create_collection("test_delete_collection") + collection.add(**records) + + assert len(client.list_collections()) == 1 + client.delete_collection("test_delete_collection") + assert len(client.list_collections()) == 0 + + +# test default embedding function +def test_default_embedding(): + embedding_function = DefaultEmbeddingFunction() + docs = ["this is a test" for _ in range(64)] + embeddings = embedding_function(docs) + assert len(embeddings) == 64 + + +def test_multiple_collections(client): + embeddings1 = np.random.rand(10, 512).astype(np.float32).tolist() + embeddings2 = np.random.rand(10, 512).astype(np.float32).tolist() + ids1 = [f"http://example.com/1/{i}" for i in range(len(embeddings1))] + ids2 = [f"http://example.com/2/{i}" for i in range(len(embeddings2))] + + client.reset() + coll1 = client.create_collection("coll1") + coll1.add(embeddings=embeddings1, ids=ids1) + + coll2 = client.create_collection("coll2") + coll2.add(embeddings=embeddings2, ids=ids2) + + assert len(client.list_collections()) == 2 + assert coll1.count() == len(embeddings1) + assert coll2.count() == len(embeddings2) + + results1 = coll1.query(query_embeddings=embeddings1[0], n_results=1) + results2 = coll2.query(query_embeddings=embeddings2[0], n_results=1) + + # progressively check the results are what we expect so we can debug when/if flakes happen + assert len(results1["ids"]) > 0 + assert len(results2["ids"]) > 0 + assert len(results1["ids"][0]) > 0 + assert len(results2["ids"][0]) > 0 + + assert results1["ids"][0][0] == ids1[0] + assert results2["ids"][0][0] == ids2[0] + + +def test_update_query(client): + client.reset() + collection = client.create_collection("test_update_query") + collection.add(**records) + + updated_records = { + "ids": [records["ids"][0]], + "embeddings": [[0.1, 0.2, 0.3]], + "documents": ["updated document"], + "metadatas": [{"foo": "bar"}], + } + + collection.update(**updated_records) + + # test query + results = collection.query( + query_embeddings=updated_records["embeddings"], + n_results=1, + include=["embeddings", "documents", "metadatas"], + ) + assert len(results["ids"][0]) == 1 + assert results["ids"][0][0] == updated_records["ids"][0] + assert results["documents"][0][0] == updated_records["documents"][0] + assert results["metadatas"][0][0]["foo"] == "bar" + assert vector_approx_equal( + results["embeddings"][0][0], updated_records["embeddings"][0] + ) + + +def test_get_nearest_neighbors_where_n_results_more_than_element(client): + client.reset() + collection = client.create_collection("testspace") + collection.add(**records) + + includes = ["embeddings", "documents", "metadatas", "distances"] + results = collection.query( + query_embeddings=[[1.1, 2.3, 3.2]], + n_results=5, + include=includes, + ) + for key in results.keys(): + if key in includes or key == "ids": + assert len(results[key][0]) == 2 + elif key == "included": + assert set(results[key]) == set(includes) + else: + assert results[key] is None + + +def test_invalid_n_results_param(client): + client.reset() + collection = client.create_collection("testspace") + collection.add(**records) + with pytest.raises(TypeError) as exc: + collection.query( + query_embeddings=[[1.1, 2.3, 3.2]], + n_results=-1, + include=["embeddings", "documents", "metadatas", "distances"], + ) + assert "Number of requested results -1, cannot be negative, or zero." in str( + exc.value + ) + assert exc.type == TypeError + + with pytest.raises(ValueError) as exc: + collection.query( + query_embeddings=[[1.1, 2.3, 3.2]], + n_results="one", + include=["embeddings", "documents", "metadatas", "distances"], + ) + assert "int" in str(exc.value) + assert exc.type == ValueError + + +initial_records = { + "embeddings": [[0, 0, 0], [1.2, 2.24, 3.2], [2.2, 3.24, 4.2]], + "ids": ["id1", "id2", "id3"], + "metadatas": [ + {"int_value": 1, "string_value": "one", "float_value": 1.001}, + {"int_value": 2}, + {"string_value": "three"}, + ], + "documents": [ + "this document is first", + "this document is second", + "this document is third", + ], +} + +new_records = { + "embeddings": [[3.0, 3.0, 1.1], [3.2, 4.24, 5.2]], + "ids": ["id1", "id4"], + "metadatas": [ + {"int_value": 1, "string_value": "one_of_one", "float_value": 1.001}, + {"int_value": 4}, + ], + "documents": [ + "this document is even more first", + "this document is new and fourth", + ], +} + + +def test_upsert(client): + client.reset() + collection = client.create_collection("test") + + collection.add(**initial_records) + assert collection.count() == 3 + + collection.upsert(**new_records) + assert collection.count() == 4 + + get_result = collection.get( + include=["embeddings", "metadatas", "documents"], ids=new_records["ids"][0] + ) + assert vector_approx_equal( + get_result["embeddings"][0], new_records["embeddings"][0] + ) + assert get_result["metadatas"][0] == new_records["metadatas"][0] + assert get_result["documents"][0] == new_records["documents"][0] + + query_result = collection.query( + query_embeddings=get_result["embeddings"], + n_results=1, + include=["embeddings", "metadatas", "documents"], + ) + assert vector_approx_equal( + query_result["embeddings"][0][0], new_records["embeddings"][0] + ) + assert query_result["metadatas"][0][0] == new_records["metadatas"][0] + assert query_result["documents"][0][0] == new_records["documents"][0] + + collection.delete(ids=initial_records["ids"][2]) + collection.upsert( + ids=initial_records["ids"][2], + embeddings=[[1.1, 0.99, 2.21]], + metadatas=[{"string_value": "a new string value"}], + ) + assert collection.count() == 4 + + get_result = collection.get( + include=["embeddings", "metadatas", "documents"], ids=["id3"] + ) + assert vector_approx_equal(get_result["embeddings"][0], [1.1, 0.99, 2.21]) + assert get_result["metadatas"][0] == {"string_value": "a new string value"} + assert get_result["documents"][0] is None + + +def test_collection_upsert_with_invalid_collection_throws(client): + client.reset() + collection = client.create_collection("test") + client.delete_collection("test") + + with pytest.raises(NotFoundError, match=r"Collection .* does not exist"): + collection.upsert(**initial_records) + + +# test to make sure add, query, update, upsert error on invalid embeddings input + + +def test_invalid_embeddings(client): + client.reset() + collection = client.create_collection("test_invalid_embeddings") + + # Add with string embeddings + invalid_records = { + "embeddings": [["0", "0", "0"], ["1.2", "2.24", "3.2"]], + "ids": ["id1", "id2"], + } + with pytest.raises(ValueError) as e: + collection.add(**invalid_records) + assert "embedding" in str(e.value) + + # Query with invalid embeddings + with pytest.raises(ValueError) as e: + collection.query( + query_embeddings=[["1.1", "2.3", "3.2"]], + n_results=1, + ) + assert "embedding" in str(e.value) + + # Update with invalid embeddings + invalid_records = { + "embeddings": [[[0], [0], [0]], [[1.2], [2.24], [3.2]]], + "ids": ["id1", "id2"], + } + with pytest.raises(ValueError) as e: + collection.update(**invalid_records) + assert "embedding" in str(e.value) + + # Upsert with invalid embeddings + invalid_records = { + "embeddings": [[[1.1, 2.3, 3.2]], [[1.2, 2.24, 3.2]]], + "ids": ["id1", "id2"], + } + with pytest.raises(ValueError) as e: + collection.upsert(**invalid_records) + assert "embedding" in str(e.value) + + +# test to make sure update shows exception for bad dimensionality + + +def test_dimensionality_exception_update(client): + client.reset() + collection = client.create_collection("test_dimensionality_update_exception") + collection.add(**minimal_records) + + with pytest.raises(Exception) as e: + collection.update(**bad_dimensionality_records) + assert "dimension" in str(e.value) + + +# test to make sure upsert shows exception for bad dimensionality + + +def test_dimensionality_exception_upsert(client): + client.reset() + collection = client.create_collection("test_dimensionality_upsert_exception") + collection.add(**minimal_records) + + with pytest.raises(Exception) as e: + collection.upsert(**bad_dimensionality_records) + assert "dimension" in str(e.value) + + +# this may be flaky on windows, so we rerun it +@pytest.mark.flaky(reruns=3, condition=sys.platform.startswith("win32")) +def test_ssl_self_signed(client_ssl): + if os.environ.get("CHROMA_INTEGRATION_TEST_ONLY"): + pytest.skip("Skipping test for integration test") + client_ssl.heartbeat() + + +# this may be flaky on windows, so we rerun it +@pytest.mark.flaky(reruns=3, condition=sys.platform.startswith("win32")) +def test_ssl_self_signed_without_ssl_verify(client_ssl): + if os.environ.get("CHROMA_INTEGRATION_TEST_ONLY"): + pytest.skip("Skipping test for integration test") + client_ssl.heartbeat() + _port = client_ssl._server._settings.chroma_server_http_port + with pytest.raises(ValueError) as e: + chromadb.HttpClient(ssl=True, port=_port) + stack_trace = traceback.format_exception( + type(e.value), e.value, e.value.__traceback__ + ) + client_ssl.clear_system_cache() + assert "CERTIFICATE_VERIFY_FAILED" in "".join(stack_trace) + + +def test_query_id_filtering_small_dataset(client): + client.reset() + collection = client.create_collection("test_query_id_filtering_small") + + num_vectors = 100 + dim = 512 + small_records = np.random.rand(100, 512).astype(np.float32).tolist() + ids = [f"{i}" for i in range(num_vectors)] + + collection.add( + embeddings=small_records, + ids=ids, + ) + + query_ids = [f"{i}" for i in range(0, num_vectors, 10)] + query_embedding = np.random.rand(dim).astype(np.float32).tolist() + results = collection.query( + query_embeddings=query_embedding, + ids=query_ids, + n_results=num_vectors, + include=[], + ) + + all_returned_ids = [item for sublist in results["ids"] for item in sublist] + assert all(id in query_ids for id in all_returned_ids) + + +def test_query_id_filtering_medium_dataset(client): + client.reset() + collection = client.create_collection("test_query_id_filtering_medium") + + num_vectors = 1000 + dim = 512 + medium_records = np.random.rand(num_vectors, dim).astype(np.float32).tolist() + ids = [f"{i}" for i in range(num_vectors)] + + collection.add( + embeddings=medium_records, + ids=ids, + ) + + query_ids = [f"{i}" for i in range(0, num_vectors, 10)] + + query_embedding = np.random.rand(dim).astype(np.float32).tolist() + results = collection.query( + query_embeddings=query_embedding, + ids=query_ids, + n_results=num_vectors, + include=[], + ) + + all_returned_ids = [item for sublist in results["ids"] for item in sublist] + assert all(id in query_ids for id in all_returned_ids) + + multi_query_embeddings = [ + np.random.rand(dim).astype(np.float32).tolist() for _ in range(3) + ] + multi_results = collection.query( + query_embeddings=multi_query_embeddings, + ids=query_ids, + n_results=10, + include=[], + ) + + for result_set in multi_results["ids"]: + assert all(id in query_ids for id in result_set) + + +def test_query_id_filtering_e2e(client): + client.reset() + collection = client.create_collection("test_query_id_filtering_e2e") + + dim = 512 + num_vectors = 100 + embeddings = np.random.rand(num_vectors, dim).astype(np.float32).tolist() + ids = [f"{i}" for i in range(num_vectors)] + metadatas = [{"index": i} for i in range(num_vectors)] + + collection.add( + embeddings=embeddings, + ids=ids, + metadatas=metadatas, + ) + + ids_to_delete = [f"{i}" for i in range(10, 30)] + collection.delete(ids=ids_to_delete) + + # modify some existing ids, and add some new ones to check query returns updated metadata + ids_to_upsert_existing = [f"{i}" for i in range(30, 50)] + new_num_vectors = num_vectors + 20 + ids_to_upsert_new = [f"{i}" for i in range(num_vectors, new_num_vectors)] + + upsert_embeddings = ( + np.random.rand(len(ids_to_upsert_existing) + len(ids_to_upsert_new), dim) + .astype(np.float32) + .tolist() + ) + upsert_metadatas = [ + {"index": i, "upserted": True} for i in range(len(upsert_embeddings)) + ] + + collection.upsert( + embeddings=upsert_embeddings, + ids=ids_to_upsert_existing + ids_to_upsert_new, + metadatas=upsert_metadatas, + ) + + valid_query_ids = ( + [f"{i}" for i in range(5, 10)] # subset of existing ids + + [f"{i}" for i in range(35, 45)] # subset of existing, but upserted + + [ + f"{i}" for i in range(num_vectors + 5, num_vectors + 15) + ] # subset of new upserted ids + ) + + includes = ["metadatas"] + query_embedding = np.random.rand(dim).astype(np.float32).tolist() + results = collection.query( + query_embeddings=query_embedding, + ids=valid_query_ids, + n_results=new_num_vectors, + include=includes, + ) + + all_returned_ids = [item for sublist in results["ids"] for item in sublist] + assert all(id in valid_query_ids for id in all_returned_ids) + + for result_index, id_list in enumerate(results["ids"]): + for item_index, item_id in enumerate(id_list): + if item_id in ids_to_upsert_existing or item_id in ids_to_upsert_new: + # checks if metadata correctly has upserted flag + assert results["metadatas"][result_index][item_index]["upserted"] + + upserted_id = ids_to_upsert_existing[0] + # test single id filtering + results = collection.query( + query_embeddings=query_embedding, + ids=upserted_id, + n_results=1, + include=includes, + ) + assert results["metadatas"][0][0]["upserted"] + + deleted_id = ids_to_delete[0] + # test deleted id filter raises + with pytest.raises(Exception) as error: + collection.query( + query_embeddings=query_embedding, + ids=deleted_id, + n_results=1, + include=includes, + ) + assert "Error finding id" in str(error.value) + + +def test_validate_sparse_vector(): + """Test SparseVector validation in __post_init__.""" + from chromadb.base_types import SparseVector + + # Test 1: Valid sparse vector - should not raise + SparseVector(indices=[0, 2, 5], values=[0.1, 0.5, 0.9]) + + # Test 2: Valid sparse vector with empty lists - should not raise + SparseVector(indices=[], values=[]) + + # Test 4: Invalid - indices not a list + with pytest.raises(ValueError, match="Expected SparseVector indices to be a list"): + SparseVector(indices="not_a_list", values=[0.1, 0.2]) # type: ignore + + # Test 5: Invalid - values not a list + with pytest.raises(ValueError, match="Expected SparseVector values to be a list"): + SparseVector(indices=[0, 1], values="not_a_list") # type: ignore + + # Test 6: Invalid - mismatched lengths + with pytest.raises( + ValueError, match="indices and values must have the same length" + ): + SparseVector(indices=[0, 1, 2], values=[0.1, 0.2]) + + # Test 7: Invalid - non-integer index + with pytest.raises(ValueError, match="SparseVector indices must be integers"): + SparseVector(indices=[0, "not_int", 2], values=[0.1, 0.2, 0.3]) # type: ignore + + # Test 8: Invalid - negative index + with pytest.raises(ValueError, match="SparseVector indices must be non-negative"): + SparseVector(indices=[0, -1, 2], values=[0.1, 0.2, 0.3]) + + # Test 9: Invalid - non-numeric value + with pytest.raises(ValueError, match="SparseVector values must be numbers"): + SparseVector(indices=[0, 1, 2], values=[0.1, "not_number", 0.3]) # type: ignore + + # Test 10: Invalid - float indices (not integers) + with pytest.raises(ValueError, match="SparseVector indices must be integers"): + SparseVector(indices=[0.0, 1.0, 2.0], values=[0.1, 0.2, 0.3]) # type: ignore + + # Test 11: Valid - integer values (not just floats) + SparseVector(indices=[0, 1, 2], values=[1, 2, 3]) + + # Test 12: Valid - mixed int and float values + SparseVector(indices=[0, 1, 2], values=[1, 2.5, 3]) + + # Test 13: Valid - large indices + SparseVector(indices=[100, 1000, 10000], values=[0.1, 0.2, 0.3]) + + # Test 14: Invalid - None as value + with pytest.raises(ValueError, match="SparseVector values must be numbers"): + SparseVector(indices=[0, 1], values=[0.1, None]) # type: ignore + + # Test 15: Invalid - None as index + with pytest.raises(ValueError, match="SparseVector indices must be integers"): + SparseVector(indices=[0, None], values=[0.1, 0.2]) # type: ignore + + # Test 16: Valid - single element + SparseVector(indices=[42], values=[3.14]) + + # Test 17: Boolean values are actually valid (bool is subclass of int in Python) + SparseVector(indices=[0, 1], values=[True, False]) # True=1, False=0 + + # Test 18: Invalid - unsorted indices + with pytest.raises( + ValueError, match="indices must be sorted in strictly ascending order" + ): + SparseVector(indices=[0, 2, 1], values=[0.1, 0.2, 0.3]) + + # Test 19: Invalid - duplicate indices (not strictly ascending) + with pytest.raises( + ValueError, match="indices must be sorted in strictly ascending order" + ): + SparseVector(indices=[0, 1, 1, 2], values=[0.1, 0.2, 0.3, 0.4]) + + # Test 20: Invalid - descending order + with pytest.raises( + ValueError, match="indices must be sorted in strictly ascending order" + ): + SparseVector(indices=[5, 3, 1], values=[0.5, 0.3, 0.1]) + + +def test_sparse_vector_in_metadata_validation(): + """Test that sparse vectors are properly validated in metadata.""" + from chromadb.api.types import validate_metadata + from chromadb.base_types import SparseVector + + # Test 1: Valid metadata with sparse vectors + sparse_vector_1 = SparseVector(indices=[0, 2, 5], values=[0.1, 0.5, 0.9]) + sparse_vector_2 = SparseVector(indices=[1, 3, 4], values=[0.2, 0.4, 0.6]) + + metadata_1 = { + "text": "document 1", + "sparse_embedding": sparse_vector_1, + "score": 0.5, + } + metadata_2 = { + "text": "document 2", + "sparse_embedding": sparse_vector_2, + "score": 0.8, + } + validate_metadata(metadata_1) + validate_metadata(metadata_2) + + # Test 2: Valid metadata with empty sparse vector + metadata_empty = { + "text": "empty sparse", + "sparse_vec": SparseVector(indices=[], values=[]), + } + validate_metadata(metadata_empty) + + # Test 3: Invalid sparse vector in metadata (construction fails) + with pytest.raises( + ValueError, match="indices and values must have the same length" + ): + invalid_metadata = { # type: ignore + "text": "invalid", + "sparse_embedding": SparseVector(indices=[0, 1], values=[0.1]), + } + + # Test 4: Invalid dict in metadata (not a SparseVector dataclass) + invalid_metadata_2 = { + "text": "missing indices", + "sparse_embedding": {"values": [0.1, 0.2]}, + } + with pytest.raises( + ValueError, + match="Expected metadata value to be a str, int, float, bool, SparseVector, list, or None", + ): + validate_metadata(invalid_metadata_2) + + # Test 5: Invalid sparse vector - negative index (construction fails) + with pytest.raises(ValueError, match="SparseVector indices must be non-negative"): + invalid_metadata_3 = { # type: ignore + "text": "negative index", + "sparse_embedding": SparseVector( + indices=[0, -1, 2], values=[0.1, 0.2, 0.3] + ), + } + + # Test 6: Invalid sparse vector - non-numeric value (construction fails) + with pytest.raises(ValueError, match="SparseVector values must be numbers"): + invalid_metadata_4 = { # type: ignore + "text": "non-numeric value", + "sparse_embedding": SparseVector( + indices=[0, 1], values=[0.1, "not_a_number"] + ), # type: ignore + } + + # Test 7: Multiple sparse vectors in metadata + metadata_multiple = { + "text": "multiple sparse vectors", + "sparse_1": SparseVector(indices=[0, 1], values=[0.1, 0.2]), + "sparse_2": SparseVector(indices=[2, 3, 4], values=[0.3, 0.4, 0.5]), + "regular_field": 42, + } + validate_metadata(metadata_multiple) + + # Test 8: Regular dict (not SparseVector) should be rejected + metadata_nested = { + "config": "some_config", + "sparse_vector": {"indices": [0, 1, 2], "values": [1.0, 2.0, 3.0]}, + } + with pytest.raises( + ValueError, + match="Expected metadata value to be a str, int, float, bool, SparseVector, list, or None", + ): + validate_metadata(metadata_nested) + + # Test 9: Large sparse vector + large_sparse = SparseVector( + indices=list(range(1000)), + values=[float(i) * 0.001 for i in range(1000)], + ) + metadata_large = {"text": "large sparse", "large_sparse_vec": large_sparse} + validate_metadata(metadata_large) + + +def test_sparse_vector_dict_format_normalization(): + """Test that dict-format sparse vectors are normalized to SparseVector instances.""" + from chromadb.api.types import normalize_metadata, validate_metadata + from chromadb.base_types import SparseVector + + # Test 1: Dict format with #type='sparse_vector' should be converted + metadata_dict_format = { + "text": "test document", + "sparse": { + TYPE_KEY: SPARSE_VECTOR_TYPE_VALUE, + "indices": [0, 2, 5], + "values": [1.0, 2.0, 3.0], + }, + } + normalized = normalize_metadata(metadata_dict_format) + + assert isinstance(normalized["sparse"], SparseVector) + assert normalized["sparse"].indices == [0, 2, 5] + assert normalized["sparse"].values == [1.0, 2.0, 3.0] + + # Should pass validation after normalization + validate_metadata(normalized) + + # Test 2: SparseVector instance should pass through unchanged + sparse_instance = SparseVector(indices=[1, 3, 4], values=[0.5, 1.5, 2.5]) + metadata_instance_format = { + "text": "test document", + "sparse": sparse_instance, + } + normalized2 = normalize_metadata(metadata_instance_format) + + assert normalized2["sparse"] is sparse_instance # Same object + validate_metadata(normalized2) + + # Test 3: Dict format with unsorted indices should be rejected during normalization + metadata_unsorted = { + "text": "unsorted", + "sparse": { + TYPE_KEY: SPARSE_VECTOR_TYPE_VALUE, + "indices": [5, 0, 2], + "values": [3.0, 1.0, 2.0], + }, + } + with pytest.raises( + ValueError, match="indices must be sorted in strictly ascending order" + ): + normalize_metadata(metadata_unsorted) + + # Test 4: Dict format with duplicate indices should be rejected + metadata_duplicates = { + "text": "duplicates", + "sparse": { + TYPE_KEY: SPARSE_VECTOR_TYPE_VALUE, + "indices": [0, 2, 2], + "values": [1.0, 2.0, 3.0], + }, + } + with pytest.raises( + ValueError, match="indices must be sorted in strictly ascending order" + ): + normalize_metadata(metadata_duplicates) + + # Test 5: Dict format with negative indices should be rejected + metadata_negative = { + "text": "negative", + "sparse": { + TYPE_KEY: SPARSE_VECTOR_TYPE_VALUE, + "indices": [-1, 0, 2], + "values": [1.0, 2.0, 3.0], + }, + } + with pytest.raises(ValueError, match="indices must be non-negative"): + normalize_metadata(metadata_negative) + + # Test 6: Dict format with length mismatch should be rejected + metadata_mismatch = { + "text": "mismatch", + "sparse": { + TYPE_KEY: SPARSE_VECTOR_TYPE_VALUE, + "indices": [0, 2], + "values": [1.0, 2.0, 3.0], + }, + } + with pytest.raises( + ValueError, match="indices and values must have the same length" + ): + normalize_metadata(metadata_mismatch) + + # Test 7: Regular dict without #type should not be converted + metadata_regular_dict = { + "text": "regular", + "config": {"key": "value"}, + } + normalized3 = normalize_metadata(metadata_regular_dict) + assert isinstance(normalized3["config"], dict) + assert normalized3["config"]["key"] == "value" + + # Test 8: Empty sparse vector in dict format + metadata_empty = { + "text": "empty", + "sparse": {TYPE_KEY: SPARSE_VECTOR_TYPE_VALUE, "indices": [], "values": []}, + } + normalized4 = normalize_metadata(metadata_empty) + assert isinstance(normalized4["sparse"], SparseVector) + assert normalized4["sparse"].indices == [] + assert normalized4["sparse"].values == [] + + # Test 9: Multiple sparse vectors in dict format + metadata_multiple = { + "sparse1": { + TYPE_KEY: SPARSE_VECTOR_TYPE_VALUE, + "indices": [0, 1], + "values": [1.0, 2.0], + }, + "sparse2": { + TYPE_KEY: SPARSE_VECTOR_TYPE_VALUE, + "indices": [2, 3], + "values": [3.0, 4.0], + }, + "regular": 42, + } + normalized5 = normalize_metadata(metadata_multiple) + assert isinstance(normalized5["sparse1"], SparseVector) + assert isinstance(normalized5["sparse2"], SparseVector) + assert normalized5["regular"] == 42 + + +def test_list_metadata_validation(): + """Test that list metadata values are properly validated.""" + from chromadb.api.types import validate_metadata, validate_update_metadata + + # Valid list metadata + validate_metadata({"tags": ["action", "comedy"]}) + validate_metadata({"scores": [1, 2, 3]}) + validate_metadata({"ratings": [4.5, 3.2]}) + validate_metadata({"flags": [True, False, True]}) + + # Lists can coexist with scalars + validate_metadata({"tags": ["a", "b"], "count": 5, "name": "test"}) + + # Empty list rejected + with pytest.raises(ValueError, match="non-empty"): + validate_metadata({"tags": []}) + + # Mixed types rejected + with pytest.raises(ValueError, match="same type"): + validate_metadata({"tags": ["a", 1]}) + + with pytest.raises(ValueError, match="same type"): + validate_metadata({"vals": [1, 1.5]}) + + with pytest.raises(ValueError, match="same type"): + validate_metadata({"vals": [True, "yes"]}) + + # Nested list rejected + with pytest.raises(ValueError, match="str, int, float, or bool"): + validate_metadata({"tags": [["nested"]]}) + + # validate_update_metadata also accepts lists + validate_update_metadata({"tags": ["action", "comedy"]}) + validate_update_metadata({"scores": [1, 2, 3]}) + + # validate_update_metadata still allows None (for deletion) + validate_update_metadata({"tags": None}) + + # Empty list rejected in update too + with pytest.raises(ValueError, match="non-empty"): + validate_update_metadata({"tags": []}) + + +def test_where_contains_validation(): + """Test that $contains/$not_contains are accepted in where clauses for metadata.""" + from chromadb.api.types import validate_where + + # All scalar types accepted + validate_where({"tags": {"$contains": "action"}}) + validate_where({"scores": {"$contains": 42}}) + validate_where({"ratings": {"$contains": 4.5}}) + validate_where({"flags": {"$contains": True}}) + + # $not_contains + validate_where({"tags": {"$not_contains": "draft"}}) + validate_where({"scores": {"$not_contains": 0}}) + + # List operand rejected (contains checks a single value, not a list) + with pytest.raises(ValueError): + validate_where({"tags": {"$contains": ["a", "b"]}}) + + # Dict operand rejected + with pytest.raises(ValueError): + validate_where({"tags": {"$contains": {"nested": True}}}) + + # Still works inside $and/$or + validate_where( + {"$and": [{"tags": {"$contains": "action"}}, {"year": {"$gt": 2020}}]} + ) + + +def _is_python_local_segment(client): + """Return True when the client is backed by the Python local segment API + (which does not yet support array metadata).""" + settings = client.get_settings() + return ( + settings.chroma_api_impl == "chromadb.api.segment.SegmentAPI" + and settings.chroma_segment_manager_impl + == "chromadb.segment.impl.manager.local.LocalSegmentManager" + ) + + +def test_array_metadata_e2e(client): + """End-to-end test: write array metadata, read it back, and query with $contains.""" + if _is_python_local_segment(client): + pytest.skip("Python local segment does not support array metadata yet") + client.reset() + collection = client.create_collection("test_array_metadata_e2e") + collection.add( + ids=["id1", "id2", "id3"], + embeddings=[[1, 0, 0], [0, 1, 0], [0, 0, 1]], + metadatas=[ + {"tags": ["action", "comedy"], "year": 2020}, + {"tags": ["drama"], "year": 2021}, + {"tags": ["action", "thriller"], "year": 2022}, + ], + ) + + # Read back: arrays should round-trip + items = collection.get(ids=["id1"]) + assert len(items["metadatas"]) == 1 + assert sorted(items["metadatas"][0]["tags"]) == ["action", "comedy"] + assert items["metadatas"][0]["year"] == 2020 + + # $contains "action" -> id1 and id3 + items = collection.get(where={"tags": {"$contains": "action"}}) + ids = sorted([m["year"] for m in items["metadatas"]]) + assert ids == [2020, 2022] + + # $contains "drama" -> id2 only + items = collection.get(where={"tags": {"$contains": "drama"}}) + assert len(items["metadatas"]) == 1 + assert items["metadatas"][0]["year"] == 2021 + + # $not_contains "action" -> id2 only + items = collection.get(where={"tags": {"$not_contains": "action"}}) + assert len(items["metadatas"]) == 1 + assert items["metadatas"][0]["year"] == 2021 + + # $contains with no match + items = collection.get(where={"tags": {"$contains": "romance"}}) + assert len(items["metadatas"]) == 0 + + +def test_array_metadata_int_contains_e2e(client): + """End-to-end: $contains on integer arrays.""" + if _is_python_local_segment(client): + pytest.skip("Python local segment does not support array metadata yet") + client.reset() + collection = client.create_collection("test_int_array_e2e") + collection.add( + ids=["id1", "id2"], + embeddings=[[1, 0, 0], [0, 1, 0]], + metadatas=[ + {"scores": [10, 20, 30]}, + {"scores": [40, 50]}, + ], + ) + + items = collection.get(where={"scores": {"$contains": 20}}) + assert len(items["ids"]) == 1 + assert items["ids"][0] == "id1" + + items = collection.get(where={"scores": {"$contains": 50}}) + assert len(items["ids"]) == 1 + assert items["ids"][0] == "id2" + + items = collection.get(where={"scores": {"$not_contains": 10}}) + assert len(items["ids"]) == 1 + assert items["ids"][0] == "id2" + + +def test_array_metadata_update_e2e(client): + """End-to-end: updating array metadata replaces old values.""" + if _is_python_local_segment(client): + pytest.skip("Python local segment does not support array metadata yet") + client.reset() + collection = client.create_collection("test_array_update_e2e") + collection.add( + ids=["id1"], + embeddings=[[1, 0, 0]], + metadatas=[{"tags": ["old_a", "old_b"]}], + ) + + # Verify initial state + items = collection.get(where={"tags": {"$contains": "old_a"}}) + assert len(items["ids"]) == 1 + + # Update to new tags + collection.update( + ids=["id1"], + metadatas=[{"tags": ["new_x"]}], + ) + + # Old values should be gone + items = collection.get(where={"tags": {"$contains": "old_a"}}) + assert len(items["ids"]) == 0 + + # New value should be present + items = collection.get(where={"tags": {"$contains": "new_x"}}) + assert len(items["ids"]) == 1 + + # Read back to confirm the array was replaced + items = collection.get(ids=["id1"]) + assert items["metadatas"][0]["tags"] == ["new_x"] + + +def test_array_metadata_mixed_with_scalar_e2e(client): + """End-to-end: records with both scalar and array metadata.""" + if _is_python_local_segment(client): + pytest.skip("Python local segment does not support array metadata yet") + client.reset() + collection = client.create_collection("test_mixed_e2e") + collection.add( + ids=["id1"], + embeddings=[[1, 0, 0]], + metadatas=[{"name": "Alice", "score": 42, "tags": ["admin", "user"]}], + ) + + items = collection.get(ids=["id1"]) + md = items["metadatas"][0] + assert md["name"] == "Alice" + assert md["score"] == 42 + assert sorted(md["tags"]) == ["admin", "user"] + + # Filter by scalar + items = collection.get(where={"score": {"$eq": 42}}) + assert len(items["ids"]) == 1 + + # Filter by array contains + items = collection.get(where={"tags": {"$contains": "admin"}}) + assert len(items["ids"]) == 1 + + # Combined $and filter: scalar + array contains + items = collection.get( + where={ + "$and": [ + {"score": {"$gte": 40}}, + {"tags": {"$contains": "admin"}}, + ] + } + ) + assert len(items["ids"]) == 1 + + +def test_metadata_type_change_scalar_to_array_e2e(client): + """End-to-end: changing a metadata field from scalar to array removes the old scalar.""" + if _is_python_local_segment(client): + pytest.skip("Python local segment does not support array metadata yet") + client.reset() + collection = client.create_collection("test_scalar_to_array") + + # Add with scalar, then immediately update to array (no intermediate get, + # so both log entries are compacted together). + collection.add( + ids=["id1"], + embeddings=[[1, 0, 0]], + metadatas=[{"tags": "old_scalar"}], + ) + collection.update( + ids=["id1"], + metadatas=[{"tags": ["new_a", "new_b"]}], + ) + + # The old scalar value must no longer match + items = collection.get(where={"tags": {"$eq": "old_scalar"}}) + assert len(items["ids"]) == 0, "Stale scalar value should have been removed" + + # The new array value should be queryable via $contains + items = collection.get(where={"tags": {"$contains": "new_a"}}) + assert len(items["ids"]) == 1 + + # Read back and verify the value is an array + items = collection.get(ids=["id1"]) + assert sorted(items["metadatas"][0]["tags"]) == ["new_a", "new_b"] + + +def test_metadata_type_change_array_to_scalar_e2e(client): + """End-to-end: changing a metadata field from array to scalar removes the old array rows.""" + if _is_python_local_segment(client): + pytest.skip("Python local segment does not support array metadata yet") + client.reset() + collection = client.create_collection("test_array_to_scalar") + + # Add with array, then immediately update to scalar (no intermediate get, + # so both log entries are compacted together). + collection.add( + ids=["id1"], + embeddings=[[1, 0, 0]], + metadatas=[{"tags": ["old_a", "old_b"]}], + ) + collection.update( + ids=["id1"], + metadatas=[{"tags": "new_scalar"}], + ) + + # The old array values must no longer match + items = collection.get(where={"tags": {"$contains": "old_a"}}) + assert len(items["ids"]) == 0, "Stale array rows should have been removed" + + # The new scalar value should be queryable via equality + items = collection.get(where={"tags": {"$eq": "new_scalar"}}) + assert len(items["ids"]) == 1 + + # Read back and verify the value is a scalar + items = collection.get(ids=["id1"]) + assert items["metadatas"][0]["tags"] == "new_scalar" + + +def test_metadata_type_change_via_upsert_e2e(client): + """End-to-end: upsert (not update) correctly cleans up when type changes.""" + if _is_python_local_segment(client): + pytest.skip("Python local segment does not support array metadata yet") + client.reset() + collection = client.create_collection("test_upsert_type_change") + + # Upsert with scalar, then upsert again changing to array. + collection.upsert( + ids=["id1"], + embeddings=[[1, 0, 0]], + metadatas=[{"tags": "scalar_val"}], + ) + collection.upsert( + ids=["id1"], + embeddings=[[1, 0, 0]], + metadatas=[{"tags": ["arr_a", "arr_b"]}], + ) + + # Old scalar must be gone. + items = collection.get(where={"tags": {"$eq": "scalar_val"}}) + assert len(items["ids"]) == 0, "Stale scalar from upsert should be removed" + + # New array must be queryable. + items = collection.get(where={"tags": {"$contains": "arr_a"}}) + assert len(items["ids"]) == 1 + + items = collection.get(ids=["id1"]) + assert sorted(items["metadatas"][0]["tags"]) == ["arr_a", "arr_b"] + + +def test_metadata_rapid_type_flip_e2e(client): + """End-to-end: scalar -> array -> scalar leaves no stale data.""" + if _is_python_local_segment(client): + pytest.skip("Python local segment does not support array metadata yet") + client.reset() + collection = client.create_collection("test_rapid_flip") + + collection.add( + ids=["id1"], + embeddings=[[1, 0, 0]], + metadatas=[{"tags": "original"}], + ) + collection.update( + ids=["id1"], + metadatas=[{"tags": ["mid_a"]}], + ) + collection.update( + ids=["id1"], + metadatas=[{"tags": "final_scalar"}], + ) + + # Original scalar gone. + items = collection.get(where={"tags": {"$eq": "original"}}) + assert len(items["ids"]) == 0, "Original scalar should be gone" + + # Intermediate array gone. + items = collection.get(where={"tags": {"$contains": "mid_a"}}) + assert len(items["ids"]) == 0, "Intermediate array should be gone" + + # Final scalar present. + items = collection.get(where={"tags": {"$eq": "final_scalar"}}) + assert len(items["ids"]) == 1 + + items = collection.get(ids=["id1"]) + assert items["metadatas"][0]["tags"] == "final_scalar" + + +def test_metadata_mixed_simultaneous_type_changes_e2e(client): + """End-to-end: one update changes 'color' scalar->array AND 'tags' array->scalar.""" + if _is_python_local_segment(client): + pytest.skip("Python local segment does not support array metadata yet") + client.reset() + collection = client.create_collection("test_mixed_type_change") + + collection.add( + ids=["id1"], + embeddings=[[1, 0, 0]], + metadatas=[{"color": "red", "tags": ["old_a", "old_b"]}], + ) + collection.update( + ids=["id1"], + metadatas=[{"color": ["blue", "green"], "tags": "new_scalar"}], + ) + + # "color" old scalar gone. + items = collection.get(where={"color": {"$eq": "red"}}) + assert len(items["ids"]) == 0, "Old color scalar should be gone" + + # "color" new array present. + items = collection.get(where={"color": {"$contains": "blue"}}) + assert len(items["ids"]) == 1 + + # "tags" old array gone. + items = collection.get(where={"tags": {"$contains": "old_a"}}) + assert len(items["ids"]) == 0, "Old tags array should be gone" + + # "tags" new scalar present. + items = collection.get(where={"tags": {"$eq": "new_scalar"}}) + assert len(items["ids"]) == 1 + + +def test_metadata_delete_after_type_change_e2e(client): + """End-to-end: add scalar, update to array, then delete key entirely.""" + if _is_python_local_segment(client): + pytest.skip("Python local segment does not support array metadata yet") + client.reset() + collection = client.create_collection("test_delete_after_type_change") + + collection.add( + ids=["id1"], + embeddings=[[1, 0, 0]], + metadatas=[{"tags": "scalar_val", "keep": "yes"}], + ) + collection.update( + ids=["id1"], + metadatas=[{"tags": ["arr_a", "arr_b"]}], + ) + collection.update( + ids=["id1"], + metadatas=[{"tags": None}], + ) + + # Record still exists (has "keep" key) but "tags" is gone. + items = collection.get(ids=["id1"]) + assert len(items["ids"]) == 1 + assert ( + "tags" not in items["metadatas"][0] + ), f"tags key should be deleted, got {items['metadatas'][0]}" + assert items["metadatas"][0]["keep"] == "yes" + + # Neither scalar nor array queries should match. + items = collection.get(where={"tags": {"$eq": "scalar_val"}}) + assert len(items["ids"]) == 0 + + items = collection.get(where={"tags": {"$contains": "arr_a"}}) + assert len(items["ids"]) == 0 + + +def test_sparse_vector_dict_format_in_record_set(): + """Test that dict-format sparse vectors work in normalize_insert_record_set.""" + from chromadb.api.types import ( + normalize_insert_record_set, + validate_insert_record_set, + ) + from chromadb.base_types import SparseVector + + # Test 1: Mix of dict format and SparseVector instances + record_set = normalize_insert_record_set( + ids=["doc1", "doc2", "doc3"], + embeddings=None, + metadatas=[ + { + "text": "test1", + "sparse": { + TYPE_KEY: SPARSE_VECTOR_TYPE_VALUE, + "indices": [0, 2], + "values": [1.0, 2.0], + }, + }, + { + "text": "test2", + "sparse": SparseVector(indices=[1, 3], values=[1.5, 2.5]), + }, + {"text": "test3"}, # No sparse vector + ], + documents=["doc one", "doc two", "doc three"], + ) + + # Both should be converted to SparseVector instances + assert isinstance(record_set["metadatas"][0]["sparse"], SparseVector) + assert isinstance(record_set["metadatas"][1]["sparse"], SparseVector) + assert "sparse" not in record_set["metadatas"][2] + + # Validation should pass + validate_insert_record_set(record_set) + + # Test 2: Verify values are correct after normalization + assert record_set["metadatas"][0]["sparse"].indices == [0, 2] + assert record_set["metadatas"][0]["sparse"].values == [1.0, 2.0] + assert record_set["metadatas"][1]["sparse"].indices == [1, 3] + assert record_set["metadatas"][1]["sparse"].values == [1.5, 2.5] + + +def test_search_result_rows() -> None: + """Test the SearchResult.rows() method for converting column-major to row-major format.""" + from chromadb.api.types import SearchResult + + # Test 1: Basic single payload with all fields + result = SearchResult( + { + "ids": [["id1", "id2", "id3"]], + "documents": [["doc1", "doc2", "doc3"]], + "embeddings": [[[1.0, 2.0], [3.0, 4.0], [5.0, 6.0]]], + "metadatas": [[{"key": "a"}, {"key": "b"}, {"key": "c"}]], + "scores": [[0.9, 0.8, 0.7]], + "select": [["document", "score", "metadata"]], + } + ) + + rows = result.rows() + assert len(rows) == 1 # One payload + assert len(rows[0]) == 3 # Three results + + # Check first row + assert rows[0][0]["id"] == "id1" + assert rows[0][0]["document"] == "doc1" + assert rows[0][0]["embedding"] == [1.0, 2.0] + assert rows[0][0]["metadata"] == {"key": "a"} + assert rows[0][0]["score"] == 0.9 + + # Check all rows have all fields + for row in rows[0]: + assert "id" in row + assert "document" in row + assert "embedding" in row + assert "metadata" in row + assert "score" in row + + # Test 2: Multiple payloads + result = SearchResult( + { + "ids": [["a1", "a2"], ["b1", "b2", "b3"]], + "documents": [["doc_a1", "doc_a2"], ["doc_b1", "doc_b2", "doc_b3"]], + "embeddings": [ + None, + [[1.0], [2.0], [3.0]], + ], # First payload has no embeddings + "metadatas": [[{"x": 1}, {"x": 2}], None], # Second payload has no metadata + "scores": [[0.5, 0.4], [0.9, 0.8, 0.7]], + "select": [["document", "score"], ["embedding", "score"]], + } + ) + + rows = result.rows() + assert len(rows) == 2 # Two payloads + assert len(rows[0]) == 2 # First payload has 2 results + assert len(rows[1]) == 3 # Second payload has 3 results + + # First payload - has docs, metadata, scores but no embeddings + assert rows[0][0] == { + "id": "a1", + "document": "doc_a1", + "metadata": {"x": 1}, + "score": 0.5, + } + assert rows[0][1] == { + "id": "a2", + "document": "doc_a2", + "metadata": {"x": 2}, + "score": 0.4, + } + + # Second payload - has docs, embeddings, scores but no metadata + assert rows[1][0] == { + "id": "b1", + "document": "doc_b1", + "embedding": [1.0], + "score": 0.9, + } + assert rows[1][1] == { + "id": "b2", + "document": "doc_b2", + "embedding": [2.0], + "score": 0.8, + } + assert rows[1][2] == { + "id": "b3", + "document": "doc_b3", + "embedding": [3.0], + "score": 0.7, + } + + # Test 3: Empty result + result = SearchResult( + { + "ids": [], + "documents": [], + "embeddings": [], + "metadatas": [], + "scores": [], + "select": [], + } + ) + + rows = result.rows() + assert rows == [] + + # Test 4: Sparse data with None values in lists + result = SearchResult( + { + "ids": [["id1", "id2", "id3"]], + "documents": [[None, "doc2", None]], # Sparse documents + "embeddings": None, # No embeddings at all + "metadatas": [[{"a": 1}, None, {"c": 3}]], # Sparse metadata + "scores": [[0.9, None, 0.7]], # Sparse scores + "select": [["document", "metadata", "score"]], + } + ) + + rows = result.rows() + assert len(rows) == 1 + assert len(rows[0]) == 3 + + # First row - only has metadata and score + assert rows[0][0] == {"id": "id1", "metadata": {"a": 1}, "score": 0.9} + + # Second row - only has document + assert rows[0][1] == {"id": "id2", "document": "doc2"} + + # Third row - has metadata and score + assert rows[0][2] == {"id": "id3", "metadata": {"c": 3}, "score": 0.7} + + # Test 5: Only IDs (minimal result) + result = SearchResult( + { + "ids": [["id1", "id2"]], + "documents": None, + "embeddings": None, + "metadatas": None, + "scores": None, + "select": [[]], + } + ) + + rows = result.rows() + assert len(rows) == 1 + assert len(rows[0]) == 2 + assert rows[0][0] == {"id": "id1"} + assert rows[0][1] == {"id": "id2"} + + # Test 6: SearchResult works as dict (backward compatibility) + result = SearchResult( + { + "ids": [["test"]], + "documents": [["test doc"]], + "metadatas": [[{"test": True}]], + "embeddings": [[[0.1, 0.2]]], + "scores": [[0.99]], + "select": [["all"]], + } + ) + + # Should work as dict + assert result["ids"] == [["test"]] + assert result.get("documents") == [["test doc"]] + assert "metadatas" in result + assert len(result) == 6 # Should have 6 keys + + # Should also have rows() method + rows = result.rows() + assert len(rows[0]) == 1 + assert rows[0][0]["id"] == "test" + + print("All SearchResult.rows() tests passed!") + + +def test_rrf_to_dict() -> None: + """Test the Rrf (Reciprocal Rank Fusion) to_dict conversion.""" + # Note: In these tests, "sparse_embedding" is just an example metadata field name. + # Users can store any data in metadata fields and reference them by name (without # prefix). + # The "#embedding" key refers to the special main embedding field. + + import pytest + from chromadb.execution.expression.operator import Rrf, Knn, Val + + # Test 1: Basic RRF with two KNN rankings (equal weight) + rrf = Rrf( + [ + Knn(query=[0.1, 0.2], return_rank=True), + Knn(query=[0.3, 0.4], key="sparse_embedding", return_rank=True), + ] + ) + + result = rrf.to_dict() + + # RRF formula: -sum(weight_i / (k + rank_i)) + # With default k=60 and equal weights (1.0 each) + # Expected: -(1.0/(60 + knn1) + 1.0/(60 + knn2)) + expected = { + "$mul": [ + {"$val": -1}, + { + "$sum": [ + { + "$div": { + "left": {"$val": 1.0}, + "right": { + "$sum": [ + {"$val": 60}, + { + "$knn": { + "query": [0.1, 0.2], + "key": "#embedding", + "limit": 16, + "return_rank": True, + } + }, + ] + }, + } + }, + { + "$div": { + "left": {"$val": 1.0}, + "right": { + "$sum": [ + {"$val": 60}, + { + "$knn": { + "query": [0.3, 0.4], + "key": "sparse_embedding", + "limit": 16, + "return_rank": True, + } + }, + ] + }, + } + }, + ] + }, + ] + } + + assert result == expected + + # Test 2: RRF with custom weights and k + rrf_weighted = Rrf( + ranks=[ + Knn(query=[0.1, 0.2], return_rank=True), + Knn(query=[0.3, 0.4], key="sparse_embedding", return_rank=True), + ], + weights=[2.0, 1.0], # Dense is 2x more important + k=100, + ) + + result_weighted = rrf_weighted.to_dict() + + # Expected: -(2.0/(100 + knn1) + 1.0/(100 + knn2)) + expected_weighted = { + "$mul": [ + {"$val": -1}, + { + "$sum": [ + { + "$div": { + "left": {"$val": 2.0}, + "right": { + "$sum": [ + {"$val": 100}, + { + "$knn": { + "query": [0.1, 0.2], + "key": "#embedding", + "limit": 16, + "return_rank": True, + } + }, + ] + }, + } + }, + { + "$div": { + "left": {"$val": 1.0}, + "right": { + "$sum": [ + {"$val": 100}, + { + "$knn": { + "query": [0.3, 0.4], + "key": "sparse_embedding", + "limit": 16, + "return_rank": True, + } + }, + ] + }, + } + }, + ] + }, + ] + } + + assert result_weighted == expected_weighted + + # Test 3: RRF with three rankings + rrf_three = Rrf( + [ + Knn(query=[0.1, 0.2], return_rank=True), + Knn(query=[0.3, 0.4], key="sparse_embedding", return_rank=True), + Val(5.0), # Can also include constant rank + ] + ) + + result_three = rrf_three.to_dict() + + # Verify it has three terms in the sum + assert "$mul" in result_three + assert "$sum" in result_three["$mul"][1] + terms = result_three["$mul"][1]["$sum"] + assert len(terms) == 3 # Three ranking strategies + + # Test 4: Error case - mismatched weights + with pytest.raises( + ValueError, match="Number of weights .* must match number of ranks" + ): + rrf_bad = Rrf( + ranks=[ + Knn(query=[0.1, 0.2], return_rank=True), + Knn(query=[0.3, 0.4], return_rank=True), + ], + weights=[1.0], # Only one weight for two ranks + ) + rrf_bad.to_dict() + + # Test 5: Error case - negative weights + with pytest.raises(ValueError, match="All weights must be non-negative"): + rrf_negative = Rrf( + ranks=[ + Knn(query=[0.1, 0.2], return_rank=True), + Knn(query=[0.3, 0.4], return_rank=True), + ], + weights=[1.0, -1.0], # Negative weight + ) + rrf_negative.to_dict() + + # Test 6: Error case - empty ranks list + with pytest.raises(ValueError, match="RRF requires at least one rank"): + rrf_empty = Rrf([]) + rrf_empty.to_dict() # Validation happens in to_dict() + + # Test 7: Error case - negative k value + with pytest.raises(ValueError, match="k must be positive"): + rrf_neg_k = Rrf([Val(1.0)], k=-5) + rrf_neg_k.to_dict() # Validation happens in to_dict() + + # Test 8: Error case - zero k value + with pytest.raises(ValueError, match="k must be positive"): + rrf_zero_k = Rrf([Val(1.0)], k=0) + rrf_zero_k.to_dict() # Validation happens in to_dict() + # Test 9: Normalize flag with weights + rrf_normalized = Rrf( + ranks=[ + Knn(query=[0.1, 0.2], return_rank=True), + Knn(query=[0.3, 0.4], key="sparse_embedding", return_rank=True), + ], + weights=[3.0, 1.0], # Will be normalized to [0.75, 0.25] + normalize=True, + k=100, + ) + + result_normalized = rrf_normalized.to_dict() + + # Expected: -(0.75/(100 + knn1) + 0.25/(100 + knn2)) + expected_normalized = { + "$mul": [ + {"$val": -1}, + { + "$sum": [ + { + "$div": { + "left": {"$val": 0.75}, + "right": { + "$sum": [ + {"$val": 100}, + { + "$knn": { + "query": [0.1, 0.2], + "key": "#embedding", + "limit": 16, + "return_rank": True, + } + }, + ] + }, + } + }, + { + "$div": { + "left": {"$val": 0.25}, + "right": { + "$sum": [ + {"$val": 100}, + { + "$knn": { + "query": [0.3, 0.4], + "key": "sparse_embedding", + "limit": 16, + "return_rank": True, + } + }, + ] + }, + } + }, + ] + }, + ] + } + + assert result_normalized == expected_normalized + + # Test 10: Normalize flag without weights (should work with defaults) + rrf_normalize_defaults = Rrf( + ranks=[ + Knn(query=[0.1, 0.2], return_rank=True), + Knn(query=[0.3, 0.4], return_rank=True), + ], + normalize=True, # Will normalize [1.0, 1.0] to [0.5, 0.5] + ) + + result_defaults = rrf_normalize_defaults.to_dict() + + # Both weights should be 0.5 after normalization + expected_defaults = { + "$mul": [ + {"$val": -1}, + { + "$sum": [ + { + "$div": { + "left": {"$val": 0.5}, + "right": { + "$sum": [ + {"$val": 60}, # Default k=60 + { + "$knn": { + "query": [0.1, 0.2], + "key": "#embedding", + "limit": 16, + "return_rank": True, + } + }, + ] + }, + } + }, + { + "$div": { + "left": {"$val": 0.5}, + "right": { + "$sum": [ + {"$val": 60}, + { + "$knn": { + "query": [0.3, 0.4], + "key": "#embedding", + "limit": 16, + "return_rank": True, + } + }, + ] + }, + } + }, + ] + }, + ] + } + + assert result_defaults == expected_defaults + + # Test 11: Error case - normalize with all zero weights + with pytest.raises(ValueError, match="Sum of weights must be positive"): + rrf_zero_weights = Rrf( + ranks=[ + Knn(query=[0.1, 0.2], return_rank=True), + Knn(query=[0.3, 0.4], return_rank=True), + ], + weights=[0.0, 0.0], + normalize=True, + ) + rrf_zero_weights.to_dict() + + print("All RRF tests passed!") + + +def test_group_by_serialization() -> None: + """Test GroupBy, MinK, and MaxK serialization and deserialization.""" + import pytest + from chromadb.execution.expression.operator import ( + GroupBy, + MinK, + MaxK, + Key, + Aggregate, + ) + + # to_dict with OneOrMany keys + group_by = GroupBy(keys=Key("category"), aggregate=MinK(keys=Key.SCORE, k=3)) + assert group_by.to_dict() == { + "keys": ["category"], + "aggregate": {"$min_k": {"keys": ["#score"], "k": 3}}, + } + + # to_dict with multiple keys and MaxK + group_by = GroupBy( + keys=[Key("year"), Key("category")], + aggregate=MaxK(keys=[Key.SCORE, Key("priority")], k=5), + ) + assert group_by.to_dict() == { + "keys": ["year", "category"], + "aggregate": {"$max_k": {"keys": ["#score", "priority"], "k": 5}}, + } + + # Round-trip + original = GroupBy(keys=[Key("category")], aggregate=MinK(keys=[Key.SCORE], k=3)) + assert GroupBy.from_dict(original.to_dict()).to_dict() == original.to_dict() + + # Empty GroupBy serializes to {} and from_dict({}) returns default GroupBy + empty_group_by = GroupBy() + assert empty_group_by.to_dict() == {} + assert GroupBy.from_dict({}).to_dict() == {} + + # Error cases + with pytest.raises(ValueError, match="requires 'keys' field"): + GroupBy.from_dict({"aggregate": {"$min_k": {"keys": ["#score"], "k": 3}}}) + + with pytest.raises(ValueError, match="requires 'aggregate' field"): + GroupBy.from_dict({"keys": ["category"]}) + + with pytest.raises(ValueError, match="keys cannot be empty"): + GroupBy.from_dict( + {"keys": [], "aggregate": {"$min_k": {"keys": ["#score"], "k": 3}}} + ) + + with pytest.raises(ValueError, match="Unknown aggregate operator"): + Aggregate.from_dict({"$unknown": {"keys": ["#score"], "k": 3}}) + + +# Expression API Tests - Testing dict support and from_dict methods +class TestSearchDictSupport: + """Test Search class dict input support.""" + + def test_search_with_dict_where(self): + """Test Search accepts dict for where parameter.""" + from chromadb.execution.expression.plan import Search + from chromadb.execution.expression.operator import Where + + # Simple equality + search = Search(where={"status": "active"}) + assert search._where is not None + assert isinstance(search._where, Where) + + # Complex where with operators + search = Search(where={"$and": [{"status": "active"}, {"score": {"$gt": 0.5}}]}) + assert search._where is not None + + def test_search_with_dict_rank(self): + """Test Search accepts dict for rank parameter.""" + from chromadb.execution.expression.plan import Search + from chromadb.execution.expression.operator import Rank + + # KNN ranking + search = Search(rank={"$knn": {"query": [0.1, 0.2]}}) + assert search._rank is not None + assert isinstance(search._rank, Rank) + + # Val ranking + search = Search(rank={"$val": 0.5}) + assert search._rank is not None + + def test_search_with_dict_limit(self): + """Test Search accepts dict and int for limit parameter.""" + from chromadb.execution.expression.plan import Search + + # Dict limit + search = Search(limit={"limit": 10, "offset": 5}) + assert search._limit.limit == 10 + assert search._limit.offset == 5 + + # Int limit (creates Limit with offset=0) + search = Search(limit=10) + assert search._limit.limit == 10 + assert search._limit.offset == 0 + + def test_search_with_dict_select(self): + """Test Search accepts dict, list, and set for select parameter.""" + from chromadb.execution.expression.plan import Search + + # Dict select + search = Search(select={"keys": ["#document", "#score"]}) + assert search._select is not None + + # List select + search = Search(select=["#document", "#metadata"]) + assert search._select is not None + + # Set select + search = Search(select={"#document", "#embedding"}) + assert search._select is not None + + def test_search_mixed_inputs(self): + """Test Search with mixed expression and dict inputs.""" + from chromadb.execution.expression.plan import Search + from chromadb.execution.expression.operator import Key + + search = Search( + where=Key("status") == "active", # Expression + rank={"$knn": {"query": [0.1, 0.2]}}, # Dict + limit=10, # Int + select=["#document"], # List + ) + assert search._where is not None + assert search._rank is not None + assert search._limit.limit == 10 + assert search._select is not None + + def test_search_builder_methods_with_dicts(self): + """Test Search builder methods accept dicts.""" + from chromadb.execution.expression.plan import Search + + search = Search().where({"status": "active"}).rank({"$val": 0.5}) + assert search._where is not None + assert search._rank is not None + + def test_search_invalid_inputs(self): + """Test Search rejects invalid input types.""" + import pytest + from chromadb.execution.expression.plan import Search + + with pytest.raises(TypeError, match="where must be"): + Search(where="invalid") + + with pytest.raises(TypeError, match="rank must be"): + Search(rank=0.5) # Primitive numbers not allowed + + with pytest.raises(TypeError, match="limit must be"): + Search(limit="10") + + with pytest.raises(TypeError, match="select must be"): + Search(select=123) + + def test_search_with_group_by(self): + """Test Search accepts group_by as dict, object, and builder method.""" + import pytest + from chromadb.execution.expression.plan import Search + from chromadb.execution.expression.operator import GroupBy, MinK, Key + + # Dict input + search = Search( + group_by={ + "keys": ["category"], + "aggregate": {"$min_k": {"keys": ["#score"], "k": 3}}, + } + ) + assert isinstance(search._group_by, GroupBy) + + # Object input and builder method + group_by = GroupBy(keys=Key("category"), aggregate=MinK(keys=Key.SCORE, k=3)) + assert Search(group_by=group_by)._group_by is group_by + assert Search().group_by(group_by)._group_by.aggregate is not None + + # Invalid inputs + with pytest.raises(TypeError, match="group_by must be"): + Search(group_by="invalid") + with pytest.raises(ValueError, match="requires 'aggregate' field"): + Search(group_by={"keys": ["category"]}) + + def test_search_group_by_serialization(self): + """Test Search serializes group_by correctly.""" + from chromadb.execution.expression.plan import Search + from chromadb.execution.expression.operator import GroupBy, MinK, Key, Knn + + # Without group_by - empty dict + search = Search().rank(Knn(query=[0.1, 0.2])).limit(10) + assert search.to_dict()["group_by"] == {} + + # With group_by - has keys and aggregate + search = Search().group_by( + GroupBy(keys=Key("category"), aggregate=MinK(keys=Key.SCORE, k=3)) + ) + result = search.to_dict()["group_by"] + assert result["keys"] == ["category"] + assert result["aggregate"] == {"$min_k": {"keys": ["#score"], "k": 3}} + + +class TestWhereFromDict: + """Test Where.from_dict() conversion.""" + + def test_simple_equality(self): + """Test simple equality conversion.""" + from chromadb.execution.expression.operator import Where, Eq + + # Shorthand for equality + where = Where.from_dict({"status": "active"}) + assert isinstance(where, Eq) + + # Explicit $eq + where = Where.from_dict({"status": {"$eq": "active"}}) + assert isinstance(where, Eq) + + def test_comparison_operators(self): + """Test comparison operator conversions.""" + from chromadb.execution.expression.operator import Where, Ne, Gt, Gte, Lt, Lte + + # $ne + where = Where.from_dict({"status": {"$ne": "inactive"}}) + assert isinstance(where, Ne) + + # $gt + where = Where.from_dict({"score": {"$gt": 0.5}}) + assert isinstance(where, Gt) + + # $gte + where = Where.from_dict({"score": {"$gte": 0.5}}) + assert isinstance(where, Gte) + + # $lt + where = Where.from_dict({"score": {"$lt": 1.0}}) + assert isinstance(where, Lt) + + # $lte + where = Where.from_dict({"score": {"$lte": 1.0}}) + assert isinstance(where, Lte) + + def test_membership_operators(self): + """Test membership operator conversions.""" + from chromadb.execution.expression.operator import Where, In, Nin + + # $in + where = Where.from_dict({"status": {"$in": ["active", "pending"]}}) + assert isinstance(where, In) + + # $nin (not in) + where = Where.from_dict({"status": {"$nin": ["deleted", "archived"]}}) + assert isinstance(where, Nin) + + def test_string_operators(self): + """Test string operator conversions.""" + from chromadb.execution.expression.operator import ( + Where, + Contains, + NotContains, + Regex, + NotRegex, + ) + + # $contains + where = Where.from_dict({"text": {"$contains": "hello"}}) + assert isinstance(where, Contains) + + # $not_contains + where = Where.from_dict({"text": {"$not_contains": "spam"}}) + assert isinstance(where, NotContains) + + # $regex + where = Where.from_dict({"text": {"$regex": "^test.*"}}) + assert isinstance(where, Regex) + + # $not_regex + where = Where.from_dict({"text": {"$not_regex": r"\d+"}}) + assert isinstance(where, NotRegex) + + def test_array_contains_operators(self): + """Test $contains/$not_contains with all scalar types for metadata array queries.""" + from chromadb.execution.expression.operator import Where, Contains, NotContains + + # String + where = Where.from_dict({"tags": {"$contains": "action"}}) + assert isinstance(where, Contains) + assert where.to_dict() == {"tags": {"$contains": "action"}} + + # Integer + where = Where.from_dict({"scores": {"$contains": 42}}) + assert isinstance(where, Contains) + assert where.to_dict() == {"scores": {"$contains": 42}} + + # Float + where = Where.from_dict({"ratings": {"$contains": 4.5}}) + assert isinstance(where, Contains) + assert where.to_dict() == {"ratings": {"$contains": 4.5}} + + # Boolean + where = Where.from_dict({"flags": {"$contains": True}}) + assert isinstance(where, Contains) + assert where.to_dict() == {"flags": {"$contains": True}} + + # $not_contains + where = Where.from_dict({"tags": {"$not_contains": "draft"}}) + assert isinstance(where, NotContains) + assert where.to_dict() == {"tags": {"$not_contains": "draft"}} + + where = Where.from_dict({"scores": {"$not_contains": 0}}) + assert isinstance(where, NotContains) + assert where.to_dict() == {"scores": {"$not_contains": 0}} + + def test_array_contains_invalid_operands(self): + """Test $contains/$not_contains reject invalid operand types.""" + import pytest + from chromadb.execution.expression.operator import Where + + with pytest.raises(TypeError, match="\\$contains requires"): + Where.from_dict({"tags": {"$contains": [1, 2]}}) + + with pytest.raises(TypeError, match="\\$not_contains requires"): + Where.from_dict({"tags": {"$not_contains": {"nested": True}}}) + + def test_array_contains_round_trip(self): + """Test $contains round-trips through to_dict/from_dict.""" + from chromadb.execution.expression.operator import Where, Key + + cases = [ + Key("tags").contains("action"), + Key("scores").contains(42), + Key("ratings").contains(4.5), + Key("flags").contains(True), + Key("tags").not_contains("draft"), + ] + for original in cases: + d = original.to_dict() + restored = Where.from_dict(d) + assert restored.to_dict() == d, f"Round-trip failed for {d}" + + def test_array_contains_in_composite(self): + """Test $contains combined with other operators via $and/$or.""" + from chromadb.execution.expression.operator import Where, And, Key + + where = (Key("tags").contains("action")) & (Key("year") > 2020) + assert isinstance(where, And) + d = where.to_dict() + restored = Where.from_dict(d) + assert restored.to_dict() == d + + def test_document_contains_requires_string(self): + """Key.DOCUMENT.contains/not_contains must receive a string.""" + import pytest + from chromadb.execution.expression.operator import Key + + # String is fine + expr = Key.DOCUMENT.contains("hello") + assert expr.to_dict() == {"#document": {"$contains": "hello"}} + + expr = Key.DOCUMENT.not_contains("hello") + assert expr.to_dict() == {"#document": {"$not_contains": "hello"}} + + # Non-string types must be rejected + for bad_value in [42, 3.14, True, False]: + with pytest.raises( + TypeError, match="\\$contains on #document requires a string" + ): + Key.DOCUMENT.contains(bad_value) + + with pytest.raises( + TypeError, match="\\$not_contains on #document requires a string" + ): + Key.DOCUMENT.not_contains(bad_value) + + # Metadata keys still accept non-string scalars + assert Key("scores").contains(42).to_dict() == {"scores": {"$contains": 42}} + assert Key("flags").not_contains(True).to_dict() == { + "flags": {"$not_contains": True} + } + + def test_logical_operators(self): + """Test logical operator conversions.""" + from chromadb.execution.expression.operator import Where, And, Or + + # $and + where = Where.from_dict( + {"$and": [{"status": "active"}, {"score": {"$gt": 0.5}}]} + ) + assert isinstance(where, And) + + # $or + where = Where.from_dict({"$or": [{"status": "active"}, {"status": "pending"}]}) + assert isinstance(where, Or) + + def test_nested_logical_operators(self): + """Test nested logical operations.""" + from chromadb.execution.expression.operator import Where, And + + where = Where.from_dict( + { + "$and": [ + {"$or": [{"status": "active"}, {"status": "pending"}]}, + {"score": {"$gte": 0.5}}, + ] + } + ) + assert isinstance(where, And) + + def test_special_keys(self): + """Test special key handling.""" + from chromadb.execution.expression.operator import Where, In + + # ID key + where = Where.from_dict({"#id": {"$in": ["id1", "id2"]}}) + assert isinstance(where, In) + + def test_invalid_where_dicts(self): + """Test invalid Where dict inputs.""" + import pytest + from chromadb.execution.expression.operator import Where + + with pytest.raises(TypeError, match="Expected dict"): + Where.from_dict("not a dict") + + with pytest.raises(ValueError, match="cannot be empty"): + Where.from_dict({}) + + with pytest.raises(ValueError, match="requires at least one condition"): + Where.from_dict({"$and": []}) + + +class TestRankFromDict: + """Test Rank.from_dict() conversion.""" + + def test_val_conversion(self): + """Test Val conversion.""" + from chromadb.execution.expression.operator import Rank, Val + + rank = Rank.from_dict({"$val": 0.5}) + assert isinstance(rank, Val) + assert rank.value == 0.5 + + def test_knn_conversion(self): + """Test KNN conversion.""" + import numpy as np + from chromadb.execution.expression.operator import Rank, Knn + + # Basic KNN with defaults + rank = Rank.from_dict({"$knn": {"query": [0.1, 0.2]}}) + assert isinstance(rank, Knn) + # Handle both list and numpy array cases + if isinstance(rank.query, np.ndarray): + # Use allclose for floating point comparison with dtype tolerance + assert np.allclose(rank.query, np.array([0.1, 0.2])) + else: + assert rank.query == [0.1, 0.2] + assert rank.key == "#embedding" # default + assert rank.limit == 16 # default + + # KNN with custom parameters + rank = Rank.from_dict( + { + "$knn": { + "query": [0.1, 0.2], + "key": "sparse_embedding", + "limit": 256, + "return_rank": True, + } + } + ) + assert rank.key == "sparse_embedding" + assert rank.limit == 256 + assert rank.return_rank + + def test_arithmetic_operators(self): + """Test arithmetic operator conversions.""" + from chromadb.execution.expression.operator import Rank, Sum, Sub, Mul, Div + + # $sum + rank = Rank.from_dict({"$sum": [{"$val": 0.5}, {"$val": 0.3}]}) + assert isinstance(rank, Sum) + + # $sub + rank = Rank.from_dict({"$sub": {"left": {"$val": 1.0}, "right": {"$val": 0.3}}}) + assert isinstance(rank, Sub) + + # $mul + rank = Rank.from_dict({"$mul": [{"$val": 2.0}, {"$val": 0.5}]}) + assert isinstance(rank, Mul) + + # $div + rank = Rank.from_dict({"$div": {"left": {"$val": 1.0}, "right": {"$val": 2.0}}}) + assert isinstance(rank, Div) + + def test_math_functions(self): + """Test math function conversions.""" + from chromadb.execution.expression.operator import Rank, Abs, Exp, Log + + # $abs + rank = Rank.from_dict({"$abs": {"$val": -0.5}}) + assert isinstance(rank, Abs) + + # $exp + rank = Rank.from_dict({"$exp": {"$val": 1.0}}) + assert isinstance(rank, Exp) + + # $log + rank = Rank.from_dict({"$log": {"$val": 2.0}}) + assert isinstance(rank, Log) + + def test_aggregation_functions(self): + """Test min/max conversions.""" + from chromadb.execution.expression.operator import Rank, Max, Min + + # $max + rank = Rank.from_dict({"$max": [{"$val": 0.5}, {"$val": 0.8}]}) + assert isinstance(rank, Max) + + # $min + rank = Rank.from_dict({"$min": [{"$val": 0.5}, {"$val": 0.8}]}) + assert isinstance(rank, Min) + + def test_complex_rank_expression(self): + """Test complex nested rank expressions.""" + from chromadb.execution.expression.operator import Rank, Sum + + rank = Rank.from_dict( + { + "$sum": [ + {"$mul": [{"$knn": {"query": [0.1, 0.2]}}, {"$val": 0.8}]}, + {"$mul": [{"$val": 0.5}, {"$val": 0.2}]}, + ] + } + ) + assert isinstance(rank, Sum) + + def test_invalid_rank_dicts(self): + """Test invalid Rank dict inputs.""" + import pytest + from chromadb.execution.expression.operator import Rank + + with pytest.raises(TypeError, match="Expected dict"): + Rank.from_dict("not a dict") + + with pytest.raises(ValueError, match="cannot be empty"): + Rank.from_dict({}) + + with pytest.raises(ValueError, match="exactly one operator"): + Rank.from_dict({"$val": 0.5, "$knn": {"query": [0.1]}}) + + with pytest.raises(TypeError, match="requires a number"): + Rank.from_dict({"$val": "not a number"}) + + +class TestLimitFromDict: + """Test Limit.from_dict() conversion.""" + + def test_limit_only(self): + """Test limit without offset.""" + from chromadb.execution.expression.operator import Limit + + limit = Limit.from_dict({"limit": 20}) + assert limit.limit == 20 + assert limit.offset == 0 # default + + def test_offset_only(self): + """Test offset without limit.""" + from chromadb.execution.expression.operator import Limit + + limit = Limit.from_dict({"offset": 10}) + assert limit.offset == 10 + assert limit.limit is None + + def test_limit_and_offset(self): + """Test both limit and offset.""" + from chromadb.execution.expression.operator import Limit + + limit = Limit.from_dict({"limit": 20, "offset": 10}) + assert limit.limit == 20 + assert limit.offset == 10 + + def test_validation(self): + """Test Limit validation.""" + import pytest + from chromadb.execution.expression.operator import Limit + + # Negative limit + with pytest.raises(ValueError, match="must be positive"): + Limit.from_dict({"limit": -1}) + + # Zero limit + with pytest.raises(ValueError, match="must be positive"): + Limit.from_dict({"limit": 0}) + + # Negative offset + with pytest.raises(ValueError, match="must be non-negative"): + Limit.from_dict({"offset": -1}) + + def test_invalid_types(self): + """Test type validation.""" + import pytest + from chromadb.execution.expression.operator import Limit + + with pytest.raises(TypeError, match="Expected dict"): + Limit.from_dict("not a dict") + + with pytest.raises(TypeError, match="must be an integer"): + Limit.from_dict({"limit": "20"}) + + with pytest.raises(TypeError, match="must be an integer"): + Limit.from_dict({"offset": 10.5}) + + def test_unexpected_keys(self): + """Test rejection of unexpected keys.""" + import pytest + from chromadb.execution.expression.operator import Limit + + with pytest.raises(ValueError, match="Unexpected keys"): + Limit.from_dict({"limit": 10, "invalid": "key"}) + + +class TestSelectFromDict: + """Test Select.from_dict() conversion.""" + + def test_special_keys(self): + """Test special key conversion.""" + from chromadb.execution.expression.operator import Select, Key + + select = Select.from_dict( + {"keys": ["#document", "#embedding", "#metadata", "#score"]} + ) + assert Key.DOCUMENT in select.keys + assert Key.EMBEDDING in select.keys + assert Key.METADATA in select.keys + assert Key.SCORE in select.keys + + def test_metadata_keys(self): + """Test regular metadata field keys.""" + from chromadb.execution.expression.operator import Select, Key + + select = Select.from_dict({"keys": ["title", "author", "date"]}) + assert Key("title") in select.keys + assert Key("author") in select.keys + assert Key("date") in select.keys + + def test_mixed_keys(self): + """Test mix of special and metadata keys.""" + from chromadb.execution.expression.operator import Select, Key + + select = Select.from_dict({"keys": ["#document", "title", "#score"]}) + assert Key.DOCUMENT in select.keys + assert Key("title") in select.keys + assert Key.SCORE in select.keys + + def test_empty_keys(self): + """Test empty keys list.""" + from chromadb.execution.expression.operator import Select + + select = Select.from_dict({"keys": []}) + assert len(select.keys) == 0 + + def test_validation(self): + """Test Select validation.""" + import pytest + from chromadb.execution.expression.operator import Select + + with pytest.raises(TypeError, match="Expected dict"): + Select.from_dict("not a dict") + + with pytest.raises(TypeError, match="must be a list/tuple/set"): + Select.from_dict({"keys": "not a list"}) + + with pytest.raises(TypeError, match="must be a string"): + Select.from_dict({"keys": [123]}) + + def test_unexpected_keys(self): + """Test rejection of unexpected keys.""" + import pytest + from chromadb.execution.expression.operator import Select + + with pytest.raises(ValueError, match="Unexpected keys"): + Select.from_dict({"keys": [], "invalid": "key"}) + + +class TestRoundTripConversion: + """Test that to_dict() and from_dict() round-trip correctly.""" + + def test_where_round_trip(self): + """Test Where round-trip conversion.""" + from chromadb.execution.expression.operator import Where, And, Key + + original = And([Key("status") == "active", Key("score") > 0.5]) + dict_form = original.to_dict() + restored = Where.from_dict(dict_form) + assert restored.to_dict() == dict_form + + def test_rank_round_trip(self): + """Test Rank round-trip conversion.""" + import numpy as np + from chromadb.execution.expression.operator import Rank, Knn, Val + + original = Knn(query=[0.1, 0.2]) * 0.8 + Val(0.5) * 0.2 + dict_form = original.to_dict() + restored = Rank.from_dict(dict_form) + restored_dict = restored.to_dict() + + # Compare with float32 precision tolerance for KNN queries + # The normalize_embeddings function converts to float32, causing precision differences + def compare_dicts(d1, d2): + if isinstance(d1, dict) and isinstance(d2, dict): + if "$knn" in d1 and "$knn" in d2: + # Special handling for KNN queries + knn1, knn2 = d1["$knn"], d2["$knn"] + if "query" in knn1 and "query" in knn2: + # Compare queries with float32 precision + q1 = np.array(knn1["query"], dtype=np.float32) + q2 = np.array(knn2["query"], dtype=np.float32) + if not np.allclose(q1, q2): + return False + # Compare other fields exactly + for key in knn1: + if key != "query" and knn1[key] != knn2.get(key): + return False + return True + + # Recursively compare other dict structures + if set(d1.keys()) != set(d2.keys()): + return False + for key in d1: + if not compare_dicts(d1[key], d2[key]): + return False + return True + elif isinstance(d1, list) and isinstance(d2, list): + if len(d1) != len(d2): + return False + return all(compare_dicts(a, b) for a, b in zip(d1, d2)) + else: + return d1 == d2 + + assert compare_dicts(restored_dict, dict_form) + + def test_limit_round_trip(self): + """Test Limit round-trip conversion.""" + from chromadb.execution.expression.operator import Limit + + original = Limit(limit=20, offset=10) + dict_form = original.to_dict() + restored = Limit.from_dict(dict_form) + assert restored.to_dict() == dict_form + + def test_select_round_trip(self): + """Test Select round-trip conversion.""" + from chromadb.execution.expression.operator import Select, Key + + original = Select(keys={Key.DOCUMENT, Key("title"), Key.SCORE}) + dict_form = original.to_dict() + restored = Select.from_dict(dict_form) + # Note: Set order might differ, so compare sets + assert set(restored.to_dict()["keys"]) == set(dict_form["keys"]) + + def test_search_round_trip(self): + """Test Search round-trip through dict inputs.""" + import numpy as np + from chromadb.execution.expression.plan import Search + from chromadb.execution.expression.operator import Key, Knn, Limit, Select + + original_search = Search( + where=Key("status") == "active", + rank=Knn(query=[0.1, 0.2]), + limit=Limit(limit=10), + select=Select(keys={Key.DOCUMENT}), + ) + + # Convert to dict + search_dict = original_search.to_dict() + + # Create new Search from dicts + new_search = Search( + where=search_dict["filter"] if search_dict["filter"] else None, + rank=search_dict["rank"] if search_dict["rank"] else None, + limit=search_dict["limit"], + select=search_dict["select"], + ) + + # Get new dict + new_dict = new_search.to_dict() + + # Compare with float32 tolerance for KNN queries + # Use the same comparison function as test_rank_round_trip + def compare_search_dicts(d1, d2): + if isinstance(d1, dict) and isinstance(d2, dict): + # Special handling for rank field with KNN + if "rank" in d1 and "rank" in d2: + rank1, rank2 = d1["rank"], d2["rank"] + if isinstance(rank1, dict) and isinstance(rank2, dict): + if "$knn" in rank1 and "$knn" in rank2: + knn1, knn2 = rank1["$knn"], rank2["$knn"] + if "query" in knn1 and "query" in knn2: + q1 = np.array(knn1["query"], dtype=np.float32) + q2 = np.array(knn2["query"], dtype=np.float32) + if not np.allclose(q1, q2): + return False + # Compare other KNN fields + for key in knn1: + if key != "query" and knn1[key] != knn2.get(key): + return False + # Compare other fields in the dict + for key in d1: + if key != "rank" and d1[key] != d2.get(key): + return False + return True + + # Normal dict comparison + if set(d1.keys()) != set(d2.keys()): + return False + for key in d1: + if isinstance(d1[key], dict) and isinstance(d2[key], dict): + if not compare_search_dicts(d1[key], d2[key]): + return False + elif d1[key] != d2[key]: + return False + return True + else: + return d1 == d2 + + assert compare_search_dicts(new_dict, search_dict) + + def test_search_round_trip_with_group_by(self): + """Test Search round-trip with group_by.""" + from chromadb.execution.expression.plan import Search + from chromadb.execution.expression.operator import Key, GroupBy, MinK + + original = Search( + where=Key("status") == "active", + group_by=GroupBy( + keys=[Key("category")], + aggregate=MinK(keys=[Key.SCORE], k=3), + ), + ) + + # Verify group_by round-trip + search_dict = original.to_dict() + assert search_dict["group_by"]["keys"] == ["category"] + assert search_dict["group_by"]["aggregate"] == { + "$min_k": {"keys": ["#score"], "k": 3} + } + + # Reconstruct and compare group_by + restored = Search(group_by=GroupBy.from_dict(search_dict["group_by"])) + assert restored.to_dict()["group_by"] == search_dict["group_by"] diff --git a/python/user_packages/Python313/site-packages/chromadb/test/test_chroma.py b/python/user_packages/Python313/site-packages/chromadb/test/test_chroma.py new file mode 100644 index 0000000000000000000000000000000000000000..298fab10c18db18f1caf6647687dcb7367a3556a --- /dev/null +++ b/python/user_packages/Python313/site-packages/chromadb/test/test_chroma.py @@ -0,0 +1,116 @@ +import unittest +import os +from unittest.mock import patch, Mock +import pytest +import chromadb +import chromadb.config +from chromadb.db.system import SysDB +from chromadb.ingest import Consumer, Producer + + +class GetDBTest(unittest.TestCase): + @patch("chromadb.db.impl.sqlite.SqliteDB", autospec=True) + def test_default_db(self, mock: Mock) -> None: + system = chromadb.config.System( + chromadb.config.Settings(persist_directory="./foo") + ) + system.instance(SysDB) + assert mock.called + + @patch("chromadb.db.impl.sqlite.SqliteDB", autospec=True) + def test_sqlite_sysdb(self, mock: Mock) -> None: + system = chromadb.config.System( + chromadb.config.Settings( + chroma_sysdb_impl="chromadb.db.impl.sqlite.SqliteDB", + persist_directory="./foo", + ) + ) + system.instance(SysDB) + assert mock.called + + @patch("chromadb.db.impl.sqlite.SqliteDB", autospec=True) + def test_sqlite_queue(self, mock: Mock) -> None: + system = chromadb.config.System( + chromadb.config.Settings( + chroma_sysdb_impl="chromadb.db.impl.sqlite.SqliteDB", + chroma_producer_impl="chromadb.db.impl.sqlite.SqliteDB", + chroma_consumer_impl="chromadb.db.impl.sqlite.SqliteDB", + persist_directory="./foo", + ) + ) + system.instance(Producer) + system.instance(Consumer) + assert mock.called + + +class GetAPITest(unittest.TestCase): + @patch("chromadb.api.segment.SegmentAPI", autospec=True) + @patch.dict( + os.environ, {"CHROMA_API_IMPL": "chromadb.api.segment.SegmentAPI"}, clear=True + ) + def test_local(self, mock_api: Mock) -> None: + client = chromadb.Client(chromadb.config.Settings(persist_directory="./foo")) + assert mock_api.called + client.clear_system_cache() + + @patch("chromadb.db.impl.sqlite.SqliteDB", autospec=True) + @patch.dict( + os.environ, {"CHROMA_API_IMPL": "chromadb.api.segment.SegmentAPI"}, clear=True + ) + def test_local_db(self, mock_db: Mock) -> None: + client = chromadb.Client(chromadb.config.Settings(persist_directory="./foo")) + assert mock_db.called + client.clear_system_cache() + + @patch("chromadb.api.fastapi.FastAPI", autospec=True) + @patch.dict(os.environ, {}, clear=True) + def test_fastapi(self, mock: Mock) -> None: + client = chromadb.Client( + chromadb.config.Settings( + chroma_api_impl="chromadb.api.fastapi.FastAPI", + persist_directory="./foo", + chroma_server_host="foo", + chroma_server_http_port=80, + ) + ) + assert mock.called + client.clear_system_cache() + + @patch("chromadb.api.fastapi.FastAPI", autospec=True) + @patch.dict(os.environ, {}, clear=True) + def test_settings_pass_to_fastapi(self, mock: Mock) -> None: + settings = chromadb.config.Settings( + chroma_api_impl="chromadb.api.fastapi.FastAPI", + chroma_server_host="foo", + chroma_server_http_port=80, + chroma_server_headers={"foo": "bar"}, + ) + client = chromadb.Client(settings) + + # Check that the mock was called + assert mock.called + + # Retrieve the arguments with which the mock was called + # `call_args` returns a tuple, where the first element is a tuple of positional arguments + # and the second element is a dictionary of keyword arguments. We assume here that + # the settings object is passed as a positional argument. + args, kwargs = mock.call_args + passed_settings = args[0] if args else None + + # Check if the settings passed to the mock match the settings we used + # raise Exception(passed_settings.settings) + assert passed_settings.settings == settings + client.clear_system_cache() + + +def test_legacy_values() -> None: + with pytest.raises(ValueError): + client = chromadb.Client( + chromadb.config.Settings( + chroma_api_impl="chromadb.api.local.LocalAPI", + persist_directory="./foo", + chroma_server_host="foo", + chroma_server_http_port=80, + ) + ) + client.clear_system_cache() diff --git a/python/user_packages/Python313/site-packages/chromadb/test/test_cli.py b/python/user_packages/Python313/site-packages/chromadb/test/test_cli.py new file mode 100644 index 0000000000000000000000000000000000000000..85de1a059d94219641226044076dab709b6f861d --- /dev/null +++ b/python/user_packages/Python313/site-packages/chromadb/test/test_cli.py @@ -0,0 +1,157 @@ +import multiprocessing +import multiprocessing.context +import sys +import time +from multiprocessing.synchronize import Event + +import chromadb +from chromadb.api.client import Client +from chromadb.api.models.Collection import Collection +from chromadb.cli import cli +from chromadb.cli.cli import build_cli_args +from chromadb.config import Settings, System +from chromadb.db.base import get_sql +from chromadb.db.impl.sqlite import SqliteDB +from pypika import Table +import numpy as np + +from chromadb.test.property import invariants + + +def wait_for_server( + host: str, port: int, + max_retries: int = 5, initial_delay: float = 1.0 +) -> bool: + """Wait for server to be ready using exponential backoff. + Args: + client: ChromaDB client instance + max_retries: Maximum number of retry attempts + initial_delay: Initial delay in seconds before first retry + Returns: + bool: True if server is ready, False if max retries exceeded + """ + delay = initial_delay + for attempt in range(max_retries): + try: + client = chromadb.HttpClient(host=host, port=port) + heartbeat = client.heartbeat() + if heartbeat > 0: + return True + except Exception: + print("Heartbeat failed, trying again...") + pass + + if attempt < max_retries - 1: + time.sleep(delay) + delay *= 2 + + return False + +def start_app(args: list[str]) -> None: + sys.argv = args + cli.app() + +def test_app() -> None: + kwargs = {"path": "chroma_test_data", "port": 8001} + args = ["chroma", "run"] + args.extend(build_cli_args(**kwargs)) + print(args) + server_process = multiprocessing.Process(target=start_app, args=(args,)) + server_process.start() + time.sleep(5) + + assert wait_for_server(host="localhost", port=8001), "Server failed to start within maximum retry attempts" + + server_process.terminate() + server_process.join() + + +def test_vacuum(sqlite_persistent: System) -> None: + system = sqlite_persistent + sqlite = system.instance(SqliteDB) + + # This is True because it's a fresh system, so let's set it to False to test that the vacuum command enables it + config = sqlite.config + config.set_parameter("automatically_purge", False) + sqlite.set_config(config) + + # Add some data + client = Client.from_system(system) + collection1 = client.create_collection("collection1") + collection2 = client.create_collection("collection2") + + def add_records(collection: Collection, num: int) -> None: + ids = [str(i) for i in range(num)] + embeddings = np.random.rand(num, 2) + collection.add(ids=ids, embeddings=embeddings) + + add_records(collection1, 100) + add_records(collection2, 2_000) + + # Maintenance log should be empty + with sqlite.tx() as cur: + t = Table("maintenance_log") + q = sqlite.querybuilder().from_(t).select("*") + sql, params = get_sql(q) + cur.execute(sql, params) + assert cur.fetchall() == [] + + sys.argv = ["chroma", "vacuum", "--path", system.settings.persist_directory, "--force"] + cli.app() + + # Maintenance log should have a vacuum entry + with sqlite.tx() as cur: + t = Table("maintenance_log") + q = sqlite.querybuilder().from_(t).select("*") + sql, params = get_sql(q) + cur.execute(sql, params) + rows = cur.fetchall() + assert len(rows) == 1 + assert rows[0][2] == "vacuum" + + # Automatic pruning should have been enabled + if hasattr(sqlite, "config"): + del ( + sqlite.config + ) # the CLI will end up starting a new instance of sqlite, so we need to force-refresh the cached config here + assert sqlite.config.get_parameter("automatically_purge").value + + # Log should be clean + invariants.log_size_below_max(system, [collection1, collection2], True) + + +def simulate_transactional_write( + settings: Settings, ready_event: Event, shutdown_event: Event +) -> None: + system = System(settings=settings) + system.start() + sqlite = system.instance(SqliteDB) + + with sqlite.tx() as cur: + cur.execute("INSERT INTO tenants DEFAULT VALUES") + ready_event.set() + shutdown_event.wait() + + system.stop() + + +def test_vacuum_errors_if_locked(sqlite_persistent: System, capfd) -> None: + """Vacuum command should fail with details if there is a long-lived lock on the database.""" + ctx = multiprocessing.get_context("spawn") + ready_event = ctx.Event() + shutdown_event = ctx.Event() + process = ctx.Process( + target=simulate_transactional_write, + args=(sqlite_persistent.settings, ready_event, shutdown_event), + ) + process.start() + ready_event.wait() + + try: + sys.argv = ["chroma", "vacuum", "--path", sqlite_persistent.settings.persist_directory, "--force", "--timeout", "10"] + cli.app() + captured = capfd.readouterr() + assert "Failed to vacuum Chroma" in captured.err.strip() + finally: + shutdown_event.set() + process.join() diff --git a/python/user_packages/Python313/site-packages/chromadb/test/test_client.py b/python/user_packages/Python313/site-packages/chromadb/test/test_client.py new file mode 100644 index 0000000000000000000000000000000000000000..b21ec15be5682bf234db5e5ff8373c5e8db19847 --- /dev/null +++ b/python/user_packages/Python313/site-packages/chromadb/test/test_client.py @@ -0,0 +1,280 @@ +import asyncio +from typing import Any, Callable, Generator, cast, Dict, Tuple +from unittest.mock import MagicMock, patch +import chromadb +from chromadb.config import Settings, System +from chromadb.api import ClientAPI +import chromadb.server.fastapi +from chromadb.api.fastapi import FastAPI +import pytest +import tempfile +import os + + +@pytest.fixture +def ephemeral_api() -> Generator[ClientAPI, None, None]: + if os.environ.get("CHROMA_INTEGRATION_TEST_ONLY"): + pytest.skip("Integration test only") + client = chromadb.EphemeralClient() + yield client + client.clear_system_cache() + + +@pytest.fixture +def persistent_api() -> Generator[ClientAPI, None, None]: + if os.environ.get("CHROMA_INTEGRATION_TEST_ONLY"): + pytest.skip("Integration test only") + client = chromadb.PersistentClient( + path=tempfile.gettempdir() + "/test_server", + ) + yield client + client.clear_system_cache() + + +HttpAPIFactory = Callable[..., ClientAPI] + + +@pytest.fixture(params=["sync_client", "async_client"]) +def http_api_factory( + request: pytest.FixtureRequest, +) -> Generator[HttpAPIFactory, None, None]: + if request.param == "sync_client": + with patch("chromadb.api.client.Client._validate_tenant_database"): + with patch("chromadb.api.client.Client.get_user_identity"): + yield chromadb.HttpClient + else: + with patch("chromadb.api.async_client.AsyncClient._validate_tenant_database"): + with patch("chromadb.api.async_client.AsyncClient.get_user_identity"): + + def factory(*args: Any, **kwargs: Any) -> Any: + cls = asyncio.get_event_loop().run_until_complete( + chromadb.AsyncHttpClient(*args, **kwargs) + ) + return cls + + yield cast(HttpAPIFactory, factory) + + +@pytest.fixture() +def http_api(http_api_factory: HttpAPIFactory) -> Generator[ClientAPI, None, None]: + if os.environ.get("CHROMA_SERVER_HTTP_PORT") is not None: + port = int(os.environ.get("CHROMA_SERVER_HTTP_PORT")) # type: ignore + client = http_api_factory(port=port) + else: + client = http_api_factory() + yield client + client.clear_system_cache() + + +def test_ephemeral_client(ephemeral_api: ClientAPI) -> None: + settings = ephemeral_api.get_settings() + assert settings.is_persistent is False + + +def test_persistent_client(persistent_api: ClientAPI) -> None: + settings = persistent_api.get_settings() + assert settings.is_persistent is True + + +def test_http_client(http_api: ClientAPI) -> None: + settings = http_api.get_settings() + assert ( + settings.chroma_api_impl == "chromadb.api.fastapi.FastAPI" + or settings.chroma_api_impl == "chromadb.api.async_fastapi.AsyncFastAPI" + ) + + +def test_http_client_with_inconsistent_host_settings( + http_api_factory: HttpAPIFactory, +) -> None: + try: + http_api_factory(settings=Settings(chroma_server_host="127.0.0.1")) + except ValueError as e: + assert ( + str(e) + == "Chroma server host provided in settings[127.0.0.1] is different to the one provided in HttpClient: [localhost]" + ) + + +def test_http_client_with_inconsistent_port_settings( + http_api_factory: HttpAPIFactory, +) -> None: + try: + http_api_factory( + port=8002, + settings=Settings( + chroma_server_http_port=8001, + ), + ) + except ValueError as e: + assert ( + str(e) + == "Chroma server http port provided in settings[8001] is different to the one provided in HttpClient: [8002]" + ) + + +def make_sync_client_factory() -> Tuple[Callable[..., Any], Dict[str, Any]]: + captured: Dict[str, Any] = {} + + # takes any positional args to match httpx.Client + def factory(*_: Any, **kwargs: Any) -> Any: + captured.update(kwargs) + session = MagicMock() + session.headers = {} + return session + + return factory, captured + + +def test_fastapi_uses_http_limits_from_settings() -> None: + settings = Settings( + chroma_api_impl="chromadb.api.fastapi.FastAPI", + chroma_server_host="localhost", + chroma_server_http_port=9000, + chroma_server_ssl_verify=True, + chroma_http_keepalive_secs=12.5, + chroma_http_max_connections=64, + chroma_http_max_keepalive_connections=16, + ) + system = System(settings) + + factory, captured = make_sync_client_factory() + + with patch.object(FastAPI, "require", side_effect=[MagicMock(), MagicMock()]): + with patch("chromadb.api.fastapi.httpx.Client", side_effect=factory): + api = FastAPI(system) + + api.stop() + limits = captured["limits"] + assert limits.keepalive_expiry == 12.5 + assert limits.max_connections == 64 + assert limits.max_keepalive_connections == 16 + assert captured["timeout"] is None + assert captured["verify"] is True + + +def test_persistent_client_close() -> None: + """Test that close() properly releases resources in PersistentClient.""" + if os.environ.get("CHROMA_INTEGRATION_TEST_ONLY"): + pytest.skip("Integration test only") + + with tempfile.TemporaryDirectory() as tmpdir: + # Create a client, add some data, and close it + client = chromadb.PersistentClient(path=tmpdir) + collection = client.create_collection("test_collection") + collection.add( + ids=["id1", "id2"], + documents=["doc1", "doc2"], + metadatas=[{"key": "value1"}, {"key": "value2"}], + ) + + # Save a reference to the system before close() removes it from the cache + system = client._system + + # Close the client + client.close() + + # Verify the system is stopped + assert system._running is False + + # Create a new client with the same path to verify data was persisted + client2 = chromadb.PersistentClient(path=tmpdir) + collection2 = client2.get_collection("test_collection") + results = collection2.get() + assert len(results["ids"]) == 2 + assert "id1" in results["ids"] + assert "id2" in results["ids"] + + client2.close() + client.clear_system_cache() + client2.clear_system_cache() + + +def test_persistent_client_context_manager() -> None: + """Test that PersistentClient works as a context manager.""" + if os.environ.get("CHROMA_INTEGRATION_TEST_ONLY"): + pytest.skip("Integration test only") + + with tempfile.TemporaryDirectory() as tmpdir: + # Use client as context manager + with chromadb.PersistentClient(path=tmpdir) as client: + # Save a reference to the system before close() removes it from the cache + system = client._system + collection = client.create_collection("test_collection") + collection.add( + ids=["id1", "id2"], + documents=["doc1", "doc2"], + metadatas=[{"key": "value1"}, {"key": "value2"}], + ) + + # Verify the system is stopped after context exit + assert system._running is False + + # Verify data was persisted + with chromadb.PersistentClient(path=tmpdir) as client2: + collection2 = client2.get_collection("test_collection") + results = collection2.get() + assert len(results["ids"]) == 2 + + client.clear_system_cache() + client2.clear_system_cache() + + +def test_ephemeral_client_close() -> None: + """Test that close() works with EphemeralClient.""" + if os.environ.get("CHROMA_INTEGRATION_TEST_ONLY"): + pytest.skip("Integration test only") + + client = chromadb.EphemeralClient() + # Save a reference to the system before close() removes it from the cache + system = client._system + collection = client.create_collection("test_collection") + collection.add(ids=["id1"], documents=["doc1"]) + + # Close the client + client.close() + + # Verify the system is stopped + assert system._running is False + + client.clear_system_cache() + + +def test_ephemeral_client_context_manager() -> None: + """Test that EphemeralClient works as a context manager.""" + if os.environ.get("CHROMA_INTEGRATION_TEST_ONLY"): + pytest.skip("Integration test only") + + with chromadb.EphemeralClient() as client: + # Save a reference to the system before close() removes it from the cache + system = client._system + collection = client.create_collection("test_collection") + collection.add(ids=["id1"], documents=["doc1"]) + assert system._running is True + + # Verify the system is stopped after context exit + assert system._running is False + + client.clear_system_cache() + + +def test_client_close_idempotent() -> None: + """Test that calling close() multiple times is a safe no-op.""" + if os.environ.get("CHROMA_INTEGRATION_TEST_ONLY"): + pytest.skip("Integration test only") + + with tempfile.TemporaryDirectory() as tmpdir: + client = chromadb.PersistentClient(path=tmpdir) + collection = client.create_collection("test_collection") + collection.add(ids=["id1"], documents=["doc1"]) + + # First close should work normally + client.close() + + # Second close should be a no-op, not raise KeyError + client.close() + + # Third close should also be safe + client.close() + + client.clear_system_cache() diff --git a/python/user_packages/Python313/site-packages/chromadb/test/test_config.py b/python/user_packages/Python313/site-packages/chromadb/test/test_config.py new file mode 100644 index 0000000000000000000000000000000000000000..f92a1723cebed8e32a132537b91dba7d40ce13c9 --- /dev/null +++ b/python/user_packages/Python313/site-packages/chromadb/test/test_config.py @@ -0,0 +1,234 @@ +from chromadb.config import Component, System, Settings +from overrides import overrides +from threading import local +from unittest.mock import patch +import pytest +import os +import random + +data = local() # use thread local just in case tests ever run in parallel + + +def reset() -> None: + global data + data.starts = [] + data.stops = [] + data.inits = [] + + +class ComponentA(Component): + def __init__(self, system: System): + data.inits += "A" + super().__init__(system) + self.require(ComponentB) + self.require(ComponentC) + + @overrides + def start(self) -> None: + data.starts += "A" + + @overrides + def stop(self) -> None: + data.stops += "A" + + +class ComponentB(Component): + def __init__(self, system: System): + data.inits += "B" + super().__init__(system) + self.require(ComponentC) + self.require(ComponentD) + + @overrides + def start(self) -> None: + data.starts += "B" + + @overrides + def stop(self) -> None: + data.stops += "B" + + +class ComponentC(Component): + def __init__(self, system: System): + data.inits += "C" + super().__init__(system) + self.require(ComponentD) + + @overrides + def start(self) -> None: + data.starts += "C" + + @overrides + def stop(self) -> None: + data.stops += "C" + + +class ComponentD(Component): + def __init__(self, system: System): + data.inits += "D" + super().__init__(system) + + @overrides + def start(self) -> None: + data.starts += "D" + + @overrides + def stop(self) -> None: + data.stops += "D" + + +# Dependency Graph for tests: +# ┌───┐ +# │ A │ +# └┬─┬┘ +# │┌▽──┐ +# ││ B │ +# │└┬─┬┘ +# ┌▽─▽┐│ +# │ C ││ +# └┬──┘│ +# ┌▽───▽┐ +# │ D │ +# └─────┘ + + +def test_leaf_only() -> None: + settings = Settings() + system = System(settings) + + reset() + + d = system.instance(ComponentD) + assert isinstance(d, ComponentD) + + assert data.inits == ["D"] + system.start() + assert data.starts == ["D"] + system.stop() + assert data.stops == ["D"] + + +def test_partial() -> None: + settings = Settings() + system = System(settings) + + reset() + + c = system.instance(ComponentC) + assert isinstance(c, ComponentC) + + assert data.inits == ["C", "D"] + system.start() + assert data.starts == ["D", "C"] + system.stop() + assert data.stops == ["C", "D"] + + +def test_system_startup() -> None: + settings = Settings() + system = System(settings) + + reset() + + a = system.instance(ComponentA) + assert isinstance(a, ComponentA) + + assert data.inits == ["A", "B", "C", "D"] + system.start() + assert data.starts == ["D", "C", "B", "A"] + system.stop() + assert data.stops == ["A", "B", "C", "D"] + + +def test_system_override_order() -> None: + settings = Settings() + system = System(settings) + + reset() + + system.instance(ComponentA) + + # Deterministically shuffle the instances map to prove that topsort is actually + # working and not just implicitly working because of insertion order. + + # This causes the test to actually fail if the deps are not wired up correctly. + random.seed(0) + entries = list(system._instances.items()) + random.shuffle(entries) + system._instances = {k: v for k, v in entries} + + system.start() + assert data.starts == ["D", "C", "B", "A"] + system.stop() + assert data.stops == ["A", "B", "C", "D"] + + +class ComponentZ(Component): + def __init__(self, system: System): + super().__init__(system) + self.require(ComponentC) + + @overrides + def start(self) -> None: + pass + + @overrides + def stop(self) -> None: + pass + + +def test_runtime_dependencies() -> None: + settings = Settings() + system = System(settings) + + reset() + + # Nothing to do, no components were requested prior to start + system.start() + assert data.starts == [] + + # Constructs dependencies and starts them in the correct order + ComponentZ(system) + assert data.starts == ["D", "C"] + system.stop() + assert data.stops == ["C", "D"] + + +def test_http_client_setting_defaults() -> None: + settings = Settings() + assert settings.chroma_http_keepalive_secs == 40.0 + assert settings.chroma_http_max_connections is None + assert settings.chroma_http_max_keepalive_connections is None + + +def test_http_client_setting_overrides() -> None: + settings = Settings( + chroma_http_keepalive_secs=5.5, + chroma_http_max_connections=123, + chroma_http_max_keepalive_connections=17, + ) + assert settings.chroma_http_keepalive_secs == 5.5 + assert settings.chroma_http_max_connections == 123 + assert settings.chroma_http_max_keepalive_connections == 17 + + +@patch.dict(os.environ, {"CHROMA_API_IMPL": "my_api_impl"}, clear=True) +def test_uses_env() -> None: + settings = Settings() + assert settings.chroma_api_impl == "my_api_impl" + + +@patch.dict(os.environ, {"MY_ENV_VAR": "my_env_var"}, clear=True) +def test_ignores_extra_env_vars() -> None: + settings = Settings() + with pytest.raises(AttributeError): + _ = settings.my_env_var + + +def test_local_ignores_extra_settings_param() -> None: + settings = Settings(extra_param="asdsdsds", tenant_id="test") + # does not error if the extra param is present in the settings object + assert settings.tenant_id == "test" + # but it should error if the extra param is accessed + with pytest.raises(AttributeError): + _ = settings.extra_param diff --git a/python/user_packages/Python313/site-packages/chromadb/test/test_multithreaded.py b/python/user_packages/Python313/site-packages/chromadb/test/test_multithreaded.py new file mode 100644 index 0000000000000000000000000000000000000000..1859b1f7d3ac0a668d170dc8005fcfe448028c52 --- /dev/null +++ b/python/user_packages/Python313/site-packages/chromadb/test/test_multithreaded.py @@ -0,0 +1,229 @@ +import multiprocessing +from concurrent.futures import Future, ThreadPoolExecutor, wait +import random +import threading +from typing import Any, Dict, List, Optional, Set, Tuple, cast +import numpy as np + +from chromadb.api import ClientAPI +import chromadb.test.property.invariants as invariants +from chromadb.api.segment import SegmentAPI +from chromadb.test.property.strategies import RecordSet +from chromadb.test.property.strategies import test_hnsw_config +from chromadb.types import Metadata + + +def generate_data_shape() -> Tuple[int, int]: + N = random.randint(10, 10000) + D = random.randint(10, 256) + return (N, D) + + +def generate_record_set(N: int, D: int) -> RecordSet: + ids = [str(i) for i in range(N)] + metadatas: List[Dict[str, int]] = [{f"{i}": i} for i in range(N)] + documents = [f"doc {i}" for i in range(N)] + embeddings = np.random.rand(N, D).tolist() + + # Create a normalized record set to compare against + normalized_record_set: RecordSet = RecordSet( + ids=ids, + embeddings=embeddings, # type: ignore + metadatas=metadatas, # type: ignore + documents=documents, + ) + + return normalized_record_set + + +# Hypothesis is bad at generating large datasets so we manually generate data in +# this test to test multithreaded add with larger datasets +def _test_multithreaded_add( + client: ClientAPI, N: int, D: int, num_workers: int +) -> None: + records_set = generate_record_set(N, D) + ids = records_set["ids"] + embeddings = records_set["embeddings"] + metadatas = records_set["metadatas"] + documents = records_set["documents"] + + print(f"Adding {N} records with {D} dimensions on {num_workers} workers") + + # TODO: batch_size and sync_threshold should be configurable + client.reset() + coll = client.create_collection(name="test", metadata=test_hnsw_config) + with ThreadPoolExecutor(max_workers=num_workers) as executor: + futures: List[Future[Any]] = [] + total_sent = -1 + while total_sent < len(ids): + # Randomly grab up to 10% of the dataset and send it to the executor + batch_size = random.randint(1, N // 10) + to_send = min(batch_size, len(ids) - total_sent) + start = total_sent + 1 + end = total_sent + to_send + 1 + if embeddings is not None and len(embeddings[start:end]) == 0: + break + future = executor.submit( + coll.add, + ids=ids[start:end], + embeddings=embeddings[start:end] if embeddings is not None else None, + metadatas=metadatas[start:end] if metadatas is not None else None, # type: ignore + documents=documents[start:end] if documents is not None else None, + ) + futures.append(future) + total_sent += to_send + + wait(futures) + + for future in futures: + exception = future.exception() + if exception is not None: + raise exception + + # Check that invariants hold + invariants.count(coll, records_set) + invariants.ids_match(coll, records_set) + invariants.metadatas_match(coll, records_set) + invariants.no_duplicates(coll) + + # Check that the ANN accuracy is good + # On a random subset of the dataset + query_indices = random.sample([i for i in range(N)], 10) + n_results = 5 + invariants.ann_accuracy( + coll, + records_set, + n_results=n_results, + query_indices=query_indices, + ) + + +def _test_interleaved_add_query( + client: ClientAPI, N: int, D: int, num_workers: int +) -> None: + """Test that will use multiple threads to interleave operations on the db and verify they work correctly""" + + client.reset() + coll = client.create_collection(name="test", metadata=test_hnsw_config) + + records_set = generate_record_set(N, D) + ids = cast(List[str], records_set["ids"]) + embeddings = cast(List[float], records_set["embeddings"]) + metadatas = cast(List[Metadata], records_set["metadatas"]) + documents = records_set["documents"] + + added_ids: Set[str] = set() + lock = threading.Lock() + + print(f"Adding {N} records with {D} dimensions on {num_workers} workers") + + def perform_operation( + operation: int, ids_to_modify: Optional[List[str]] = None + ) -> None: + """Perform a random operation on the collection""" + if operation == 0: + assert ids_to_modify is not None + indices_to_modify = [ids.index(id) for id in ids_to_modify] + # Add a subset of the dataset + if len(indices_to_modify) == 0: + return + coll.add( + ids=ids_to_modify, + embeddings=[embeddings[i] for i in indices_to_modify] + if embeddings is not None + else None, + metadatas=[metadatas[i] for i in indices_to_modify] + if metadatas is not None + else None, + documents=[documents[i] for i in indices_to_modify] + if documents is not None + else None, + ) + with lock: + added_ids.update(ids_to_modify) + elif operation == 1: + currently_added_ids = [] + n_results = 5 + with lock: + currently_added_ids = list(added_ids.copy()) + currently_added_indices = [ids.index(id) for id in currently_added_ids] + if ( + len(currently_added_ids) == 0 + or len(currently_added_indices) < n_results + ): + return + # Query the collection, we can't test the results because we want to interleave + # queries and adds. We cannot do so without a lock and serializing the operations + # which would defeat the purpose of this test. Instead we interleave queries and + # adds and check the invariants at the end + query_indices = random.sample( + currently_added_indices, + min(10, len(currently_added_indices)), + ) + query_vectors = [embeddings[i] for i in query_indices] + # Query the collections + coll.query( + query_vectors, + n_results=n_results, + ) + + with ThreadPoolExecutor(max_workers=num_workers) as executor: + futures: List[Future[Any]] = [] + total_sent = -1 + while total_sent < len(ids) - 1: + operation = random.randint(0, 2) + if operation == 0: + # Randomly grab up to 10% of the dataset and send it to the executor + batch_size = random.randint(1, N // 10) + to_send = min(batch_size, len(ids) - total_sent) + start = total_sent + 1 + end = total_sent + to_send + 1 + future = executor.submit(perform_operation, operation, ids[start:end]) + futures.append(future) + total_sent += to_send + elif operation == 1: + future = executor.submit( + perform_operation, + operation, + ) + futures.append(future) + + wait(futures) + + for future in futures: + exception = future.exception() + if exception is not None: + raise exception + if ( + isinstance(client, SegmentAPI) and client.get_settings().is_persistent is True + ): # we can't check invariants for FastAPI + invariants.fd_not_exceeding_threadpool_size(num_workers) + # Check that invariants hold + invariants.count(coll, records_set) + invariants.ids_match(coll, records_set) + invariants.metadatas_match(coll, records_set) + invariants.no_duplicates(coll) + # Check that the ANN accuracy is good + # On a random subset of the dataset + query_indices = random.sample([i for i in range(N)], 10) + n_results = 5 + invariants.ann_accuracy( + coll, + records_set, + n_results=n_results, + query_indices=query_indices, + ) + + +def test_multithreaded_add(client: ClientAPI) -> None: + for i in range(3): + num_workers = random.randint(2, multiprocessing.cpu_count() * 2) + N, D = generate_data_shape() + _test_multithreaded_add(client, N, D, num_workers) + + +def test_interleaved_add_query(client: ClientAPI) -> None: + for i in range(3): + num_workers = random.randint(2, multiprocessing.cpu_count() * 2) + N, D = generate_data_shape() + _test_interleaved_add_query(client, N, D, num_workers) diff --git a/python/user_packages/Python313/site-packages/chromadb/test/utils/__pycache__/cross_version.cpython-313.pyc b/python/user_packages/Python313/site-packages/chromadb/test/utils/__pycache__/cross_version.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4070dc83b4943c058c0f38c188bc0eb52802f7d8 Binary files /dev/null and b/python/user_packages/Python313/site-packages/chromadb/test/utils/__pycache__/cross_version.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/chromadb/test/utils/__pycache__/distance_functions.cpython-313.pyc b/python/user_packages/Python313/site-packages/chromadb/test/utils/__pycache__/distance_functions.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..709dcaebe136708a229e59e10f155ecab75f01ee Binary files /dev/null and b/python/user_packages/Python313/site-packages/chromadb/test/utils/__pycache__/distance_functions.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/chromadb/test/utils/__pycache__/test_embedding_function_schemas.cpython-313.pyc b/python/user_packages/Python313/site-packages/chromadb/test/utils/__pycache__/test_embedding_function_schemas.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b4ca4ea9bc85af61bbd32ce9709cf137326250ed Binary files /dev/null and b/python/user_packages/Python313/site-packages/chromadb/test/utils/__pycache__/test_embedding_function_schemas.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/chromadb/test/utils/__pycache__/test_result_df_transform.cpython-313.pyc b/python/user_packages/Python313/site-packages/chromadb/test/utils/__pycache__/test_result_df_transform.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6294ba804538fed4c65e31a45b2eee025a6380b3 Binary files /dev/null and b/python/user_packages/Python313/site-packages/chromadb/test/utils/__pycache__/test_result_df_transform.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/chromadb/test/utils/__pycache__/test_wait_for_version_increase.cpython-313.pyc b/python/user_packages/Python313/site-packages/chromadb/test/utils/__pycache__/test_wait_for_version_increase.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0549b0a2f887b2e9d5b911820645ae5baf9e65c9 Binary files /dev/null and b/python/user_packages/Python313/site-packages/chromadb/test/utils/__pycache__/test_wait_for_version_increase.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/chromadb/test/utils/__pycache__/wait_for_version_increase.cpython-313.pyc b/python/user_packages/Python313/site-packages/chromadb/test/utils/__pycache__/wait_for_version_increase.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d4eda87111d48a6e309ef74111549f7c582ef86c Binary files /dev/null and b/python/user_packages/Python313/site-packages/chromadb/test/utils/__pycache__/wait_for_version_increase.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/chromadb/test/utils/cross_version.py b/python/user_packages/Python313/site-packages/chromadb/test/utils/cross_version.py new file mode 100644 index 0000000000000000000000000000000000000000..c4b6dad21fcaf20f31baa2109ddd9e50be107c16 --- /dev/null +++ b/python/user_packages/Python313/site-packages/chromadb/test/utils/cross_version.py @@ -0,0 +1,71 @@ +import sys +import subprocess +import os +import tempfile +from types import ModuleType +from typing import Dict, List + +base_install_dir = ( + tempfile.gettempdir() + + f"/worker-{os.environ.get('PYTEST_XDIST_WORKER', 'unknown')}" + + "/persistence_test_chromadb_versions" +) + + +def get_path_to_version_install(version: str) -> str: + return base_install_dir + "/" + version + + +def switch_to_version(version: str, versioned_modules: List[str]) -> ModuleType: + module_name = "chromadb" + # Remove old version from sys.modules, except test modules + old_modules = { + n: m + for n, m in sys.modules.items() + if n == module_name + or (n.startswith(module_name + ".")) + or n in versioned_modules + or (any(n.startswith(m + ".") for m in versioned_modules)) + } + for n in old_modules: + del sys.modules[n] + # Load the target version and override the path to the installed version + # https://docs.python.org/3/library/importlib.html#importing-a-source-file-directly + sys.path.insert(0, get_path_to_version_install(version)) + import chromadb + + assert chromadb.__version__ == version + return chromadb + + +def get_path_to_version_library(version: str) -> str: + return get_path_to_version_install(version) + "/chromadb/__init__.py" + + +def install_version(version: str, dep_overrides: Dict[str, str]) -> None: + # Check if already installed + version_library = get_path_to_version_library(version) + if os.path.exists(version_library): + return + path = get_path_to_version_install(version) + install(f"chromadb=={version}", path, dep_overrides) + + +def install(pkg: str, path: str, dep_overrides: Dict[str, str]) -> int: + os.makedirs(path, exist_ok=True) + + # -q -q to suppress pip output to ERROR level + # https://pip.pypa.io/en/stable/cli/pip/#quiet + command = [sys.executable, "-m", "pip", "-q", "-q", "install", pkg] + + for dep, operator_version in dep_overrides.items(): + command.append(f"{dep}{operator_version}") + + # Only add --no-binary=chroma-hnswlib if it's in the dependencies + if "chroma-hnswlib" in pkg or any("chroma-hnswlib" in dep for dep in dep_overrides): + command.append("--no-binary=chroma-hnswlib") + + command.append(f"--target={path}") + + print(f"Installing chromadb version {pkg} to {path}") + return subprocess.check_call(command) diff --git a/python/user_packages/Python313/site-packages/chromadb/test/utils/distance_functions.py b/python/user_packages/Python313/site-packages/chromadb/test/utils/distance_functions.py new file mode 100644 index 0000000000000000000000000000000000000000..50c0fc927e0e47ec26cf823c0aac63140e0ebabc --- /dev/null +++ b/python/user_packages/Python313/site-packages/chromadb/test/utils/distance_functions.py @@ -0,0 +1,7 @@ +from chromadb.utils.distance_functions import cosine +import numpy as np + + +def test_cosine_zero() -> None: + x = np.array([0.0, 0.0], dtype=np.float16) + assert cosine(x, x) == 1.0 diff --git a/python/user_packages/Python313/site-packages/chromadb/test/utils/test_embedding_function_schemas.py b/python/user_packages/Python313/site-packages/chromadb/test/utils/test_embedding_function_schemas.py new file mode 100644 index 0000000000000000000000000000000000000000..b57d1bbc237de856928e0a423b92646497a2dbc7 --- /dev/null +++ b/python/user_packages/Python313/site-packages/chromadb/test/utils/test_embedding_function_schemas.py @@ -0,0 +1,456 @@ +import pytest +from typing import List, Any, Callable, Dict +from jsonschema import ValidationError +from unittest.mock import MagicMock, create_autospec +from chromadb.utils.embedding_functions.schemas import ( + validate_config_schema, + load_schema, + get_available_schemas, +) +from chromadb.utils.embedding_functions import ( + known_embedding_functions, + sparse_known_embedding_functions, +) +from chromadb.api.types import Documents, Embeddings +from pytest import MonkeyPatch + +# Skip these embedding functions in tests +SKIP_EMBEDDING_FUNCTIONS = [ + "chroma_langchain", +] + + +def get_embedding_function_names() -> List[str]: + """Get all embedding function names to test""" + return [ + name + for name in known_embedding_functions.keys() + if name not in SKIP_EMBEDDING_FUNCTIONS + ] + + +class TestEmbeddingFunctionSchemas: + """Test class for embedding function schemas""" + + @pytest.mark.parametrize("ef_name", get_embedding_function_names()) + def test_embedding_function_config_roundtrip( + self, + ef_name: str, + mock_embeddings: Callable[[Documents], Embeddings], + mock_common_deps: MonkeyPatch, + ) -> None: + """Test embedding function configuration roundtrip""" + ef_class = known_embedding_functions[ef_name] + + # Create an autospec of the embedding function class + mock_ef = create_autospec(ef_class, instance=True) + + # Mock the __call__ method + mock_call = MagicMock(return_value=mock_embeddings(["test"])) + mock_ef.__call__ = mock_call + + # For chroma-cloud-qwen, mock get_config to return valid data + if ef_name == "chroma-cloud-qwen": + from chromadb.utils.embedding_functions.chroma_cloud_qwen_embedding_function import ( + ChromaCloudQwenEmbeddingModel, + CHROMA_CLOUD_QWEN_DEFAULT_INSTRUCTIONS, + ) + + mock_ef.get_config.return_value = { + "api_key_env_var": "CHROMA_API_KEY", + "model": ChromaCloudQwenEmbeddingModel.QWEN3_EMBEDDING_0p6B.value, + "task": "nl_to_code", + "instructions": CHROMA_CLOUD_QWEN_DEFAULT_INSTRUCTIONS, + } + + # Mock the class constructor to return our mock instance + mock_common_deps.setattr( + ef_class, "__new__", lambda cls, *args, **kwargs: mock_ef + ) + + # Create instance with minimal args (constructor will be mocked) + ef_instance = ef_class() + + # Get the config (this will use the real method) + config = ef_instance.get_config() + + # Test recreation from config + new_instance = ef_class.build_from_config(config) + new_config = new_instance.get_config() + + # Configs should match + assert ( + config == new_config + ), f"Configs don't match after recreation for {ef_name}" + + def test_schema_required_fields(self) -> None: + """Test that schemas enforce required fields""" + for schema_name in get_available_schemas(): + schema = load_schema(schema_name) + if "required" not in schema: + continue + + # Create minimal valid config + config = {} + for field in schema["required"]: + field_schema = schema["properties"][field] + field_type = ( + field_schema["type"][0] + if isinstance(field_schema["type"], list) + else field_schema["type"] + ) + config[field] = self._get_dummy_value(field_type) + + # Test each required field + for field in schema["required"]: + test_config = config.copy() + del test_config[field] + with pytest.raises(ValidationError): + validate_config_schema(test_config, schema_name) + + @staticmethod + def _get_dummy_value(field_type: str) -> Any: + """Get a dummy value for a given field type""" + type_map = { + "string": "dummy", + "integer": 0, + "number": 0.0, + "boolean": False, + "object": {}, + "array": [], + } + return type_map.get(field_type, "dummy") + + def test_schema_additional_properties(self) -> None: + """Test that schemas reject additional properties""" + for schema_name in get_available_schemas(): + schema = load_schema(schema_name) + config = {} + + # Add required fields + if "required" in schema: + for field in schema["required"]: + field_schema = schema["properties"][field] + field_type = ( + field_schema["type"][0] + if isinstance(field_schema["type"], list) + else field_schema["type"] + ) + config[field] = self._get_dummy_value(field_type) + + # Add additional property + test_config = config.copy() + test_config["additional_property"] = "value" + + # Test validation + if schema.get("additionalProperties", True) is False: + with pytest.raises(ValidationError): + validate_config_schema(test_config, schema_name) + + def _create_valid_config_from_schema( + self, schema: Dict[str, Any] + ) -> Dict[str, Any]: + """Create a valid config from a schema by filling in required fields""" + config: Dict[str, Any] = {} + + if "required" in schema and "properties" in schema: + for field in schema["required"]: + if field in schema["properties"]: + field_schema = schema["properties"][field] + config[field] = self._get_value_from_field_schema(field_schema) + + return config + + def _get_value_from_field_schema(self, field_schema: Dict[str, Any]) -> Any: + """Get a valid value from a field schema""" + # Handle enums - use first enum value + if "enum" in field_schema: + return field_schema["enum"][0] + + # Handle type (could be a list or single value) + field_type = field_schema.get("type") + if field_type is None: + return "dummy" # Fallback if no type specified + + if isinstance(field_type, list): + # If null is in the type list, prefer non-null type + non_null_types = [t for t in field_type if t != "null"] + field_type = non_null_types[0] if non_null_types else field_type[0] + + if field_type == "object": + # Handle nested objects + nested_config = {} + if "properties" in field_schema: + nested_required = field_schema.get("required", []) + for prop in nested_required: + if prop in field_schema["properties"]: + nested_config[prop] = self._get_value_from_field_schema( + field_schema["properties"][prop] + ) + return nested_config if nested_config else {} + + if field_type == "array": + # Return empty array for arrays + return [] + + # Use the existing dummy value method for primitive types + return self._get_dummy_value(field_type) + + def _has_custom_validation(self, ef_class: Any) -> bool: + """Check if validate_config actually validates (not just base implementation)""" + try: + # Try with an obviously invalid config - if it doesn't raise, it's base implementation + invalid_config = {"__invalid_test_config__": True} + try: + ef_class.validate_config(invalid_config) + # If we get here without exception, it's using base implementation + return False + except (ValidationError, ValueError, FileNotFoundError): + # If it raises any validation-related error, it's actually validating + return True + except Exception: + # Any other exception means it's trying to validate (e.g., schema not found) + return True + + def _setup_env_vars_for_ef( + self, ef_name: str, mock_common_deps: MonkeyPatch + ) -> None: + """Set up environment variables needed for embedding function instantiation""" + # Map of embedding function names to their default API key environment variable names + api_key_env_vars = { + "cohere": "CHROMA_COHERE_API_KEY", + "openai": "CHROMA_OPENAI_API_KEY", + "huggingface": "CHROMA_HUGGINGFACE_API_KEY", + "huggingface_server": "CHROMA_HUGGINGFACE_API_KEY", + "google_palm": "CHROMA_GOOGLE_PALM_API_KEY", + "google_genai": "GEMINI_API_KEY", + "google_generative_ai": "GEMINI_API_KEY", + "google_vertex": "CHROMA_GOOGLE_VERTEX_API_KEY", + "jina": "CHROMA_JINA_API_KEY", + "mistral": "MISTRAL_API_KEY", + "morph": "MORPH_API_KEY", + "voyageai": "CHROMA_VOYAGE_API_KEY", + "cloudflare_workers_ai": "CHROMA_CLOUDFLARE_API_KEY", + "together_ai": "CHROMA_TOGETHER_AI_API_KEY", + "baseten": "CHROMA_BASETEN_API_KEY", + "roboflow": "CHROMA_ROBOFLOW_API_KEY", + "amazon_bedrock": "AWS_ACCESS_KEY_ID", # AWS uses different env vars + "chroma-cloud-qwen": "CHROMA_API_KEY", + # Sparse embedding functions + "chroma-cloud-splade": "CHROMA_API_KEY", + } + + # Set API key environment variable if needed + if ef_name in api_key_env_vars: + mock_common_deps.setenv(api_key_env_vars[ef_name], "test-api-key") + + # Special cases that need additional environment variables + if ef_name == "amazon_bedrock": + mock_common_deps.setenv("AWS_SECRET_ACCESS_KEY", "test-secret-key") + mock_common_deps.setenv("AWS_REGION", "us-east-1") + + def _create_ef_instance( + self, ef_name: str, ef_class: Any, mock_common_deps: MonkeyPatch + ) -> Any: + """Create an embedding function instance, handling special cases""" + # Set up environment variables first + self._setup_env_vars_for_ef(ef_name, mock_common_deps) + + # Mock missing modules that are imported inside __init__ methods + import sys + + # Create mock modules + mock_pil = MagicMock() + mock_pil_image = MagicMock() + mock_google_genai = MagicMock() + mock_vertexai = MagicMock() + mock_vertexai_lm = MagicMock() + mock_boto3 = MagicMock() + mock_jina = MagicMock() + mock_mistralai = MagicMock() + + # Mock boto3.Session for amazon_bedrock + mock_boto3_session = MagicMock() + mock_session_instance = MagicMock() + mock_session_instance.region_name = "us-east-1" + mock_session_instance.profile_name = None + mock_session_instance.client.return_value = MagicMock() + mock_boto3_session.return_value = mock_session_instance + mock_boto3.Session = mock_boto3_session + + # Mock vertexai.init and TextEmbeddingModel + mock_text_embedding_model = MagicMock() + mock_text_embedding_model.from_pretrained.return_value = MagicMock() + mock_vertexai_lm.TextEmbeddingModel = mock_text_embedding_model + mock_vertexai.language_models = mock_vertexai_lm + mock_vertexai.init = MagicMock() + + # Mock google.generativeai and google.genai - need to set up google module first + mock_google = MagicMock() + mock_google_genai.configure = MagicMock() # For palm.configure() + mock_google_genai.GenerativeModel = MagicMock(return_value=MagicMock()) + mock_google.generativeai = mock_google_genai + mock_google_genai_new = MagicMock() + mock_google.genai = mock_google_genai_new + + # Mock jina Client + mock_jina.Client = MagicMock() + + # Mock mistralai + mock_mistral_client = MagicMock() + mock_mistral_client.return_value.embeddings.create.return_value.data = [ + MagicMock(embedding=[0.1, 0.2, 0.3]) + ] + mock_mistralai.Mistral = mock_mistral_client + + # Add missing modules to sys.modules using monkeypatch + modules_to_mock = { + "PIL": mock_pil, + "PIL.Image": mock_pil_image, + "google": mock_google, + "google.generativeai": mock_google_genai, + "google.genai": mock_google_genai_new, + "google.genai.types": MagicMock(), + "vertexai": mock_vertexai, + "vertexai.language_models": mock_vertexai_lm, + "boto3": mock_boto3, + "jina": mock_jina, + "mistralai": mock_mistralai, + } + + for module_name, mock_module in modules_to_mock.items(): + mock_common_deps.setitem(sys.modules, module_name, mock_module) + + # Special cases that need additional arguments + if ef_name == "cloudflare_workers_ai": + return ef_class( + model_name="test-model", + account_id="test-account-id", + ) + elif ef_name == "baseten": + # Baseten needs api_key explicitly passed even with env var + return ef_class( + api_key="test-api-key", + api_base="https://test.api.baseten.co", + ) + elif ef_name == "amazon_bedrock": + # Amazon Bedrock needs a boto3 session - create a mock session + # boto3 is already mocked in sys.modules above + mock_session = mock_boto3.Session(region_name="us-east-1") + return ef_class( + session=mock_session, + model_name="amazon.titan-embed-text-v1", + ) + elif ef_name == "huggingface_server": + return ef_class(url="http://localhost:8080") + elif ef_name == "google_vertex": + return ef_class(project_id="test-project", region="us-central1") + elif ef_name == "mistral": + return ef_class(model="mistral-embed") + elif ef_name == "roboflow": + return ef_class() # No model_name needed + elif ef_name == "chroma-cloud-qwen": + from chromadb.utils.embedding_functions.chroma_cloud_qwen_embedding_function import ( + ChromaCloudQwenEmbeddingModel, + ) + + return ef_class( + model=ChromaCloudQwenEmbeddingModel.QWEN3_EMBEDDING_0p6B, + task="nl_to_code", + ) + else: + # Try with no args first + try: + return ef_class() + except Exception: + # If that fails, try with common minimal args + return ef_class(model_name="test-model") + + @pytest.mark.parametrize("ef_name", get_embedding_function_names()) + def test_validate_config_with_schema( + self, + ef_name: str, + mock_embeddings: Callable[[Documents], Embeddings], + mock_common_deps: MonkeyPatch, + ) -> None: + """Test that validate_config works correctly with actual configs from embedding functions""" + ef_class = known_embedding_functions[ef_name] + + # Skip if the embedding function doesn't have a validate_config method + if not hasattr(ef_class, "validate_config"): + pytest.skip(f"{ef_name} does not have validate_config method") + + # Check if it's callable (static methods are callable on the class) + if not callable(getattr(ef_class, "validate_config", None)): + pytest.skip(f"{ef_name} validate_config is not callable") + + # Skip if using base implementation (doesn't actually validate) + if not self._has_custom_validation(ef_class): + pytest.skip( + f"{ef_name} uses base validate_config implementation (no validation)" + ) + + # Create a real instance to get the actual config + # We'll mock __call__ to avoid needing to actually generate embeddings + try: + ef_instance = self._create_ef_instance(ef_name, ef_class, mock_common_deps) + except Exception as e: + pytest.skip( + f"{ef_name} requires arguments that we cannot provide without external deps: {e}" + ) + + # Mock only __call__ to avoid needing to actually generate embeddings + mock_call = MagicMock(return_value=mock_embeddings(["test"])) + mock_common_deps.setattr(ef_instance, "__call__", mock_call) + + # Get the actual config from the embedding function (this uses the real get_config method) + config = ef_instance.get_config() + + # Filter out None values - optional fields with None shouldn't be included in validation + # This matches common JSON schema practice where optional fields are omitted rather than null + config = {k: v for k, v in config.items() if v is not None} + + # Validate the actual config using the embedding function's validate_config method + ef_class.validate_config(config) + + def test_validate_config_sparse_embedding_functions( + self, + mock_embeddings: Callable[[Documents], Embeddings], + mock_common_deps: MonkeyPatch, + ) -> None: + """Test validate_config for sparse embedding functions with actual configs""" + for ef_name, ef_class in sparse_known_embedding_functions.items(): + # Skip if the embedding function doesn't have a validate_config method + if not hasattr(ef_class, "validate_config"): + continue + + # Check if it's callable (static methods are callable on the class) + if not callable(getattr(ef_class, "validate_config", None)): + continue + + # Skip if using base implementation (doesn't actually validate) + if not self._has_custom_validation(ef_class): + continue + + # Create a real instance to get the actual config + # We'll mock __call__ to avoid needing to actually generate embeddings + try: + ef_instance = self._create_ef_instance( + ef_name, ef_class, mock_common_deps + ) + except Exception: + continue # Skip if we can't create instance + + # Mock only __call__ to avoid needing to actually generate embeddings + mock_call = MagicMock(return_value=mock_embeddings(["test"])) + mock_common_deps.setattr(ef_instance, "__call__", mock_call) + + # Get the actual config from the embedding function (this uses the real get_config method) + config = ef_instance.get_config() + + # Filter out None values - optional fields with None shouldn't be included in validation + # This matches common JSON schema practice where optional fields are omitted rather than null + config = {k: v for k, v in config.items() if v is not None} + + # Validate the actual config using the embedding function's validate_config method + ef_class.validate_config(config) diff --git a/python/user_packages/Python313/site-packages/chromadb/test/utils/test_result_df_transform.py b/python/user_packages/Python313/site-packages/chromadb/test/utils/test_result_df_transform.py new file mode 100644 index 0000000000000000000000000000000000000000..8c6600b95c3a3df45e585dab97dc389990760bc6 --- /dev/null +++ b/python/user_packages/Python313/site-packages/chromadb/test/utils/test_result_df_transform.py @@ -0,0 +1,184 @@ +import numpy as np +from typing import List, Dict, Any, cast, Union +from chromadb.utils.results import ( + _transform_embeddings, + _add_query_fields, + _add_get_fields, + query_result_to_dfs, + get_result_to_df, +) +from chromadb.api.types import ( + QueryResult, + GetResult, +) +from numpy.typing import NDArray + + +def test_transform_embeddings() -> None: + # Test with None input + assert _transform_embeddings(None) is None + + # Test with numpy arrays + embeddings = cast( + List[NDArray[Union[np.int32, np.float32]]], + [np.array([1.0, 2.0]), np.array([3.0, 4.0])], + ) + transformed = _transform_embeddings(embeddings) + assert isinstance(transformed, list) + assert transformed == [[1.0, 2.0], [3.0, 4.0]] + + # Test with list of lists + embeddings = cast( + List[NDArray[Union[np.int32, np.float32]]], + [np.array([1.0, 2.0]), np.array([3.0, 4.0])], + ) + transformed = _transform_embeddings(embeddings) + assert transformed == [[1.0, 2.0], [3.0, 4.0]] + + +def test_add_query_fields() -> None: + data_dict: Dict[str, Any] = {} + query_result: QueryResult = { + "ids": [["id1"], ["id2"]], + "embeddings": [[np.array([1.0, 2.0])], [np.array([3.0, 4.0])]], + "documents": [["doc1"], ["doc2"]], + "metadatas": [[{"key": "value1"}], [{"key": "value2"}]], + "distances": [[0.1], [0.2]], + "uris": [["uri1", "uri2"]], + "data": [ + [np.array([1, 2, 3]), np.array([4, 5, 6])] + ], # Using numpy arrays as Image type + "included": ["embeddings", "documents", "metadatas", "distances"], + } + + _add_query_fields(data_dict, query_result, 0) + assert np.array_equal(data_dict["embedding"], [np.array([1.0, 2.0])]) + assert data_dict["document"] == ["doc1"] + assert data_dict["metadata"] == [{"key": "value1"}] + assert data_dict["distance"] == [0.1] + + +def test_add_get_fields() -> None: + data_dict: Dict[str, Any] = {} + get_result: GetResult = { + "ids": ["id1", "id2"], + "embeddings": [np.array([1.0, 2.0]), np.array([3.0, 4.0])], + "documents": ["doc1", "doc2"], + "metadatas": [{"key": "value1"}, {"key": "value2"}], + "uris": ["uri1", "uri2"], + "data": [ + np.array([1, 2, 3]), + np.array([4, 5, 6]), + ], # Using numpy arrays as Image type + "included": ["embeddings", "documents", "metadatas"], + } + + _add_get_fields(data_dict, get_result) + assert all( + np.array_equal(a, b) + for a, b in zip( + data_dict["embedding"], [np.array([1.0, 2.0]), np.array([3.0, 4.0])] + ) + ) + assert data_dict["document"] == ["doc1", "doc2"] + assert data_dict["metadata"] == [{"key": "value1"}, {"key": "value2"}] + + +def test_query_result_to_dfs() -> None: + query_result: QueryResult = { + "ids": [["id1", "id2"]], + "embeddings": [[np.array([1.0, 2.0]), np.array([3.0, 4.0])]], + "documents": [["doc1", "doc2"]], + "metadatas": [[{"key": "value1"}, {"key": "value2"}]], + "distances": [[0.1, 0.2]], + "uris": [["uri1", "uri2"]], + "data": [ + [np.array([1, 2, 3]), np.array([4, 5, 6])] + ], # Using numpy arrays as Image type + "included": ["embeddings", "documents", "metadatas", "distances"], + } + + dfs = query_result_to_dfs(query_result) + assert len(dfs) == 1 # Only one query + + # Test DataFrame + df = dfs[0] + assert df.index[0] == "id1" + assert df["document"].iloc[0] == "doc1" + assert df["metadata"].iloc[0] == {"key": "value1"} + assert np.array_equal(df["embedding"].iloc[0], np.array([1.0, 2.0])) + assert df["distance"].iloc[0] == 0.1 + + # Test column order + assert list(df.columns) == ["embedding", "document", "metadata", "distance"] + + +def test_get_result_to_df() -> None: + get_result: GetResult = { + "ids": ["id1", "id2"], + "embeddings": [np.array([1.0, 2.0]), np.array([3.0, 4.0])], + "documents": ["doc1", "doc2"], + "metadatas": [{"key": "value1"}, {"key": "value2"}], + "uris": ["uri1", "uri2"], + "data": [ + np.array([1, 2, 3]), + np.array([4, 5, 6]), + ], # Using numpy arrays as Image type + "included": ["embeddings", "documents", "metadatas"], + } + + df = get_result_to_df(get_result) + assert len(df) == 2 + assert list(df.index) == ["id1", "id2"] + assert df["document"].tolist() == ["doc1", "doc2"] + assert df["metadata"].tolist() == [{"key": "value1"}, {"key": "value2"}] + assert all( + np.array_equal(a, b) + for a, b in zip( + df["embedding"].tolist(), [np.array([1.0, 2.0]), np.array([3.0, 4.0])] + ) + ) + + # Test column order + assert list(df.columns) == ["embedding", "document", "metadata"] + + +def test_query_result_to_dfs_with_missing_fields() -> None: + query_result: QueryResult = { + "ids": [["id1"]], + "documents": [["doc1"]], + "embeddings": [[]], # type:ignore + "metadatas": [[]], + "distances": [[]], + "uris": [[]], + "data": [[]], + "included": ["documents"], + } + + dfs = query_result_to_dfs(query_result) + assert len(dfs) == 1 + df = dfs[0] + assert df.index[0] == "id1" + assert df["document"].iloc[0] == "doc1" + assert "metadata" not in df.columns + assert "embedding" not in df.columns + assert "distance" not in df.columns + + +def test_get_result_to_df_with_missing_fields() -> None: + get_result: GetResult = { + "ids": ["id1", "id2"], + "documents": ["doc1", "doc2"], + "embeddings": [], + "metadatas": [], + "uris": [], + "data": [], + "included": ["documents"], + } + + df = get_result_to_df(get_result) + assert len(df) == 2 + assert list(df.index) == ["id1", "id2"] + assert df["document"].tolist() == ["doc1", "doc2"] + assert "metadata" not in df.columns + assert "embedding" not in df.columns diff --git a/python/user_packages/Python313/site-packages/chromadb/test/utils/test_wait_for_version_increase.py b/python/user_packages/Python313/site-packages/chromadb/test/utils/test_wait_for_version_increase.py new file mode 100644 index 0000000000000000000000000000000000000000..d9d87a0acc9e2f8995d176691240f0673ee60628 --- /dev/null +++ b/python/user_packages/Python313/site-packages/chromadb/test/utils/test_wait_for_version_increase.py @@ -0,0 +1,53 @@ +from types import SimpleNamespace + +import pytest + +import chromadb.test.utils.wait_for_version_increase as wait_module + + +class _FakeClient: + def __init__(self, collection_id: str = "test-collection-id") -> None: + self._collection = SimpleNamespace(id=collection_id) + + def get_collection(self, collection_name: str) -> SimpleNamespace: + return self._collection + + +def test_wait_for_version_increase_logs_target_version( + monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str] +) -> None: + client = _FakeClient() + versions = iter([5, 5, 6]) + times = iter([100.0, 101.0, 102.0]) + + monkeypatch.setattr(wait_module, "COMPACTION_SLEEP", 10) + monkeypatch.setattr(wait_module, "get_collection_version", lambda *_: next(versions)) + monkeypatch.setattr(wait_module.time, "sleep", lambda _: None) + monkeypatch.setattr(wait_module.time, "time", lambda: next(times)) + + new_version = wait_module.wait_for_version_increase(client, "test-collection", 5) + + assert new_version == 6 + assert ( + "[wait_for_version_increase] collection=test-collection " + "waiting for version >= 6 (current=5, timeout=10s)" + ) in capsys.readouterr().out + + +def test_wait_for_version_increase_timeout_mentions_waited_version( + monkeypatch: pytest.MonkeyPatch, +) -> None: + client = _FakeClient() + versions = iter([8, 8]) + times = iter([200.0, 212.0]) + + monkeypatch.setattr(wait_module, "COMPACTION_SLEEP", 10) + monkeypatch.setattr(wait_module, "get_collection_version", lambda *_: next(versions)) + monkeypatch.setattr(wait_module.time, "sleep", lambda _: None) + monkeypatch.setattr(wait_module.time, "time", lambda: next(times)) + + with pytest.raises( + TimeoutError, + match="waited for version >= 9, last seen version 8", + ): + wait_module.wait_for_version_increase(client, "test-collection", 8) diff --git a/python/user_packages/Python313/site-packages/chromadb/test/utils/wait_for_version_increase.py b/python/user_packages/Python313/site-packages/chromadb/test/utils/wait_for_version_increase.py new file mode 100644 index 0000000000000000000000000000000000000000..ed4965b047f1875ff5d83617ead32f0ad3041e22 --- /dev/null +++ b/python/user_packages/Python313/site-packages/chromadb/test/utils/wait_for_version_increase.py @@ -0,0 +1,42 @@ +import time +from chromadb.api import ClientAPI +from chromadb.test.conftest import COMPACTION_SLEEP + +TIMEOUT_INTERVAL = 1 + + +def get_collection_version(client: ClientAPI, collection_name: str) -> int: + coll = client.get_collection(collection_name) + return coll.get_model()["version"] + + +def wait_for_version_increase( + client: ClientAPI, + collection_name: str, + initial_version: int, + additional_time: int = 0, +) -> int: + timeout = COMPACTION_SLEEP + deadline = time.time() + timeout + additional_time + target_version = initial_version + 1 + + curr_version = get_collection_version(client, collection_name) + if curr_version == initial_version: + print( + "[wait_for_version_increase] " + f"collection={collection_name} " + f"waiting for version >= {target_version} " + f"(current={curr_version}, timeout={timeout + additional_time}s)" + ) + while curr_version == initial_version: + time.sleep(TIMEOUT_INTERVAL) + if time.time() > deadline: + collection_id = client.get_collection(collection_name).id + raise TimeoutError( + "Model was not updated in time for " + f"{collection_id}; waited for version >= {target_version}, " + f"last seen version {curr_version}" + ) + curr_version = get_collection_version(client, collection_name) + + return curr_version diff --git a/python/user_packages/Python313/site-packages/chromadb/utils/__init__.py b/python/user_packages/Python313/site-packages/chromadb/utils/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..64f7239d7f0a44987939276b6c7e3b0b547e545d --- /dev/null +++ b/python/user_packages/Python313/site-packages/chromadb/utils/__init__.py @@ -0,0 +1,12 @@ +import importlib +from typing import Type, TypeVar, cast + +C = TypeVar("C") + + +def get_class(fqn: str, type: Type[C]) -> Type[C]: + """Given a fully qualifed class name, import the module and return the class""" + module_name, class_name = fqn.rsplit(".", 1) + module = importlib.import_module(module_name) + cls = getattr(module, class_name) + return cast(Type[C], cls) diff --git a/python/user_packages/Python313/site-packages/chromadb/utils/__pycache__/__init__.cpython-313.pyc b/python/user_packages/Python313/site-packages/chromadb/utils/__pycache__/__init__.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ee111f8782d63b8f61864a8994cf2d93f7349881 Binary files /dev/null and b/python/user_packages/Python313/site-packages/chromadb/utils/__pycache__/__init__.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/chromadb/utils/__pycache__/async_to_sync.cpython-313.pyc b/python/user_packages/Python313/site-packages/chromadb/utils/__pycache__/async_to_sync.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..af3440d8e3372ec96f5594358f28ece4b438367c Binary files /dev/null and b/python/user_packages/Python313/site-packages/chromadb/utils/__pycache__/async_to_sync.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/chromadb/utils/__pycache__/batch_utils.cpython-313.pyc b/python/user_packages/Python313/site-packages/chromadb/utils/__pycache__/batch_utils.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..078200471bb594da758e30f4ebea85f1ec28c242 Binary files /dev/null and b/python/user_packages/Python313/site-packages/chromadb/utils/__pycache__/batch_utils.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/chromadb/utils/__pycache__/data_loaders.cpython-313.pyc b/python/user_packages/Python313/site-packages/chromadb/utils/__pycache__/data_loaders.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8986b120f7744a2a4ec92f0d77e3fa149ffc8e04 Binary files /dev/null and b/python/user_packages/Python313/site-packages/chromadb/utils/__pycache__/data_loaders.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/chromadb/utils/__pycache__/delete_file.cpython-313.pyc b/python/user_packages/Python313/site-packages/chromadb/utils/__pycache__/delete_file.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0a05204afdee35c8d7acf805384980334de5bb03 Binary files /dev/null and b/python/user_packages/Python313/site-packages/chromadb/utils/__pycache__/delete_file.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/chromadb/utils/__pycache__/directory.cpython-313.pyc b/python/user_packages/Python313/site-packages/chromadb/utils/__pycache__/directory.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6e5c87fd088fa1d9410c79ab4710e4a0454cc1f2 Binary files /dev/null and b/python/user_packages/Python313/site-packages/chromadb/utils/__pycache__/directory.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/chromadb/utils/__pycache__/distance_functions.cpython-313.pyc b/python/user_packages/Python313/site-packages/chromadb/utils/__pycache__/distance_functions.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4e18c6d854c959bb91ffdc117c4e9583c4fe2daa Binary files /dev/null and b/python/user_packages/Python313/site-packages/chromadb/utils/__pycache__/distance_functions.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/chromadb/utils/__pycache__/fastapi.cpython-313.pyc b/python/user_packages/Python313/site-packages/chromadb/utils/__pycache__/fastapi.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9fde852789a246f370709020b97662fcbba04d46 Binary files /dev/null and b/python/user_packages/Python313/site-packages/chromadb/utils/__pycache__/fastapi.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/chromadb/utils/__pycache__/lru_cache.cpython-313.pyc b/python/user_packages/Python313/site-packages/chromadb/utils/__pycache__/lru_cache.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9a2747b3ad1950262f1cf1948ed85359dabc9940 Binary files /dev/null and b/python/user_packages/Python313/site-packages/chromadb/utils/__pycache__/lru_cache.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/chromadb/utils/__pycache__/messageid.cpython-313.pyc b/python/user_packages/Python313/site-packages/chromadb/utils/__pycache__/messageid.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c49e01ae0b3e008571f3cceece20e283aeb55e88 Binary files /dev/null and b/python/user_packages/Python313/site-packages/chromadb/utils/__pycache__/messageid.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/chromadb/utils/__pycache__/read_write_lock.cpython-313.pyc b/python/user_packages/Python313/site-packages/chromadb/utils/__pycache__/read_write_lock.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..788ae01e6473fa2f668ea101510152e985099078 Binary files /dev/null and b/python/user_packages/Python313/site-packages/chromadb/utils/__pycache__/read_write_lock.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/chromadb/utils/__pycache__/rendezvous_hash.cpython-313.pyc b/python/user_packages/Python313/site-packages/chromadb/utils/__pycache__/rendezvous_hash.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d87ecb1866305a29f63c3cf60ebd5d21a2eecfc3 Binary files /dev/null and b/python/user_packages/Python313/site-packages/chromadb/utils/__pycache__/rendezvous_hash.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/chromadb/utils/__pycache__/results.cpython-313.pyc b/python/user_packages/Python313/site-packages/chromadb/utils/__pycache__/results.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b26d946d612bf8e5e8c586b9d6da26cc7d279f58 Binary files /dev/null and b/python/user_packages/Python313/site-packages/chromadb/utils/__pycache__/results.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/chromadb/utils/__pycache__/sparse_embedding_utils.cpython-313.pyc b/python/user_packages/Python313/site-packages/chromadb/utils/__pycache__/sparse_embedding_utils.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..726764ce6ca33e74e5e1abe48ac6ec71fb5828fb Binary files /dev/null and b/python/user_packages/Python313/site-packages/chromadb/utils/__pycache__/sparse_embedding_utils.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/chromadb/utils/__pycache__/statistics.cpython-313.pyc b/python/user_packages/Python313/site-packages/chromadb/utils/__pycache__/statistics.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..98bafb65527c5bfe8ba647a59f78a93695af2321 Binary files /dev/null and b/python/user_packages/Python313/site-packages/chromadb/utils/__pycache__/statistics.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/chromadb/utils/async_to_sync.py b/python/user_packages/Python313/site-packages/chromadb/utils/async_to_sync.py new file mode 100644 index 0000000000000000000000000000000000000000..0ee077bd24c17bb2c2b350f4796ff634c4b1a612 --- /dev/null +++ b/python/user_packages/Python313/site-packages/chromadb/utils/async_to_sync.py @@ -0,0 +1,63 @@ +import inspect +import asyncio +from typing import Any, Callable, Coroutine, TypeVar +from typing_extensions import ParamSpec + + +P = ParamSpec("P") +R = TypeVar("R") + + +def async_to_sync(func: Callable[P, Coroutine[Any, Any, R]]) -> Callable[P, R]: + """A function decorator that converts an async function to a sync function. + + This should generally not be used in production code paths. + """ + + def sync_wrapper(*args, **kwargs): # type: ignore + loop = None + try: + loop = asyncio.get_event_loop() + except RuntimeError: + loop = asyncio.new_event_loop() + asyncio.set_event_loop(loop) + + if loop.is_running(): + return func(*args, **kwargs) + + result = loop.run_until_complete(func(*args, **kwargs)) + + def convert_result(result: Any) -> Any: + if isinstance(result, list): + return [convert_result(r) for r in result] + + if isinstance(result, object): + return async_class_to_sync(result) + + if callable(result): + return async_to_sync(result) + + return result + + return convert_result(result) + + return sync_wrapper + + +T = TypeVar("T") + + +def async_class_to_sync(cls: T) -> T: + """A decorator that converts a class with async methods to a class with sync methods. + + This should generally not be used in production code paths. + """ + for attr, value in inspect.getmembers(cls): + if ( + callable(value) + and inspect.iscoroutinefunction(value) + and not attr.startswith("__") + ): + setattr(cls, attr, async_to_sync(value)) + + return cls diff --git a/python/user_packages/Python313/site-packages/chromadb/utils/batch_utils.py b/python/user_packages/Python313/site-packages/chromadb/utils/batch_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..5b824745340b659520931fabee1dd6a2c0faa75c --- /dev/null +++ b/python/user_packages/Python313/site-packages/chromadb/utils/batch_utils.py @@ -0,0 +1,36 @@ +from typing import Optional, Tuple, List +from chromadb.api import BaseAPI +from chromadb.api.types import ( + Documents, + Embeddings, + IDs, + Metadatas, +) + + +def create_batches( + api: BaseAPI, + ids: IDs, + embeddings: Optional[Embeddings] = None, + metadatas: Optional[Metadatas] = None, + documents: Optional[Documents] = None, +) -> List[Tuple[IDs, Optional[Embeddings], Optional[Metadatas], Optional[Documents]]]: + _batches: List[ + Tuple[IDs, Optional[Embeddings], Optional[Metadatas], Optional[Documents]] + ] = [] + if len(ids) > api.get_max_batch_size(): + # create split batches + for i in range(0, len(ids), api.get_max_batch_size()): + _batches.append( + ( + ids[i : i + api.get_max_batch_size()], + embeddings[i : i + api.get_max_batch_size()] + if embeddings is not None + else None, + metadatas[i : i + api.get_max_batch_size()] if metadatas else None, + documents[i : i + api.get_max_batch_size()] if documents else None, + ) + ) + else: + _batches.append((ids, embeddings, metadatas, documents)) + return _batches diff --git a/python/user_packages/Python313/site-packages/chromadb/utils/data_loaders.py b/python/user_packages/Python313/site-packages/chromadb/utils/data_loaders.py new file mode 100644 index 0000000000000000000000000000000000000000..252c7bb9aab5010a52790bf8f3c99210a9725e62 --- /dev/null +++ b/python/user_packages/Python313/site-packages/chromadb/utils/data_loaders.py @@ -0,0 +1,31 @@ +import importlib +import multiprocessing +from typing import Optional, Sequence, List, Tuple +import numpy as np +from chromadb.api.types import URI, DataLoader, Image, URIs +from concurrent.futures import ThreadPoolExecutor + + +class ImageLoader(DataLoader[List[Optional[Image]]]): + def __init__(self, max_workers: int = multiprocessing.cpu_count()) -> None: + try: + self._PILImage = importlib.import_module("PIL.Image") + self._max_workers = max_workers + except ImportError: + raise ValueError( + "The PIL python package is not installed. Please install it with `pip install pillow`" + ) + + def _load_image(self, uri: Optional[URI]) -> Optional[Image]: + return np.array(self._PILImage.open(uri)) if uri is not None else None + + def __call__(self, uris: Sequence[Optional[URI]]) -> List[Optional[Image]]: + with ThreadPoolExecutor(max_workers=self._max_workers) as executor: + return list(executor.map(self._load_image, uris)) + + +class ChromaLangchainPassthroughDataLoader(DataLoader[List[Optional[Image]]]): + # This is a simple pass through data loader that just returns the input data with "images" + # flag which lets the langchain embedding function know that the data is image uris + def __call__(self, uris: URIs) -> Tuple[str, URIs]: # type: ignore + return ("images", uris) diff --git a/python/user_packages/Python313/site-packages/chromadb/utils/delete_file.py b/python/user_packages/Python313/site-packages/chromadb/utils/delete_file.py new file mode 100644 index 0000000000000000000000000000000000000000..ac3a12a479b91abc650271dcb299505365c3ffae --- /dev/null +++ b/python/user_packages/Python313/site-packages/chromadb/utils/delete_file.py @@ -0,0 +1,38 @@ +import os +import random +import gc +import time + + +# Borrowed from https://github.com/rogerbinns/apsw/blob/master/apsw/tests.py#L224 +# Used to delete sqlite files on Windows, since Windows file locking +# behaves differently to other operating systems +# This should only be used for test or non-production code, such as in reset_state. +def delete_file(name: str) -> None: + try: + os.remove(name) + except Exception: + pass + + chars = list("abcdefghijklmn") + random.shuffle(chars) + newname = name + "-n-" + "".join(chars) + count = 0 + while os.path.exists(name): + count += 1 + try: + os.rename(name, newname) + except Exception: + if count > 30: + n = list("abcdefghijklmnopqrstuvwxyz") + random.shuffle(n) + final_name = "".join(n) + try: + os.rename( + name, "chroma-to-clean" + final_name + ".deletememanually" + ) + except Exception: + pass + break + time.sleep(0.1) + gc.collect() diff --git a/python/user_packages/Python313/site-packages/chromadb/utils/directory.py b/python/user_packages/Python313/site-packages/chromadb/utils/directory.py new file mode 100644 index 0000000000000000000000000000000000000000..1942cd6de5d5d462dee2d71ca0039112eb230a50 --- /dev/null +++ b/python/user_packages/Python313/site-packages/chromadb/utils/directory.py @@ -0,0 +1,22 @@ +import os + + +def get_directory_size(directory: str) -> int: + """ + Calculate the total size of the directory by walking through each file. + + Parameters: + directory (str): The path of the directory for which to calculate the size. + + Returns: + total_size (int): The total size of the directory in bytes. + """ + total_size = 0 + for dirpath, _, filenames in os.walk(directory): + for f in filenames: + fp = os.path.join(dirpath, f) + # skip if it is symbolic link + if not os.path.islink(fp): + total_size += os.path.getsize(fp) + + return total_size diff --git a/python/user_packages/Python313/site-packages/chromadb/utils/distance_functions.py b/python/user_packages/Python313/site-packages/chromadb/utils/distance_functions.py new file mode 100644 index 0000000000000000000000000000000000000000..d128507dcfaffd07d12d100851d8b13744dd69f7 --- /dev/null +++ b/python/user_packages/Python313/site-packages/chromadb/utils/distance_functions.py @@ -0,0 +1,32 @@ +""" +These functions match what the spec of hnswlib is. +""" +from typing import Union, cast +import numpy as np +from numpy.typing import NDArray + +Vector = NDArray[Union[np.int32, np.float32, np.int16, np.float16]] + + +def l2(x: Vector, y: Vector) -> float: + return (np.linalg.norm(x - y) ** 2).item() + + +def cosine(x: Vector, y: Vector) -> float: + # This epsilon is used to prevent division by zero, and the value is the same + # https://github.com/nmslib/hnswlib/blob/359b2ba87358224963986f709e593d799064ace6/python_bindings/bindings.cpp#L238 + + # We need to adapt the epsilon to the precision of the input + NORM_EPS = 1e-30 + if x.dtype == np.float16 or y.dtype == np.float16: + NORM_EPS = 1e-7 + return cast( + float, + ( + 1.0 - np.dot(x, y) / ((np.linalg.norm(x) * np.linalg.norm(y)) + NORM_EPS) + ).item(), + ) + + +def ip(x: Vector, y: Vector) -> float: + return cast(float, (1.0 - np.dot(x, y)).item()) diff --git a/python/user_packages/Python313/site-packages/chromadb/utils/embedding_functions/__init__.py b/python/user_packages/Python313/site-packages/chromadb/utils/embedding_functions/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..d1052dab0a36be804049d58b6897b4c7605025b3 --- /dev/null +++ b/python/user_packages/Python313/site-packages/chromadb/utils/embedding_functions/__init__.py @@ -0,0 +1,307 @@ +from typing import Dict, Any, Type, Set +from chromadb.api.types import ( + EmbeddingFunction, + DefaultEmbeddingFunction, + SparseEmbeddingFunction, +) + +# Import all embedding functions +from chromadb.utils.embedding_functions.cohere_embedding_function import ( + CohereEmbeddingFunction, +) +from chromadb.utils.embedding_functions.openai_embedding_function import ( + OpenAIEmbeddingFunction, +) +from chromadb.utils.embedding_functions.huggingface_embedding_function import ( + HuggingFaceEmbeddingFunction, + HuggingFaceEmbeddingServer, +) +from chromadb.utils.embedding_functions.sentence_transformer_embedding_function import ( + SentenceTransformerEmbeddingFunction, +) +from chromadb.utils.embedding_functions.google_embedding_function import ( + GooglePalmEmbeddingFunction, + GoogleGenerativeAiEmbeddingFunction, + GoogleVertexEmbeddingFunction, + GoogleGeminiEmbeddingFunction, + GoogleGenaiEmbeddingFunction, # Backward compatibility alias +) +from chromadb.utils.embedding_functions.ollama_embedding_function import ( + OllamaEmbeddingFunction, +) +from chromadb.utils.embedding_functions.instructor_embedding_function import ( + InstructorEmbeddingFunction, +) +from chromadb.utils.embedding_functions.jina_embedding_function import ( + JinaEmbeddingFunction, + JinaQueryConfig, +) +from chromadb.utils.embedding_functions.voyageai_embedding_function import ( + VoyageAIEmbeddingFunction, +) +from chromadb.utils.embedding_functions.onnx_mini_lm_l6_v2 import ONNXMiniLM_L6_V2 +from chromadb.utils.embedding_functions.open_clip_embedding_function import ( + OpenCLIPEmbeddingFunction, +) +from chromadb.utils.embedding_functions.roboflow_embedding_function import ( + RoboflowEmbeddingFunction, +) +from chromadb.utils.embedding_functions.text2vec_embedding_function import ( + Text2VecEmbeddingFunction, +) +from chromadb.utils.embedding_functions.amazon_bedrock_embedding_function import ( + AmazonBedrockEmbeddingFunction, +) +from chromadb.utils.embedding_functions.chroma_langchain_embedding_function import ( + ChromaLangchainEmbeddingFunction, +) +from chromadb.utils.embedding_functions.baseten_embedding_function import ( + BasetenEmbeddingFunction, +) +from chromadb.utils.embedding_functions.cloudflare_workers_ai_embedding_function import ( + CloudflareWorkersAIEmbeddingFunction, +) +from chromadb.utils.embedding_functions.together_ai_embedding_function import ( + TogetherAIEmbeddingFunction, +) +from chromadb.utils.embedding_functions.mistral_embedding_function import ( + MistralEmbeddingFunction, +) +from chromadb.utils.embedding_functions.morph_embedding_function import ( + MorphEmbeddingFunction, +) +from chromadb.utils.embedding_functions.nomic_embedding_function import ( + NomicEmbeddingFunction, + NomicQueryConfig, +) +from chromadb.utils.embedding_functions.huggingface_sparse_embedding_function import ( + HuggingFaceSparseEmbeddingFunction, +) +from chromadb.utils.embedding_functions.fastembed_sparse_embedding_function import ( + FastembedSparseEmbeddingFunction, +) +from chromadb.utils.embedding_functions.bm25_embedding_function import ( + Bm25EmbeddingFunction, +) +from chromadb.utils.embedding_functions.chroma_cloud_qwen_embedding_function import ( + ChromaCloudQwenEmbeddingFunction, +) +from chromadb.utils.embedding_functions.chroma_cloud_splade_embedding_function import ( + ChromaCloudSpladeEmbeddingFunction, +) +from chromadb.utils.embedding_functions.chroma_bm25_embedding_function import ( + ChromaBm25EmbeddingFunction, +) +from chromadb.utils.embedding_functions.perplexity_embedding_function import ( + PerplexityEmbeddingFunction, +) + + +# Get all the class names for backward compatibility +_all_classes: Set[str] = { + "CohereEmbeddingFunction", + "OpenAIEmbeddingFunction", + "HuggingFaceEmbeddingFunction", + "HuggingFaceEmbeddingServer", + "SentenceTransformerEmbeddingFunction", + "GooglePalmEmbeddingFunction", + "GoogleGenerativeAiEmbeddingFunction", + "GoogleVertexEmbeddingFunction", + "GoogleGeminiEmbeddingFunction", + "GoogleGenaiEmbeddingFunction", # Backward compatibility alias + "OllamaEmbeddingFunction", + "InstructorEmbeddingFunction", + "JinaEmbeddingFunction", + "MistralEmbeddingFunction", + "MorphEmbeddingFunction", + "NomicEmbeddingFunction", + "VoyageAIEmbeddingFunction", + "ONNXMiniLM_L6_V2", + "OpenCLIPEmbeddingFunction", + "RoboflowEmbeddingFunction", + "Text2VecEmbeddingFunction", + "AmazonBedrockEmbeddingFunction", + "ChromaLangchainEmbeddingFunction", + "BasetenEmbeddingFunction", + "CloudflareWorkersAIEmbeddingFunction", + "TogetherAIEmbeddingFunction", + "DefaultEmbeddingFunction", + "HuggingFaceSparseEmbeddingFunction", + "FastembedSparseEmbeddingFunction", + "Bm25EmbeddingFunction", + "ChromaCloudQwenEmbeddingFunction", + "ChromaCloudSpladeEmbeddingFunction", + "ChromaBm25EmbeddingFunction", + "PerplexityEmbeddingFunction" +} + + +def get_builtins() -> Set[str]: + return _all_classes + + +# Dictionary of supported embedding functions +known_embedding_functions: Dict[str, Type[EmbeddingFunction]] = { # type: ignore + "cohere": CohereEmbeddingFunction, + "openai": OpenAIEmbeddingFunction, + "huggingface": HuggingFaceEmbeddingFunction, + "huggingface_server": HuggingFaceEmbeddingServer, + "sentence_transformer": SentenceTransformerEmbeddingFunction, + "google_palm": GooglePalmEmbeddingFunction, + "google_generative_ai": GoogleGenerativeAiEmbeddingFunction, + "google_vertex": GoogleVertexEmbeddingFunction, + "google_gemini": GoogleGeminiEmbeddingFunction, + "google_genai": GoogleGeminiEmbeddingFunction, # Backward compatibility alias + "ollama": OllamaEmbeddingFunction, + "instructor": InstructorEmbeddingFunction, + "jina": JinaEmbeddingFunction, + "mistral": MistralEmbeddingFunction, + "morph": MorphEmbeddingFunction, + "nomic": NomicEmbeddingFunction, + "voyageai": VoyageAIEmbeddingFunction, + "onnx_mini_lm_l6_v2": ONNXMiniLM_L6_V2, + "open_clip": OpenCLIPEmbeddingFunction, + "roboflow": RoboflowEmbeddingFunction, + "text2vec": Text2VecEmbeddingFunction, + "amazon_bedrock": AmazonBedrockEmbeddingFunction, + "chroma_langchain": ChromaLangchainEmbeddingFunction, + "baseten": BasetenEmbeddingFunction, + "default": DefaultEmbeddingFunction, + "cloudflare_workers_ai": CloudflareWorkersAIEmbeddingFunction, + "together_ai": TogetherAIEmbeddingFunction, + "chroma-cloud-qwen": ChromaCloudQwenEmbeddingFunction, + "perplexity": PerplexityEmbeddingFunction, +} + +sparse_known_embedding_functions: Dict[str, Type[SparseEmbeddingFunction]] = { # type: ignore + "huggingface_sparse": HuggingFaceSparseEmbeddingFunction, + "fastembed_sparse": FastembedSparseEmbeddingFunction, + "bm25": Bm25EmbeddingFunction, + "chroma-cloud-splade": ChromaCloudSpladeEmbeddingFunction, + "chroma_bm25": ChromaBm25EmbeddingFunction, +} + + +def register_embedding_function(ef_class=None): # type: ignore + """Register a custom embedding function. + + Can be used as a decorator: + @register_embedding_function + class MyEmbedding(EmbeddingFunction): + @classmethod + def name(cls): return "my_embedding" + + Or directly: + register_embedding_function(MyEmbedding) + + Args: + ef_class: The embedding function class to register. + """ + + def _register(cls): # type: ignore + try: + name = cls.name() + known_embedding_functions[name] = cls + except Exception as e: + raise ValueError(f"Failed to register embedding function: {e}") + return cls # Return the class unchanged + + # If called with a class, register it immediately + if ef_class is not None: + return _register(ef_class) # type: ignore + + # If called without arguments, return a decorator + return _register + + +def register_sparse_embedding_function(ef_class=None): # type: ignore + """Register a custom sparse embedding function. + + Can be used as a decorator: + @register_sparse_embedding_function + class MySparseEmbeddingFunction(SparseEmbeddingFunction): + @classmethod + def name(cls): return "my_sparse_embedding" + """ + + def _register(cls): # type: ignore + try: + name = cls.name() + sparse_known_embedding_functions[name] = cls + except Exception as e: + raise ValueError(f"Failed to register sparse embedding function: {e}") + return cls # Return the class unchanged + + if ef_class is not None: + return _register(ef_class) # type: ignore + + return _register + + +# Function to convert config to embedding function +def config_to_embedding_function(config: Dict[str, Any]) -> EmbeddingFunction: # type: ignore + """Convert a config dictionary to an embedding function. + + Args: + config: The config dictionary. + + Returns: + The embedding function. + """ + if "name" not in config: + raise ValueError("Config must contain a 'name' field.") + + name = config["name"] + if name not in known_embedding_functions: + raise ValueError(f"Unsupported embedding function: {name}") + + ef_config = config.get("config", {}) + + if known_embedding_functions[name] is None: + raise ValueError(f"Unsupported embedding function: {name}") + + return known_embedding_functions[name].build_from_config(ef_config) + + +__all__ = [ + "EmbeddingFunction", + "DefaultEmbeddingFunction", + "CohereEmbeddingFunction", + "OpenAIEmbeddingFunction", + "BasetenEmbeddingFunction", + "CloudflareWorkersAIEmbeddingFunction", + "HuggingFaceEmbeddingFunction", + "HuggingFaceEmbeddingServer", + "SentenceTransformerEmbeddingFunction", + "GooglePalmEmbeddingFunction", + "GoogleGenerativeAiEmbeddingFunction", + "GoogleVertexEmbeddingFunction", + "GoogleGeminiEmbeddingFunction", + "GoogleGenaiEmbeddingFunction", # Backward compatibility alias + "OllamaEmbeddingFunction", + "InstructorEmbeddingFunction", + "JinaEmbeddingFunction", + "JinaQueryConfig", + "MistralEmbeddingFunction", + "MorphEmbeddingFunction", + "NomicEmbeddingFunction", + "NomicQueryConfig", + "VoyageAIEmbeddingFunction", + "ONNXMiniLM_L6_V2", + "OpenCLIPEmbeddingFunction", + "RoboflowEmbeddingFunction", + "Text2VecEmbeddingFunction", + "AmazonBedrockEmbeddingFunction", + "ChromaLangchainEmbeddingFunction", + "TogetherAIEmbeddingFunction", + "HuggingFaceSparseEmbeddingFunction", + "FastembedSparseEmbeddingFunction", + "Bm25EmbeddingFunction", + "ChromaCloudQwenEmbeddingFunction", + "ChromaCloudSpladeEmbeddingFunction", + "ChromaBm25EmbeddingFunction", + "PerplexityEmbeddingFunction", + "register_embedding_function", + "config_to_embedding_function", + "known_embedding_functions", +] diff --git a/python/user_packages/Python313/site-packages/chromadb/utils/embedding_functions/__pycache__/__init__.cpython-313.pyc b/python/user_packages/Python313/site-packages/chromadb/utils/embedding_functions/__pycache__/__init__.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3537f5570b2dd18813278d97bdcdb8c42845425f Binary files /dev/null and b/python/user_packages/Python313/site-packages/chromadb/utils/embedding_functions/__pycache__/__init__.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/chromadb/utils/embedding_functions/__pycache__/amazon_bedrock_embedding_function.cpython-313.pyc b/python/user_packages/Python313/site-packages/chromadb/utils/embedding_functions/__pycache__/amazon_bedrock_embedding_function.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3835296cb0c777ff5c973041283e3038b85a1db1 Binary files /dev/null and b/python/user_packages/Python313/site-packages/chromadb/utils/embedding_functions/__pycache__/amazon_bedrock_embedding_function.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/chromadb/utils/embedding_functions/__pycache__/baseten_embedding_function.cpython-313.pyc b/python/user_packages/Python313/site-packages/chromadb/utils/embedding_functions/__pycache__/baseten_embedding_function.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..00a592c0a7323e6c7de89e75e777bfad53adb5ac Binary files /dev/null and b/python/user_packages/Python313/site-packages/chromadb/utils/embedding_functions/__pycache__/baseten_embedding_function.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/chromadb/utils/embedding_functions/__pycache__/bm25_embedding_function.cpython-313.pyc b/python/user_packages/Python313/site-packages/chromadb/utils/embedding_functions/__pycache__/bm25_embedding_function.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..495605230b1b81959d3baed7b0d27424e1e96df1 Binary files /dev/null and b/python/user_packages/Python313/site-packages/chromadb/utils/embedding_functions/__pycache__/bm25_embedding_function.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/chromadb/utils/embedding_functions/__pycache__/chroma_bm25_embedding_function.cpython-313.pyc b/python/user_packages/Python313/site-packages/chromadb/utils/embedding_functions/__pycache__/chroma_bm25_embedding_function.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..28ce50f3a24a1590b998624d2d3ffac3b35aeed7 Binary files /dev/null and b/python/user_packages/Python313/site-packages/chromadb/utils/embedding_functions/__pycache__/chroma_bm25_embedding_function.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/chromadb/utils/embedding_functions/__pycache__/chroma_cloud_qwen_embedding_function.cpython-313.pyc b/python/user_packages/Python313/site-packages/chromadb/utils/embedding_functions/__pycache__/chroma_cloud_qwen_embedding_function.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a9e6e51e1d7118c0f856cf21f3b0416891f95c4a Binary files /dev/null and b/python/user_packages/Python313/site-packages/chromadb/utils/embedding_functions/__pycache__/chroma_cloud_qwen_embedding_function.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/chromadb/utils/embedding_functions/__pycache__/chroma_cloud_splade_embedding_function.cpython-313.pyc b/python/user_packages/Python313/site-packages/chromadb/utils/embedding_functions/__pycache__/chroma_cloud_splade_embedding_function.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..43d759abe87f8dbecc95d25c5282f29ab9753e2f Binary files /dev/null and b/python/user_packages/Python313/site-packages/chromadb/utils/embedding_functions/__pycache__/chroma_cloud_splade_embedding_function.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/chromadb/utils/embedding_functions/__pycache__/chroma_langchain_embedding_function.cpython-313.pyc b/python/user_packages/Python313/site-packages/chromadb/utils/embedding_functions/__pycache__/chroma_langchain_embedding_function.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2e634ef88bba0a4050bab6b689b8e5efdcaedd43 Binary files /dev/null and b/python/user_packages/Python313/site-packages/chromadb/utils/embedding_functions/__pycache__/chroma_langchain_embedding_function.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/chromadb/utils/embedding_functions/__pycache__/cloudflare_workers_ai_embedding_function.cpython-313.pyc b/python/user_packages/Python313/site-packages/chromadb/utils/embedding_functions/__pycache__/cloudflare_workers_ai_embedding_function.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..18975588a53f3c08cc69a102645e19378a459a83 Binary files /dev/null and b/python/user_packages/Python313/site-packages/chromadb/utils/embedding_functions/__pycache__/cloudflare_workers_ai_embedding_function.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/chromadb/utils/embedding_functions/__pycache__/cohere_embedding_function.cpython-313.pyc b/python/user_packages/Python313/site-packages/chromadb/utils/embedding_functions/__pycache__/cohere_embedding_function.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..28c9891e82eced5b13bc4c50f6dc86c24fda0fa8 Binary files /dev/null and b/python/user_packages/Python313/site-packages/chromadb/utils/embedding_functions/__pycache__/cohere_embedding_function.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/chromadb/utils/embedding_functions/__pycache__/fastembed_sparse_embedding_function.cpython-313.pyc b/python/user_packages/Python313/site-packages/chromadb/utils/embedding_functions/__pycache__/fastembed_sparse_embedding_function.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4c491f18118522022493fa50856850eb493c4227 Binary files /dev/null and b/python/user_packages/Python313/site-packages/chromadb/utils/embedding_functions/__pycache__/fastembed_sparse_embedding_function.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/chromadb/utils/embedding_functions/__pycache__/google_embedding_function.cpython-313.pyc b/python/user_packages/Python313/site-packages/chromadb/utils/embedding_functions/__pycache__/google_embedding_function.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7f651f3cc6456b64ae235fb69f8450d153d3b78a Binary files /dev/null and b/python/user_packages/Python313/site-packages/chromadb/utils/embedding_functions/__pycache__/google_embedding_function.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/chromadb/utils/embedding_functions/__pycache__/huggingface_embedding_function.cpython-313.pyc b/python/user_packages/Python313/site-packages/chromadb/utils/embedding_functions/__pycache__/huggingface_embedding_function.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..00a259ef7c5180f4624dd1eccaa72d9ed7efe4f9 Binary files /dev/null and b/python/user_packages/Python313/site-packages/chromadb/utils/embedding_functions/__pycache__/huggingface_embedding_function.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/chromadb/utils/embedding_functions/__pycache__/huggingface_sparse_embedding_function.cpython-313.pyc b/python/user_packages/Python313/site-packages/chromadb/utils/embedding_functions/__pycache__/huggingface_sparse_embedding_function.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..280c6ec4cf468ac8bcf2a10b2ec758cc0057a69e Binary files /dev/null and b/python/user_packages/Python313/site-packages/chromadb/utils/embedding_functions/__pycache__/huggingface_sparse_embedding_function.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/chromadb/utils/embedding_functions/__pycache__/instructor_embedding_function.cpython-313.pyc b/python/user_packages/Python313/site-packages/chromadb/utils/embedding_functions/__pycache__/instructor_embedding_function.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..147d8a7e44e5cefcaf3a3ad4cf93ede4a0f2b4d2 Binary files /dev/null and b/python/user_packages/Python313/site-packages/chromadb/utils/embedding_functions/__pycache__/instructor_embedding_function.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/chromadb/utils/embedding_functions/__pycache__/jina_embedding_function.cpython-313.pyc b/python/user_packages/Python313/site-packages/chromadb/utils/embedding_functions/__pycache__/jina_embedding_function.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3f886612289cc0aaac070932d3e1bed8d2ab7897 Binary files /dev/null and b/python/user_packages/Python313/site-packages/chromadb/utils/embedding_functions/__pycache__/jina_embedding_function.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/chromadb/utils/embedding_functions/__pycache__/mistral_embedding_function.cpython-313.pyc b/python/user_packages/Python313/site-packages/chromadb/utils/embedding_functions/__pycache__/mistral_embedding_function.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b56723b66b3fad61a2638901fbef835ed885f513 Binary files /dev/null and b/python/user_packages/Python313/site-packages/chromadb/utils/embedding_functions/__pycache__/mistral_embedding_function.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/chromadb/utils/embedding_functions/__pycache__/morph_embedding_function.cpython-313.pyc b/python/user_packages/Python313/site-packages/chromadb/utils/embedding_functions/__pycache__/morph_embedding_function.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8df4a04de8df3dc1104e842f7451d9869265b1e8 Binary files /dev/null and b/python/user_packages/Python313/site-packages/chromadb/utils/embedding_functions/__pycache__/morph_embedding_function.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/chromadb/utils/embedding_functions/__pycache__/nomic_embedding_function.cpython-313.pyc b/python/user_packages/Python313/site-packages/chromadb/utils/embedding_functions/__pycache__/nomic_embedding_function.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e5128d79b58162b6229ff4bdde853ba301a30c81 Binary files /dev/null and b/python/user_packages/Python313/site-packages/chromadb/utils/embedding_functions/__pycache__/nomic_embedding_function.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/chromadb/utils/embedding_functions/__pycache__/ollama_embedding_function.cpython-313.pyc b/python/user_packages/Python313/site-packages/chromadb/utils/embedding_functions/__pycache__/ollama_embedding_function.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..650b87fc5fbaec3c265a781d2e0bb1cc0d1829b7 Binary files /dev/null and b/python/user_packages/Python313/site-packages/chromadb/utils/embedding_functions/__pycache__/ollama_embedding_function.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/chromadb/utils/embedding_functions/__pycache__/onnx_mini_lm_l6_v2.cpython-313.pyc b/python/user_packages/Python313/site-packages/chromadb/utils/embedding_functions/__pycache__/onnx_mini_lm_l6_v2.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..15405db52ba26077cc783b7881c2bb85a263ed1c Binary files /dev/null and b/python/user_packages/Python313/site-packages/chromadb/utils/embedding_functions/__pycache__/onnx_mini_lm_l6_v2.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/chromadb/utils/embedding_functions/__pycache__/open_clip_embedding_function.cpython-313.pyc b/python/user_packages/Python313/site-packages/chromadb/utils/embedding_functions/__pycache__/open_clip_embedding_function.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9bd81e10ff73fc12403dcee3d9bd18e5f11a146d Binary files /dev/null and b/python/user_packages/Python313/site-packages/chromadb/utils/embedding_functions/__pycache__/open_clip_embedding_function.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/chromadb/utils/embedding_functions/__pycache__/openai_embedding_function.cpython-313.pyc b/python/user_packages/Python313/site-packages/chromadb/utils/embedding_functions/__pycache__/openai_embedding_function.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b0689a68481fefce42ab7d24170f4af5f367a32a Binary files /dev/null and b/python/user_packages/Python313/site-packages/chromadb/utils/embedding_functions/__pycache__/openai_embedding_function.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/chromadb/utils/embedding_functions/__pycache__/perplexity_embedding_function.cpython-313.pyc b/python/user_packages/Python313/site-packages/chromadb/utils/embedding_functions/__pycache__/perplexity_embedding_function.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e86cab91a5c0db4002a68859667a2b8f5be5d691 Binary files /dev/null and b/python/user_packages/Python313/site-packages/chromadb/utils/embedding_functions/__pycache__/perplexity_embedding_function.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/chromadb/utils/embedding_functions/__pycache__/roboflow_embedding_function.cpython-313.pyc b/python/user_packages/Python313/site-packages/chromadb/utils/embedding_functions/__pycache__/roboflow_embedding_function.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e1b7a7ad4a232b22ef0b242bd739aa5013dcc1c5 Binary files /dev/null and b/python/user_packages/Python313/site-packages/chromadb/utils/embedding_functions/__pycache__/roboflow_embedding_function.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/chromadb/utils/embedding_functions/__pycache__/sentence_transformer_embedding_function.cpython-313.pyc b/python/user_packages/Python313/site-packages/chromadb/utils/embedding_functions/__pycache__/sentence_transformer_embedding_function.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a88f6e631227ea76db005e051cb66f501a0955bd Binary files /dev/null and b/python/user_packages/Python313/site-packages/chromadb/utils/embedding_functions/__pycache__/sentence_transformer_embedding_function.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/chromadb/utils/embedding_functions/__pycache__/text2vec_embedding_function.cpython-313.pyc b/python/user_packages/Python313/site-packages/chromadb/utils/embedding_functions/__pycache__/text2vec_embedding_function.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..86ca84da7e7bc70b96b9c190dd90d42e1c859548 Binary files /dev/null and b/python/user_packages/Python313/site-packages/chromadb/utils/embedding_functions/__pycache__/text2vec_embedding_function.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/chromadb/utils/embedding_functions/__pycache__/together_ai_embedding_function.cpython-313.pyc b/python/user_packages/Python313/site-packages/chromadb/utils/embedding_functions/__pycache__/together_ai_embedding_function.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ef028a7f960d05162650da0188b1d51bdad43722 Binary files /dev/null and b/python/user_packages/Python313/site-packages/chromadb/utils/embedding_functions/__pycache__/together_ai_embedding_function.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/chromadb/utils/embedding_functions/__pycache__/utils.cpython-313.pyc b/python/user_packages/Python313/site-packages/chromadb/utils/embedding_functions/__pycache__/utils.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5b0695e39d8346e99efbe0436ee2868df6324f89 Binary files /dev/null and b/python/user_packages/Python313/site-packages/chromadb/utils/embedding_functions/__pycache__/utils.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/chromadb/utils/embedding_functions/__pycache__/voyageai_embedding_function.cpython-313.pyc b/python/user_packages/Python313/site-packages/chromadb/utils/embedding_functions/__pycache__/voyageai_embedding_function.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..087ecc79adbff8e8c5ccc26775ae693e15244857 Binary files /dev/null and b/python/user_packages/Python313/site-packages/chromadb/utils/embedding_functions/__pycache__/voyageai_embedding_function.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/chromadb/utils/embedding_functions/amazon_bedrock_embedding_function.py b/python/user_packages/Python313/site-packages/chromadb/utils/embedding_functions/amazon_bedrock_embedding_function.py new file mode 100644 index 0000000000000000000000000000000000000000..91d10769cf699947ccb45f00a7a728b745611d74 --- /dev/null +++ b/python/user_packages/Python313/site-packages/chromadb/utils/embedding_functions/amazon_bedrock_embedding_function.py @@ -0,0 +1,138 @@ +from chromadb.utils.embedding_functions.schemas import validate_config_schema +from chromadb.api.types import Embeddings, Documents, EmbeddingFunction +from typing import Dict, Any, cast +import json +import numpy as np + + +class AmazonBedrockEmbeddingFunction(EmbeddingFunction[Documents]): + """ + This class is used to generate embeddings for a list of texts using Amazon Bedrock. + """ + + def __init__( + self, + session: Any, + model_name: str = "amazon.titan-embed-text-v1", + **kwargs: Any, + ): + """Initialize AmazonBedrockEmbeddingFunction. + + Args: + session (boto3.Session): The boto3 session to use. You need to have boto3 + installed, `pip install boto3`. Access & secret key are not supported. + model_name (str, optional): Identifier of the model, defaults to "amazon.titan-embed-text-v1" + **kwargs: Additional arguments to pass to the boto3 client. + + Example: + >>> import boto3 + >>> session = boto3.Session(profile_name="profile", region_name="us-east-1") + >>> bedrock = AmazonBedrockEmbeddingFunction(session=session) + >>> texts = ["Hello, world!", "How are you?"] + >>> embeddings = bedrock(texts) + """ + + self.model_name = model_name + # check kwargs are primitives only + for key, value in kwargs.items(): + if not isinstance(value, (str, int, float, bool, list, dict, tuple)): + raise ValueError(f"Keyword argument {key} is not a primitive type") + self.kwargs = kwargs + + # Store the session for serialization + self._session_args = {} + if hasattr(session, "region_name") and session.region_name: + self._session_args["region_name"] = session.region_name + if hasattr(session, "profile_name") and session.profile_name: + self._session_args["profile_name"] = session.profile_name + + self._client = session.client( + service_name="bedrock-runtime", + **kwargs, + ) + + def __call__(self, input: Documents) -> Embeddings: + """ + Generate embeddings for the given documents. + + Args: + input: Documents to generate embeddings for. + + Returns: + Embeddings for the documents. + """ + accept = "application/json" + content_type = "application/json" + embeddings = [] + + for text in input: + input_body = {"inputText": text} + body = json.dumps(input_body) + response = self._client.invoke_model( + body=body, + modelId=self.model_name, + accept=accept, + contentType=content_type, + ) + response_body = json.loads(response.get("body").read()) + embedding = response_body.get("embedding") + embeddings.append(np.array(embedding, dtype=np.float32)) + + # Convert to the expected Embeddings type + return cast(Embeddings, embeddings) + + @staticmethod + def name() -> str: + return "amazon_bedrock" + + @staticmethod + def build_from_config(config: Dict[str, Any]) -> "EmbeddingFunction[Documents]": + try: + import boto3 + except ImportError: + raise ValueError( + "The boto3 python package is not installed. Please install it with `pip install boto3`" + ) + + model_name = config.get("model_name") + session_args = config.get("session_args") + if model_name is None: + assert False, "This code should not be reached" + kwargs = config.get("kwargs", {}) + + if session_args is None: + session = boto3.Session() + else: + session = boto3.Session(**session_args) + + return AmazonBedrockEmbeddingFunction( + session=session, model_name=model_name, **kwargs + ) + + def get_config(self) -> Dict[str, Any]: + return { + "model_name": self.model_name, + "session_args": self._session_args, + "kwargs": self.kwargs, + } + + def validate_config_update( + self, old_config: Dict[str, Any], new_config: Dict[str, Any] + ) -> None: + if "model_name" in new_config: + raise ValueError( + "The model name cannot be changed after the embedding function has been initialized." + ) + + @staticmethod + def validate_config(config: Dict[str, Any]) -> None: + """ + Validate the configuration using the JSON schema. + + Args: + config: Configuration to validate + + Raises: + ValidationError: If the configuration does not match the schema + """ + validate_config_schema(config, "amazon_bedrock") diff --git a/python/user_packages/Python313/site-packages/chromadb/utils/embedding_functions/baseten_embedding_function.py b/python/user_packages/Python313/site-packages/chromadb/utils/embedding_functions/baseten_embedding_function.py new file mode 100644 index 0000000000000000000000000000000000000000..96829c69726e51747ea561d94e396a2113aef7e0 --- /dev/null +++ b/python/user_packages/Python313/site-packages/chromadb/utils/embedding_functions/baseten_embedding_function.py @@ -0,0 +1,116 @@ +import os +from chromadb.utils.embedding_functions.openai_embedding_function import ( + OpenAIEmbeddingFunction, +) +from chromadb.utils.embedding_functions.schemas import validate_config_schema +from typing import Dict, Any, Optional, List +from chromadb.api.types import Space +import warnings + + +class BasetenEmbeddingFunction(OpenAIEmbeddingFunction): + def __init__( + self, + api_key: Optional[str], + api_base: str, + api_key_env_var: str = "CHROMA_BASETEN_API_KEY", + ): + """ + Initialize the BasetenEmbeddingFunction. + Args: + api_key (str, optional): The API key for your Baseten account + api_base (str, required): The Baseten URL of the deployment + api_key_env_var (str, optional): The environment variable to use for the API key. Defaults to "CHROMA_BASETEN_API_KEY". + """ + try: + import openai + except ImportError: + raise ValueError( + "The openai python package is not installed. Please install it with `pip install openai`" + ) + + if api_key is not None: + warnings.warn( + "Direct api_key configuration will not be persisted. " + "Please use environment variables via api_key_env_var for persistent storage.", + DeprecationWarning, + ) + + if os.getenv("BASETEN_API_KEY") is not None: + self.api_key_env_var = "BASETEN_API_KEY" + else: + self.api_key_env_var = api_key_env_var + + # Prioritize api_key argument, then environment variable + resolved_api_key = api_key or os.getenv(self.api_key_env_var) + if not resolved_api_key: + raise ValueError( + f"API key not provided and {self.api_key_env_var} environment variable is not set." + ) + self.api_key = resolved_api_key + if not api_base: + raise ValueError("The api_base argument must be provided.") + self.api_base = api_base + self.model_name = "baseten-embedding-model" + self.dimensions = None + + self.client = openai.OpenAI(api_key=self.api_key, base_url=self.api_base) + + @staticmethod + def name() -> str: + return "baseten" + + def default_space(self) -> Space: + return "cosine" + + def supported_spaces(self) -> List[Space]: + return ["cosine", "l2", "ip"] + + def get_config(self) -> Dict[str, Any]: + return {"api_base": self.api_base, "api_key_env_var": self.api_key_env_var} + + @staticmethod + def build_from_config(config: Dict[str, Any]) -> "BasetenEmbeddingFunction": + """ + Build the BasetenEmbeddingFunction from a configuration dictionary. + + Args: + config (Dict[str, Any]): A dictionary containing the configuration parameters. + Expected keys: 'api_key', 'api_base', 'api_key_env_var'. + + Returns: + BasetenEmbeddingFunction: An instance of BasetenEmbeddingFunction. + """ + api_key_env_var = config.get("api_key_env_var") + api_base = config.get("api_base") + if api_key_env_var is None or api_base is None: + raise ValueError( + "Missing 'api_key_env_var' or 'api_base' in configuration for BasetenEmbeddingFunction." + ) + + # Note: We rely on the __init__ method to handle potential missing api_key + # by checking the environment variable if the config value is None. + # However, api_base must be present either in config or have a default. + if api_base is None: + raise ValueError( + "Missing 'api_base' in configuration for BasetenEmbeddingFunction." + ) + + return BasetenEmbeddingFunction( + api_key=None, # Pass None if not in config, __init__ will check env var + api_base=api_base, + api_key_env_var=api_key_env_var, + ) + + @staticmethod + def validate_config(config: Dict[str, Any]) -> None: + """ + Validate the configuration using the JSON schema. + + Args: + config: Configuration to validate + + Raises: + ValidationError: If the configuration does not match the schema + """ + validate_config_schema(config, "baseten") diff --git a/python/user_packages/Python313/site-packages/chromadb/utils/embedding_functions/bm25_embedding_function.py b/python/user_packages/Python313/site-packages/chromadb/utils/embedding_functions/bm25_embedding_function.py new file mode 100644 index 0000000000000000000000000000000000000000..5fd10339f7546cafca7816a2b22967dd59075365 --- /dev/null +++ b/python/user_packages/Python313/site-packages/chromadb/utils/embedding_functions/bm25_embedding_function.py @@ -0,0 +1,234 @@ +from chromadb.api.types import ( + SparseEmbeddingFunction, + SparseVectors, + Documents, +) +from typing import Dict, Any, TypedDict, Optional +from typing import cast, Literal +import warnings +from chromadb.utils.embedding_functions.schemas import validate_config_schema +from chromadb.utils.sparse_embedding_utils import normalize_sparse_vector + +TaskType = Literal["document", "query"] + + +class Bm25EmbeddingFunctionQueryConfig(TypedDict): + task: TaskType + + +class Bm25EmbeddingFunction(SparseEmbeddingFunction[Documents]): + def __init__( + self, + avg_len: Optional[float] = None, + task: Optional[TaskType] = "document", + cache_dir: Optional[str] = None, + k: Optional[float] = None, + b: Optional[float] = None, + language: Optional[str] = None, + token_max_length: Optional[int] = None, + disable_stemmer: Optional[bool] = None, + specific_model_path: Optional[str] = None, + query_config: Optional[Bm25EmbeddingFunctionQueryConfig] = None, + **kwargs: Any, + ): + """Initialize SparseEncoderEmbeddingFunction. + + Args: + avg_len(float, optional): The average length of the documents in the corpus. + task (str, optional): Task to perform, can be "document" or "query" + cache_dir (str, optional): The path to the cache directory. + k (float, optional): The k parameter in the BM25 formula. Defines the saturation of the term frequency. + b (float, optional): The b parameter in the BM25 formula. Defines the importance of the document length. + language (str, optional): Specifies the language for the stemmer. + token_max_length (int, optional): The maximum length of the tokens. + disable_stemmer (bool, optional): Disable the stemmer. + specific_model_path (str, optional): The path to the specific model. + query_config (dict, optional): Configuration for the query, can be "task" + **kwargs: Additional arguments to pass to the Bm25 model. + """ + warnings.warn( + "Bm25EmbeddingFunction is deprecated. Please use ChromaBm25EmbeddingFunction instead.", + DeprecationWarning, + stacklevel=2, + ) + try: + from fastembed.sparse.bm25 import Bm25 + except ImportError: + raise ValueError( + "The fastembed python package is not installed. Please install it with `pip install fastembed`" + ) + + self.task = task + self.query_config = query_config + self.cache_dir = cache_dir + self.k = k + self.b = b + self.avg_len = avg_len + self.language = language + self.token_max_length = token_max_length + self.disable_stemmer = disable_stemmer + self.specific_model_path = specific_model_path + for key, value in kwargs.items(): + if not isinstance(value, (str, int, float, bool, list, dict, tuple)): + raise ValueError(f"Keyword argument {key} is not a primitive type") + self.kwargs = kwargs + bm25_kwargs = { + "model_name": "Qdrant/bm25", + } + optional_params = { + "cache_dir": cache_dir, + "k": k, + "b": b, + "avg_len": avg_len, + "language": language, + "token_max_length": token_max_length, + "disable_stemmer": disable_stemmer, + "specific_model_path": specific_model_path, + } + for key, value in optional_params.items(): + if value is not None: + bm25_kwargs[key] = value + bm25_kwargs.update({k: v for k, v in kwargs.items() if v is not None}) + self._model = Bm25(**bm25_kwargs) + + def __call__(self, input: Documents) -> SparseVectors: + """Generate embeddings for the given documents. + + Args: + input: Documents to generate embeddings for. + + Returns: + Embeddings for the documents. + """ + try: + from fastembed.sparse.bm25 import Bm25 + except ImportError: + raise ValueError( + "The fastembed python package is not installed. Please install it with `pip install fastembed`" + ) + model = cast(Bm25, self._model) + if self.task == "document": + embeddings = model.embed( + list(input), + ) + elif self.task == "query": + embeddings = model.query_embed( + list(input), + ) + else: + raise ValueError(f"Invalid task: {self.task}") + + sparse_vectors: SparseVectors = [] + + for vec in embeddings: + sparse_vectors.append( + normalize_sparse_vector( + indices=vec.indices.tolist(), values=vec.values.tolist() + ) + ) + + return sparse_vectors + + def embed_query(self, input: Documents) -> SparseVectors: + try: + from fastembed.sparse.bm25 import Bm25 + except ImportError: + raise ValueError( + "The fastembed python package is not installed. Please install it with `pip install fastembed`" + ) + model = cast(Bm25, self._model) + if self.query_config is not None: + task = self.query_config.get("task") + if task == "document": + embeddings = model.embed( + list(input), + ) + elif task == "query": + embeddings = model.query_embed( + list(input), + ) + else: + raise ValueError(f"Invalid task: {task}") + + sparse_vectors: SparseVectors = [] + + for vec in embeddings: + sparse_vectors.append( + normalize_sparse_vector( + indices=vec.indices.tolist(), values=vec.values.tolist() + ) + ) + + return sparse_vectors + + else: + return self.__call__(input) + + @staticmethod + def name() -> str: + return "bm25" + + @staticmethod + def build_from_config( + config: Dict[str, Any] + ) -> "SparseEmbeddingFunction[Documents]": + task = config.get("task") + query_config = config.get("query_config") + cache_dir = config.get("cache_dir") + k = config.get("k") + b = config.get("b") + avg_len = config.get("avg_len") + language = config.get("language") + token_max_length = config.get("token_max_length") + disable_stemmer = config.get("disable_stemmer") + specific_model_path = config.get("specific_model_path") + kwargs = config.get("kwargs", {}) + + return Bm25EmbeddingFunction( + task=task, + query_config=query_config, + cache_dir=cache_dir, + k=k, + b=b, + avg_len=avg_len, + language=language, + token_max_length=token_max_length, + disable_stemmer=disable_stemmer, + specific_model_path=specific_model_path, + **kwargs, + ) + + def get_config(self) -> Dict[str, Any]: + return { + "task": self.task, + "query_config": self.query_config, + "cache_dir": self.cache_dir, + "k": self.k, + "b": self.b, + "avg_len": self.avg_len, + "language": self.language, + "token_max_length": self.token_max_length, + "disable_stemmer": self.disable_stemmer, + "specific_model_path": self.specific_model_path, + "kwargs": self.kwargs, + } + + def validate_config_update( + self, old_config: Dict[str, Any], new_config: Dict[str, Any] + ) -> None: + # Users should be able to change the path if needed, so we should not validate that. + # e.g. moving file path from /v1/my-model.bin to /v2/my-model.bin + return + + @staticmethod + def validate_config(config: Dict[str, Any]) -> None: + """ + Validate the configuration using the JSON schema. + + Args: + config: Configuration to validate + + Raises: + ValidationError: If the configuration does not match the schema + """ + validate_config_schema(config, "bm25") \ No newline at end of file diff --git a/python/user_packages/Python313/site-packages/chromadb/utils/embedding_functions/chroma_bm25_embedding_function.py b/python/user_packages/Python313/site-packages/chromadb/utils/embedding_functions/chroma_bm25_embedding_function.py new file mode 100644 index 0000000000000000000000000000000000000000..56362bc8c1e98d4573554c3c0934330fa3dff24b --- /dev/null +++ b/python/user_packages/Python313/site-packages/chromadb/utils/embedding_functions/chroma_bm25_embedding_function.py @@ -0,0 +1,178 @@ +from __future__ import annotations + +from collections import Counter +from typing import Any, Dict, Iterable, List, Optional, TypedDict + +from chromadb.api.types import Documents, SparseEmbeddingFunction, SparseVectors +from chromadb.base_types import SparseVector +from chromadb.utils.embedding_functions.schemas import validate_config_schema +from chromadb.utils.embedding_functions.schemas.bm25_tokenizer import ( + Bm25Tokenizer, + DEFAULT_CHROMA_BM25_STOPWORDS as _DEFAULT_STOPWORDS, + get_english_stemmer, + Murmur3AbsHasher, +) + +NAME = "chroma_bm25" + +DEFAULT_K = 1.2 +DEFAULT_B = 0.75 +DEFAULT_AVG_DOC_LENGTH = 256.0 +DEFAULT_TOKEN_MAX_LENGTH = 40 + +DEFAULT_CHROMA_BM25_STOPWORDS: List[str] = list(_DEFAULT_STOPWORDS) + + +class _HashedToken: + __slots__ = ("hash", "label") + + def __init__(self, hash: int, label: Optional[str]): + self.hash = hash + self.label = label + + def __hash__(self) -> int: + return self.hash + + def __eq__(self, other: object) -> bool: + if not isinstance(other, _HashedToken): + return NotImplemented + return self.hash == other.hash + + def __lt__(self, other: "_HashedToken") -> bool: + return self.hash < other.hash + + +class ChromaBm25Config(TypedDict, total=False): + k: float + b: float + avg_doc_length: float + token_max_length: int + stopwords: List[str] + include_tokens: bool + + +class ChromaBm25EmbeddingFunction(SparseEmbeddingFunction[Documents]): + def __init__( + self, + k: float = DEFAULT_K, + b: float = DEFAULT_B, + avg_doc_length: float = DEFAULT_AVG_DOC_LENGTH, + token_max_length: int = DEFAULT_TOKEN_MAX_LENGTH, + stopwords: Optional[Iterable[str]] = None, + include_tokens: bool = False, + ) -> None: + """Initialize the BM25 sparse embedding function.""" + + self.k = float(k) + self.b = float(b) + self.avg_doc_length = float(avg_doc_length) + self.token_max_length = int(token_max_length) + self.include_tokens = bool(include_tokens) + + if stopwords is not None: + self.stopwords: Optional[List[str]] = [str(word) for word in stopwords] + self._stopword_list: Iterable[str] = self.stopwords + else: + self.stopwords = None + self._stopword_list = DEFAULT_CHROMA_BM25_STOPWORDS + + self._hasher = Murmur3AbsHasher() + + def _encode(self, text: str) -> SparseVector: + stemmer = get_english_stemmer() + tokenizer = Bm25Tokenizer(stemmer, self._stopword_list, self.token_max_length) + tokens = tokenizer.tokenize(text) + + if not tokens: + return SparseVector(indices=[], values=[]) + + doc_len = float(len(tokens)) + counts = Counter( + _HashedToken( + self._hasher.hash(token), token if self.include_tokens else None + ) + for token in tokens + ) + + sorted_keys = sorted(counts.keys()) + indices: List[int] = [] + values: List[float] = [] + labels: Optional[List[str]] = [] if self.include_tokens else None + + for key in sorted_keys: + tf = float(counts[key]) + denominator = tf + self.k * ( + 1 - self.b + (self.b * doc_len) / self.avg_doc_length + ) + score = tf * (self.k + 1) / denominator + + indices.append(key.hash) + values.append(score) + if labels is not None and key.label is not None: + labels.append(key.label) + + return SparseVector(indices=indices, values=values, labels=labels) + + def __call__(self, input: Documents) -> SparseVectors: + sparse_vectors: SparseVectors = [] + + if not input: + return sparse_vectors + + for document in input: + sparse_vectors.append(self._encode(document)) + + return sparse_vectors + + def embed_query(self, input: Documents) -> SparseVectors: + return self.__call__(input) + + @staticmethod + def name() -> str: + return NAME + + @staticmethod + def build_from_config( + config: Dict[str, Any], + ) -> "SparseEmbeddingFunction[Documents]": + return ChromaBm25EmbeddingFunction( + k=config.get("k", DEFAULT_K), + b=config.get("b", DEFAULT_B), + avg_doc_length=config.get("avg_doc_length", DEFAULT_AVG_DOC_LENGTH), + token_max_length=config.get("token_max_length", DEFAULT_TOKEN_MAX_LENGTH), + stopwords=config.get("stopwords"), + include_tokens=config.get("include_tokens", False), + ) + + def get_config(self) -> Dict[str, Any]: + config: Dict[str, Any] = { + "k": self.k, + "b": self.b, + "avg_doc_length": self.avg_doc_length, + "token_max_length": self.token_max_length, + "include_tokens": self.include_tokens, + } + + if self.stopwords is not None: + config["stopwords"] = list(self.stopwords) + + return config + + def validate_config_update( + self, old_config: Dict[str, Any], new_config: Dict[str, Any] + ) -> None: + mutable_keys = { + "k", + "b", + "avg_doc_length", + "token_max_length", + "stopwords", + "include_tokens", + } + for key in new_config: + if key not in mutable_keys: + raise ValueError(f"Updating '{key}' is not supported for {NAME}") + + @staticmethod + def validate_config(config: Dict[str, Any]) -> None: + validate_config_schema(config, NAME) diff --git a/python/user_packages/Python313/site-packages/chromadb/utils/embedding_functions/chroma_cloud_qwen_embedding_function.py b/python/user_packages/Python313/site-packages/chromadb/utils/embedding_functions/chroma_cloud_qwen_embedding_function.py new file mode 100644 index 0000000000000000000000000000000000000000..69f3e5d715e6c41d01e915a81aec8d2fb75461b9 --- /dev/null +++ b/python/user_packages/Python313/site-packages/chromadb/utils/embedding_functions/chroma_cloud_qwen_embedding_function.py @@ -0,0 +1,232 @@ +from chromadb.api.types import Embeddings, Documents, EmbeddingFunction, Space +from typing import List, Dict, Any, Union, Optional +import os +import numpy as np +from chromadb.utils.embedding_functions.schemas import validate_config_schema +from chromadb.utils.embedding_functions.utils import _get_shared_system_client, get_chroma_embed_url +from enum import Enum + + +class ChromaCloudQwenEmbeddingModel(Enum): + QWEN3_EMBEDDING_0p6B = "Qwen/Qwen3-Embedding-0.6B" + + +class ChromaCloudQwenEmbeddingTarget(Enum): + DOCUMENTS = "documents" + QUERY = "query" + + +ChromaCloudQwenEmbeddingInstructions = Dict[ + str, Dict[ChromaCloudQwenEmbeddingTarget, str] +] + +CHROMA_CLOUD_QWEN_DEFAULT_INSTRUCTIONS: ChromaCloudQwenEmbeddingInstructions = { + "nl_to_code": { + ChromaCloudQwenEmbeddingTarget.DOCUMENTS: "", + # Taken from https://github.com/QwenLM/Qwen3-Embedding/blob/main/evaluation/task_prompts.json + ChromaCloudQwenEmbeddingTarget.QUERY: "Given a question about coding, retrieval code or passage that can solve user's question", + } +} + + +class ChromaCloudQwenEmbeddingFunction(EmbeddingFunction[Documents]): + def __init__( + self, + model: ChromaCloudQwenEmbeddingModel, + task: Optional[str], + instructions: ChromaCloudQwenEmbeddingInstructions = CHROMA_CLOUD_QWEN_DEFAULT_INSTRUCTIONS, + api_key_env_var: str = "CHROMA_API_KEY", + ): + """ + Initialize the ChromaCloudQwenEmbeddingFunction. + + Args: + model (ChromaCloudQwenEmbeddingModel): The specific Qwen model to use for embeddings. + task (str, optional): The task for which embeddings are being generated. If None or empty, + empty instructions will be used for both documents and queries. + instructions (ChromaCloudQwenEmbeddingInstructions, optional): A dictionary containing + custom instructions to use for the specified Qwen model. Defaults to CHROMA_CLOUD_QWEN_DEFAULT_INSTRUCTIONS. + api_key_env_var (str, optional): Environment variable name that contains your API key. + Defaults to "CHROMA_API_KEY". + """ + try: + import httpx + except ImportError: + raise ValueError( + "The httpx python package is not installed. Please install it with `pip install httpx`" + ) + + self.api_key_env_var = api_key_env_var + # First, try to get API key from environment variable + self.api_key = os.getenv(api_key_env_var) + # If not found in env var, try to get it from existing client instances + if not self.api_key: + SharedSystemClient = _get_shared_system_client() + self.api_key = SharedSystemClient.get_chroma_cloud_api_key_from_clients() + # Raise error if still no API key found + if not self.api_key: + raise ValueError( + f"API key not found in environment variable {api_key_env_var} " + f"or in any existing client instances" + ) + + self.model = model + self.task = task + self.instructions = instructions + + self._api_url = get_chroma_embed_url() + self._session = httpx.Client() + self._session.headers.update( + { + "x-chroma-token": self.api_key, + "x-chroma-embedding-model": self.model.value, + } + ) + + def _parse_response(self, response: Any) -> Embeddings: + """ + Convert the response from the Chroma Embedding API to a list of numpy arrays. + + Args: + response (Any): The response from the Chroma Embedding API. + + Returns: + Embeddings: A list of numpy arrays representing the embeddings. + """ + if "embeddings" not in response: + raise RuntimeError(response.get("error", "Unknown error")) + + embeddings: List[List[float]] = response["embeddings"] + + return [np.array(embedding, dtype=np.float32) for embedding in embeddings] + + def __call__(self, input: Documents) -> Embeddings: + """ + Generate embeddings for the given documents. + + Args: + input: Documents to generate embeddings for. + + Returns: + Embeddings for the documents. + """ + if not input: + return [] + + instruction = "" + if self.task and self.task in self.instructions: + instruction = self.instructions[self.task][ + ChromaCloudQwenEmbeddingTarget.DOCUMENTS + ] + + payload: Dict[str, Union[str, Documents]] = { + "instructions": instruction, + "texts": input, + } + + response = self._session.post(self._api_url, json=payload, timeout=60).json() + + return self._parse_response(response) + + def embed_query(self, input: Documents) -> Embeddings: + """ + Get the embeddings for a query input. + """ + if not input: + return [] + + instruction = "" + if self.task and self.task in self.instructions: + instruction = self.instructions[self.task][ + ChromaCloudQwenEmbeddingTarget.QUERY + ] + + payload: Dict[str, Union[str, Documents]] = { + "instructions": instruction, + "texts": input, + } + + response = self._session.post(self._api_url, json=payload, timeout=60).json() + + return self._parse_response(response) + + @staticmethod + def name() -> str: + return "chroma-cloud-qwen" + + def default_space(self) -> Space: + return "cosine" + + def supported_spaces(self) -> List[Space]: + return ["cosine", "l2", "ip"] + + @staticmethod + def build_from_config(config: Dict[str, Any]) -> "EmbeddingFunction[Documents]": + model = config.get("model") + task = config.get("task") + instructions = config.get("instructions") + api_key_env_var = config.get("api_key_env_var") + + if model is None or task is None: + assert False, "Config is missing a required field" + + # Deserialize instructions dict from string keys to enum keys + deserialized_instructions = CHROMA_CLOUD_QWEN_DEFAULT_INSTRUCTIONS + if instructions is not None: + deserialized_instructions = {} + for task_key, targets in instructions.items(): + deserialized_instructions[task_key] = {} + for target_key, instruction in targets.items(): + # Convert string key to enum + target_enum = ChromaCloudQwenEmbeddingTarget(target_key) + deserialized_instructions[task_key][target_enum] = instruction + deserialized_instructions[task_key][target_enum] = instruction + + return ChromaCloudQwenEmbeddingFunction( + model=ChromaCloudQwenEmbeddingModel(model), + task=task, + instructions=deserialized_instructions, + api_key_env_var=api_key_env_var or "CHROMA_API_KEY", + ) + + def get_config(self) -> Dict[str, Any]: + # Serialize instructions dict with enum keys to string keys for JSON compatibility + serialized_instructions = { + task: {target.value: instruction for target, instruction in targets.items()} + for task, targets in self.instructions.items() + } + return { + "api_key_env_var": self.api_key_env_var, + "model": self.model.value, + "task": self.task, + "instructions": serialized_instructions, + } + + def validate_config_update( + self, old_config: Dict[str, Any], new_config: Dict[str, Any] + ) -> None: + if "model" in new_config: + raise ValueError( + "The model cannot be changed after the embedding function has been initialized." + ) + elif "task" in new_config: + raise ValueError( + "The task cannot be changed after the embedding function has been initialized." + ) + elif "instructions" in new_config: + raise ValueError( + "The instructions cannot be changed after the embedding function has been initialized." + ) + + @staticmethod + def validate_config(config: Dict[str, Any]) -> None: + """ + Validate the configuration using the JSON schema. + + Args: + config: Configuration to validate + + Raises: + ValidationError: If the configuration does not match the schema + """ + validate_config_schema(config, "chroma-cloud-qwen") diff --git a/python/user_packages/Python313/site-packages/chromadb/utils/embedding_functions/chroma_cloud_splade_embedding_function.py b/python/user_packages/Python313/site-packages/chromadb/utils/embedding_functions/chroma_cloud_splade_embedding_function.py new file mode 100644 index 0000000000000000000000000000000000000000..5627a6ef0982ebd2a671034a5e8b19aebe27ccb8 --- /dev/null +++ b/python/user_packages/Python313/site-packages/chromadb/utils/embedding_functions/chroma_cloud_splade_embedding_function.py @@ -0,0 +1,181 @@ +from chromadb.api.types import ( + SparseEmbeddingFunction, + SparseVector, + SparseVectors, + Documents, +) +from typing import Dict, Any, List, Optional +from enum import Enum +from chromadb.utils.embedding_functions.schemas import validate_config_schema +from chromadb.utils.sparse_embedding_utils import normalize_sparse_vector +import os +from typing import Union +from chromadb.utils.embedding_functions.utils import _get_shared_system_client, get_chroma_embed_url + + +class ChromaCloudSpladeEmbeddingModel(Enum): + SPLADE_PP_EN_V1 = "prithivida/Splade_PP_en_v1" + + +class ChromaCloudSpladeEmbeddingFunction(SparseEmbeddingFunction[Documents]): + def __init__( + self, + api_key_env_var: str = "CHROMA_API_KEY", + model: ChromaCloudSpladeEmbeddingModel = ChromaCloudSpladeEmbeddingModel.SPLADE_PP_EN_V1, + include_tokens: bool = False, + ): + """ + Initialize the ChromaCloudSpladeEmbeddingFunction. + + Args: + api_key_env_var (str, optional): Environment variable name that contains your API key. + Defaults to "CHROMA_API_KEY". + """ + try: + import httpx + except ImportError: + raise ValueError( + "The httpx python package is not installed. Please install it with `pip install httpx`" + ) + self.api_key_env_var = api_key_env_var + # First, try to get API key from environment variable + self.api_key = os.getenv(self.api_key_env_var) + # If not found in env var, try to get it from existing client instances + if not self.api_key: + SharedSystemClient = _get_shared_system_client() + self.api_key = SharedSystemClient.get_chroma_cloud_api_key_from_clients() + # Raise error if still no API key found + if not self.api_key: + raise ValueError( + f"API key not found in environment variable {self.api_key_env_var} " + f"or in any existing client instances" + ) + self.model = model + self.include_tokens = bool(include_tokens) + self._api_url = f"{get_chroma_embed_url()}/embed_sparse" + self._session = httpx.Client() + self._session.headers.update( + { + "x-chroma-token": self.api_key, + "x-chroma-embedding-model": self.model.value, + } + ) + + def __del__(self) -> None: + """ + Cleanup the HTTP client session when the object is destroyed. + """ + if hasattr(self, "_session"): + self._session.close() + + def close(self) -> None: + """ + Explicitly close the HTTP client session. + Call this method when you're done using the embedding function. + """ + if hasattr(self, "_session"): + self._session.close() + + def __call__(self, input: Documents) -> SparseVectors: + """ + Generate embeddings for the given documents. + + Args: + input (Documents): The documents to generate embeddings for. + """ + if not input: + return [] + + payload: Dict[str, Union[str, Documents]] = { + "texts": list(input), + "task": "", + "target": "", + "fetch_tokens": "true" if self.include_tokens is True else "false", + } + + try: + import httpx + + response = self._session.post(self._api_url, json=payload, timeout=60) + response.raise_for_status() + json_response = response.json() + return self._parse_response(json_response) + except httpx.HTTPStatusError as e: + raise RuntimeError( + f"Failed to get embeddings from Chroma Cloud API: HTTP {e.response.status_code} - {e.response.text}" + ) + except httpx.TimeoutException: + raise RuntimeError("Request to Chroma Cloud API timed out after 60 seconds") + except httpx.HTTPError as e: + raise RuntimeError(f"Failed to get embeddings from Chroma Cloud API: {e}") + except Exception as e: + raise RuntimeError(f"Unexpected error calling Chroma Cloud API: {e}") + + def _parse_response(self, response: Any) -> SparseVectors: + """ + Parse the response from the Chroma Cloud Sparse Embedding API. + """ + raw_embeddings = response["embeddings"] + + # Normalize each sparse vector (sort indices and validate) + normalized_vectors: SparseVectors = [] + for emb in raw_embeddings: + # Handle both dict format and SparseVector format + if isinstance(emb, dict): + indices = emb.get("indices", []) + values = emb.get("values", []) + raw_labels = emb.get("labels") if self.include_tokens else None + labels: Optional[List[str]] = raw_labels if raw_labels else None + else: + # Already a SparseVector, extract its data + assert isinstance(emb, SparseVector) + indices = emb.indices + values = emb.values + labels = emb.labels if self.include_tokens else None + + normalized_vectors.append( + normalize_sparse_vector(indices=indices, values=values, labels=labels) + ) + + return normalized_vectors + + @staticmethod + def name() -> str: + return "chroma-cloud-splade" + + @staticmethod + def build_from_config( + config: Dict[str, Any] + ) -> "SparseEmbeddingFunction[Documents]": + api_key_env_var = config.get("api_key_env_var") + model = config.get("model") + if model is None: + raise ValueError("model must be provided in config") + if not api_key_env_var: + raise ValueError("api_key_env_var must be provided in config") + return ChromaCloudSpladeEmbeddingFunction( + api_key_env_var=api_key_env_var, + model=ChromaCloudSpladeEmbeddingModel(model), + include_tokens=config.get("include_tokens", False), + ) + + def get_config(self) -> Dict[str, Any]: + return { + "api_key_env_var": self.api_key_env_var, + "model": self.model.value, + "include_tokens": self.include_tokens, + } + + def validate_config_update( + self, old_config: Dict[str, Any], new_config: Dict[str, Any] + ) -> None: + immutable_keys = {"include_tokens", "model"} + for key in immutable_keys: + if key in new_config and new_config[key] != old_config.get(key): + raise ValueError( + f"Updating '{key}' is not supported for chroma-cloud-splade" + ) + + @staticmethod + def validate_config(config: Dict[str, Any]) -> None: + validate_config_schema(config, "chroma-cloud-splade") diff --git a/python/user_packages/Python313/site-packages/chromadb/utils/embedding_functions/chroma_langchain_embedding_function.py b/python/user_packages/Python313/site-packages/chromadb/utils/embedding_functions/chroma_langchain_embedding_function.py new file mode 100644 index 0000000000000000000000000000000000000000..ed5c22db18a8017ac711762a6ca2609e466225a1 --- /dev/null +++ b/python/user_packages/Python313/site-packages/chromadb/utils/embedding_functions/chroma_langchain_embedding_function.py @@ -0,0 +1,171 @@ +from chromadb.api.types import ( + Documents, + Embeddings, + Images, + Embeddable, + EmbeddingFunction, +) +from chromadb.utils.embedding_functions.schemas import validate_config_schema +from typing import List, Dict, Any, Union, cast, Sequence +import numpy as np + + +def create_langchain_embedding( + langchain_embedding_fn: Any, +) -> "ChromaLangchainEmbeddingFunction": + """ + Create a ChromaLangchainEmbeddingFunction from a langchain embedding function. + + Args: + langchain_embedding_fn: The langchain embedding function to use. + + Returns: + A ChromaLangchainEmbeddingFunction that wraps the langchain embedding function. + """ + + return ChromaLangchainEmbeddingFunction(embedding_function=langchain_embedding_fn) + + +class ChromaLangchainEmbeddingFunction(EmbeddingFunction[Embeddable]): + """ + This class is used as bridge between langchain embedding functions and custom chroma embedding functions. + """ + + def __init__(self, embedding_function: Any) -> None: + """ + Initialize the ChromaLangchainEmbeddingFunction + + Args: + embedding_function: The embedding function implementing Embeddings from langchain_core. + """ + try: + import langchain_core.embeddings + + LangchainEmbeddings = langchain_core.embeddings.Embeddings + except ImportError: + raise ValueError( + "The langchain_core python package is not installed. Please install it with `pip install langchain-core`" + ) + + if not isinstance(embedding_function, LangchainEmbeddings): + raise ValueError( + "The embedding_function must implement the Embeddings interface from langchain_core." + ) + + self.embedding_function = embedding_function + + # Store the class name for serialization + self._embedding_function_class = embedding_function.__class__.__name__ + + def embed_documents(self, documents: Sequence[str]) -> List[List[float]]: + """ + Embed documents using the langchain embedding function. + + Args: + documents: The documents to embed. + + Returns: + The embeddings for the documents. + """ + return cast( + List[List[float]], self.embedding_function.embed_documents(list(documents)) + ) + + def embed_query(self, query: str) -> List[float]: + """ + Embed a query using the langchain embedding function. + + Args: + query: The query to embed. + + Returns: + The embedding for the query. + """ + return cast(List[float], self.embedding_function.embed_query(query)) + + def embed_image(self, uris: List[str]) -> List[List[float]]: + """ + Embed images using the langchain embedding function. + + Args: + uris: The URIs of the images to embed. + + Returns: + The embeddings for the images. + """ + if hasattr(self.embedding_function, "embed_image"): + return cast(List[List[float]], self.embedding_function.embed_image(uris)) + else: + raise ValueError( + "The provided embedding function does not support image embeddings." + ) + + def __call__(self, input: Union[Documents, Images]) -> Embeddings: + """ + Get the embeddings for a list of texts or images. + + Args: + input: A list of texts or images to get embeddings for. + Images should be provided as a list of URIs passed through the langchain data loader + + Returns: + The embeddings for the texts or images. + + Example: + >>> from langchain_openai import OpenAIEmbeddings + >>> langchain_embedding = ChromaLangchainEmbeddingFunction(embedding_function=OpenAIEmbeddings(model="text-embedding-3-large")) + >>> texts = ["Hello, world!", "How are you?"] + >>> embeddings = langchain_embedding(texts) + """ + # Due to langchain quirks, the dataloader returns a tuple if the input is uris of images + if isinstance(input, tuple) and len(input) == 2 and input[0] == "images": + embeddings = self.embed_image(list(input[1])) + else: + # Cast to Sequence[str] to satisfy the type checker + embeddings = self.embed_documents(cast(Sequence[str], input)) + + # Convert to numpy arrays + return [np.array(embedding, dtype=np.float32) for embedding in embeddings] + + @staticmethod + def name() -> str: + return "langchain" + + @staticmethod + def build_from_config( + config: Dict[str, Any] + ) -> "EmbeddingFunction[Union[Documents, Images]]": + # This is a placeholder implementation since we can't easily serialize and deserialize + # langchain embedding functions. Users will need to recreate the langchain embedding function + # and pass it to create_langchain_embedding. + raise NotImplementedError( + "Building a ChromaLangchainEmbeddingFunction from config is not supported. " + "Please recreate the langchain embedding function and pass it to create_langchain_embedding." + ) + + def get_config(self) -> Dict[str, Any]: + return { + "embedding_function_class": self._embedding_function_class, + "note": "This is a placeholder config. You will need to recreate the langchain embedding function.", + } + + def validate_config_update( + self, old_config: Dict[str, Any], new_config: Dict[str, Any] + ) -> None: + raise NotImplementedError( + "Updating a ChromaLangchainEmbeddingFunction config is not supported. " + "Please recreate the langchain embedding function and pass it to create_langchain_embedding." + ) + + @staticmethod + def validate_config(config: Dict[str, Any]) -> None: + """ + Validate the configuration using the JSON schema. + + Args: + config: Configuration to validate + + Raises: + ValidationError: If the configuration does not match the schema + """ + validate_config_schema(config, "chroma_langchain") diff --git a/python/user_packages/Python313/site-packages/chromadb/utils/embedding_functions/cloudflare_workers_ai_embedding_function.py b/python/user_packages/Python313/site-packages/chromadb/utils/embedding_functions/cloudflare_workers_ai_embedding_function.py new file mode 100644 index 0000000000000000000000000000000000000000..d587f471a656c3ff93b3b9cb3063f5296a7ea128 --- /dev/null +++ b/python/user_packages/Python313/site-packages/chromadb/utils/embedding_functions/cloudflare_workers_ai_embedding_function.py @@ -0,0 +1,159 @@ +from chromadb.api.types import ( + Embeddings, + Documents, + EmbeddingFunction, + Space, +) +from typing import List, Dict, Any, Optional +import os +from chromadb.utils.embedding_functions.schemas import validate_config_schema +from typing import cast +import warnings + +BASE_URL = "https://api.cloudflare.com/client/v4/accounts" +GATEWAY_BASE_URL = "https://gateway.ai.cloudflare.com/v1" + + +class CloudflareWorkersAIEmbeddingFunction(EmbeddingFunction[Documents]): + """ + This class is used to get embeddings for a list of texts using the Cloudflare Workers AI API. + It requires an API key and a model name. + """ + + def __init__( + self, + model_name: str, + account_id: str, + api_key: Optional[str] = None, + api_key_env_var: str = "CHROMA_CLOUDFLARE_API_KEY", + gateway_id: Optional[str] = None, + ): + """ + Initialize the CloudflareWorkersAIEmbeddingFunction. See the docs for supported models here: + https://developers.cloudflare.com/workers-ai/models/ + + Args: + model_name: The name of the model to use for text embeddings. + account_id: The account ID for the Cloudflare Workers AI API. + api_key: The API key for the Cloudflare Workers AI API. + api_key_env_var: The environment variable name for the Cloudflare Workers AI API key. + """ + try: + import httpx + except ImportError: + raise ValueError( + "The httpx python package is not installed. Please install it with `pip install httpx`" + ) + + if api_key is not None: + warnings.warn( + "Direct api_key configuration will not be persisted. " + "Please use environment variables via api_key_env_var for persistent storage.", + DeprecationWarning, + ) + self.model_name = model_name + self.account_id = account_id + + if os.getenv("CLOUDFLARE_API_KEY") is not None: + self.api_key_env_var = "CLOUDFLARE_API_KEY" + else: + self.api_key_env_var = api_key_env_var + + self.api_key = api_key or os.getenv(self.api_key_env_var) + self.gateway_id = gateway_id + + if not self.api_key: + raise ValueError( + f"The {self.api_key_env_var} environment variable is not set." + ) + + if self.gateway_id: + self._api_url = f"{GATEWAY_BASE_URL}/{self.account_id}/{self.gateway_id}/workers-ai/{self.model_name}" + else: + self._api_url = f"{BASE_URL}/{self.account_id}/ai/run/{self.model_name}" + + self._session = httpx.Client() + self._session.headers.update( + {"Authorization": f"Bearer {self.api_key}", "Accept-Encoding": "identity"} + ) + + def __call__(self, input: Documents) -> Embeddings: + """ + Generate embeddings for the given documents. + + Args: + input: Documents to generate embeddings for. + + Returns: + Embeddings for the documents. + """ + if not all(isinstance(item, str) for item in input): + raise ValueError( + "Cloudflare Workers AI only supports text documents, not images" + ) + + payload: Dict[str, Any] = { + "text": input, + } + + resp = self._session.post(self._api_url, json=payload).json() + + if "result" not in resp and "data" not in resp["result"]: + raise RuntimeError(resp.get("detail", "Unknown error")) + + return cast(Embeddings, resp["result"]["data"]) + + @staticmethod + def name() -> str: + return "cloudflare_workers_ai" + + def default_space(self) -> Space: + return "cosine" + + def supported_spaces(self) -> List[Space]: + return ["cosine", "l2", "ip"] + + @staticmethod + def build_from_config(config: Dict[str, Any]) -> "EmbeddingFunction[Documents]": + api_key_env_var = config.get("api_key_env_var") + model_name = config.get("model_name") + account_id = config.get("account_id") + gateway_id = config.get("gateway_id", None) + if api_key_env_var is None or model_name is None or account_id is None: + assert False, "This code should not be reached" + + return CloudflareWorkersAIEmbeddingFunction( + api_key_env_var=api_key_env_var, + model_name=model_name, + account_id=account_id, + gateway_id=gateway_id, + ) + + def get_config(self) -> Dict[str, Any]: + return { + "api_key_env_var": self.api_key_env_var, + "model_name": self.model_name, + "account_id": self.account_id, + "gateway_id": self.gateway_id, + } + + def validate_config_update( + self, old_config: Dict[str, Any], new_config: Dict[str, Any] + ) -> None: + if "model_name" in new_config: + raise ValueError( + "The model name cannot be changed after the embedding function has been initialized." + ) + + @staticmethod + def validate_config(config: Dict[str, Any]) -> None: + """ + Validate the configuration using the JSON schema. + + Args: + config: Configuration to validate + + Raises: + ValidationError: If the configuration does not match the schema + """ + validate_config_schema(config, "cloudflare_workers_ai") diff --git a/python/user_packages/Python313/site-packages/chromadb/utils/embedding_functions/cohere_embedding_function.py b/python/user_packages/Python313/site-packages/chromadb/utils/embedding_functions/cohere_embedding_function.py new file mode 100644 index 0000000000000000000000000000000000000000..9e1a6664f937986bcc82287e0ff4a3b0695b4107 --- /dev/null +++ b/python/user_packages/Python313/site-packages/chromadb/utils/embedding_functions/cohere_embedding_function.py @@ -0,0 +1,182 @@ +from chromadb.api.types import ( + Embeddings, + Embeddable, + EmbeddingFunction, + Space, + is_image, + is_document, +) +from typing import List, Dict, Any, Optional +import os +import numpy as np +from chromadb.utils.embedding_functions.schemas import validate_config_schema +import base64 +import io +import importlib +import warnings + + +class CohereEmbeddingFunction(EmbeddingFunction[Embeddable]): + def __init__( + self, + api_key: Optional[str] = None, + model_name: str = "large", + api_key_env_var: str = "CHROMA_COHERE_API_KEY", + ): + try: + import cohere + except ImportError: + raise ValueError( + "The cohere python package is not installed. Please install it with `pip install cohere`" + ) + + try: + self._PILImage = importlib.import_module("PIL.Image") + except ImportError: + raise ValueError( + "The PIL python package is not installed. Please install it with `pip install pillow`" + ) + + if api_key is not None: + warnings.warn( + "Direct api_key configuration will not be persisted. " + "Please use environment variables via api_key_env_var for persistent storage.", + DeprecationWarning, + ) + if os.getenv("COHERE_API_KEY") is not None: + self.api_key_env_var = "COHERE_API_KEY" + else: + self.api_key_env_var = api_key_env_var + + self.api_key = api_key or os.getenv(self.api_key_env_var) + if not self.api_key: + raise ValueError( + f"The {self.api_key_env_var} environment variable is not set." + ) + + self.model_name = model_name + + self.client = cohere.Client(self.api_key) + + def __call__(self, input: Embeddable) -> Embeddings: + """ + Generate embeddings for the given documents. + + Args: + input: Documents or images to generate embeddings for. + + Returns: + Embeddings for the documents. + """ + + # Cohere works with images. if all are texts, return the embeddings for the texts + if all(is_document(item) for item in input): + return [ + np.array(embeddings, dtype=np.float32) + for embeddings in self.client.embed( + texts=[str(item) for item in input], + model=self.model_name, + input_type="search_document", + ).embeddings + ] + + elif all(is_image(item) for item in input): + base64_images = [] + for image_np in input: + if not isinstance(image_np, np.ndarray): + raise ValueError( + f"Expected image input to be a numpy array, got {type(image_np)}" + ) + + try: + pil_image = self._PILImage.fromarray(image_np) + + buffer = io.BytesIO() + pil_image.save(buffer, format="PNG") + img_bytes = buffer.getvalue() + + # Encode bytes to base64 string + base64_string = base64.b64encode(img_bytes).decode("utf-8") + + data_uri = f"data:image/png;base64,{base64_string}" + base64_images.append(data_uri) + + except Exception as e: + raise ValueError( + f"Failed to convert image numpy array to base64 data URI: {e}" + ) from e + + return [ + np.array(embeddings, dtype=np.float32) + for embeddings in self.client.embed( + images=base64_images, + model=self.model_name, + input_type="image", + ).embeddings + ] + else: + # Check if it's a mix or neither + has_texts = any(is_document(item) for item in input) + has_images = any(is_image(item) for item in input) + if has_texts and has_images: + raise ValueError( + "Input contains a mix of text documents and images, which is not supported. Provide either all texts or all images." + ) + else: + raise ValueError( + "Input must be a list of text documents (str) or a list of images (numpy arrays)." + ) + + @staticmethod + def name() -> str: + return "cohere" + + def default_space(self) -> Space: + if self.model_name == "embed-multilingual-v2.0": + return "ip" + return "cosine" + + def supported_spaces(self) -> List[Space]: + if self.model_name == "embed-english-v2.0": + return ["cosine"] + elif self.model_name == "embed-english-light-v2.0": + return ["cosine"] + elif self.model_name == "embed-multilingual-v2.0": + return ["ip"] + else: + return ["cosine", "l2", "ip"] + + @staticmethod + def build_from_config(config: Dict[str, Any]) -> "EmbeddingFunction[Embeddable]": + api_key_env_var = config.get("api_key_env_var") + model_name = config.get("model_name") + if api_key_env_var is None or model_name is None: + assert False, "This code should not be reached" + + return CohereEmbeddingFunction( + api_key_env_var=api_key_env_var, model_name=model_name + ) + + def get_config(self) -> Dict[str, Any]: + return {"api_key_env_var": self.api_key_env_var, "model_name": self.model_name} + + def validate_config_update( + self, old_config: Dict[str, Any], new_config: Dict[str, Any] + ) -> None: + if "model_name" in new_config: + raise ValueError( + "The model name cannot be changed after the embedding function has been initialized." + ) + + @staticmethod + def validate_config(config: Dict[str, Any]) -> None: + """ + Validate the configuration using the JSON schema. + + Args: + config: Configuration to validate + + Raises: + ValidationError: If the configuration does not match the schema + """ + validate_config_schema(config, "cohere") diff --git a/python/user_packages/Python313/site-packages/chromadb/utils/embedding_functions/fastembed_sparse_embedding_function.py b/python/user_packages/Python313/site-packages/chromadb/utils/embedding_functions/fastembed_sparse_embedding_function.py new file mode 100644 index 0000000000000000000000000000000000000000..53fb570fbefa3dab6fc8a08aee90501a66c2acc3 --- /dev/null +++ b/python/user_packages/Python313/site-packages/chromadb/utils/embedding_functions/fastembed_sparse_embedding_function.py @@ -0,0 +1,205 @@ +from chromadb.api.types import ( + SparseEmbeddingFunction, + SparseVectors, + Documents, +) +from typing import Dict, Any, TypedDict, Optional +from typing import cast, Literal +from chromadb.utils.embedding_functions.schemas import validate_config_schema +from chromadb.utils.sparse_embedding_utils import normalize_sparse_vector + +TaskType = Literal["document", "query"] + + +class FastembedSparseEmbeddingFunctionQueryConfig(TypedDict): + task: TaskType + + +class FastembedSparseEmbeddingFunction(SparseEmbeddingFunction[Documents]): + def __init__( + self, + model_name: str, + task: Optional[TaskType] = "document", + cache_dir: Optional[str] = None, + threads: Optional[int] = None, + cuda: Optional[bool] = None, + device_ids: Optional[list[int]] = None, + lazy_load: Optional[bool] = None, + query_config: Optional[FastembedSparseEmbeddingFunctionQueryConfig] = None, + **kwargs: Any, + ): + """Initialize SparseEncoderEmbeddingFunction. + + Args: + model_name (str, optional): Identifier of the Fastembed model + List of commonly used models: Qdrant/bm25, prithivida/Splade_PP_en_v1, Qdrant/minicoil-v1 + task (str, optional): Task to perform, can be "document" or "query" + cache_dir (str, optional): The path to the cache directory. + threads (int, optional): The number of threads to use for the model. + cuda (bool, optional): Whether to use CUDA. + device_ids (list[int], optional): The device IDs to use for the model. + lazy_load (bool, optional): Whether to lazy load the model. + query_config (dict, optional): Configuration for the query, can be "task" + **kwargs: Additional arguments to pass to the model. + """ + try: + from fastembed import SparseTextEmbedding + except ImportError: + raise ValueError( + "The fastembed python package is not installed. Please install it with `pip install fastembed`" + ) + + self.task = task + self.query_config = query_config + self.model_name = model_name + self.cache_dir = cache_dir + self.threads = threads + self.cuda = cuda + self.device_ids = device_ids + self.lazy_load = lazy_load + for key, value in kwargs.items(): + if not isinstance(value, (str, int, float, bool, list, dict, tuple)): + raise ValueError(f"Keyword argument {key} is not a primitive type") + self.kwargs = kwargs + self._model = SparseTextEmbedding( + model_name, cache_dir, threads, cuda, device_ids, lazy_load, **kwargs + ) + + def __call__(self, input: Documents) -> SparseVectors: + """Generate embeddings for the given documents. + + Args: + input: Documents to generate embeddings for. + + Returns: + Embeddings for the documents. + """ + try: + from fastembed import SparseTextEmbedding + except ImportError: + raise ValueError( + "The fastembed python package is not installed. Please install it with `pip install fastembed`" + ) + model = cast(SparseTextEmbedding, self._model) + if self.task == "document": + embeddings = model.embed( + list(input), + ) + elif self.task == "query": + embeddings = model.query_embed( + list(input), + ) + else: + raise ValueError(f"Invalid task: {self.task}") + + sparse_vectors: SparseVectors = [] + + for vec in embeddings: + sparse_vectors.append( + normalize_sparse_vector( + indices=vec.indices.tolist(), values=vec.values.tolist() + ) + ) + + return sparse_vectors + + def embed_query(self, input: Documents) -> SparseVectors: + try: + from fastembed import SparseTextEmbedding + except ImportError: + raise ValueError( + "The fastembed python package is not installed. Please install it with `pip install fastembed`" + ) + model = cast(SparseTextEmbedding, self._model) + if self.query_config is not None: + task = self.query_config.get("task") + if task == "document": + embeddings = model.embed( + list(input), + ) + elif task == "query": + embeddings = model.query_embed( + list(input), + ) + else: + raise ValueError(f"Invalid task: {task}") + + sparse_vectors: SparseVectors = [] + + for vec in embeddings: + sparse_vectors.append( + normalize_sparse_vector( + indices=vec.indices.tolist(), values=vec.values.tolist() + ) + ) + + return sparse_vectors + + else: + return self.__call__(input) + + @staticmethod + def name() -> str: + return "fastembed_sparse" + + @staticmethod + def build_from_config( + config: Dict[str, Any] + ) -> "SparseEmbeddingFunction[Documents]": + model_name = config.get("model_name") + task = config.get("task") + query_config = config.get("query_config") + cache_dir = config.get("cache_dir") + threads = config.get("threads") + cuda = config.get("cuda") + device_ids = config.get("device_ids") + lazy_load = config.get("lazy_load") + kwargs = config.get("kwargs", {}) + if model_name is None: + assert False, "This code should not be reached" + + return FastembedSparseEmbeddingFunction( + model_name=model_name, + task=task, + query_config=query_config, + cache_dir=cache_dir, + threads=threads, + cuda=cuda, + device_ids=device_ids, + lazy_load=lazy_load, + **kwargs, + ) + + def get_config(self) -> Dict[str, Any]: + return { + "model_name": self.model_name, + "task": self.task, + "query_config": self.query_config, + "cache_dir": self.cache_dir, + "threads": self.threads, + "cuda": self.cuda, + "device_ids": self.device_ids, + "lazy_load": self.lazy_load, + "kwargs": self.kwargs, + } + + def validate_config_update( + self, old_config: Dict[str, Any], new_config: Dict[str, Any] + ) -> None: + # model_name is also used as the identifier for model path if stored locally. + # Users should be able to change the path if needed, so we should not validate that. + # e.g. moving file path from /v1/my-model.bin to /v2/my-model.bin + return + + @staticmethod + def validate_config(config: Dict[str, Any]) -> None: + """ + Validate the configuration using the JSON schema. + + Args: + config: Configuration to validate + + Raises: + ValidationError: If the configuration does not match the schema + """ + validate_config_schema(config, "fastembed_sparse") diff --git a/python/user_packages/Python313/site-packages/chromadb/utils/embedding_functions/google_embedding_function.py b/python/user_packages/Python313/site-packages/chromadb/utils/embedding_functions/google_embedding_function.py new file mode 100644 index 0000000000000000000000000000000000000000..67796dab8e446cf61e9ce49a911bcb1830da1f01 --- /dev/null +++ b/python/user_packages/Python313/site-packages/chromadb/utils/embedding_functions/google_embedding_function.py @@ -0,0 +1,642 @@ +from chromadb.api.types import Embeddings, Documents, EmbeddingFunction, Space +from chromadb import __version__ +from typing import List, Dict, Any, cast, Optional +import os +import numpy as np +import numpy.typing as npt +from chromadb.utils.embedding_functions.schemas import validate_config_schema +import warnings + + +class GoogleGeminiEmbeddingFunction(EmbeddingFunction[Documents]): + """To use this EmbeddingFunction, you must have the google-genai Python package installed and have a Gemini API key.""" + + def __init__( + self, + model_name: str = "gemini-embedding-001", + task_type: Optional[str] = None, + dimension: Optional[int] = None, + api_key_env_var: Optional[str] = "GEMINI_API_KEY", + vertexai: Optional[bool] = None, + project: Optional[str] = None, + location: Optional[str] = None, + ): + """ + Initialize the GoogleGeminiEmbeddingFunction. + + Args: + model_name (str, optional): The name of the model to use for text embeddings. + Defaults to "gemini-embedding-001". + task_type (str, optional): The task type for the embeddings. + Valid values include SEMANTIC_SIMILARITY, CLASSIFICATION, CLUSTERING, + RETRIEVAL_DOCUMENT, RETRIEVAL_QUERY, CODE_RETRIEVAL_QUERY, + QUESTION_ANSWERING, FACT_VERIFICATION. + dimension (int, optional): The output dimensionality for the embeddings. + Supported range: 128–3072. If None, the model's default is used. + api_key_env_var (str, optional): Environment variable name that contains your API key. + Defaults to "GEMINI_API_KEY". + vertexai (bool, optional): Whether to use Vertex AI. + If enabled, an API key must not be provided, and the environment variable `GOOGLE_APPLICATION_CREDENTIALS` must be set to the path of your service account JSON file. + project (str, optional): The Google Cloud project ID (required for Vertex AI). + location (str, optional): The Google Cloud location/region (required for Vertex AI). + """ + try: + import google.genai as genai + except ImportError: + raise ValueError( + "The google-genai python package is not installed. Please install it with `pip install google-genai`" + ) + + self.model_name = model_name + self.task_type = task_type + self.dimension = dimension + self.api_key_env_var = api_key_env_var + self.vertexai = vertexai + self.project = project + self.location = location + self.api_key = os.getenv(self.api_key_env_var) if self.api_key_env_var else None + if self.api_key and self.vertexai: + raise ValueError( + "Vertex AI and API key are mutually exclusive in the client initializer." + ) + if not self.api_key and not self.vertexai: + raise ValueError( + f"The {self.api_key_env_var} environment variable must be set if vertexai is not enabled." + ) + + from google.genai import types + + self.client = genai.Client( + api_key=self.api_key, + vertexai=vertexai, + project=project, + location=location, + http_options=types.HttpOptions( + headers={"x-goog-api-client": f"chroma/{__version__}"} + ), + ) + + def __call__(self, input: Documents) -> Embeddings: + """ + Generate embeddings for the given documents. + + Args: + input: Documents to generate embeddings for. + + Returns: + Embeddings for the documents. + """ + if not input: + raise ValueError("Input documents cannot be empty") + if not isinstance(input, (list, tuple)): + raise ValueError("Input must be a list or tuple of documents") + if not all(isinstance(doc, str) for doc in input): + raise ValueError("All input documents must be strings") + + from google.genai.types import EmbedContentConfig + + config = EmbedContentConfig( + task_type=self.task_type, + output_dimensionality=self.dimension, + ) + + try: + response = self.client.models.embed_content( + model=self.model_name, + contents=input, + config=config, + ) + except Exception as e: + raise ValueError(f"Failed to generate embeddings: {str(e)}") from e + + # Validate response structure + if not hasattr(response, "embeddings") or not response.embeddings: + raise ValueError("No embeddings returned from the API") + + embeddings_list = [] + for ce in response.embeddings: + if not hasattr(ce, "values"): + raise ValueError("Malformed embedding response: missing 'values'") + embeddings_list.append(np.array(ce.values, dtype=np.float32)) + + return cast(Embeddings, embeddings_list) + + @staticmethod + def name() -> str: + return "google_gemini" + + def default_space(self) -> Space: + return "cosine" + + def supported_spaces(self) -> List[Space]: + return ["cosine", "l2", "ip"] + + @staticmethod + def build_from_config(config: Dict[str, Any]) -> "EmbeddingFunction[Documents]": + model_name = config.get("model_name") + task_type = config.get("task_type") + dimension = config.get("dimension") + api_key_env_var = config.get("api_key_env_var", "GEMINI_API_KEY") + vertexai = config.get("vertexai") + project = config.get("project") + location = config.get("location") + + if model_name is None: + raise ValueError("The model name is required.") + + return GoogleGeminiEmbeddingFunction( + model_name=model_name, + task_type=task_type, + dimension=dimension, + api_key_env_var=api_key_env_var, + vertexai=vertexai, + project=project, + location=location, + ) + + def get_config(self) -> Dict[str, Any]: + config: Dict[str, Any] = { + "model_name": self.model_name, + "api_key_env_var": self.api_key_env_var, + "vertexai": self.vertexai, + "project": self.project, + "location": self.location, + } + if self.task_type is not None: + config["task_type"] = self.task_type + if self.dimension is not None: + config["dimension"] = self.dimension + return config + + def validate_config_update( + self, old_config: Dict[str, Any], new_config: Dict[str, Any] + ) -> None: + if "model_name" in new_config: + raise ValueError( + "The model name cannot be changed after the embedding function has been initialized." + ) + if "dimension" in new_config: + raise ValueError( + "The dimension cannot be changed after the embedding function has been initialized." + ) + if "vertexai" in new_config: + raise ValueError( + "The vertexai cannot be changed after the embedding function has been initialized." + ) + if "project" in new_config: + raise ValueError( + "The project cannot be changed after the embedding function has been initialized." + ) + if "location" in new_config: + raise ValueError( + "The location cannot be changed after the embedding function has been initialized." + ) + + @staticmethod + def validate_config(config: Dict[str, Any]) -> None: + """ + Validate the configuration using the JSON schema. + + Args: + config: Configuration to validate + + Raises: + ValidationError: If the configuration does not match the schema + """ + validate_config_schema(config, "google_gemini") + + +# Backward compatibility alias +GoogleGenaiEmbeddingFunction = GoogleGeminiEmbeddingFunction + + +class GoogleGenerativeAiEmbeddingFunction(EmbeddingFunction[Documents]): + """To use this EmbeddingFunction, you must have the google.generativeai Python package installed and have a Google API key.""" + + def __init__( + self, + api_key: Optional[str] = None, + model_name: str = "gemini-embedding-001", + task_type: str = "RETRIEVAL_DOCUMENT", + api_key_env_var: str = "GEMINI_API_KEY", + dimension: Optional[int] = None, + ): + """ + Initialize the GoogleGenerativeAiEmbeddingFunction. + + Args: + api_key_env_var (str, optional): Environment variable name that contains your API key for the Google Generative AI API. + Defaults to "GEMINI_API_KEY". + model_name (str, optional): The name of the model to use for text embeddings. + Defaults to "gemini-embedding-001". + task_type (str, optional): The task type for the embeddings. + Use "RETRIEVAL_DOCUMENT" for embedding documents and "RETRIEVAL_QUERY" for embedding queries. + Defaults to "RETRIEVAL_DOCUMENT". + dimension (int, optional): The output dimensionality for the embeddings. + If None, the model's default dimensionality is used. + """ + try: + import google.generativeai as genai + except ImportError: + raise ValueError( + "The Google Generative AI python package is not installed. Please install it with `pip install google-generativeai`" + ) + + if api_key is not None: + warnings.warn( + "Direct api_key configuration will not be persisted. " + "Please use environment variables via api_key_env_var for persistent storage.", + DeprecationWarning, + ) + if os.getenv("GOOGLE_API_KEY") is not None: + self.api_key_env_var = "GOOGLE_API_KEY" + else: + self.api_key_env_var = api_key_env_var + + self.api_key = api_key or os.getenv(self.api_key_env_var) + if not self.api_key: + raise ValueError( + f"The {self.api_key_env_var} environment variable is not set." + ) + + self.model_name = model_name + self.task_type = task_type + self.dimension = dimension + + genai.configure( + api_key=self.api_key, + client_options={"headers": {"x-goog-api-client": f"chroma/{__version__}"}}, + ) + self._genai = genai + + def __call__(self, input: Documents) -> Embeddings: + """ + Generate embeddings for the given documents. + + Args: + input: Documents to generate embeddings for. + + Returns: + Embeddings for the documents. + """ + if not all(isinstance(item, str) for item in input): + raise ValueError( + "Google Generative AI only supports text documents, not images" + ) + + embeddings_list: List[npt.NDArray[np.float32]] = [] + for text in input: + kwargs: Dict[str, Any] = { + "model": self.model_name, + "content": text, + "task_type": self.task_type, + } + if self.dimension is not None: + kwargs["output_dimensionality"] = self.dimension + embedding_result = self._genai.embed_content(**kwargs) + embeddings_list.append( + np.array(embedding_result["embedding"], dtype=np.float32) + ) + + return cast(Embeddings, embeddings_list) + + @staticmethod + def name() -> str: + return "google_generative_ai" + + def default_space(self) -> Space: + return "cosine" + + def supported_spaces(self) -> List[Space]: + return ["cosine", "l2", "ip"] + + @staticmethod + def build_from_config(config: Dict[str, Any]) -> "EmbeddingFunction[Documents]": + api_key_env_var = config.get("api_key_env_var") + model_name = config.get("model_name") + task_type = config.get("task_type") + dimension = config.get("dimension") + + if api_key_env_var is None or model_name is None or task_type is None: + assert False, "This code should not be reached" + + return GoogleGenerativeAiEmbeddingFunction( + api_key_env_var=api_key_env_var, + model_name=model_name, + task_type=task_type, + dimension=dimension, + ) + + def get_config(self) -> Dict[str, Any]: + config: Dict[str, Any] = { + "api_key_env_var": self.api_key_env_var, + "model_name": self.model_name, + "task_type": self.task_type, + } + if self.dimension is not None: + config["dimension"] = self.dimension + return config + + def validate_config_update( + self, old_config: Dict[str, Any], new_config: Dict[str, Any] + ) -> None: + if "model_name" in new_config: + raise ValueError( + "The model name cannot be changed after the embedding function has been initialized." + ) + if "task_type" in new_config: + raise ValueError( + "The task type cannot be changed after the embedding function has been initialized." + ) + if "dimension" in new_config: + raise ValueError( + "The dimension cannot be changed after the embedding function has been initialized." + ) + + @staticmethod + def validate_config(config: Dict[str, Any]) -> None: + """ + Validate the configuration using the JSON schema. + + Args: + config: Configuration to validate + + Raises: + ValidationError: If the configuration does not match the schema + """ + validate_config_schema(config, "google_generative_ai") + + +class GooglePalmEmbeddingFunction(EmbeddingFunction[Documents]): + """To use this EmbeddingFunction, you must have the google.generativeai Python package installed and have a PaLM API key.""" + + def __init__( + self, + api_key: Optional[str] = None, + model_name: str = "models/embedding-gecko-001", + api_key_env_var: str = "CHROMA_GOOGLE_PALM_API_KEY", + ): + """ + Initialize the GooglePalmEmbeddingFunction. + + Args: + api_key_env_var (str, optional): Environment variable name that contains your API key for the Google PaLM API. + Defaults to "CHROMA_GOOGLE_PALM_API_KEY". + model_name (str, optional): The name of the model to use for text embeddings. + Defaults to "models/embedding-gecko-001". + """ + try: + import google.generativeai as palm + except ImportError: + raise ValueError( + "The Google Generative AI python package is not installed. Please install it with `pip install google-generativeai`" + ) + + if api_key is not None: + warnings.warn( + "Direct api_key configuration will not be persisted. " + "Please use environment variables via api_key_env_var for persistent storage.", + DeprecationWarning, + ) + if os.getenv("GOOGLE_API_KEY") is not None: + self.api_key_env_var = "GOOGLE_API_KEY" + else: + self.api_key_env_var = api_key_env_var + + self.api_key = api_key or os.getenv(self.api_key_env_var) + if not self.api_key: + raise ValueError( + f"The {self.api_key_env_var} environment variable is not set." + ) + + self.model_name = model_name + + palm.configure( + api_key=self.api_key, + client_options={"headers": {"x-goog-api-client": f"chroma/{__version__}"}}, + ) + self._palm = palm + + def __call__(self, input: Documents) -> Embeddings: + """ + Generate embeddings for the given documents. + + Args: + input: Documents or images to generate embeddings for. + + Returns: + Embeddings for the documents. + """ + # Google PaLM only works with text documents + if not all(isinstance(item, str) for item in input): + raise ValueError("Google PaLM only supports text documents, not images") + + return [ + np.array( + self._palm.generate_embeddings(model=self.model_name, text=text)[ + "embedding" + ], + dtype=np.float32, + ) + for text in input + ] + + @staticmethod + def name() -> str: + return "google_palm" + + def default_space(self) -> Space: + return "cosine" + + def supported_spaces(self) -> List[Space]: + return ["cosine", "l2", "ip"] + + @staticmethod + def build_from_config(config: Dict[str, Any]) -> "EmbeddingFunction[Documents]": + api_key_env_var = config.get("api_key_env_var") + model_name = config.get("model_name") + + if api_key_env_var is None or model_name is None: + assert False, "This code should not be reached" + + return GooglePalmEmbeddingFunction( + api_key_env_var=api_key_env_var, model_name=model_name + ) + + def get_config(self) -> Dict[str, Any]: + return {"api_key_env_var": self.api_key_env_var, "model_name": self.model_name} + + def validate_config_update( + self, old_config: Dict[str, Any], new_config: Dict[str, Any] + ) -> None: + if "model_name" in new_config: + raise ValueError( + "The model name cannot be changed after the embedding function has been initialized." + ) + + @staticmethod + def validate_config(config: Dict[str, Any]) -> None: + """ + Validate the configuration using the JSON schema. + + Args: + config: Configuration to validate + + Raises: + ValidationError: If the configuration does not match the schema + """ + validate_config_schema(config, "google_palm") + + +class GoogleVertexEmbeddingFunction(EmbeddingFunction[Documents]): + """To use this EmbeddingFunction, you must have the vertexai Python package installed and have Google Cloud credentials configured.""" + + def __init__( + self, + api_key: Optional[str] = None, + model_name: str = "textembedding-gecko", + project_id: str = "cloud-large-language-models", + region: str = "us-central1", + api_key_env_var: str = "CHROMA_GOOGLE_VERTEX_API_KEY", + ): + """ + Initialize the GoogleVertexEmbeddingFunction. + + Args: + api_key_env_var (str, optional): Environment variable name that contains your API key for the Google Vertex AI API. + Defaults to "CHROMA_GOOGLE_VERTEX_API_KEY". + model_name (str, optional): The name of the model to use for text embeddings. + Defaults to "textembedding-gecko". + project_id (str, optional): The Google Cloud project ID. + Defaults to "cloud-large-language-models". + region (str, optional): The Google Cloud region. + Defaults to "us-central1". + """ + try: + import vertexai + from vertexai.language_models import TextEmbeddingModel + except ImportError: + raise ValueError( + "The vertexai python package is not installed. Please install it with `pip install google-cloud-aiplatform`" + ) + + if api_key is not None: + warnings.warn( + "Direct api_key configuration will not be persisted. " + "Please use environment variables via api_key_env_var for persistent storage.", + DeprecationWarning, + ) + if os.getenv("GOOGLE_API_KEY") is not None: + self.api_key_env_var = "GOOGLE_API_KEY" + else: + self.api_key_env_var = api_key_env_var + + self.api_key = api_key or os.getenv(self.api_key_env_var) + if not self.api_key: + raise ValueError( + f"The {self.api_key_env_var} environment variable is not set." + ) + + self.model_name = model_name + self.project_id = project_id + self.region = region + + vertexai.init( + project=project_id, + location=region, + request_metadata=[("x-goog-api-client", f"chroma/{__version__}")], + ) + self._model = TextEmbeddingModel.from_pretrained(model_name) + + def __call__(self, input: Documents) -> Embeddings: + """ + Generate embeddings for the given documents. + + Args: + input: Documents or images to generate embeddings for. + + Returns: + Embeddings for the documents. + """ + # Google Vertex only works with text documents + if not all(isinstance(item, str) for item in input): + raise ValueError("Google Vertex only supports text documents, not images") + + embeddings_list: List[npt.NDArray[np.float32]] = [] + for text in input: + embedding_result = self._model.get_embeddings([text]) + embeddings_list.append( + np.array(embedding_result[0].values, dtype=np.float32) + ) + + # Convert to the expected Embeddings type (List[Vector]) + return cast(Embeddings, embeddings_list) + + @staticmethod + def name() -> str: + return "google_vertex" + + def default_space(self) -> Space: + return "cosine" + + def supported_spaces(self) -> List[Space]: + return ["cosine", "l2", "ip"] + + @staticmethod + def build_from_config(config: Dict[str, Any]) -> "EmbeddingFunction[Documents]": + api_key_env_var = config.get("api_key_env_var") + model_name = config.get("model_name") + project_id = config.get("project_id") + region = config.get("region") + + if ( + api_key_env_var is None + or model_name is None + or project_id is None + or region is None + ): + assert False, "This code should not be reached" + + return GoogleVertexEmbeddingFunction( + api_key_env_var=api_key_env_var, + model_name=model_name, + project_id=project_id, + region=region, + ) + + def get_config(self) -> Dict[str, Any]: + return { + "api_key_env_var": self.api_key_env_var, + "model_name": self.model_name, + "project_id": self.project_id, + "region": self.region, + } + + def validate_config_update( + self, old_config: Dict[str, Any], new_config: Dict[str, Any] + ) -> None: + if "model_name" in new_config: + raise ValueError( + "The model name cannot be changed after the embedding function has been initialized." + ) + if "project_id" in new_config: + raise ValueError( + "The project ID cannot be changed after the embedding function has been initialized." + ) + if "region" in new_config: + raise ValueError( + "The region cannot be changed after the embedding function has been initialized." + ) + + @staticmethod + def validate_config(config: Dict[str, Any]) -> None: + """ + Validate the configuration using the JSON schema. + + Args: + config: Configuration to validate + + Raises: + ValidationError: If the configuration does not match the schema + """ + validate_config_schema(config, "google_vertex") diff --git a/python/user_packages/Python313/site-packages/chromadb/utils/embedding_functions/huggingface_embedding_function.py b/python/user_packages/Python313/site-packages/chromadb/utils/embedding_functions/huggingface_embedding_function.py new file mode 100644 index 0000000000000000000000000000000000000000..fd980a17742b810ab71ecc270de6d9bd3ad47ba9 --- /dev/null +++ b/python/user_packages/Python313/site-packages/chromadb/utils/embedding_functions/huggingface_embedding_function.py @@ -0,0 +1,245 @@ +from chromadb.api.types import Embeddings, Documents, EmbeddingFunction, Space +from typing import List, Dict, Any, Optional +import os +import numpy as np +from chromadb.utils.embedding_functions.schemas import validate_config_schema +import warnings + + +class HuggingFaceEmbeddingFunction(EmbeddingFunction[Documents]): + """ + This class is used to get embeddings for a list of texts using the HuggingFace API. + It requires an API key and a model name. The default model name is "sentence-transformers/all-MiniLM-L6-v2". + """ + + def __init__( + self, + api_key: Optional[str] = None, + model_name: str = "sentence-transformers/all-MiniLM-L6-v2", + api_key_env_var: str = "CHROMA_HUGGINGFACE_API_KEY", + ): + """ + Initialize the HuggingFaceEmbeddingFunction. + + Args: + api_key_env_var (str, optional): Environment variable name that contains your API key for the HuggingFace API. + Defaults to "CHROMA_HUGGINGFACE_API_KEY". + model_name (str, optional): The name of the model to use for text embeddings. + Defaults to "sentence-transformers/all-MiniLM-L6-v2". + """ + try: + import httpx + except ImportError: + raise ValueError( + "The httpx python package is not installed. Please install it with `pip install httpx`" + ) + + if api_key is not None: + warnings.warn( + "Direct api_key configuration will not be persisted. " + "Please use environment variables via api_key_env_var for persistent storage.", + DeprecationWarning, + ) + if os.getenv("HUGGINGFACE_API_KEY") is not None: + self.api_key_env_var = "HUGGINGFACE_API_KEY" + else: + self.api_key_env_var = api_key_env_var + + self.api_key = api_key or os.getenv(self.api_key_env_var) + if not self.api_key: + raise ValueError( + f"The {self.api_key_env_var} environment variable is not set." + ) + + self.model_name = model_name + + self._api_url = f"https://api-inference.huggingface.co/pipeline/feature-extraction/{model_name}" + self._session = httpx.Client() + self._session.headers.update({"Authorization": f"Bearer {self.api_key}"}) + + def __call__(self, input: Documents) -> Embeddings: + """ + Get the embeddings for a list of texts. + + Args: + input (Documents): A list of texts to get embeddings for. + + Returns: + Embeddings: The embeddings for the texts. + + Example: + >>> hugging_face = HuggingFaceEmbeddingFunction(api_key_env_var="CHROMA_HUGGINGFACE_API_KEY") + >>> texts = ["Hello, world!", "How are you?"] + >>> embeddings = hugging_face(texts) + """ + # Call HuggingFace Embedding API for each document + response = self._session.post( + self._api_url, + json={"inputs": input, "options": {"wait_for_model": True}}, + ).json() + + # Convert to numpy arrays + return [np.array(embedding, dtype=np.float32) for embedding in response] + + @staticmethod + def name() -> str: + return "huggingface" + + def default_space(self) -> Space: + return "cosine" + + def supported_spaces(self) -> List[Space]: + return ["cosine", "l2", "ip"] + + @staticmethod + def build_from_config(config: Dict[str, Any]) -> "EmbeddingFunction[Documents]": + api_key_env_var = config.get("api_key_env_var") + model_name = config.get("model_name") + + if api_key_env_var is None or model_name is None: + assert False, "This code should not be reached" + + return HuggingFaceEmbeddingFunction( + api_key_env_var=api_key_env_var, model_name=model_name + ) + + def get_config(self) -> Dict[str, Any]: + return {"api_key_env_var": self.api_key_env_var, "model_name": self.model_name} + + def validate_config_update( + self, old_config: Dict[str, Any], new_config: Dict[str, Any] + ) -> None: + if "model_name" in new_config: + raise ValueError( + "The model name cannot be changed after the embedding function has been initialized." + ) + + @staticmethod + def validate_config(config: Dict[str, Any]) -> None: + """ + Validate the configuration using the JSON schema. + + Args: + config: Configuration to validate + + Raises: + ValidationError: If the configuration does not match the schema + """ + validate_config_schema(config, "huggingface") + + +class HuggingFaceEmbeddingServer(EmbeddingFunction[Documents]): + """ + This class is used to get embeddings for a list of texts using the HuggingFace Embedding server + (https://github.com/huggingface/text-embeddings-inference). + The embedding model is configured in the server. + """ + + def __init__( + self, + url: str, + api_key_env_var: Optional[str] = None, + api_key: Optional[str] = None, + ): + """ + Initialize the HuggingFaceEmbeddingServer. + + Args: + url (str): The URL of the HuggingFace Embedding Server. + api_key (Optional[str]): The API key for the HuggingFace Embedding Server. + api_key_env_var (str, optional): Environment variable name that contains your API key for the HuggingFace API. + """ + try: + import httpx + except ImportError: + raise ValueError( + "The httpx python package is not installed. Please install it with `pip install httpx`" + ) + + if api_key is not None: + warnings.warn( + "Direct api_key configuration will not be persisted. " + "Please use environment variables via api_key_env_var for persistent storage.", + DeprecationWarning, + ) + + self.url = url + + self.api_key_env_var = api_key_env_var + if os.getenv("HUGGINGFACE_API_KEY") is not None: + self.api_key_env_var = "HUGGINGFACE_API_KEY" + + if self.api_key_env_var is not None: + self.api_key = api_key or os.getenv(self.api_key_env_var) + else: + self.api_key = api_key + + self._api_url = f"{url}" + self._session = httpx.Client() + + if self.api_key is not None: + self._session.headers.update({"Authorization": f"Bearer {self.api_key}"}) + + def __call__(self, input: Documents) -> Embeddings: + """ + Get the embeddings for a list of texts. + + Args: + input (Documents): A list of texts to get embeddings for. + + Returns: + Embeddings: The embeddings for the texts. + + Example: + >>> hugging_face = HuggingFaceEmbeddingServer(url="http://localhost:8080/embed") + >>> texts = ["Hello, world!", "How are you?"] + >>> embeddings = hugging_face(texts) + """ + # Call HuggingFace Embedding Server API for each document + response = self._session.post(self._api_url, json={"inputs": input}).json() + + # Convert to numpy arrays + return [np.array(embedding, dtype=np.float32) for embedding in response] + + @staticmethod + def name() -> str: + return "huggingface_server" + + def default_space(self) -> Space: + return "cosine" + + def supported_spaces(self) -> List[Space]: + return ["cosine", "l2", "ip"] + + @staticmethod + def build_from_config(config: Dict[str, Any]) -> "EmbeddingFunction[Documents]": + url = config.get("url") + api_key_env_var = config.get("api_key_env_var") + if url is None: + raise ValueError("URL must be provided for HuggingFaceEmbeddingServer") + + return HuggingFaceEmbeddingServer(url=url, api_key_env_var=api_key_env_var) + + def get_config(self) -> Dict[str, Any]: + return {"url": self.url, "api_key_env_var": self.api_key_env_var} + + def validate_config_update( + self, old_config: Dict[str, Any], new_config: Dict[str, Any] + ) -> None: + if "url" in new_config and new_config["url"] != self.url: + raise ValueError( + "The URL cannot be changed after the embedding function has been initialized." + ) + + @staticmethod + def validate_config(config: Dict[str, Any]) -> None: + """ + Validate the configuration using the JSON schema. + + Args: + config: Configuration to validate + + Raises: + ValidationError: If the configuration does not match the schema + """ + validate_config_schema(config, "huggingface_server") diff --git a/python/user_packages/Python313/site-packages/chromadb/utils/embedding_functions/huggingface_sparse_embedding_function.py b/python/user_packages/Python313/site-packages/chromadb/utils/embedding_functions/huggingface_sparse_embedding_function.py new file mode 100644 index 0000000000000000000000000000000000000000..0bbbea321d7c47a5d3e1763b1e728e8fac1f18a9 --- /dev/null +++ b/python/user_packages/Python313/site-packages/chromadb/utils/embedding_functions/huggingface_sparse_embedding_function.py @@ -0,0 +1,200 @@ +from chromadb.api.types import ( + SparseEmbeddingFunction, + SparseVectors, + Documents, +) +from typing import Dict, Any, TypedDict, Optional +import numpy as np +from typing import cast, Literal +from chromadb.utils.embedding_functions.schemas import validate_config_schema +from chromadb.utils.sparse_embedding_utils import normalize_sparse_vector + +TaskType = Literal["document", "query"] + + +class HuggingFaceSparseEmbeddingFunctionQueryConfig(TypedDict): + task: TaskType + + +class HuggingFaceSparseEmbeddingFunction(SparseEmbeddingFunction[Documents]): + # Since we do dynamic imports we have to type this as Any + models: Dict[str, Any] = {} + + def __init__( + self, + model_name: str, + device: str, + task: Optional[TaskType] = "document", + query_config: Optional[HuggingFaceSparseEmbeddingFunctionQueryConfig] = None, + **kwargs: Any, + ): + """Initialize SparseEncoderEmbeddingFunction. + + Args: + model_name (str, optional): Identifier of the Huggingface SparseEncoder model + Some common models: prithivida/Splade_PP_en_v1, naver/splade-cocondenser-ensembledistil, naver/splade-v3 + device (str, optional): Device used for computation + **kwargs: Additional arguments to pass to the Splade model. + """ + try: + from sentence_transformers import SparseEncoder + except ImportError: + raise ValueError( + "The sentence_transformers python package is not installed. Please install it with `pip install sentence_transformers`" + ) + + self.model_name = model_name + self.device = device + self.task = task + self.query_config = query_config + for key, value in kwargs.items(): + if not isinstance(value, (str, int, float, bool, list, dict, tuple)): + raise ValueError(f"Keyword argument {key} is not a primitive type") + self.kwargs = kwargs + + if model_name not in self.models: + self.models[model_name] = SparseEncoder( + model_name_or_path=model_name, device=device, **kwargs + ) + self._model = self.models[model_name] + + def __call__(self, input: Documents) -> SparseVectors: + """Generate embeddings for the given documents. + + Args: + input: Documents to generate embeddings for. + + Returns: + Embeddings for the documents. + """ + try: + from sentence_transformers import SparseEncoder + except ImportError: + raise ValueError( + "The sentence_transformers python package is not installed. Please install it with `pip install sentence_transformers`" + ) + model = cast(SparseEncoder, self._model) + if self.task == "document": + embeddings = model.encode_document( + list(input), + ) + elif self.task == "query": + embeddings = model.encode_query( + list(input), + ) + else: + raise ValueError(f"Invalid task: {self.task}") + + sparse_vectors: SparseVectors = [] + + for vec in embeddings: + # Convert sparse tensor to dense array if needed + if hasattr(vec, "to_dense"): + vec_dense = vec.to_dense().numpy() + else: + vec_dense = vec.numpy() if hasattr(vec, "numpy") else np.array(vec) + + nz = np.where(vec_dense != 0)[0] + sparse_vectors.append( + normalize_sparse_vector( + indices=nz.tolist(), values=vec_dense[nz].tolist() + ) + ) + + return sparse_vectors + + def embed_query(self, input: Documents) -> SparseVectors: + try: + from sentence_transformers import SparseEncoder + except ImportError: + raise ValueError( + "The sentence_transformers python package is not installed. Please install it with `pip install sentence_transformers`" + ) + model = cast(SparseEncoder, self._model) + if self.query_config is not None: + if self.query_config.get("task") == "document": + embeddings = model.encode_document( + list(input), + ) + elif self.query_config.get("task") == "query": + embeddings = model.encode_query( + list(input), + ) + else: + raise ValueError(f"Invalid task: {self.query_config.get('task')}") + + sparse_vectors: SparseVectors = [] + + for vec in embeddings: + # Convert sparse tensor to dense array if needed + if hasattr(vec, "to_dense"): + vec_dense = vec.to_dense().numpy() + else: + vec_dense = vec.numpy() if hasattr(vec, "numpy") else np.array(vec) + + nz = np.where(vec_dense != 0)[0] + sparse_vectors.append( + normalize_sparse_vector( + indices=nz.tolist(), values=vec_dense[nz].tolist() + ) + ) + + return sparse_vectors + + else: + return self.__call__(input) + + @staticmethod + def name() -> str: + return "huggingface_sparse" + + @staticmethod + def build_from_config( + config: Dict[str, Any] + ) -> "SparseEmbeddingFunction[Documents]": + model_name = config.get("model_name") + device = config.get("device") + task = config.get("task") + query_config = config.get("query_config") + kwargs = config.get("kwargs", {}) + + if model_name is None or device is None: + assert False, "This code should not be reached" + + return HuggingFaceSparseEmbeddingFunction( + model_name=model_name, + device=device, + task=task, + query_config=query_config, + **kwargs, + ) + + def get_config(self) -> Dict[str, Any]: + return { + "model_name": self.model_name, + "device": self.device, + "task": self.task, + "query_config": self.query_config, + "kwargs": self.kwargs, + } + + def validate_config_update( + self, old_config: Dict[str, Any], new_config: Dict[str, Any] + ) -> None: + # model_name is also used as the identifier for model path if stored locally. + # Users should be able to change the path if needed, so we should not validate that. + # e.g. moving file path from /v1/my-model.bin to /v2/my-model.bin + return + + @staticmethod + def validate_config(config: Dict[str, Any]) -> None: + """ + Validate the configuration using the JSON schema. + + Args: + config: Configuration to validate + + Raises: + ValidationError: If the configuration does not match the schema + """ + validate_config_schema(config, "huggingface_sparse") diff --git a/python/user_packages/Python313/site-packages/chromadb/utils/embedding_functions/instructor_embedding_function.py b/python/user_packages/Python313/site-packages/chromadb/utils/embedding_functions/instructor_embedding_function.py new file mode 100644 index 0000000000000000000000000000000000000000..13de23058647d9406fe8ceb1509bb02c2af0b2a7 --- /dev/null +++ b/python/user_packages/Python313/site-packages/chromadb/utils/embedding_functions/instructor_embedding_function.py @@ -0,0 +1,118 @@ +from chromadb.api.types import Embeddings, Documents, EmbeddingFunction, Space +from chromadb.utils.embedding_functions.schemas import validate_config_schema +from typing import List, Dict, Any, Optional +import numpy as np + + +class InstructorEmbeddingFunction(EmbeddingFunction[Documents]): + """ + This class is used to generate embeddings for a list of texts using the Instructor embedding model. + """ + + # If you have a GPU with at least 6GB try model_name = "hkunlp/instructor-xl" and device = "cuda" + # for a full list of options: https://github.com/HKUNLP/instructor-embedding#model-list + def __init__( + self, + model_name: str = "hkunlp/instructor-base", + device: str = "cpu", + instruction: Optional[str] = None, + ): + """ + Initialize the InstructorEmbeddingFunction. + + Args: + model_name (str, optional): The name of the model to use for text embeddings. + Defaults to "hkunlp/instructor-base". + device (str, optional): The device to use for computation. + Defaults to "cpu". + instruction (str, optional): The instruction to use for the embeddings. + Defaults to None. + """ + try: + from InstructorEmbedding import INSTRUCTOR + except ImportError: + raise ValueError( + "The InstructorEmbedding python package is not installed. Please install it with `pip install InstructorEmbedding`" + ) + + self.model_name = model_name + self.device = device + self.instruction = instruction + + self._model = INSTRUCTOR(model_name_or_path=model_name, device=device) + + def __call__(self, input: Documents) -> Embeddings: + """ + Generate embeddings for the given documents. + + Args: + input: Documents or images to generate embeddings for. + + Returns: + Embeddings for the documents. + """ + # Instructor only works with text documents + if not all(isinstance(item, str) for item in input): + raise ValueError("Instructor only supports text documents, not images") + + if self.instruction is None: + embeddings = self._model.encode(input, convert_to_numpy=True) + else: + texts_with_instructions = [[self.instruction, text] for text in input] + embeddings = self._model.encode( + texts_with_instructions, convert_to_numpy=True + ) + + # Convert to numpy arrays + return [np.array(embedding, dtype=np.float32) for embedding in embeddings] + + @staticmethod + def name() -> str: + return "instructor" + + def default_space(self) -> Space: + return "cosine" + + def supported_spaces(self) -> List[Space]: + return ["cosine", "l2", "ip"] + + @staticmethod + def build_from_config(config: Dict[str, Any]) -> "EmbeddingFunction[Documents]": + model_name = config.get("model_name") + device = config.get("device") + instruction = config.get("instruction") + + if model_name is None or device is None: + assert False, "This code should not be reached" + + return InstructorEmbeddingFunction( + model_name=model_name, device=device, instruction=instruction + ) + + def get_config(self) -> Dict[str, Any]: + return { + "model_name": self.model_name, + "device": self.device, + "instruction": self.instruction, + } + + def validate_config_update( + self, old_config: Dict[str, Any], new_config: Dict[str, Any] + ) -> None: + # model_name is also used as the identifier for model path if stored locally. + # Users should be able to change the path if needed, so we should not validate that. + # e.g. moving file path from /v1/my-model.bin to /v2/my-model.bin + return + + @staticmethod + def validate_config(config: Dict[str, Any]) -> None: + """ + Validate the configuration using the JSON schema. + + Args: + config: Configuration to validate + + Raises: + ValidationError: If the configuration does not match the schema + """ + validate_config_schema(config, "instructor") diff --git a/python/user_packages/Python313/site-packages/chromadb/utils/embedding_functions/jina_embedding_function.py b/python/user_packages/Python313/site-packages/chromadb/utils/embedding_functions/jina_embedding_function.py new file mode 100644 index 0000000000000000000000000000000000000000..150285b2e695cd4e8d55caa49edb98d7e09f1f23 --- /dev/null +++ b/python/user_packages/Python313/site-packages/chromadb/utils/embedding_functions/jina_embedding_function.py @@ -0,0 +1,283 @@ +from chromadb.api.types import ( + Embeddings, + EmbeddingFunction, + Space, + Embeddable, + is_image, + is_document, +) +from chromadb.utils.embedding_functions.schemas import validate_config_schema +from typing import List, Dict, Any, Union, Optional, TypedDict +import os +import numpy as np +import warnings +import importlib +import base64 +import io + + +class JinaQueryConfig(TypedDict): + task: str + + +class JinaEmbeddingFunction(EmbeddingFunction[Embeddable]): + """ + This class is used to get embeddings for a list of texts using the Jina AI API. + It requires an API key and a model name. The default model name is "jina-embeddings-v2-base-en". + """ + + def __init__( + self, + api_key: Optional[str] = None, + model_name: str = "jina-embeddings-v2-base-en", + api_key_env_var: str = "CHROMA_JINA_API_KEY", + task: Optional[str] = None, + late_chunking: Optional[bool] = None, + truncate: Optional[bool] = None, + dimensions: Optional[int] = None, + embedding_type: Optional[str] = None, + normalized: Optional[bool] = None, + query_config: Optional[JinaQueryConfig] = None, + ): + """ + Initialize the JinaEmbeddingFunction. + + Args: + api_key_env_var (str, optional): Environment variable name that contains your API key for the Jina AI API. + Defaults to "CHROMA_JINA_API_KEY". + model_name (str, optional): The name of the model to use for text embeddings. + Defaults to "jina-embeddings-v2-base-en". + task (str, optional): The task to use for the Jina AI API. + Defaults to None. + late_chunking (bool, optional): Whether to use late chunking for the Jina AI API. + Defaults to None. + truncate (bool, optional): Whether to truncate the Jina AI API. + Defaults to None. + dimensions (int, optional): The number of dimensions to use for the Jina AI API. + Defaults to None. + embedding_type (str, optional): The type of embedding to use for the Jina AI API. + Defaults to None. + normalized (bool, optional): Whether to normalize the Jina AI API. + Defaults to None. + + """ + try: + import httpx + except ImportError: + raise ValueError( + "The httpx python package is not installed. Please install it with `pip install httpx`" + ) + try: + self._PILImage = importlib.import_module("PIL.Image") + except ImportError: + raise ValueError( + "The PIL python package is not installed. Please install it with `pip install pillow`" + ) + + if api_key is not None: + warnings.warn( + "Direct api_key configuration will not be persisted. " + "Please use environment variables via api_key_env_var for persistent storage.", + DeprecationWarning, + ) + + if os.getenv("JINA_API_KEY") is not None: + self.api_key_env_var = "JINA_API_KEY" + else: + self.api_key_env_var = api_key_env_var + + self.api_key = api_key or os.getenv(self.api_key_env_var) + if not self.api_key: + raise ValueError( + f"The {self.api_key_env_var} environment variable is not set." + ) + + self.model_name = model_name + + # Initialize optional attributes to None + self.task = task + self.late_chunking = late_chunking + self.truncate = truncate + self.dimensions = dimensions + self.embedding_type = embedding_type + self.normalized = normalized + self.query_config = query_config + + self._api_url = "https://api.jina.ai/v1/embeddings" + self._session = httpx.Client() + self._session.headers.update( + {"Authorization": f"Bearer {self.api_key}", "Accept-Encoding": "identity"} + ) + + def _build_payload(self, input: Embeddable, is_query: bool) -> Dict[str, Any]: + payload: Dict[str, Any] = { + "input": [], + "model": self.model_name, + } + if all(is_document(item) for item in input): + payload["input"] = input + else: + for item in input: + if is_document(item): + payload["input"].append({"text": item}) + elif is_image(item): + try: + pil_image = self._PILImage.fromarray(item) + + buffer = io.BytesIO() + pil_image.save(buffer, format="PNG") + img_bytes = buffer.getvalue() + + # Encode bytes to base64 string + base64_string = base64.b64encode(img_bytes).decode("utf-8") + + except Exception as e: + raise ValueError( + f"Failed to convert image numpy array to base64 data URI: {e}" + ) from e + payload["input"].append({"image": base64_string}) + + if self.task is not None: + payload["task"] = self.task + if self.late_chunking is not None: + payload["late_chunking"] = self.late_chunking + if self.truncate is not None: + payload["truncate"] = self.truncate + if self.dimensions is not None: + payload["dimensions"] = self.dimensions + if self.embedding_type is not None: + payload["embedding_type"] = self.embedding_type + if self.normalized is not None: + payload["normalized"] = self.normalized + + # overwrite parameteres when query payload is used + if is_query and self.query_config is not None: + for key, value in self.query_config.items(): + payload[key] = value + + return payload + + def _convert_resp(self, resp: Any, is_query: bool = False) -> Embeddings: + """ + Convert the response from the Jina AI API to a list of numpy arrays. + + Args: + resp (Any): The response from the Jina AI API. + + Returns: + Embeddings: A list of numpy arrays representing the embeddings. + """ + if "data" not in resp: + raise RuntimeError(resp.get("detail", "Unknown error")) + + embeddings_data: List[Dict[str, Union[int, List[float]]]] = resp["data"] + + # Sort resulting embeddings by index + sorted_embeddings = sorted(embeddings_data, key=lambda e: e["index"]) + + # Return embeddings as numpy arrays + return [ + np.array(result["embedding"], dtype=np.float32) + for result in sorted_embeddings + ] + + def __call__(self, input: Embeddable) -> Embeddings: + """ + Get the embeddings for a list of texts. + + Args: + input (Embeddable): A list of texts and/or images to get embeddings for. + + Returns: + Embeddings: The embeddings for the texts. + + Example: + >>> jina_ai_fn = JinaEmbeddingFunction(api_key_env_var="CHROMA_JINA_API_KEY") + >>> input = ["Hello, world!", "How are you?"] + """ + + payload = self._build_payload(input, is_query=False) + + # Call Jina AI Embedding API + resp = self._session.post(self._api_url, json=payload, timeout=60).json() + + return self._convert_resp(resp) + + def embed_query(self, input: Embeddable) -> Embeddings: + payload = self._build_payload(input, is_query=True) + + # Call Jina AI Embedding API + resp = self._session.post(self._api_url, json=payload, timeout=60).json() + + return self._convert_resp(resp, is_query=True) + + @staticmethod + def name() -> str: + return "jina" + + def default_space(self) -> Space: + return "cosine" + + def supported_spaces(self) -> List[Space]: + return ["cosine", "l2", "ip"] + + @staticmethod + def build_from_config(config: Dict[str, Any]) -> "EmbeddingFunction[Embeddable]": + api_key_env_var = config.get("api_key_env_var") + model_name = config.get("model_name") + task = config.get("task") + late_chunking = config.get("late_chunking") + truncate = config.get("truncate") + dimensions = config.get("dimensions") + embedding_type = config.get("embedding_type") + normalized = config.get("normalized") + query_config = config.get("query_config") + + if api_key_env_var is None or model_name is None: + assert False, "This code should not be reached" # this is for type checking + + return JinaEmbeddingFunction( + api_key_env_var=api_key_env_var, + model_name=model_name, + task=task, + late_chunking=late_chunking, + truncate=truncate, + dimensions=dimensions, + embedding_type=embedding_type, + normalized=normalized, + query_config=query_config, + ) + + def get_config(self) -> Dict[str, Any]: + return { + "api_key_env_var": self.api_key_env_var, + "model_name": self.model_name, + "task": self.task, + "late_chunking": self.late_chunking, + "truncate": self.truncate, + "dimensions": self.dimensions, + "embedding_type": self.embedding_type, + "normalized": self.normalized, + "query_config": self.query_config, + } + + def validate_config_update( + self, old_config: Dict[str, Any], new_config: Dict[str, Any] + ) -> None: + if "model_name" in new_config: + raise ValueError( + "The model name cannot be changed after the embedding function has been initialized." + ) + + @staticmethod + def validate_config(config: Dict[str, Any]) -> None: + """ + Validate the configuration using the JSON schema. + + Args: + config: Configuration to validate + + Raises: + ValidationError: If the configuration does not match the schema + """ + validate_config_schema(config, "jina") diff --git a/python/user_packages/Python313/site-packages/chromadb/utils/embedding_functions/mistral_embedding_function.py b/python/user_packages/Python313/site-packages/chromadb/utils/embedding_functions/mistral_embedding_function.py new file mode 100644 index 0000000000000000000000000000000000000000..1d1b10e2e4dc3b392b178a8c203a7e8a419fde01 --- /dev/null +++ b/python/user_packages/Python313/site-packages/chromadb/utils/embedding_functions/mistral_embedding_function.py @@ -0,0 +1,92 @@ +from chromadb.api.types import Embeddings, Documents, EmbeddingFunction, Space +from chromadb.utils.embedding_functions.schemas import validate_config_schema +from typing import List, Dict, Any +import os +import numpy as np + + +class MistralEmbeddingFunction(EmbeddingFunction[Documents]): + def __init__( + self, + model: str, + api_key_env_var: str = "MISTRAL_API_KEY", + ): + """ + Initialize the MistralEmbeddingFunction. + + Args: + model (str): The name of the model to use for text embeddings. + api_key_env_var (str): The environment variable name for the Mistral API key. + """ + try: + from mistralai import Mistral + except ImportError: + raise ValueError( + "The mistralai python package is not installed. Please install it with `pip install mistralai`" + ) + self.model = model + self.api_key_env_var = api_key_env_var + self.api_key = os.getenv(api_key_env_var) + if not self.api_key: + raise ValueError(f"The {api_key_env_var} environment variable is not set.") + self.client = Mistral(api_key=self.api_key) + + def __call__(self, input: Documents) -> Embeddings: + """ + Get the embeddings for a list of texts. + + Args: + input (Documents): A list of texts to get embeddings for. + """ + if not all(isinstance(item, str) for item in input): + raise ValueError("Mistral only supports text documents, not images") + output = self.client.embeddings.create( + model=self.model, + inputs=input, + ) + + # Extract embeddings from the response + return [np.array(data.embedding) for data in output.data] + + @staticmethod + def name() -> str: + return "mistral" + + def default_space(self) -> Space: + return "cosine" + + def supported_spaces(self) -> List[Space]: + return ["cosine", "l2", "ip"] + + @staticmethod + def build_from_config(config: Dict[str, Any]) -> "EmbeddingFunction[Documents]": + model = config.get("model") + api_key_env_var = config.get("api_key_env_var") + + if model is None or api_key_env_var is None: + assert False, "This code should not be reached" # this is for type checking + return MistralEmbeddingFunction(model=model, api_key_env_var=api_key_env_var) + + def get_config(self) -> Dict[str, Any]: + return { + "model": self.model, + "api_key_env_var": self.api_key_env_var, + } + + def validate_config_update( + self, old_config: Dict[str, Any], new_config: Dict[str, Any] + ) -> None: + if "model" in new_config: + raise ValueError( + "The model cannot be changed after the embedding function has been initialized." + ) + + @staticmethod + def validate_config(config: Dict[str, Any]) -> None: + """ + Validate the configuration using the JSON schema. + + Args: + config: Configuration to validate + """ + validate_config_schema(config, "mistral") diff --git a/python/user_packages/Python313/site-packages/chromadb/utils/embedding_functions/morph_embedding_function.py b/python/user_packages/Python313/site-packages/chromadb/utils/embedding_functions/morph_embedding_function.py new file mode 100644 index 0000000000000000000000000000000000000000..6004914e0e1fe261bd0296af1b7af4e30ef98321 --- /dev/null +++ b/python/user_packages/Python313/site-packages/chromadb/utils/embedding_functions/morph_embedding_function.py @@ -0,0 +1,147 @@ +from chromadb.api.types import Embeddings, Documents, EmbeddingFunction, Space +from typing import List, Dict, Any, Optional +import os +import numpy as np +from chromadb.utils.embedding_functions.schemas import validate_config_schema +import warnings + + +class MorphEmbeddingFunction(EmbeddingFunction[Documents]): + def __init__( + self, + api_key: Optional[str] = None, + model_name: str = "morph-embedding-v2", + api_base: str = "https://api.morphllm.com/v1", + encoding_format: str = "float", + api_key_env_var: str = "MORPH_API_KEY", + ): + """ + Initialize the MorphEmbeddingFunction. + + Args: + api_key (str, optional): The API key for the Morph API. If not provided, + it will be read from the environment variable specified by api_key_env_var. + model_name (str, optional): The name of the model to use for embeddings. + Defaults to "morph-embedding-v2". + api_base (str, optional): The base URL for the Morph API. + Defaults to "https://api.morphllm.com/v1". + encoding_format (str, optional): The format for embeddings (float or base64). + Defaults to "float". + api_key_env_var (str, optional): Environment variable name that contains your API key. + Defaults to "MORPH_API_KEY". + """ + try: + import openai + except ImportError: + raise ValueError( + "The openai python package is not installed. Please install it with `pip install openai`. " + "Note: Morph uses the OpenAI client library for API communication." + ) + + if api_key is not None: + warnings.warn( + "Direct api_key configuration will not be persisted. " + "Please use environment variables via api_key_env_var for persistent storage.", + DeprecationWarning, + ) + + self.api_key_env_var = api_key_env_var + self.api_key = api_key or os.getenv(api_key_env_var) + if not self.api_key: + raise ValueError(f"The {api_key_env_var} environment variable is not set.") + + self.model_name = model_name + self.api_base = api_base + self.encoding_format = encoding_format + + # Initialize the OpenAI client with Morph's base URL + self.client = openai.OpenAI( + api_key=self.api_key, + base_url=self.api_base, + ) + + def __call__(self, input: Documents) -> Embeddings: + """ + Generate embeddings for the given documents. + + Args: + input: Documents to generate embeddings for. + + Returns: + Embeddings for the documents. + """ + # Handle empty input + if not input: + return [] + + # Prepare embedding parameters + embedding_params: Dict[str, Any] = { + "model": self.model_name, + "input": input, + "encoding_format": self.encoding_format, + } + + # Get embeddings from Morph API + response = self.client.embeddings.create(**embedding_params) + + # Extract embeddings from response + return [np.array(data.embedding, dtype=np.float32) for data in response.data] + + @staticmethod + def name() -> str: + return "morph" + + def default_space(self) -> Space: + # Morph embeddings work best with cosine similarity + return "cosine" + + def supported_spaces(self) -> List[Space]: + return ["cosine", "l2", "ip"] + + @staticmethod + def build_from_config(config: Dict[str, Any]) -> "EmbeddingFunction[Documents]": + # Extract parameters from config + api_key_env_var = config.get("api_key_env_var") + model_name = config.get("model_name") + api_base = config.get("api_base") + encoding_format = config.get("encoding_format") + + if api_key_env_var is None or model_name is None: + assert False, "This code should not be reached" + + # Create and return the embedding function + return MorphEmbeddingFunction( + api_key_env_var=api_key_env_var, + model_name=model_name, + api_base=api_base if api_base is not None else "https://api.morphllm.com/v1", + encoding_format=encoding_format if encoding_format is not None else "float", + ) + + def get_config(self) -> Dict[str, Any]: + return { + "api_key_env_var": self.api_key_env_var, + "model_name": self.model_name, + "api_base": self.api_base, + "encoding_format": self.encoding_format, + } + + def validate_config_update( + self, old_config: Dict[str, Any], new_config: Dict[str, Any] + ) -> None: + if "model_name" in new_config: + raise ValueError( + "The model name cannot be changed after the embedding function has been initialized." + ) + + @staticmethod + def validate_config(config: Dict[str, Any]) -> None: + """ + Validate the configuration using the JSON schema. + + Args: + config: Configuration to validate + + Raises: + ValidationError: If the configuration does not match the schema + """ + validate_config_schema(config, "morph") \ No newline at end of file diff --git a/python/user_packages/Python313/site-packages/chromadb/utils/embedding_functions/nomic_embedding_function.py b/python/user_packages/Python313/site-packages/chromadb/utils/embedding_functions/nomic_embedding_function.py new file mode 100644 index 0000000000000000000000000000000000000000..be8cb883d716a1dedfc47a417bf0f3a72fcf67ba --- /dev/null +++ b/python/user_packages/Python313/site-packages/chromadb/utils/embedding_functions/nomic_embedding_function.py @@ -0,0 +1,129 @@ +from chromadb.api.types import ( + Embeddings, + Documents, + EmbeddingFunction, + Space, +) +from chromadb.utils.embedding_functions.schemas import validate_config_schema +from typing import List, Dict, Any, TypedDict, Optional +import os +import numpy as np + + +class NomicQueryConfig(TypedDict): + task_type: str + + +class NomicEmbeddingFunction(EmbeddingFunction[Documents]): + """ + This class is used to get embeddings for a list of texts using the Nomic API. + """ + + def __init__( + self, + model: str, + task_type: str, + query_config: Optional[NomicQueryConfig], + api_key_env_var: str = "NOMIC_API_KEY", + ): + """ + Initialize the NomicEmbeddingFunction. + + Args: + model (str): The name of the model to use for text embeddings. + task_type (str): The type of task to embed with. See reference https://docs.nomic.ai/platform/embeddings-and-retrieval/text-embedding#embedding-task-types + query_config (Optional[NomicQueryConfig]): The configuration for setting task type for queries + api_key_env_var (str): The environment variable name for the Nomic API key. Defaults to "NOMIC_API_KEY". + + Supported task types: search_document, search_query, classification, clustering + """ + try: + from nomic import embed + except ImportError: + raise ValueError( + "The nomic python package is not installed. Please install it with `pip install nomic`" + ) + + self.model = model + self.task_type = task_type + self.api_key_env_var = api_key_env_var + self.api_key = os.getenv(api_key_env_var) + self.query_config = query_config + if not self.api_key: + raise ValueError(f"The {api_key_env_var} environment variable is not set.") + self.embed = embed + + def __call__(self, input: Documents) -> Embeddings: + if not all(isinstance(item, str) for item in input): + raise ValueError("Nomic only supports text documents, not images") + output = self.embed.text( + model=self.model, + texts=input, + task_type=self.task_type, + ) + return [np.array(data.embedding) for data in output.data] + + def embed_query(self, input: Documents) -> Embeddings: + if not all(isinstance(item, str) for item in input): + raise ValueError("Nomic only supports text queries, not images") + + task_type = ( + self.query_config.get("task_type") if self.query_config else self.task_type + ) + output = self.embed.text( + model=self.model, + texts=input, + task_type=task_type, + ) + return [np.array(data.embedding) for data in output.data] + + @staticmethod + def name() -> str: + return "nomic" + + def default_space(self) -> Space: + return "cosine" + + def supported_spaces(self) -> List[Space]: + return ["cosine", "l2", "ip"] + + @staticmethod + def build_from_config(config: Dict[str, Any]) -> "EmbeddingFunction[Documents]": + model = config.get("model") + api_key_env_var = config.get("api_key_env_var") + task_type = config.get("task_type") + query_config = config.get("query_config") + if model is None or api_key_env_var is None or task_type is None: + assert False, "This code should not be reached" # this is for type checking + return NomicEmbeddingFunction( + model=model, + api_key_env_var=api_key_env_var, + task_type=task_type, + query_config=query_config, + ) + + def get_config(self) -> Dict[str, Any]: + return { + "model": self.model, + "api_key_env_var": self.api_key_env_var, + "task_type": self.task_type, + "query_config": self.query_config, + } + + def validate_config_update( + self, old_config: Dict[str, Any], new_config: Dict[str, Any] + ) -> None: + if "model" in new_config: + raise ValueError( + "The model cannot be changed after the embedding function has been initialized." + ) + + @staticmethod + def validate_config(config: Dict[str, Any]) -> None: + """ + Validate the configuration using the JSON schema. + + Args: + config: Configuration to validate + """ + validate_config_schema(config, "nomic") diff --git a/python/user_packages/Python313/site-packages/chromadb/utils/embedding_functions/ollama_embedding_function.py b/python/user_packages/Python313/site-packages/chromadb/utils/embedding_functions/ollama_embedding_function.py new file mode 100644 index 0000000000000000000000000000000000000000..fb5ab214bfe179bce27e8f1022778f0828657a60 --- /dev/null +++ b/python/user_packages/Python313/site-packages/chromadb/utils/embedding_functions/ollama_embedding_function.py @@ -0,0 +1,117 @@ +from chromadb.api.types import Embeddings, Documents, EmbeddingFunction, Space +from chromadb.utils.embedding_functions.schemas import validate_config_schema +from typing import List, Dict, Any +import numpy as np +from urllib.parse import urlparse + +DEFAULT_MODEL_NAME = "chroma/all-minilm-l6-v2-f32" + + +class OllamaEmbeddingFunction(EmbeddingFunction[Documents]): + """ + This class is used to generate embeddings for a list of texts using the Ollama Embedding API + (https://github.com/ollama/ollama/blob/main/docs/api.md#generate-embeddings). + """ + + def __init__( + self, + url: str = "http://localhost:11434", + model_name: str = DEFAULT_MODEL_NAME, + timeout: int = 60, + ) -> None: + """ + Initialize the Ollama Embedding Function. + + Args: + url (str): The Base URL of the Ollama Server (default: "http://localhost:11434"). + model_name (str): The name of the model to use for text embeddings. + Defaults to "chroma/all-minilm-l6-v2-f32", for available models see https://ollama.com/library. + timeout (int): The timeout for the API call in seconds. Defaults to 60. + """ + try: + from ollama import Client + except ImportError: + raise ValueError( + "The ollama python package is not installed. Please install it with `pip install ollama`" + ) + + self.url = url + self.model_name = model_name + self.timeout = timeout + + # Adding this for backwards compatibility with the old version of the EF + self._base_url = url + if self._base_url.endswith("/api/embeddings"): + parsed_url = urlparse(url) + self._base_url = f"{parsed_url.scheme}://{parsed_url.netloc}" + + self._client = Client(host=self._base_url, timeout=timeout) + + def __call__(self, input: Documents) -> Embeddings: + """ + Get the embeddings for a list of texts. + + Args: + input (Documents): A list of texts to get embeddings for. + + Returns: + Embeddings: The embeddings for the texts. + + Example: + >>> ollama_ef = OllamaEmbeddingFunction() + >>> texts = ["Hello, world!", "How are you?"] + >>> embeddings = ollama_ef(texts) + """ + # Call Ollama client + response = self._client.embed(model=self.model_name, input=input) + + # Convert to numpy arrays + return [ + np.array(embedding, dtype=np.float32) + for embedding in response["embeddings"] + ] + + @staticmethod + def name() -> str: + return "ollama" + + def default_space(self) -> Space: + return "cosine" + + def supported_spaces(self) -> List[Space]: + return ["cosine", "l2", "ip"] + + @staticmethod + def build_from_config(config: Dict[str, Any]) -> "EmbeddingFunction[Documents]": + url = config.get("url") + model_name = config.get("model_name") + timeout = config.get("timeout") + + if url is None or model_name is None or timeout is None: + assert False, "This code should not be reached" + + return OllamaEmbeddingFunction(url=url, model_name=model_name, timeout=timeout) + + def get_config(self) -> Dict[str, Any]: + return {"url": self.url, "model_name": self.model_name, "timeout": self.timeout} + + def validate_config_update( + self, old_config: Dict[str, Any], new_config: Dict[str, Any] + ) -> None: + if "model_name" in new_config: + raise ValueError( + "The model name cannot be changed after the embedding function has been initialized." + ) + + @staticmethod + def validate_config(config: Dict[str, Any]) -> None: + """ + Validate the configuration using the JSON schema. + + Args: + config: Configuration to validate + + Raises: + ValidationError: If the configuration does not match the schema + """ + validate_config_schema(config, "ollama") diff --git a/python/user_packages/Python313/site-packages/chromadb/utils/embedding_functions/onnx_mini_lm_l6_v2.py b/python/user_packages/Python313/site-packages/chromadb/utils/embedding_functions/onnx_mini_lm_l6_v2.py new file mode 100644 index 0000000000000000000000000000000000000000..a937ed00683c35b0242fd21da116b153cbac017e --- /dev/null +++ b/python/user_packages/Python313/site-packages/chromadb/utils/embedding_functions/onnx_mini_lm_l6_v2.py @@ -0,0 +1,364 @@ +import hashlib +import importlib +import logging +import os +import tarfile +import sys +from functools import cached_property +from pathlib import Path +from typing import List, Dict, Any, Optional, cast + +import numpy as np +import numpy.typing as npt +import httpx +from tenacity import retry, retry_if_exception, stop_after_attempt, wait_random + +from chromadb.api.types import Documents, Embeddings, EmbeddingFunction, Space +from chromadb.utils.embedding_functions.schemas import validate_config_schema + +logger = logging.getLogger(__name__) + + +def _verify_sha256(fname: str, expected_sha256: str) -> bool: + sha256_hash = hashlib.sha256() + with open(fname, "rb") as f: + # Read and update hash in chunks to avoid using too much memory + for byte_block in iter(lambda: f.read(4096), b""): + sha256_hash.update(byte_block) + + return sha256_hash.hexdigest() == expected_sha256 + + +# In order to remove dependencies on sentence-transformers, which in turn depends on +# pytorch and sentence-piece we have created a default ONNX embedding function that +# implements the same functionality as "all-MiniLM-L6-v2" from sentence-transformers. +# visit https://github.com/chroma-core/onnx-embedding for the source code to generate +# and verify the ONNX model. +class ONNXMiniLM_L6_V2(EmbeddingFunction[Documents]): + MODEL_NAME = "all-MiniLM-L6-v2" + DOWNLOAD_PATH = Path.home() / ".cache" / "chroma" / "onnx_models" / MODEL_NAME + EXTRACTED_FOLDER_NAME = "onnx" + ARCHIVE_FILENAME = "onnx.tar.gz" + MODEL_DOWNLOAD_URL = ( + "https://chroma-onnx-models.s3.amazonaws.com/all-MiniLM-L6-v2/onnx.tar.gz" + ) + _MODEL_SHA256 = "913d7300ceae3b2dbc2c50d1de4baacab4be7b9380491c27fab7418616a16ec3" + + def __init__(self, preferred_providers: Optional[List[str]] = None) -> None: + """ + Initialize the ONNXMiniLM_L6_V2 embedding function. + + Args: + preferred_providers (List[str], optional): The preferred ONNX runtime providers. + Defaults to None. + """ + # convert the list to set for unique values + if preferred_providers and not all( + [isinstance(i, str) for i in preferred_providers] + ): + raise ValueError("Preferred providers must be a list of strings") + # check for duplicate providers + if preferred_providers and len(preferred_providers) != len( + set(preferred_providers) + ): + raise ValueError("Preferred providers must be unique") + + self._preferred_providers = preferred_providers + + try: + # Equivalent to import onnxruntime + self.ort = importlib.import_module("onnxruntime") + except ImportError: + raise ValueError( + "The onnxruntime python package is not installed. Please install it with `pip install onnxruntime`" + ) + try: + # Equivalent to from tokenizers import Tokenizer + self.Tokenizer = importlib.import_module("tokenizers").Tokenizer + except ImportError: + raise ValueError( + "The tokenizers python package is not installed. Please install it with `pip install tokenizers`" + ) + try: + # Equivalent to from tqdm import tqdm + self.tqdm = importlib.import_module("tqdm").tqdm + except ImportError: + raise ValueError( + "The tqdm python package is not installed. Please install it with `pip install tqdm`" + ) + + # Borrowed from https://gist.github.com/yanqd0/c13ed29e29432e3cf3e7c38467f42f51 + # Download with tqdm to preserve the sentence-transformers experience + @retry( # type: ignore + reraise=True, + stop=stop_after_attempt(3), + wait=wait_random(min=1, max=3), + retry=retry_if_exception(lambda e: "does not match expected SHA256" in str(e)), + ) + def _download(self, url: str, fname: str, chunk_size: int = 1024) -> None: + """ + Download the onnx model from the URL and save it to the file path. + + Args: + url: The URL to download the model from. + fname: The path to save the model to. + chunk_size: The chunk size to use when downloading. + """ + with httpx.stream("GET", url) as resp: + total = int(resp.headers.get("content-length", 0)) + with open(fname, "wb") as file, self.tqdm( + desc=str(fname), + total=total, + unit="iB", + unit_scale=True, + unit_divisor=1024, + ) as bar: + for data in resp.iter_bytes(chunk_size=chunk_size): + size = file.write(data) + bar.update(size) + + if not _verify_sha256(fname, self._MODEL_SHA256): + os.remove(fname) + raise ValueError( + f"Downloaded file {fname} does not match expected SHA256 hash. Corrupted download or malicious file." + ) + + # Use pytorches default epsilon for division by zero + # https://pytorch.org/docs/stable/generated/torch.nn.functional.normalize.html + def _normalize(self, v: npt.NDArray[np.float32]) -> npt.NDArray[np.float32]: + """ + Normalize a vector. + + Args: + v: The vector to normalize. + + Returns: + The normalized vector. + """ + norm = np.linalg.norm(v, axis=1) + # Handle division by zero + norm[norm == 0] = 1e-12 + return cast(npt.NDArray[np.float32], v / norm[:, np.newaxis]) + + def _forward( + self, documents: List[str], batch_size: int = 32 + ) -> npt.NDArray[np.float32]: + """ + Generate embeddings for a list of documents. + + Args: + documents: The documents to generate embeddings for. + batch_size: The batch size to use when generating embeddings. + + Returns: + The embeddings for the documents. + """ + all_embeddings = [] + for i in range(0, len(documents), batch_size): + batch = documents[i : i + batch_size] + + # Encode each document separately + encoded = [self.tokenizer.encode(d) for d in batch] + + # Check if any document exceeds the max tokens + for doc_tokens in encoded: + if len(doc_tokens.ids) > self.max_tokens(): + raise ValueError( + f"Document length {len(doc_tokens.ids)} is greater than the max tokens {self.max_tokens()}" + ) + + input_ids = np.array([e.ids for e in encoded]) + attention_mask = np.array([e.attention_mask for e in encoded]) + + onnx_input = { + "input_ids": np.array(input_ids, dtype=np.int64), + "attention_mask": np.array(attention_mask, dtype=np.int64), + "token_type_ids": np.array( + [np.zeros(len(e), dtype=np.int64) for e in input_ids], + dtype=np.int64, + ), + } + + model_output = self.model.run(None, onnx_input) + last_hidden_state = model_output[0] + + # Perform mean pooling with attention weighting + input_mask_expanded = np.broadcast_to( + np.expand_dims(attention_mask, -1), last_hidden_state.shape + ) + embeddings = np.sum(last_hidden_state * input_mask_expanded, 1) / np.clip( + input_mask_expanded.sum(1), a_min=1e-9, a_max=None + ) + + embeddings = self._normalize(embeddings).astype(np.float32) + all_embeddings.append(embeddings) + + return np.concatenate(all_embeddings) + + @cached_property + def tokenizer(self) -> Any: + """ + Get the tokenizer for the model. + + Returns: + The tokenizer for the model. + """ + tokenizer = self.Tokenizer.from_file( + os.path.join( + self.DOWNLOAD_PATH, self.EXTRACTED_FOLDER_NAME, "tokenizer.json" + ) + ) + # max_seq_length = 256, for some reason sentence-transformers uses 256 even though the HF config has a max length of 128 + # https://github.com/UKPLab/sentence-transformers/blob/3e1929fddef16df94f8bc6e3b10598a98f46e62d/docs/_static/html/models_en_sentence_embeddings.html#LL480 + tokenizer.enable_truncation(max_length=256) + tokenizer.enable_padding(pad_id=0, pad_token="[PAD]", length=256) + return tokenizer + + @cached_property + def model(self) -> Any: + """ + Get the model. + + Returns: + The model. + """ + if self._preferred_providers is None or len(self._preferred_providers) == 0: + if len(self.ort.get_available_providers()) > 0: + logger.debug( + f"WARNING: No ONNX providers provided, defaulting to available providers: " + f"{self.ort.get_available_providers()}" + ) + self._preferred_providers = self.ort.get_available_providers() + elif not set(self._preferred_providers).issubset( + set(self.ort.get_available_providers()) + ): + raise ValueError( + f"Preferred providers must be subset of available providers: {self.ort.get_available_providers()}" + ) + + # Suppress onnxruntime warnings + so = self.ort.SessionOptions() + so.log_severity_level = 3 + so.graph_optimization_level = self.ort.GraphOptimizationLevel.ORT_ENABLE_ALL + + if ( + self._preferred_providers + and "CoreMLExecutionProvider" in self._preferred_providers + ): + # remove CoreMLExecutionProvider from the list, it is not as well optimized as CPU. + self._preferred_providers.remove("CoreMLExecutionProvider") + + return self.ort.InferenceSession( + os.path.join(self.DOWNLOAD_PATH, self.EXTRACTED_FOLDER_NAME, "model.onnx"), + # Since 1.9 onnyx runtime requires providers to be specified when there are multiple available + providers=self._preferred_providers, + sess_options=so, + ) + + def __call__(self, input: Documents) -> Embeddings: + """ + Generate embeddings for the given documents. + + Args: + input: Documents to generate embeddings for. + + Returns: + Embeddings for the documents. + """ + + # Only download the model when it is actually used + self._download_model_if_not_exists() + + # Generate embeddings + embeddings = self._forward(input) + + # Convert to list of numpy arrays for the expected Embeddings type + return cast( + Embeddings, + [np.array(embedding, dtype=np.float32) for embedding in embeddings], + ) + + def _download_model_if_not_exists(self) -> None: + """ + Download the model if it doesn't exist. + """ + onnx_files = [ + "config.json", + "model.onnx", + "special_tokens_map.json", + "tokenizer_config.json", + "tokenizer.json", + "vocab.txt", + ] + extracted_folder = os.path.join(self.DOWNLOAD_PATH, self.EXTRACTED_FOLDER_NAME) + onnx_files_exist = True + for f in onnx_files: + if not os.path.exists(os.path.join(extracted_folder, f)): + onnx_files_exist = False + break + # Model is not downloaded yet + if not onnx_files_exist: + os.makedirs(self.DOWNLOAD_PATH, exist_ok=True) + if not os.path.exists( + os.path.join(self.DOWNLOAD_PATH, self.ARCHIVE_FILENAME) + ) or not _verify_sha256( + os.path.join(self.DOWNLOAD_PATH, self.ARCHIVE_FILENAME), + self._MODEL_SHA256, + ): + self._download( + url=self.MODEL_DOWNLOAD_URL, + fname=os.path.join(self.DOWNLOAD_PATH, self.ARCHIVE_FILENAME), + ) + with tarfile.open( + name=os.path.join(self.DOWNLOAD_PATH, self.ARCHIVE_FILENAME), + mode="r:gz", + ) as tar: + if sys.version_info >= (3, 12): + tar.extractall(path=self.DOWNLOAD_PATH, filter="data") + else: + # filter argument was added in Python 3.12 + # https://docs.python.org/3/library/tarfile.html#tarfile.TarFile.extractall + # In versions prior to 3.12, this provides the same behavior as filter="data" + tar.extractall(path=self.DOWNLOAD_PATH) + + @staticmethod + def name() -> str: + return "onnx_mini_lm_l6_v2" + + def default_space(self) -> Space: + return "cosine" + + def supported_spaces(self) -> List[Space]: + return ["cosine", "l2", "ip"] + + def max_tokens(self) -> int: + # Default token limit for ONNX Mini LM L6 V2 model + return 256 + + @staticmethod + def build_from_config(config: Dict[str, Any]) -> "EmbeddingFunction[Documents]": + preferred_providers = config.get("preferred_providers") + + return ONNXMiniLM_L6_V2(preferred_providers=preferred_providers) + + def get_config(self) -> Dict[str, Any]: + return {"preferred_providers": self._preferred_providers} + + def validate_config_update( + self, old_config: Dict[str, Any], new_config: Dict[str, Any] + ) -> None: + # Preferred providers can be changed, so no validation needed + pass + + @staticmethod + def validate_config(config: Dict[str, Any]) -> None: + """ + Validate the configuration using the JSON schema. + + Args: + config: Configuration to validate + + Raises: + ValidationError: If the configuration does not match the schema + """ + validate_config_schema(config, "onnx_mini_lm_l6_v2") diff --git a/python/user_packages/Python313/site-packages/chromadb/utils/embedding_functions/open_clip_embedding_function.py b/python/user_packages/Python313/site-packages/chromadb/utils/embedding_functions/open_clip_embedding_function.py new file mode 100644 index 0000000000000000000000000000000000000000..42401fc25ff3124460161d44bb9dae1db3353f8a --- /dev/null +++ b/python/user_packages/Python313/site-packages/chromadb/utils/embedding_functions/open_clip_embedding_function.py @@ -0,0 +1,187 @@ +from chromadb.api.types import EmbeddingFunction, Space +from chromadb.utils.embedding_functions.schemas import validate_config_schema +from chromadb.api.types import ( + Document, + Documents, + Embedding, + Embeddings, + Image, + Images, + is_document, + is_image, + Embeddable, +) +from typing import List, Dict, Any, Union, Optional, cast +import numpy as np +import importlib + + +class OpenCLIPEmbeddingFunction(EmbeddingFunction[Embeddable]): + """ + This class is used to generate embeddings for a list of texts or images using the Open CLIP model. + """ + + def __init__( + self, + model_name: str = "ViT-B-32", + checkpoint: str = "laion2b_s34b_b79k", + device: Optional[str] = "cpu", + ) -> None: + """ + Initialize the OpenCLIPEmbeddingFunction. + + Args: + model_name (str, optional): The name of the model to use for embeddings. + Defaults to "ViT-B-32". + checkpoint (str, optional): The checkpoint to use for the model. + Defaults to "laion2b_s34b_b79k". + device (str, optional): The device to use for computation. + Defaults to "cpu". + """ + try: + import open_clip + except ImportError: + raise ValueError( + "The open_clip python package is not installed. Please install it with `pip install open-clip-torch`. https://github.com/mlfoundations/open_clip" + ) + + try: + self._torch = importlib.import_module("torch") + except ImportError: + raise ValueError( + "The torch python package is not installed. Please install it with `pip install torch`" + ) + + try: + self._PILImage = importlib.import_module("PIL.Image") + except ImportError: + raise ValueError( + "The PIL python package is not installed. Please install it with `pip install pillow`" + ) + + self.model_name = model_name + self.checkpoint = checkpoint + self.device = device + + model, _, preprocess = open_clip.create_model_and_transforms( + model_name=model_name, pretrained=checkpoint + ) + self._model = model + self._model.to(device) + self._preprocess = preprocess + self._tokenizer = open_clip.get_tokenizer(model_name=model_name) + + def _encode_image(self, image: Image) -> Embedding: + """ + Encode an image using the Open CLIP model. + + Args: + image: The image to encode. + + Returns: + The embedding for the image. + """ + pil_image = self._PILImage.fromarray(image) + with self._torch.no_grad(): + image_features = self._model.encode_image( + self._preprocess(pil_image).unsqueeze(0).to(self.device) + ) + image_features /= image_features.norm(dim=-1, keepdim=True) + return cast(Embedding, image_features.squeeze().cpu().numpy()) + + def _encode_text(self, text: Document) -> Embedding: + """ + Encode a text using the Open CLIP model. + + Args: + text: The text to encode. + + Returns: + The embedding for the text. + """ + with self._torch.no_grad(): + text_features = self._model.encode_text( + self._tokenizer(text).to(self.device) + ) + text_features /= text_features.norm(dim=-1, keepdim=True) + return cast(Embedding, text_features.squeeze().cpu().numpy()) + + def __call__(self, input: Embeddable) -> Embeddings: + """ + Generate embeddings for the given documents or images. + + Args: + input: Documents or images to generate embeddings for. + + Returns: + Embeddings for the documents or images. + """ + embeddings: Embeddings = [] + for item in input: + if is_image(item): + embeddings.append( + np.array(self._encode_image(cast(Image, item)), dtype=np.float32) + ) + elif is_document(item): + embeddings.append( + np.array(self._encode_text(cast(Document, item)), dtype=np.float32) + ) + + return embeddings + + @staticmethod + def name() -> str: + return "open_clip" + + def default_space(self) -> Space: + return "cosine" + + def supported_spaces(self) -> List[Space]: + return ["cosine", "l2", "ip"] + + @staticmethod + def build_from_config( + config: Dict[str, Any] + ) -> "EmbeddingFunction[Union[Documents, Images]]": + model_name = config.get("model_name") + checkpoint = config.get("checkpoint") + device = config.get("device") + + if model_name is None or checkpoint is None or device is None: + assert False, "This code should not be reached" + + return OpenCLIPEmbeddingFunction( + model_name=model_name, checkpoint=checkpoint, device=device + ) + + def get_config(self) -> Dict[str, Any]: + return { + "model_name": self.model_name, + "checkpoint": self.checkpoint, + "device": self.device, + } + + def validate_config_update( + self, old_config: Dict[str, Any], new_config: Dict[str, Any] + ) -> None: + if "model_name" in new_config: + raise ValueError( + "The model name cannot be changed after the embedding function has been initialized." + ) + if "checkpoint" in new_config: + raise ValueError( + "The checkpoint cannot be changed after the embedding function has been initialized." + ) + + @staticmethod + def validate_config(config: Dict[str, Any]) -> None: + """ + Validate the configuration using the JSON schema. + + Args: + config: Configuration to validate + + Raises: + ValidationError: If the configuration does not match the schema + """ + validate_config_schema(config, "open_clip") diff --git a/python/user_packages/Python313/site-packages/chromadb/utils/embedding_functions/openai_embedding_function.py b/python/user_packages/Python313/site-packages/chromadb/utils/embedding_functions/openai_embedding_function.py new file mode 100644 index 0000000000000000000000000000000000000000..26d0c7f2553eb70b6136f04ddb4c7e2def7348fd --- /dev/null +++ b/python/user_packages/Python313/site-packages/chromadb/utils/embedding_functions/openai_embedding_function.py @@ -0,0 +1,210 @@ +from chromadb.api.types import Embeddings, Documents, EmbeddingFunction, Space +from typing import List, Dict, Any, Optional +import os +import numpy as np +from chromadb.utils.embedding_functions.schemas import validate_config_schema +import warnings + + +class OpenAIEmbeddingFunction(EmbeddingFunction[Documents]): + def __init__( + self, + api_key: Optional[str] = None, + model_name: str = "text-embedding-ada-002", + organization_id: Optional[str] = None, + api_base: Optional[str] = None, + api_type: Optional[str] = None, + api_version: Optional[str] = None, + deployment_id: Optional[str] = None, + default_headers: Optional[Dict[str, str]] = None, + dimensions: Optional[int] = None, + api_key_env_var: str = "CHROMA_OPENAI_API_KEY", + ): + """ + Initialize the OpenAIEmbeddingFunction. + Args: + api_key_env_var (str, optional): Environment variable name that contains your API key for the OpenAI API. + Defaults to "CHROMA_OPENAI_API_KEY". + model_name (str, optional): The name of the model to use for text + embeddings. Defaults to "text-embedding-ada-002". + organization_id(str, optional): The OpenAI organization ID if applicable + api_base (str, optional): The base path for the API. If not provided, + it will use the base path for the OpenAI API. This can be used to + point to a different deployment, such as an Azure deployment. + api_type (str, optional): The type of the API deployment. This can be + used to specify a different deployment, such as 'azure'. If not + provided, it will use the default OpenAI deployment. + api_version (str, optional): The api version for the API. If not provided, + it will use the api version for the OpenAI API. This can be used to + point to a different deployment, such as an Azure deployment. + deployment_id (str, optional): Deployment ID for Azure OpenAI. + default_headers (Dict[str, str], optional): A mapping of default headers to be sent with each API request. + dimensions (int, optional): The number of dimensions for the embeddings. + Only supported for `text-embedding-3` or later models from OpenAI. + https://platform.openai.com/docs/api-reference/embeddings/create#embeddings-create-dimensions + """ + try: + import openai + except ImportError: + raise ValueError( + "The openai python package is not installed. Please install it with `pip install openai`" + ) + + if api_key is not None: + warnings.warn( + "Direct api_key configuration will not be persisted. " + "Please use environment variables via api_key_env_var for persistent storage.", + DeprecationWarning, + ) + + if os.getenv("OPENAI_API_KEY") is not None: + self.api_key_env_var = "OPENAI_API_KEY" + else: + self.api_key_env_var = api_key_env_var + + self.api_key = api_key or os.getenv(self.api_key_env_var) + if not self.api_key: + raise ValueError( + f"The {self.api_key_env_var} environment variable is not set." + ) + + self.model_name = model_name + self.organization_id = organization_id + self.api_base = api_base + self.api_type = api_type + self.api_version = api_version + self.deployment_id = deployment_id + self.default_headers = default_headers + self.dimensions = dimensions + + # Initialize the OpenAI client + client_params: Dict[str, Any] = {"api_key": self.api_key} + + if self.organization_id is not None: + client_params["organization"] = self.organization_id + if self.api_base is not None: + client_params["base_url"] = self.api_base + if self.default_headers is not None: + client_params["default_headers"] = self.default_headers + + self.client = openai.OpenAI(**client_params) + + # For Azure OpenAI + if self.api_type == "azure": + if self.api_version is None: + raise ValueError("api_version must be specified for Azure OpenAI") + if self.deployment_id is None: + raise ValueError("deployment_id must be specified for Azure OpenAI") + if self.api_base is None: + raise ValueError("api_base must be specified for Azure OpenAI") + + from openai import AzureOpenAI + + self.client = AzureOpenAI( + api_key=self.api_key, + api_version=self.api_version, + azure_endpoint=self.api_base, + azure_deployment=self.deployment_id, + default_headers=self.default_headers, + ) + + def __call__(self, input: Documents) -> Embeddings: + """ + Generate embeddings for the given documents. + Args: + input: Documents to generate embeddings for. + Returns: + Embeddings for the documents. + """ + # Handle batching + if not input: + return [] + + # Prepare embedding parameters + embedding_params: Dict[str, Any] = { + "model": self.model_name, + "input": input, + } + + if self.dimensions is not None and "text-embedding-3" in self.model_name: + embedding_params["dimensions"] = self.dimensions + + # Get embeddings + response = self.client.embeddings.create(**embedding_params) + + # Extract embeddings from response + return [np.array(data.embedding, dtype=np.float32) for data in response.data] + + @staticmethod + def name() -> str: + return "openai" + + def default_space(self) -> Space: + # OpenAI embeddings work best with cosine similarity + return "cosine" + + def supported_spaces(self) -> List[Space]: + return ["cosine", "l2", "ip"] + + @staticmethod + def build_from_config(config: Dict[str, Any]) -> "EmbeddingFunction[Documents]": + # Extract parameters from config + api_key_env_var = config.get("api_key_env_var") + model_name = config.get("model_name") + organization_id = config.get("organization_id") + api_base = config.get("api_base") + api_type = config.get("api_type") + api_version = config.get("api_version") + deployment_id = config.get("deployment_id") + default_headers = config.get("default_headers") + dimensions = config.get("dimensions") + + if api_key_env_var is None or model_name is None: + assert False, "This code should not be reached" + + # Create and return the embedding function + return OpenAIEmbeddingFunction( + api_key_env_var=api_key_env_var, + model_name=model_name, + organization_id=organization_id, + api_base=api_base, + api_type=api_type, + api_version=api_version, + deployment_id=deployment_id, + default_headers=default_headers, + dimensions=dimensions, + ) + + def get_config(self) -> Dict[str, Any]: + return { + "api_key_env_var": self.api_key_env_var, + "model_name": self.model_name, + "organization_id": self.organization_id, + "api_base": self.api_base, + "api_type": self.api_type, + "api_version": self.api_version, + "deployment_id": self.deployment_id, + "default_headers": self.default_headers, + "dimensions": self.dimensions, + } + + def validate_config_update( + self, old_config: Dict[str, Any], new_config: Dict[str, Any] + ) -> None: + if "model_name" in new_config: + raise ValueError( + "The model name cannot be changed after the embedding function has been initialized." + ) + + @staticmethod + def validate_config(config: Dict[str, Any]) -> None: + """ + Validate the configuration using the JSON schema. + + Args: + config: Configuration to validate + + Raises: + ValidationError: If the configuration does not match the schema + """ + validate_config_schema(config, "openai") diff --git a/python/user_packages/Python313/site-packages/chromadb/utils/embedding_functions/perplexity_embedding_function.py b/python/user_packages/Python313/site-packages/chromadb/utils/embedding_functions/perplexity_embedding_function.py new file mode 100644 index 0000000000000000000000000000000000000000..f1bbdcfa0dc279876f951f2f2ad301ed16ee7ccd --- /dev/null +++ b/python/user_packages/Python313/site-packages/chromadb/utils/embedding_functions/perplexity_embedding_function.py @@ -0,0 +1,136 @@ +from chromadb.api.types import EmbeddingFunction, Space, Embeddings, Documents +from chromadb.utils.embedding_functions.schemas import validate_config_schema +from chromadb.utils.embedding_functions.utils import decode_embedding +from typing import List, Dict, Any, Optional +import os +import numpy as np +import warnings +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + import perplexity + + +class PerplexityEmbeddingFunction(EmbeddingFunction[Documents]): + """ + This class is used to generate embeddings for a list of texts using the Perplexity API. + """ + + def __init__( + self, + api_key: Optional[str] = None, + model_name: str = "pplx-embed-v1-0.6b", + api_key_env_var: str = "PERPLEXITY_API_KEY", + dimensions: Optional[int] = None, + ): + """ + Initialize the PerplexityEmbeddingFunction. + + Args: + api_key_env_var (str, optional): Environment variable name that contains your API key for the Perplexity API. + Defaults to "PERPLEXITY_API_KEY". + model_name (str, optional): The name of the model to use for text embeddings. + Defaults to "pplx-embed-v1-0.6b". + api_key (str, optional): API key for the Perplexity API. If not provided, will look for it in the environment variable. + dimensions (int, optional): Perplexity embeddings support Matryoshka representation learning, allowing you + to reduce embedding dimensions while maintaining quality. + """ + try: + import perplexity + except ImportError: + raise ValueError( + "The perplexityai python package is not installed. Please install it with `pip install perplexityai`" + ) + + if api_key is not None: + warnings.warn( + "Direct api_key configuration will not be persisted. " + "Please use environment variables via api_key_env_var for persistent storage.", + DeprecationWarning, + ) + + if os.getenv("PERPLEXITY_API_KEY") is not None: + self.api_key_env_var = "PERPLEXITY_API_KEY" + else: + self.api_key_env_var = api_key_env_var + + self.api_key = api_key or os.getenv(self.api_key_env_var) + if not self.api_key: + raise ValueError( + f"The {self.api_key_env_var} environment variable is not set." + ) + + self.model_name = model_name + self.dimensions = dimensions + self._client = perplexity.Perplexity(api_key=self.api_key) + + def __call__(self, input: Documents) -> Embeddings: + """ + Generate embeddings for the given documents. + + Args: + input: Documents to generate embeddings for. + + Returns: + Embeddings for the documents. + """ + response = self._client.embeddings.create( + input=input, + model=self.model_name, + dimensions=self.dimensions + ) + + return [decode_embedding(emb.embedding) for emb in response.data] + + @staticmethod + def name() -> str: + return "perplexity" + + def default_space(self) -> Space: + return "cosine" + + def supported_spaces(self) -> List[Space]: + return ["cosine", "l2", "ip"] + + @staticmethod + def build_from_config(config: Dict[str, Any]) -> "EmbeddingFunction[Documents]": + api_key_env_var = config.get("api_key_env_var") + model_name = config.get("model_name") + dimensions = config.get("dimensions") + + if api_key_env_var is None or model_name is None: + assert False, "This code should not be reached" + + return PerplexityEmbeddingFunction( + api_key_env_var=api_key_env_var, + model_name=model_name, + dimensions=dimensions, + ) + + def get_config(self) -> Dict[str, Any]: + return { + "api_key_env_var": self.api_key_env_var, + "model_name": self.model_name, + "dimensions": self.dimensions, + } + + def validate_config_update( + self, old_config: Dict[str, Any], new_config: Dict[str, Any] + ) -> None: + if "model_name" in new_config: + raise ValueError( + "The model name cannot be changed after the embedding function has been initialized." + ) + + @staticmethod + def validate_config(config: Dict[str, Any]) -> None: + """ + Validate the configuration using the JSON schema. + + Args: + config: Configuration to validate + + Raises: + ValidationError: If the configuration does not match the schema + """ + validate_config_schema(config, "perplexity") diff --git a/python/user_packages/Python313/site-packages/chromadb/utils/embedding_functions/roboflow_embedding_function.py b/python/user_packages/Python313/site-packages/chromadb/utils/embedding_functions/roboflow_embedding_function.py new file mode 100644 index 0000000000000000000000000000000000000000..1366941069812c87bdc17622bd6487d15500f59f --- /dev/null +++ b/python/user_packages/Python313/site-packages/chromadb/utils/embedding_functions/roboflow_embedding_function.py @@ -0,0 +1,165 @@ +from chromadb.utils.embedding_functions.schemas import validate_config_schema +from chromadb.api.types import ( + Documents, + Embeddings, + Images, + is_document, + is_image, + Embeddable, + EmbeddingFunction, + Space, +) +from typing import List, Dict, Any, Union, cast, Optional +import os +import importlib +import base64 +from io import BytesIO +import numpy as np +import warnings + + +class RoboflowEmbeddingFunction(EmbeddingFunction[Embeddable]): + """ + This class is used to generate embeddings for a list of texts or images using the Roboflow API. + """ + + def __init__( + self, + api_key: Optional[str] = None, + api_url: str = "https://infer.roboflow.com", + api_key_env_var: str = "CHROMA_ROBOFLOW_API_KEY", + ) -> None: + """ + Create a RoboflowEmbeddingFunction. + + Args: + api_key_env_var (str, optional): Environment variable name that contains your API key for the Roboflow API. + Defaults to "CHROMA_ROBOFLOW_API_KEY". + api_url (str, optional): The URL of the Roboflow API. + Defaults to "https://infer.roboflow.com". + """ + + if api_key is not None: + warnings.warn( + "Direct api_key configuration will not be persisted. " + "Please use environment variables via api_key_env_var for persistent storage.", + DeprecationWarning, + ) + if os.getenv("ROBOFLOW_API_KEY") is not None: + self.api_key_env_var = "ROBOFLOW_API_KEY" + else: + self.api_key_env_var = api_key_env_var + + self.api_key = api_key or os.getenv(self.api_key_env_var) + if not self.api_key: + raise ValueError( + f"The {self.api_key_env_var} environment variable is not set." + ) + + self.api_url = api_url + + try: + self._PILImage = importlib.import_module("PIL.Image") + except ImportError: + raise ValueError( + "The PIL python package is not installed. Please install it with `pip install pillow`" + ) + + self._httpx = importlib.import_module("httpx") + + def __call__(self, input: Embeddable) -> Embeddings: + """ + Generate embeddings for the given documents or images. + + Args: + input: Documents or images to generate embeddings for. + + Returns: + Embeddings for the documents or images. + """ + embeddings = [] + + for item in input: + if is_image(item): + image = self._PILImage.fromarray(item) + + buffer = BytesIO() + image.save(buffer, format="JPEG") + base64_image = base64.b64encode(buffer.getvalue()).decode("utf-8") + + infer_clip_payload_image = { + "image": { + "type": "base64", + "value": base64_image, + }, + } + + res = self._httpx.post( + f"{self.api_url}/clip/embed_image?api_key={self.api_key}", + json=infer_clip_payload_image, + ) + + result = res.json()["embeddings"] + embeddings.append(np.array(result[0], dtype=np.float32)) + + elif is_document(item): + infer_clip_payload_text = { + "text": item, + } + + res = self._httpx.post( + f"{self.api_url}/clip/embed_text?api_key={self.api_key}", + json=infer_clip_payload_text, + ) + + result = res.json()["embeddings"] + embeddings.append(np.array(result[0], dtype=np.float32)) + + # Cast to the expected Embeddings type + return cast(Embeddings, embeddings) + + @staticmethod + def name() -> str: + return "roboflow" + + def default_space(self) -> Space: + return "cosine" + + def supported_spaces(self) -> List[Space]: + return ["cosine", "l2", "ip"] + + @staticmethod + def build_from_config( + config: Dict[str, Any] + ) -> "EmbeddingFunction[Union[Documents, Images]]": + api_key_env_var = config.get("api_key_env_var") + api_url = config.get("api_url") + + if api_key_env_var is None or api_url is None: + assert False, "This code should not be reached" + + return RoboflowEmbeddingFunction( + api_key_env_var=api_key_env_var, api_url=api_url + ) + + def get_config(self) -> Dict[str, Any]: + return {"api_key_env_var": self.api_key_env_var, "api_url": self.api_url} + + def validate_config_update( + self, old_config: Dict[str, Any], new_config: Dict[str, Any] + ) -> None: + # API URL can be changed, so no validation needed + pass + + @staticmethod + def validate_config(config: Dict[str, Any]) -> None: + """ + Validate the configuration using the JSON schema. + + Args: + config: Configuration to validate + + Raises: + ValidationError: If the configuration does not match the schema + """ + validate_config_schema(config, "roboflow") diff --git a/python/user_packages/Python313/site-packages/chromadb/utils/embedding_functions/schemas/README.md b/python/user_packages/Python313/site-packages/chromadb/utils/embedding_functions/schemas/README.md new file mode 100644 index 0000000000000000000000000000000000000000..d060817257dddb8f234189120fd81fa05702b51d --- /dev/null +++ b/python/user_packages/Python313/site-packages/chromadb/utils/embedding_functions/schemas/README.md @@ -0,0 +1,41 @@ +# Embedding Function Schemas + +This directory contains JSON schemas for all embedding functions in Chroma. The purpose of having this schema is to support cross language compatibility, and to validate that changes in one client library do not accidentally diverge from others. + +## Schema Structure + +Each schema follows the JSON Schema Draft-07 specification and includes: + +- `version`: The version of the schema +- `title`: The title of the schema +- `description`: A description of the schema +- `properties`: The properties that can be configured for the embedding function +- `required`: The properties that are required for the embedding function +- `additionalProperties`: Whether additional properties are allowed (always set to `false` to ensure strict validation) + +## Usage + +The schemas can be used to validate the configuration of embedding functions using the `validate_config` function: + +```python +from chromadb.utils.embedding_functions.schemas import validate_config + +# Validate a configuration +config = { + "api_key_env_var": "CHROMA_OPENAI_API_KEY", + "model_name": "text-embedding-ada-002" +} +validate_config(config, "openai") +``` + +## Adding New Schemas + +To add a new schema: + +1. Create a new JSON file in this directory with the name of the embedding function (e.g., `new_function.json`) +2. Define the schema following the JSON Schema Draft-07 specification +3. Update the embedding function to use the schema for validation + +## Schema Versioning + +Each schema includes a version number to support future changes to embedding function configurations. When making changes to a schema, increment the version number to ensure backward compatibility. diff --git a/python/user_packages/Python313/site-packages/chromadb/utils/embedding_functions/schemas/__init__.py b/python/user_packages/Python313/site-packages/chromadb/utils/embedding_functions/schemas/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..4f7596cdc255b69de40eaff1daf26aaaa5a24a3d --- /dev/null +++ b/python/user_packages/Python313/site-packages/chromadb/utils/embedding_functions/schemas/__init__.py @@ -0,0 +1,19 @@ +from chromadb.utils.embedding_functions.schemas.schema_utils import ( + validate_config_schema, + load_schema, + get_schema_version, +) +from chromadb.utils.embedding_functions.schemas.registry import ( + get_available_schemas, + get_schema_info, + get_embedding_function_names, +) + +__all__ = [ + "validate_config_schema", + "load_schema", + "get_schema_version", + "get_available_schemas", + "get_schema_info", + "get_embedding_function_names", +] diff --git a/python/user_packages/Python313/site-packages/chromadb/utils/embedding_functions/schemas/__pycache__/__init__.cpython-313.pyc b/python/user_packages/Python313/site-packages/chromadb/utils/embedding_functions/schemas/__pycache__/__init__.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c4e8051a3bfd5b1978fcf2953dee91d031dc24d8 Binary files /dev/null and b/python/user_packages/Python313/site-packages/chromadb/utils/embedding_functions/schemas/__pycache__/__init__.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/chromadb/utils/embedding_functions/schemas/__pycache__/bm25_tokenizer.cpython-313.pyc b/python/user_packages/Python313/site-packages/chromadb/utils/embedding_functions/schemas/__pycache__/bm25_tokenizer.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6c003858c1769e08239e3e4e1fbf06333f3aa3f3 Binary files /dev/null and b/python/user_packages/Python313/site-packages/chromadb/utils/embedding_functions/schemas/__pycache__/bm25_tokenizer.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/chromadb/utils/embedding_functions/schemas/__pycache__/registry.cpython-313.pyc b/python/user_packages/Python313/site-packages/chromadb/utils/embedding_functions/schemas/__pycache__/registry.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1c39507ac4a82e398e7603340189e938ba6dc9b6 Binary files /dev/null and b/python/user_packages/Python313/site-packages/chromadb/utils/embedding_functions/schemas/__pycache__/registry.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/chromadb/utils/embedding_functions/schemas/__pycache__/schema_utils.cpython-313.pyc b/python/user_packages/Python313/site-packages/chromadb/utils/embedding_functions/schemas/__pycache__/schema_utils.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1caa4f4f80efe8c00ba9aeb7702722a123c5320f Binary files /dev/null and b/python/user_packages/Python313/site-packages/chromadb/utils/embedding_functions/schemas/__pycache__/schema_utils.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/chromadb/utils/embedding_functions/schemas/bm25_tokenizer.py b/python/user_packages/Python313/site-packages/chromadb/utils/embedding_functions/schemas/bm25_tokenizer.py new file mode 100644 index 0000000000000000000000000000000000000000..895f2edd5b0ea6d0efdfdc890f10bb29ef53486f --- /dev/null +++ b/python/user_packages/Python313/site-packages/chromadb/utils/embedding_functions/schemas/bm25_tokenizer.py @@ -0,0 +1,282 @@ +from __future__ import annotations + +import re +from typing import Iterable, List, Protocol, cast + + +DEFAULT_ENGLISH_STOPWORDS: List[str] = [ + "a", + "about", + "above", + "after", + "again", + "against", + "ain", + "all", + "am", + "an", + "and", + "any", + "are", + "aren", + "aren't", + "as", + "at", + "be", + "because", + "been", + "before", + "being", + "below", + "between", + "both", + "but", + "by", + "can", + "couldn", + "couldn't", + "d", + "did", + "didn", + "didn't", + "do", + "does", + "doesn", + "doesn't", + "doing", + "don", + "don't", + "down", + "during", + "each", + "few", + "for", + "from", + "further", + "had", + "hadn", + "hadn't", + "has", + "hasn", + "hasn't", + "have", + "haven", + "haven't", + "having", + "he", + "her", + "here", + "hers", + "herself", + "him", + "himself", + "his", + "how", + "i", + "if", + "in", + "into", + "is", + "isn", + "isn't", + "it", + "it's", + "its", + "itself", + "just", + "ll", + "m", + "ma", + "me", + "mightn", + "mightn't", + "more", + "most", + "mustn", + "mustn't", + "my", + "myself", + "needn", + "needn't", + "no", + "nor", + "not", + "now", + "o", + "of", + "off", + "on", + "once", + "only", + "or", + "other", + "our", + "ours", + "ourselves", + "out", + "over", + "own", + "re", + "s", + "same", + "shan", + "shan't", + "she", + "she's", + "should", + "should've", + "shouldn", + "shouldn't", + "so", + "some", + "such", + "t", + "than", + "that", + "that'll", + "the", + "their", + "theirs", + "them", + "themselves", + "then", + "there", + "these", + "they", + "this", + "those", + "through", + "to", + "too", + "under", + "until", + "up", + "ve", + "very", + "was", + "wasn", + "wasn't", + "we", + "were", + "weren", + "weren't", + "what", + "when", + "where", + "which", + "while", + "who", + "whom", + "why", + "will", + "with", + "won", + "won't", + "wouldn", + "wouldn't", + "y", + "you", + "you'd", + "you'll", + "you're", + "you've", + "your", + "yours", + "yourself", + "yourselves", +] + + +DEFAULT_CHROMA_BM25_STOPWORDS: List[str] = list(DEFAULT_ENGLISH_STOPWORDS) + + +class SnowballStemmer(Protocol): + def stem(self, token: str) -> str: # pragma: no cover - protocol definition + ... + + +class _SnowballStemmerAdapter: + """Adapter that provides the uniform `stem` API used across languages.""" + + def __init__(self) -> None: + try: + import snowballstemmer + except ImportError: + raise ValueError( + "The snowballstemmer python package is not installed. Please install it with `pip install snowballstemmer`" + ) + + self._stemmer = snowballstemmer.stemmer("english") + + def stem(self, token: str) -> str: + return cast(str, self._stemmer.stemWord(token)) + + +def get_english_stemmer() -> SnowballStemmer: + """Return a Snowball stemmer for English.""" + return _SnowballStemmerAdapter() + + +class Bm25Tokenizer: + """Tokenizer with stopword filtering and stemming used by BM25 embeddings.""" + + def __init__( + self, + stemmer: SnowballStemmer, + stopwords: Iterable[str], + token_max_length: int, + ) -> None: + self._stemmer = stemmer + self._stopwords = {word.lower() for word in stopwords} + self._token_max_length = token_max_length + self._non_alphanumeric_pattern = re.compile(r"[^\w\s]+", flags=re.UNICODE) + + def _remove_non_alphanumeric(self, text: str) -> str: + return self._non_alphanumeric_pattern.sub(" ", text) + + @staticmethod + def _simple_tokenize(text: str) -> List[str]: + return [token for token in text.lower().split() if token] + + def tokenize(self, text: str) -> List[str]: + cleaned = self._remove_non_alphanumeric(text) + raw_tokens = self._simple_tokenize(cleaned) + + tokens: List[str] = [] + for token in raw_tokens: + if token in self._stopwords: + continue + + if len(token) > self._token_max_length: + continue + + stemmed = self._stemmer.stem(token).strip() + if stemmed: + tokens.append(stemmed) + + return tokens + + +class Murmur3AbsHasher: + def __init__(self, seed: int = 0) -> None: + try: + import mmh3 + except ImportError: + raise ValueError( + "The murmurhash3 python package is not installed. Please install it with `pip install murmurhash3`" + ) + self.hasher = mmh3.hash + self.seed = seed + + def hash(self, token: str) -> int: + return cast(int, abs(self.hasher(token, seed=self.seed))) + + +__all__ = [ + "Bm25Tokenizer", + "DEFAULT_CHROMA_BM25_STOPWORDS", + "DEFAULT_ENGLISH_STOPWORDS", + "SnowballStemmer", + "get_english_stemmer", + "Murmur3AbsHasher", +] diff --git a/python/user_packages/Python313/site-packages/chromadb/utils/embedding_functions/schemas/registry.py b/python/user_packages/Python313/site-packages/chromadb/utils/embedding_functions/schemas/registry.py new file mode 100644 index 0000000000000000000000000000000000000000..02de07a0a9205997b114c51abe52bc6faf9c435f --- /dev/null +++ b/python/user_packages/Python313/site-packages/chromadb/utils/embedding_functions/schemas/registry.py @@ -0,0 +1,55 @@ +""" +Schema Registry for Embedding Functions + +This module provides a registry of all available schemas for embedding functions. +It can be used to get information about available schemas and their versions. +""" + +from typing import Dict, List, Set +import os +import json +from .schema_utils import SCHEMAS_DIR + + +def get_available_schemas() -> List[str]: + """ + Get a list of all available schemas. + + Returns: + A list of schema names (without .json extension) + """ + schemas = [] + for filename in os.listdir(SCHEMAS_DIR): + if filename.endswith(".json") and filename != "base_schema.json": + schemas.append(filename[:-5]) # Remove .json extension + return schemas + + +def get_schema_info() -> Dict[str, Dict[str, str]]: + """ + Get information about all available schemas. + + Returns: + A dictionary mapping schema names to information about the schema + """ + schema_info = {} + for schema_name in get_available_schemas(): + schema_path = os.path.join(SCHEMAS_DIR, f"{schema_name}.json") + with open(schema_path, "r") as f: + schema = json.load(f) + schema_info[schema_name] = { + "version": schema.get("version", "1.0.0"), + "title": schema.get("title", ""), + "description": schema.get("description", ""), + } + return schema_info + + +def get_embedding_function_names() -> Set[str]: + """ + Get a set of all embedding function names that have schemas. + + Returns: + A set of embedding function names + """ + return set(get_available_schemas()) diff --git a/python/user_packages/Python313/site-packages/chromadb/utils/embedding_functions/schemas/schema_utils.py b/python/user_packages/Python313/site-packages/chromadb/utils/embedding_functions/schemas/schema_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..a9c14cf384ebd96b3d7cb278d7c5fea34c44dd7d --- /dev/null +++ b/python/user_packages/Python313/site-packages/chromadb/utils/embedding_functions/schemas/schema_utils.py @@ -0,0 +1,85 @@ +import json +import os +from typing import Dict, Any, cast +import jsonschema +from jsonschema import ValidationError + +# Path to the schemas directory +SCHEMAS_DIR = os.path.join( + os.path.dirname( + os.path.dirname(os.path.dirname(os.path.dirname(os.path.dirname(__file__)))) + ), + "schemas", + "embedding_functions", +) + +cached_schemas: Dict[str, Dict[str, Any]] = {} + + +def load_schema(schema_name: str) -> Dict[str, Any]: + """ + Load a JSON schema from the schemas directory. + + Args: + schema_name: Name of the schema file (without .json extension) + + Returns: + The loaded schema as a dictionary + + Raises: + FileNotFoundError: If the schema file does not exist + json.JSONDecodeError: If the schema file is not valid JSON + """ + if schema_name in cached_schemas: + return cached_schemas[schema_name] + schema_path = os.path.join(SCHEMAS_DIR, f"{schema_name}.json") + with open(schema_path, "r") as f: + schema = cast(Dict[str, Any], json.load(f)) + cached_schemas[schema_name] = schema + return schema + + +def validate_config_schema(config: Dict[str, Any], schema_name: str) -> None: + """ + Validate a configuration against a schema. + + Args: + config: Configuration to validate + schema_name: Name of the schema file (without .json extension) + + Raises: + ValidationError: If the configuration does not match the schema + FileNotFoundError: If the schema file does not exist + json.JSONDecodeError: If the schema file is not valid JSON + """ + schema = load_schema(schema_name) + try: + jsonschema.validate(instance=config, schema=schema) + except ValidationError as e: + # Enhance the error message with more context + error_path = "/".join(str(path) for path in e.path) + error_message = ( + f"Config validation failed for schema '{schema_name}': {e.message}" + ) + if error_path: + error_message += f" at path '{error_path}'" + raise ValidationError(error_message) from e + + +def get_schema_version(schema_name: str) -> str: + """ + Get the version of a schema. + + Args: + schema_name: Name of the schema file (without .json extension) + + Returns: + The schema version as a string + + Raises: + FileNotFoundError: If the schema file does not exist + json.JSONDecodeError: If the schema file is not valid JSON + KeyError: If the schema does not have a version + """ + schema = load_schema(schema_name) + return cast(str, schema.get("version", "1.0.0")) diff --git a/python/user_packages/Python313/site-packages/chromadb/utils/embedding_functions/sentence_transformer_embedding_function.py b/python/user_packages/Python313/site-packages/chromadb/utils/embedding_functions/sentence_transformer_embedding_function.py new file mode 100644 index 0000000000000000000000000000000000000000..2ddcef6bf2cfe698e0aa8a23beb98a72c45badb7 --- /dev/null +++ b/python/user_packages/Python313/site-packages/chromadb/utils/embedding_functions/sentence_transformer_embedding_function.py @@ -0,0 +1,121 @@ +from chromadb.api.types import EmbeddingFunction, Space, Embeddings, Documents +from typing import List, Dict, Any +import numpy as np +from chromadb.utils.embedding_functions.schemas import validate_config_schema + + +class SentenceTransformerEmbeddingFunction(EmbeddingFunction[Documents]): + # Since we do dynamic imports we have to type this as Any + models: Dict[str, Any] = {} + + # If you have a beefier machine, try "gtr-t5-large". + # for a full list of options: https://huggingface.co/sentence-transformers, https://www.sbert.net/docs/pretrained_models.html + def __init__( + self, + model_name: str = "all-MiniLM-L6-v2", + device: str = "cpu", + normalize_embeddings: bool = False, + **kwargs: Any, + ): + """Initialize SentenceTransformerEmbeddingFunction. + + Args: + model_name (str, optional): Identifier of the SentenceTransformer model, defaults to "all-MiniLM-L6-v2" + device (str, optional): Device used for computation, defaults to "cpu" + normalize_embeddings (bool, optional): Whether to normalize returned vectors, defaults to False + **kwargs: Additional arguments to pass to the SentenceTransformer model. + """ + try: + from sentence_transformers import SentenceTransformer + except ImportError: + raise ValueError( + "The sentence_transformers python package is not installed. Please install it with `pip install sentence_transformers`" + ) + + self.model_name = model_name + self.device = device + self.normalize_embeddings = normalize_embeddings + for key, value in kwargs.items(): + if not isinstance(value, (str, int, float, bool, list, dict, tuple)): + raise ValueError(f"Keyword argument {key} is not a primitive type") + self.kwargs = kwargs + + if model_name not in self.models: + self.models[model_name] = SentenceTransformer( + model_name_or_path=model_name, device=device, **kwargs + ) + self._model = self.models[model_name] + + def __call__(self, input: Documents) -> Embeddings: + """Generate embeddings for the given documents. + + Args: + input: Documents to generate embeddings for. + + Returns: + Embeddings for the documents. + """ + embeddings = self._model.encode( + list(input), + convert_to_numpy=True, + normalize_embeddings=self.normalize_embeddings, + ) + + return [np.array(embedding, dtype=np.float32) for embedding in embeddings] + + @staticmethod + def name() -> str: + return "sentence_transformer" + + def default_space(self) -> Space: + # If normalize_embeddings is True, cosine is equivalent to dot product + return "cosine" + + def supported_spaces(self) -> List[Space]: + return ["cosine", "l2", "ip"] + + @staticmethod + def build_from_config(config: Dict[str, Any]) -> "EmbeddingFunction[Documents]": + model_name = config.get("model_name") + device = config.get("device") + normalize_embeddings = config.get("normalize_embeddings") + kwargs = config.get("kwargs", {}) + + if model_name is None or device is None or normalize_embeddings is None: + assert False, "This code should not be reached" + + return SentenceTransformerEmbeddingFunction( + model_name=model_name, + device=device, + normalize_embeddings=normalize_embeddings, + **kwargs, + ) + + def get_config(self) -> Dict[str, Any]: + return { + "model_name": self.model_name, + "device": self.device, + "normalize_embeddings": self.normalize_embeddings, + "kwargs": self.kwargs, + } + + def validate_config_update( + self, old_config: Dict[str, Any], new_config: Dict[str, Any] + ) -> None: + # model_name is also used as the identifier for model path if stored locally. + # Users should be able to change the path if needed, so we should not validate that. + # e.g. moving file path from /v1/my-model.bin to /v2/my-model.bin + return + + @staticmethod + def validate_config(config: Dict[str, Any]) -> None: + """ + Validate the configuration using the JSON schema. + + Args: + config: Configuration to validate + + Raises: + ValidationError: If the configuration does not match the schema + """ + validate_config_schema(config, "sentence_transformer") diff --git a/python/user_packages/Python313/site-packages/chromadb/utils/embedding_functions/text2vec_embedding_function.py b/python/user_packages/Python313/site-packages/chromadb/utils/embedding_functions/text2vec_embedding_function.py new file mode 100644 index 0000000000000000000000000000000000000000..1de67f66e40a4d23943a8b798bf5679cce39c460 --- /dev/null +++ b/python/user_packages/Python313/site-packages/chromadb/utils/embedding_functions/text2vec_embedding_function.py @@ -0,0 +1,90 @@ +from chromadb.api.types import EmbeddingFunction, Space, Embeddings, Documents +from chromadb.utils.embedding_functions.schemas import validate_config_schema +from typing import List, Dict, Any +import numpy as np + + +class Text2VecEmbeddingFunction(EmbeddingFunction[Documents]): + """ + This class is used to generate embeddings for a list of texts using the Text2Vec model. + """ + + def __init__(self, model_name: str = "shibing624/text2vec-base-chinese"): + """ + Initialize the Text2VecEmbeddingFunction. + + Args: + model_name (str, optional): The name of the model to use for text embeddings. + Defaults to "shibing624/text2vec-base-chinese". + """ + try: + from text2vec import SentenceModel + except ImportError: + raise ValueError( + "The text2vec python package is not installed. Please install it with `pip install text2vec`" + ) + + self.model_name = model_name + self._model = SentenceModel(model_name_or_path=model_name) + + def __call__(self, input: Documents) -> Embeddings: + """ + Generate embeddings for the given documents. + + Args: + input: Documents or images to generate embeddings for. + + Returns: + Embeddings for the documents. + """ + # Text2Vec only works with text documents + if not all(isinstance(item, str) for item in input): + raise ValueError("Text2Vec only supports text documents, not images") + + embeddings = self._model.encode(list(input), convert_to_numpy=True) + + # Convert to numpy arrays + return [np.array(embedding, dtype=np.float32) for embedding in embeddings] + + @staticmethod + def name() -> str: + return "text2vec" + + def default_space(self) -> Space: + return "cosine" + + def supported_spaces(self) -> List[Space]: + return ["cosine", "l2", "ip"] + + @staticmethod + def build_from_config(config: Dict[str, Any]) -> "EmbeddingFunction[Documents]": + model_name = config.get("model_name") + + if model_name is None: + assert False, "This code should not be reached" + + return Text2VecEmbeddingFunction(model_name=model_name) + + def get_config(self) -> Dict[str, Any]: + return {"model_name": self.model_name} + + def validate_config_update( + self, old_config: Dict[str, Any], new_config: Dict[str, Any] + ) -> None: + # model_name is also used as the identifier for model path if stored locally. + # Users should be able to change the path if needed, so we should not validate that. + # e.g. moving file path from /v1/my-model.bin to /v2/my-model.bin + return + + @staticmethod + def validate_config(config: Dict[str, Any]) -> None: + """ + Validate the configuration using the JSON schema. + + Args: + config: Configuration to validate + + Raises: + ValidationError: If the configuration does not match the schema + """ + validate_config_schema(config, "text2vec") diff --git a/python/user_packages/Python313/site-packages/chromadb/utils/embedding_functions/together_ai_embedding_function.py b/python/user_packages/Python313/site-packages/chromadb/utils/embedding_functions/together_ai_embedding_function.py new file mode 100644 index 0000000000000000000000000000000000000000..7489731eb69d000b4d8dce5ab33fc5dcae330bfe --- /dev/null +++ b/python/user_packages/Python313/site-packages/chromadb/utils/embedding_functions/together_ai_embedding_function.py @@ -0,0 +1,146 @@ +from chromadb.api.types import ( + Embeddings, + Documents, + EmbeddingFunction, + Space, +) +from typing import List, Dict, Any, Optional +import os +from chromadb.utils.embedding_functions.schemas import validate_config_schema +from typing import cast +import warnings + +ENDPOINT = "https://api.together.xyz/v1/embeddings" + + +class TogetherAIEmbeddingFunction(EmbeddingFunction[Documents]): + """ + This class is used to get embeddings for a list of texts using the Together AI API. + """ + + def __init__( + self, + model_name: str, + api_key: Optional[str] = None, + api_key_env_var: str = "CHROMA_TOGETHER_AI_API_KEY", + ): + """ + Initialize the TogetherAIEmbeddingFunction. See the docs for supported models here: + https://docs.together.ai/docs/serverless-models#embedding-models + + Args: + model_name: The name of the model to use for text embeddings. + api_key: The API key to use for the Together AI API. + api_key_env_var: The environment variable to use for the Together AI API key. + """ + try: + import httpx + except ImportError: + raise ValueError( + "The httpx python package is not installed. Please install it with `pip install httpx`" + ) + + if api_key is not None: + warnings.warn( + "Direct api_key configuration will not be persisted. " + "Please use environment variables via api_key_env_var for persistent storage.", + DeprecationWarning, + ) + + self.model_name = model_name + + if os.getenv("TOGETHER_API_KEY") is not None: + self.api_key_env_var = "TOGETHER_API_KEY" + else: + self.api_key_env_var = api_key_env_var + + self.api_key = api_key or os.getenv(self.api_key_env_var) + if not self.api_key: + raise ValueError( + f"The {self.api_key_env_var} environment variable is not set." + ) + + self._session = httpx.Client() + self._session.headers.update( + { + "Authorization": f"Bearer {self.api_key}", + "Content-Type": "application/json", + "accept": "application/json", + } + ) + + def __call__(self, input: Documents) -> Embeddings: + """ + Embed a list of texts using the Together AI API. + + Args: + input: A list of texts to embed. + """ + + if not input: + raise ValueError("Input is required") + + if not isinstance(input, list): + raise ValueError("Input must be a list") + + if not all(isinstance(item, str) for item in input): + raise ValueError("All items in input must be strings") + + response = self._session.post( + ENDPOINT, + json={"model": self.model_name, "input": input}, + ) + + response.raise_for_status() + + data = response.json() + + embeddings = [item["embedding"] for item in data["data"]] + + return cast(Embeddings, embeddings) + + @staticmethod + def name() -> str: + return "together_ai" + + def default_space(self) -> Space: + return "cosine" + + def supported_spaces(self) -> List[Space]: + return ["cosine", "l2", "ip"] + + @staticmethod + def build_from_config(config: Dict[str, Any]) -> "EmbeddingFunction[Documents]": + api_key_env_var = config.get("api_key_env_var") + model_name = config.get("model_name") + + if api_key_env_var is None or model_name is None: + raise ValueError("api_key_env_var and model_name must be provided") + + return TogetherAIEmbeddingFunction( + model_name=model_name, api_key_env_var=api_key_env_var + ) + + def get_config(self) -> Dict[str, Any]: + return { + "api_key_env_var": self.api_key_env_var, + "model_name": self.model_name, + } + + def validate_config_update( + self, old_config: Dict[str, Any], new_config: Dict[str, Any] + ) -> None: + if "model_name" in new_config: + raise ValueError( + "The model name cannot be changed after the embedding function has been initialized." + ) + + @staticmethod + def validate_config(config: Dict[str, Any]) -> None: + """ + Validate the configuration using the JSON schema. + + Args: + config: Configuration to validate + """ + validate_config_schema(config, "together_ai") diff --git a/python/user_packages/Python313/site-packages/chromadb/utils/embedding_functions/utils.py b/python/user_packages/Python313/site-packages/chromadb/utils/embedding_functions/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..aa045e1de92cc8bcea990f8d7f05053c2b4ef5fb --- /dev/null +++ b/python/user_packages/Python313/site-packages/chromadb/utils/embedding_functions/utils.py @@ -0,0 +1,26 @@ +import base64 +import os +import numpy as np +from typing import TYPE_CHECKING + +DEFAULT_CHROMA_EMBED_URL = "https://embed.trychroma.com" + + +def get_chroma_embed_url() -> str: + """Return embed base URL from CHROMA_EMBED_URL or default without trailing slash.""" + return (os.environ.get("CHROMA_EMBED_URL") or DEFAULT_CHROMA_EMBED_URL).rstrip("/") + +if TYPE_CHECKING: + from chromadb.api.shared_system_client import SharedSystemClient + + +def _get_shared_system_client() -> "type[SharedSystemClient]": + """Lazy import of SharedSystemClient to avoid circular imports.""" + from chromadb.api.shared_system_client import SharedSystemClient + + return SharedSystemClient + + +def decode_embedding(b64_string: str): + """Decode a base64-encoded int8 embedding.""" + return np.frombuffer(base64.b64decode(b64_string), dtype=np.int8).astype(np.float32) diff --git a/python/user_packages/Python313/site-packages/chromadb/utils/embedding_functions/voyageai_embedding_function.py b/python/user_packages/Python313/site-packages/chromadb/utils/embedding_functions/voyageai_embedding_function.py new file mode 100644 index 0000000000000000000000000000000000000000..c67647988d2550e33b7d3ead38c39fc189acb2f7 --- /dev/null +++ b/python/user_packages/Python313/site-packages/chromadb/utils/embedding_functions/voyageai_embedding_function.py @@ -0,0 +1,142 @@ +from chromadb.api.types import EmbeddingFunction, Space, Embeddings, Documents +from chromadb.utils.embedding_functions.schemas import validate_config_schema +from typing import List, Dict, Any, Optional +import os +import numpy as np +import warnings + + +class VoyageAIEmbeddingFunction(EmbeddingFunction[Documents]): + """ + This class is used to generate embeddings for a list of texts using the VoyageAI API. + """ + + def __init__( + self, + api_key: Optional[str] = None, + model_name: str = "voyage-large-2", + api_key_env_var: str = "CHROMA_VOYAGE_API_KEY", + input_type: Optional[str] = None, + truncation: bool = True, + ): + """ + Initialize the VoyageAIEmbeddingFunction. + + Args: + api_key_env_var (str, optional): Environment variable name that contains your API key for the VoyageAI API. + Defaults to "CHROMA_VOYAGE_API_KEY". + model_name (str, optional): The name of the model to use for text embeddings. + Defaults to "voyage-large-2". + api_key (str, optional): API key for the VoyageAI API. If not provided, will look for it in the environment variable. + input_type (str, optional): The type of input to use for the VoyageAI API. + Defaults to None. + truncation (bool): Whether to truncate the input text. + Defaults to True. + """ + try: + import voyageai + except ImportError: + raise ValueError( + "The voyageai python package is not installed. Please install it with `pip install voyageai`" + ) + + if api_key is not None: + warnings.warn( + "Direct api_key configuration will not be persisted. " + "Please use environment variables via api_key_env_var for persistent storage.", + DeprecationWarning, + ) + + if os.getenv("VOYAGE_API_KEY") is not None: + self.api_key_env_var = "VOYAGE_API_KEY" + else: + self.api_key_env_var = api_key_env_var + + self.api_key = api_key or os.getenv(self.api_key_env_var) + if not self.api_key: + raise ValueError( + f"The {self.api_key_env_var} environment variable is not set." + ) + + self.model_name = model_name + self.input_type = input_type + self.truncation = truncation + self._client = voyageai.Client(api_key=self.api_key) + + def __call__(self, input: Documents) -> Embeddings: + """ + Generate embeddings for the given documents. + + Args: + input: Documents to generate embeddings for. + + Returns: + Embeddings for the documents. + """ + embeddings = self._client.embed( + texts=input, + model=self.model_name, + input_type=self.input_type, + truncation=self.truncation, + ) + + # Convert to numpy arrays + return [ + np.array(embedding, dtype=np.float32) for embedding in embeddings.embeddings + ] + + @staticmethod + def name() -> str: + return "voyageai" + + def default_space(self) -> Space: + return "cosine" + + def supported_spaces(self) -> List[Space]: + return ["cosine", "l2", "ip"] + + @staticmethod + def build_from_config(config: Dict[str, Any]) -> "EmbeddingFunction[Documents]": + api_key_env_var = config.get("api_key_env_var") + model_name = config.get("model_name") + input_type = config.get("input_type") + truncation = config.get("truncation") + + if api_key_env_var is None or model_name is None: + assert False, "This code should not be reached" + + return VoyageAIEmbeddingFunction( + api_key_env_var=api_key_env_var, + model_name=model_name, + input_type=input_type, + truncation=truncation if truncation is not None else True, + ) + + def get_config(self) -> Dict[str, Any]: + return { + "api_key_env_var": self.api_key_env_var, + "model_name": self.model_name, + "input_type": self.input_type, + "truncation": self.truncation, + } + + def validate_config_update( + self, old_config: Dict[str, Any], new_config: Dict[str, Any] + ) -> None: + if "model_name" in new_config: + raise ValueError( + "The model name cannot be changed after the embedding function has been initialized." + ) + + @staticmethod + def validate_config(config: Dict[str, Any]) -> None: + """ + Validate the configuration using the JSON schema. + + Args: + config: Configuration to validate + + Raises: + ValidationError: If the configuration does not match the schema + """ + validate_config_schema(config, "voyageai") diff --git a/python/user_packages/Python313/site-packages/chromadb/utils/fastapi.py b/python/user_packages/Python313/site-packages/chromadb/utils/fastapi.py new file mode 100644 index 0000000000000000000000000000000000000000..8179cd9c9b6e48822e777bb42f9c169b32c20a7c --- /dev/null +++ b/python/user_packages/Python313/site-packages/chromadb/utils/fastapi.py @@ -0,0 +1,18 @@ +from uuid import UUID +from starlette.responses import JSONResponse + +from chromadb.errors import ChromaError, InvalidUUIDError + + +def fastapi_json_response(error: ChromaError) -> JSONResponse: + return JSONResponse( + content={"error": error.name(), "message": error.message()}, + status_code=error.code(), + ) + + +def string_to_uuid(uuid_str: str) -> UUID: + try: + return UUID(uuid_str) + except ValueError: + raise InvalidUUIDError(f"Could not parse {uuid_str} as a UUID") diff --git a/python/user_packages/Python313/site-packages/chromadb/utils/lru_cache.py b/python/user_packages/Python313/site-packages/chromadb/utils/lru_cache.py new file mode 100644 index 0000000000000000000000000000000000000000..92450e7e83fd7de1b232efca87fad430de19d6f1 --- /dev/null +++ b/python/user_packages/Python313/site-packages/chromadb/utils/lru_cache.py @@ -0,0 +1,32 @@ +from collections import OrderedDict +from typing import Any, Callable, Generic, Optional, TypeVar + + +K = TypeVar("K") +V = TypeVar("V") + + +class LRUCache(Generic[K, V]): + """A simple LRU cache implementation, based on the OrderedDict class, which allows + for a callback to be invoked when an item is evicted from the cache.""" + + def __init__(self, capacity: int, callback: Optional[Callable[[K, V], Any]] = None): + self.capacity = capacity + self.cache: OrderedDict[K, V] = OrderedDict() + self.callback = callback + + def get(self, key: K) -> Optional[V]: + if key not in self.cache: + return None + value = self.cache.pop(key) + self.cache[key] = value + return value + + def set(self, key: K, value: V) -> None: + if key in self.cache: + self.cache.pop(key) + elif len(self.cache) == self.capacity: + evicted_key, evicted_value = self.cache.popitem(last=False) + if self.callback: + self.callback(evicted_key, evicted_value) + self.cache[key] = value diff --git a/python/user_packages/Python313/site-packages/chromadb/utils/messageid.py b/python/user_packages/Python313/site-packages/chromadb/utils/messageid.py new file mode 100644 index 0000000000000000000000000000000000000000..7df4bc64f128944d6a5688496111482cb9854bd2 --- /dev/null +++ b/python/user_packages/Python313/site-packages/chromadb/utils/messageid.py @@ -0,0 +1,8 @@ +def int_to_bytes(int: int) -> bytes: + """Convert int to a 24 byte big endian byte string""" + return int.to_bytes(24, "big") + + +def bytes_to_int(bytes: bytes) -> int: + """Convert a 24 byte big endian byte string to an int""" + return int.from_bytes(bytes, "big") diff --git a/python/user_packages/Python313/site-packages/chromadb/utils/read_write_lock.py b/python/user_packages/Python313/site-packages/chromadb/utils/read_write_lock.py new file mode 100644 index 0000000000000000000000000000000000000000..b6d78cc9492676b56ca8466772b86686d62f80d3 --- /dev/null +++ b/python/user_packages/Python313/site-packages/chromadb/utils/read_write_lock.py @@ -0,0 +1,74 @@ +import threading +from types import TracebackType +from typing import Optional, Type + + +class ReadWriteLock: + """A lock object that allows many simultaneous "read locks", but + only one "write lock." """ + + def __init__(self) -> None: + self._read_ready = threading.Condition(threading.RLock()) + self._readers = 0 + + def acquire_read(self) -> None: + """Acquire a read lock. Blocks only if a thread has + acquired the write lock.""" + self._read_ready.acquire() + try: + self._readers += 1 + finally: + self._read_ready.release() + + def release_read(self) -> None: + """Release a read lock.""" + self._read_ready.acquire() + try: + self._readers -= 1 + if not self._readers: + self._read_ready.notify_all() + finally: + self._read_ready.release() + + def acquire_write(self) -> None: + """Acquire a write lock. Blocks until there are no + acquired read or write locks.""" + self._read_ready.acquire() + while self._readers > 0: + self._read_ready.wait() + + def release_write(self) -> None: + """Release a write lock.""" + self._read_ready.release() + + +class ReadRWLock: + def __init__(self, rwLock: ReadWriteLock): + self.rwLock = rwLock + + def __enter__(self) -> None: + self.rwLock.acquire_read() + + def __exit__( + self, + exc_type: Optional[Type[BaseException]], + exc_value: Optional[BaseException], + traceback: Optional[TracebackType], + ) -> None: + self.rwLock.release_read() + + +class WriteRWLock: + def __init__(self, rwLock: ReadWriteLock): + self.rwLock = rwLock + + def __enter__(self) -> None: + self.rwLock.acquire_write() + + def __exit__( + self, + exc_type: Optional[Type[BaseException]], + exc_value: Optional[BaseException], + traceback: Optional[TracebackType], + ) -> None: + self.rwLock.release_write() diff --git a/python/user_packages/Python313/site-packages/chromadb/utils/rendezvous_hash.py b/python/user_packages/Python313/site-packages/chromadb/utils/rendezvous_hash.py new file mode 100644 index 0000000000000000000000000000000000000000..27847b00ef5f4b560a09310e1870c3dea77ffb4c --- /dev/null +++ b/python/user_packages/Python313/site-packages/chromadb/utils/rendezvous_hash.py @@ -0,0 +1,68 @@ +# An implementation of https://en.wikipedia.org/wiki/Rendezvous_hashing +from typing import Callable, List, Tuple +import mmh3 +import heapq + +Hasher = Callable[[str, str], int] +Member = str +Members = List[str] +Key = str + + +def assign( + key: Key, members: Members, hasher: Hasher, replication: int +) -> List[Member]: + """Assigns a key to a member using the rendezvous hashing algorithm + Args: + key: The key to assign + members: The list of members to assign the key to + hasher: The hashing function to use + replication: The number of members to assign the key to + Returns: + A list of members that the key has been assigned to + """ + + if replication > len(members): + raise ValueError( + "Replication factor cannot be greater than the number of members" + ) + if len(members) == 0: + raise ValueError("Cannot assign key to empty memberlist") + if len(members) == 1: + # Don't copy the input list for some safety + return [members[0]] + if key == "": + raise ValueError("Cannot assign empty key") + + member_score_heap: List[Tuple[int, Member]] = [] + for member in members: + score = -hasher(member, key) + # Invert the score since heapq is a min heap + heapq.heappush(member_score_heap, (score, member)) + + output_members: List[Member] = [] + for _ in range(replication): + member_and_score = heapq.heappop(member_score_heap) + output_members.append(member_and_score[1]) + + return output_members + + +def merge_hashes(x: int, y: int) -> int: + """murmurhash3 mix 64-bit""" + acc = x ^ y + acc ^= acc >> 33 + acc = ( + acc * 0xFF51AFD7ED558CCD + ) % 2**64 # We need to mod here to prevent python from using arbitrary size int + acc ^= acc >> 33 + acc = (acc * 0xC4CEB9FE1A85EC53) % 2**64 + acc ^= acc >> 33 + return acc + + +def murmur3hasher(member: Member, key: Key) -> int: + """Hashes the key and member using the murmur3 hashing algorithm""" + member_hash = mmh3.hash64(member, signed=False)[0] + key_hash = mmh3.hash64(key, signed=False)[0] + return merge_hashes(member_hash, key_hash) diff --git a/python/user_packages/Python313/site-packages/chromadb/utils/results.py b/python/user_packages/Python313/site-packages/chromadb/utils/results.py new file mode 100644 index 0000000000000000000000000000000000000000..bdc80961ef647a2b70adebee3d54db0673ddb528 --- /dev/null +++ b/python/user_packages/Python313/site-packages/chromadb/utils/results.py @@ -0,0 +1,125 @@ +from typing import List, Dict, Any, Optional, Union +import numpy as np +import pandas as pd +from chromadb.api.types import QueryResult, GetResult + + +def _transform_embeddings( + embeddings: Optional[List[np.ndarray]], # type: ignore +) -> Optional[Union[List[List[float]], List[np.ndarray]]]: # type: ignore + """ + Transform embeddings from numpy arrays to lists of floats. + This is a shared helper function to avoid duplicating the transformation logic. + """ + if embeddings is None: + return None + return ( + [emb.tolist() for emb in embeddings] + if isinstance(embeddings[0], np.ndarray) + else embeddings + ) + + +def _add_query_fields( + data_dict: Dict[str, Any], + query_result: QueryResult, + query_idx: int, +) -> None: + """ + Helper function to add fields from a query result to a dictionary. + Handles the nested array structure specific to query results. + + Args: + data_dict: Dictionary to add the fields to + query_result: QueryResult containing the data + query_idx: Index of the current query being processed + """ + for field in query_result["included"]: + value = query_result.get(field) + if value is not None: + key = field.rstrip("s") # DF naming convention is not plural + if field == "embeddings": + value = _transform_embeddings(value) # type: ignore + if isinstance(value, list) and len(value) > 0: + value = value[query_idx] # type: ignore + data_dict[key] = value + + +def _add_get_fields( + data_dict: Dict[str, Any], + get_result: GetResult, +) -> None: + """ + Helper function to add fields from a get result to a dictionary. + Handles the flat array structure specific to get results. + + Args: + data_dict: Dictionary to add the fields to + get_result: GetResult containing the data + """ + for field in get_result["included"]: + value = get_result.get(field) + if value is not None: + key = field.rstrip("s") # DF naming convention is not plural + if field == "embeddings": + value = _transform_embeddings(value) # type: ignore + data_dict[key] = value + + +def query_result_to_dfs(query_result: QueryResult) -> List["pd.DataFrame"]: + """ + Function to convert QueryResult to list of DataFrames. + Handles the nested array structure specific to query results. + Column order is defined by the order of the fields in the QueryResult. + + Args: + query_result: QueryResult to convert to DataFrames. + + Returns: + List of DataFrames. + """ + try: + import pandas as pd + except ImportError: + raise ImportError("pandas is required to convert query results to DataFrames.") + + dfs = [] + num_queries = len(query_result["ids"]) + + for i in range(num_queries): + data_for_df: Dict[str, Any] = {} + data_for_df["id"] = query_result["ids"][i] + + _add_query_fields(data_for_df, query_result, i) + + df = pd.DataFrame(data_for_df) + df.set_index("id", inplace=True) + dfs.append(df) + return dfs + + +def get_result_to_df(get_result: GetResult) -> "pd.DataFrame": + """ + Function to convert GetResult to a DataFrame. + Handles the flat array structure specific to get results. + Column order is defined by the order of the fields in the GetResult. + + Args: + get_result: GetResult to convert to a DataFrame. + + Returns: + DataFrame. + """ + try: + import pandas as pd + except ImportError: + raise ImportError("pandas is required to convert get results to a DataFrame.") + + data_for_df: Dict[str, Any] = {} + data_for_df["id"] = get_result["ids"] + + _add_get_fields(data_for_df, get_result) + + df = pd.DataFrame(data_for_df) + df.set_index("id", inplace=True) + return df diff --git a/python/user_packages/Python313/site-packages/chromadb/utils/sparse_embedding_utils.py b/python/user_packages/Python313/site-packages/chromadb/utils/sparse_embedding_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..4e4d726ed14b8f0571f7892d31d5262db8c34afc --- /dev/null +++ b/python/user_packages/Python313/site-packages/chromadb/utils/sparse_embedding_utils.py @@ -0,0 +1,49 @@ +from typing import List, Optional, Tuple +from chromadb.base_types import SparseVector + + +def normalize_sparse_vector( + indices: List[int], + values: List[float], + labels: Optional[List[str]] = None +) -> SparseVector: + """Normalize and create a SparseVector by sorting indices and values together. + + This function takes raw indices and values (which may be unsorted or have duplicates) + and returns a properly constructed SparseVector with sorted indices. + + Args: + indices: List of dimension indices (may be unsorted) + values: List of values corresponding to each index + labels: Optional list of string labels corresponding to each index + + Returns: + SparseVector with indices sorted in ascending order + + Raises: + ValueError: If indices and values have different lengths + ValueError: If there are duplicate indices (after sorting) + ValueError: If indices are negative + ValueError: If values are not numeric + ValueError: If labels is provided and has different length than indices + """ + if not indices: + return SparseVector(indices=[], values=[], labels=None) + + # Sort indices, values, and labels together by index + if labels is not None: + sorted_triples = sorted(zip(indices, values, labels), key=lambda x: x[0]) + sorted_indices, sorted_values, sorted_labels = zip(*sorted_triples) + return SparseVector( + indices=list(sorted_indices), + values=list(sorted_values), + labels=list(sorted_labels) + ) + else: + sorted_pairs = sorted(zip(indices, values), key=lambda x: x[0]) + sorted_indices, sorted_values = zip(*sorted_pairs) + return SparseVector( + indices=list(sorted_indices), + values=list(sorted_values), + labels=None + ) diff --git a/python/user_packages/Python313/site-packages/chromadb/utils/statistics.py b/python/user_packages/Python313/site-packages/chromadb/utils/statistics.py new file mode 100644 index 0000000000000000000000000000000000000000..a2847ca46002dcbec8e6e2569c0ffaddc8623916 --- /dev/null +++ b/python/user_packages/Python313/site-packages/chromadb/utils/statistics.py @@ -0,0 +1,272 @@ +"""Utility functions for managing collection statistics. + +This module provides standalone functions for enabling, disabling, and retrieving +statistics for ChromaDB collections. These functions work with the attached function +system to automatically compute metadata value frequencies. + +Example: + >>> from chromadb.utils.statistics import attach_statistics_function, get_statistics + >>> import chromadb + >>> + >>> client = chromadb.Client() + >>> collection = client.get_or_create_collection("my_collection") + >>> + >>> # Attach statistics function with output collection name + >>> attach_statistics_function(collection, "my_collection_statistics") + >>> + >>> # Add some data + >>> collection.add( + ... ids=["id1", "id2"], + ... documents=["doc1", "doc2"], + ... metadatas=[{"category": "A"}, {"category": "B"}] + ... ) + >>> + >>> # Get statistics from the named output collection + >>> stats = get_statistics(collection, "my_collection_statistics") + >>> print(stats) +""" + +from typing import TYPE_CHECKING, Optional, Dict, Any, cast, Tuple +from collections import defaultdict +from chromadb.api.types import OneOrMany, Where, maybe_cast_one_to_many +from chromadb.api.functions import STATISTICS_FUNCTION + +if TYPE_CHECKING: + from chromadb.api.models.Collection import Collection + from chromadb.api.models.AttachedFunction import AttachedFunction + + +def get_statistics_fn_name(collection: "Collection") -> str: + """Generate the default name for the statistics attached function. + + Args: + collection: The collection to generate the name for + + Returns: + str: The statistics function name + """ + return f"{collection.name}_stats" + + +def attach_statistics_function( + collection: "Collection", stats_collection_name: str +) -> Tuple["AttachedFunction", bool]: + """Attach statistics collection function to a collection. + + This attaches the statistics function which will automatically compute + and update metadata value frequencies whenever records are added, updated, + or deleted. + + Args: + collection: The collection to enable statistics for + stats_collection_name: Name of the collection where statistics will be stored. + + Returns: + Tuple of (AttachedFunction, created) where created is True if newly created, + False if already existed (idempotent request) + + Example: + >>> attached_fn, created = attach_statistics_function(collection, "my_collection_statistics") + >>> if created: + ... print("Statistics function newly attached") + >>> collection.add(ids=["id1"], documents=["doc1"], metadatas=[{"key": "value"}]) + >>> # Statistics are automatically computed + >>> stats = get_statistics(collection, "my_collection_statistics") + """ + return collection.attach_function( + function=STATISTICS_FUNCTION, + name=get_statistics_fn_name(collection), + output_collection=stats_collection_name, + params=None, + ) + + +def get_statistics_fn(collection: "Collection") -> "AttachedFunction": + """Get the statistics attached function for a collection. + + Args: + collection: The collection to get the statistics function for + + Returns: + AttachedFunction: The statistics function + + Raises: + NotFoundError: If statistics are not enabled + AssertionError: If the attached function is not a statistics function + """ + af = collection.get_attached_function(get_statistics_fn_name(collection)) + assert ( + af.function_name == "statistics" + ), "Attached function is not a statistics function" + return af + + +def detach_statistics_function( + collection: "Collection", delete_stats_collection: bool = False +) -> bool: + """Detach statistics collection function from a collection. + + Args: + collection: The collection to disable statistics for + delete_stats_collection: If True, also delete the statistics output collection. + Defaults to False. + + Returns: + bool: True if successful + + Example: + >>> detach_statistics_function(collection, delete_stats_collection=True) + """ + attached_fn = get_statistics_fn(collection) + return collection.detach_function( + attached_fn.name, delete_output_collection=delete_stats_collection + ) + + +def get_statistics( + collection: "Collection", + stats_collection_name: str, + keys: Optional[OneOrMany[str]] = None, +) -> Dict[str, Any]: + """Get the current statistics for a collection. + + Statistics include frequency counts for all metadata key-value pairs, + as well as a summary with the total record count. + + Args: + collection: The collection to get statistics for + stats_collection_name: Name of the statistics collection to read from. + keys: Optional metadata key(s) to filter statistics for. Can be a single key + string or a list of keys. If provided, only returns statistics for + those specific keys. + + Returns: + Dict[str, Any]: A dictionary with the structure: + { + "statistics": { + "key1": { + "value1": {"count": count, ...}, + "value2": {"count": count, ...} + }, + "key2": {...}, + ... + }, + "summary": { + "total_count": count + } + } + + Example: + >>> attach_statistics_function(collection, "my_collection_statistics") + >>> collection.add( + ... ids=["id1", "id2"], + ... documents=["doc1", "doc2"], + ... metadatas=[{"category": "A", "score": 10}, {"category": "B", "score": 10}] + ... ) + >>> # Wait for statistics to be computed + >>> stats = get_statistics(collection, "my_collection_statistics") + >>> print(stats) + { + "statistics": { + "category": { + "A": {"count": 1}, + "B": {"count": 1} + }, + "score": { + "10": {"count": 2} + } + }, + "summary": { + "total_count": 2 + } + } + + Raises: + ValueError: If more than 30 keys are provided in the keys filter. + """ + # Normalize keys to list + keys_list = maybe_cast_one_to_many(keys) + + # Validate keys count to avoid issues with large $in queries + MAX_KEYS = 30 + if keys_list is not None and len(keys_list) > MAX_KEYS: + raise ValueError( + f"Too many keys provided: {len(keys_list)}. " + f"Maximum allowed is {MAX_KEYS} keys per request. " + "Consider calling get_statistics multiple times with smaller key batches." + ) + + # Import here to avoid circular dependency + from chromadb.api.models.Collection import Collection + + # Get the statistics output collection model from the server + stats_collection_model = collection._client.get_collection( + name=stats_collection_name, + tenant=collection.tenant, + database=collection.database, + ) + + # Wrap it in a Collection object to access get/query methods + stats_collection = Collection( + client=collection._client, + model=stats_collection_model, + embedding_function=None, # Statistics collections don't need embedding functions + data_loader=None, + ) + + # Get all statistics records by paginating through the stats collection + stats: Dict[str, Dict[str, Dict[str, int]]] = defaultdict(lambda: defaultdict(dict)) + summary: Dict[str, Any] = {} + + offset = 0 + # When filtering by keys, also include "summary" entries to get total_count + where_filter: Optional[Where] = ( + cast(Where, {"key": {"$in": keys_list + ["summary"]}}) + if keys_list is not None + else None + ) + + while True: + page = stats_collection.get( + include=["metadatas"], offset=offset, where=where_filter + ) + + metadatas = page.get("metadatas") or [] + if not metadatas: + break + + for metadata in metadatas: + if metadata is None: + continue + + meta_key = metadata.get("key") + value = metadata.get("value") + value_label = metadata.get("value_label") + value_type = metadata.get("type") + count = metadata.get("count") + + if ( + meta_key is not None + and value is not None + and value_type is not None + and count is not None + ): + if meta_key == "summary": + if value == "total_count": + summary["total_count"] = count + else: + # Prioritize value_label if present, otherwise use value + stats_key = value_label if value_label is not None else value + assert isinstance(meta_key, str) + assert isinstance(stats_key, str) + assert isinstance(count, int) + stats[meta_key][stats_key]["count"] = count + + # Advance to next page using the actual number of items returned + offset += len(metadatas) + + result = {"statistics": dict(stats)} + if summary: + result["summary"] = summary + + return result diff --git a/python/user_packages/Python313/site-packages/chromadb_rust_bindings/__pycache__/__init__.cpython-313.pyc b/python/user_packages/Python313/site-packages/chromadb_rust_bindings/__pycache__/__init__.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6bea47c351eff59ffa4badabab3ade521181731a Binary files /dev/null and b/python/user_packages/Python313/site-packages/chromadb_rust_bindings/__pycache__/__init__.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/click-8.3.3.dist-info/licenses/LICENSE.txt b/python/user_packages/Python313/site-packages/click-8.3.3.dist-info/licenses/LICENSE.txt new file mode 100644 index 0000000000000000000000000000000000000000..d12a849186982399c537c5b9a8fd77bf2edd5eab --- /dev/null +++ b/python/user_packages/Python313/site-packages/click-8.3.3.dist-info/licenses/LICENSE.txt @@ -0,0 +1,28 @@ +Copyright 2014 Pallets + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: + +1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + +2. 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. + +3. Neither the name of the copyright holder 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. diff --git a/python/user_packages/Python313/site-packages/click/__pycache__/__init__.cpython-313.pyc b/python/user_packages/Python313/site-packages/click/__pycache__/__init__.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..28541bea83fce643a477d253c799e49c314c9bcd Binary files /dev/null and b/python/user_packages/Python313/site-packages/click/__pycache__/__init__.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/click/__pycache__/_compat.cpython-313.pyc b/python/user_packages/Python313/site-packages/click/__pycache__/_compat.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..092b2f14e82e93f1097d5ce437548b3305294380 Binary files /dev/null and b/python/user_packages/Python313/site-packages/click/__pycache__/_compat.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/click/__pycache__/_termui_impl.cpython-313.pyc b/python/user_packages/Python313/site-packages/click/__pycache__/_termui_impl.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9519e4e93022ef456ed6daf3dfa36f967f7a9c06 Binary files /dev/null and b/python/user_packages/Python313/site-packages/click/__pycache__/_termui_impl.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/click/__pycache__/_textwrap.cpython-313.pyc b/python/user_packages/Python313/site-packages/click/__pycache__/_textwrap.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f363dbb2cb9914f03cbf3ed2372fc2ada08b1ce2 Binary files /dev/null and b/python/user_packages/Python313/site-packages/click/__pycache__/_textwrap.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/click/__pycache__/_utils.cpython-313.pyc b/python/user_packages/Python313/site-packages/click/__pycache__/_utils.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..fc8d4ffe1746e6e68a18acf4bd5af93009d6749e Binary files /dev/null and b/python/user_packages/Python313/site-packages/click/__pycache__/_utils.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/click/__pycache__/_winconsole.cpython-313.pyc b/python/user_packages/Python313/site-packages/click/__pycache__/_winconsole.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4dc8062afe623c67d07d82174dec97f6996af2fb Binary files /dev/null and b/python/user_packages/Python313/site-packages/click/__pycache__/_winconsole.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/click/__pycache__/decorators.cpython-313.pyc b/python/user_packages/Python313/site-packages/click/__pycache__/decorators.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..cdfae0f3f3fe32beb2db7b01e541242b1e030451 Binary files /dev/null and b/python/user_packages/Python313/site-packages/click/__pycache__/decorators.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/click/__pycache__/exceptions.cpython-313.pyc b/python/user_packages/Python313/site-packages/click/__pycache__/exceptions.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..82d5b090f7a2308e2b4d86c6e15733938c4d8b5e Binary files /dev/null and b/python/user_packages/Python313/site-packages/click/__pycache__/exceptions.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/click/__pycache__/formatting.cpython-313.pyc b/python/user_packages/Python313/site-packages/click/__pycache__/formatting.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..359efaa792a6bc8335afd48298fddefaf0588288 Binary files /dev/null and b/python/user_packages/Python313/site-packages/click/__pycache__/formatting.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/click/__pycache__/globals.cpython-313.pyc b/python/user_packages/Python313/site-packages/click/__pycache__/globals.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b1002bcb3282c38418045ff81d1f2bfe6c245415 Binary files /dev/null and b/python/user_packages/Python313/site-packages/click/__pycache__/globals.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/click/__pycache__/parser.cpython-313.pyc b/python/user_packages/Python313/site-packages/click/__pycache__/parser.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6b7fc1d1f579002268ca78cae9d873d075187da6 Binary files /dev/null and b/python/user_packages/Python313/site-packages/click/__pycache__/parser.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/click/__pycache__/shell_completion.cpython-313.pyc b/python/user_packages/Python313/site-packages/click/__pycache__/shell_completion.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9d25bc8ca44948bc1928bd02828924aca0c0dc00 Binary files /dev/null and b/python/user_packages/Python313/site-packages/click/__pycache__/shell_completion.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/click/__pycache__/termui.cpython-313.pyc b/python/user_packages/Python313/site-packages/click/__pycache__/termui.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4715bc1e13e4f5eba84f7d35160a18e539d3b9fa Binary files /dev/null and b/python/user_packages/Python313/site-packages/click/__pycache__/termui.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/click/__pycache__/testing.cpython-313.pyc b/python/user_packages/Python313/site-packages/click/__pycache__/testing.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..481ff8c37b89a166916fc3b093b453f4faf333ba Binary files /dev/null and b/python/user_packages/Python313/site-packages/click/__pycache__/testing.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/click/__pycache__/types.cpython-313.pyc b/python/user_packages/Python313/site-packages/click/__pycache__/types.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..fc69046df03a2457e005dfdef51780f2cd7532f5 Binary files /dev/null and b/python/user_packages/Python313/site-packages/click/__pycache__/types.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/click/__pycache__/utils.cpython-313.pyc b/python/user_packages/Python313/site-packages/click/__pycache__/utils.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9b948693e613120ece6401ecce676747e13a51a9 Binary files /dev/null and b/python/user_packages/Python313/site-packages/click/__pycache__/utils.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/colorama-0.4.6.dist-info/licenses/LICENSE.txt b/python/user_packages/Python313/site-packages/colorama-0.4.6.dist-info/licenses/LICENSE.txt new file mode 100644 index 0000000000000000000000000000000000000000..3105888ec149d10cad51c11d332779e94b548661 --- /dev/null +++ b/python/user_packages/Python313/site-packages/colorama-0.4.6.dist-info/licenses/LICENSE.txt @@ -0,0 +1,27 @@ +Copyright (c) 2010 Jonathan Hartley +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 copyright holders, nor those 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. diff --git a/python/user_packages/Python313/site-packages/colorama/__pycache__/__init__.cpython-313.pyc b/python/user_packages/Python313/site-packages/colorama/__pycache__/__init__.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..86e7897fc5b8a5e4caba06032931b71f7220f4f4 Binary files /dev/null and b/python/user_packages/Python313/site-packages/colorama/__pycache__/__init__.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/colorama/__pycache__/ansi.cpython-313.pyc b/python/user_packages/Python313/site-packages/colorama/__pycache__/ansi.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7148df04c1cb9d0f5b3dfe3bbb9649b3da8ef612 Binary files /dev/null and b/python/user_packages/Python313/site-packages/colorama/__pycache__/ansi.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/colorama/__pycache__/ansitowin32.cpython-313.pyc b/python/user_packages/Python313/site-packages/colorama/__pycache__/ansitowin32.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..bbb486810d4cb238d7082cf8dc6df4d2531ad1dc Binary files /dev/null and b/python/user_packages/Python313/site-packages/colorama/__pycache__/ansitowin32.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/colorama/__pycache__/initialise.cpython-313.pyc b/python/user_packages/Python313/site-packages/colorama/__pycache__/initialise.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2b50bbdbef3c81c9f07602a682310efa65b2e599 Binary files /dev/null and b/python/user_packages/Python313/site-packages/colorama/__pycache__/initialise.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/colorama/__pycache__/win32.cpython-313.pyc b/python/user_packages/Python313/site-packages/colorama/__pycache__/win32.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..fcffaa848caa254d39b8be3656d0ff4af0237ffe Binary files /dev/null and b/python/user_packages/Python313/site-packages/colorama/__pycache__/win32.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/colorama/__pycache__/winterm.cpython-313.pyc b/python/user_packages/Python313/site-packages/colorama/__pycache__/winterm.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3650ad9b4fb040f390c749ebf2963d6e25581f1e Binary files /dev/null and b/python/user_packages/Python313/site-packages/colorama/__pycache__/winterm.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/colorama/tests/__init__.py b/python/user_packages/Python313/site-packages/colorama/tests/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..8c5661e93a205bf4fb22404d4fc50f902cc31369 --- /dev/null +++ b/python/user_packages/Python313/site-packages/colorama/tests/__init__.py @@ -0,0 +1 @@ +# Copyright Jonathan Hartley 2013. BSD 3-Clause license, see LICENSE file. diff --git a/python/user_packages/Python313/site-packages/colorama/tests/__pycache__/__init__.cpython-313.pyc b/python/user_packages/Python313/site-packages/colorama/tests/__pycache__/__init__.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..aef93ce3fe18c91e130e947fdeda7b0cd5edf8c5 Binary files /dev/null and b/python/user_packages/Python313/site-packages/colorama/tests/__pycache__/__init__.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/colorama/tests/__pycache__/ansi_test.cpython-313.pyc b/python/user_packages/Python313/site-packages/colorama/tests/__pycache__/ansi_test.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..68f07e990b40588c34873e0b0f759175d203e44b Binary files /dev/null and b/python/user_packages/Python313/site-packages/colorama/tests/__pycache__/ansi_test.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/colorama/tests/__pycache__/ansitowin32_test.cpython-313.pyc b/python/user_packages/Python313/site-packages/colorama/tests/__pycache__/ansitowin32_test.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..264fa69d43016e0a8df877e0ac0a47f110aed3c2 Binary files /dev/null and b/python/user_packages/Python313/site-packages/colorama/tests/__pycache__/ansitowin32_test.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/colorama/tests/__pycache__/initialise_test.cpython-313.pyc b/python/user_packages/Python313/site-packages/colorama/tests/__pycache__/initialise_test.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..810ea25a797f12efafeb41ff7b542b908264be75 Binary files /dev/null and b/python/user_packages/Python313/site-packages/colorama/tests/__pycache__/initialise_test.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/colorama/tests/__pycache__/isatty_test.cpython-313.pyc b/python/user_packages/Python313/site-packages/colorama/tests/__pycache__/isatty_test.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e8d13f8e6d15ab55ff9b69233958afd8f09b6d32 Binary files /dev/null and b/python/user_packages/Python313/site-packages/colorama/tests/__pycache__/isatty_test.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/colorama/tests/__pycache__/utils.cpython-313.pyc b/python/user_packages/Python313/site-packages/colorama/tests/__pycache__/utils.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4be6e0c9bfd7175e6beff0fae997b92eb9e20ee4 Binary files /dev/null and b/python/user_packages/Python313/site-packages/colorama/tests/__pycache__/utils.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/colorama/tests/__pycache__/winterm_test.cpython-313.pyc b/python/user_packages/Python313/site-packages/colorama/tests/__pycache__/winterm_test.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..bb33576696b255dc3d26a02647d7d7f17a75e42f Binary files /dev/null and b/python/user_packages/Python313/site-packages/colorama/tests/__pycache__/winterm_test.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/colorama/tests/ansi_test.py b/python/user_packages/Python313/site-packages/colorama/tests/ansi_test.py new file mode 100644 index 0000000000000000000000000000000000000000..0a20c80f882066e0e1323b0c7f61e22913c32e35 --- /dev/null +++ b/python/user_packages/Python313/site-packages/colorama/tests/ansi_test.py @@ -0,0 +1,76 @@ +# Copyright Jonathan Hartley 2013. BSD 3-Clause license, see LICENSE file. +import sys +from unittest import TestCase, main + +from ..ansi import Back, Fore, Style +from ..ansitowin32 import AnsiToWin32 + +stdout_orig = sys.stdout +stderr_orig = sys.stderr + + +class AnsiTest(TestCase): + + def setUp(self): + # sanity check: stdout should be a file or StringIO object. + # It will only be AnsiToWin32 if init() has previously wrapped it + self.assertNotEqual(type(sys.stdout), AnsiToWin32) + self.assertNotEqual(type(sys.stderr), AnsiToWin32) + + def tearDown(self): + sys.stdout = stdout_orig + sys.stderr = stderr_orig + + + def testForeAttributes(self): + self.assertEqual(Fore.BLACK, '\033[30m') + self.assertEqual(Fore.RED, '\033[31m') + self.assertEqual(Fore.GREEN, '\033[32m') + self.assertEqual(Fore.YELLOW, '\033[33m') + self.assertEqual(Fore.BLUE, '\033[34m') + self.assertEqual(Fore.MAGENTA, '\033[35m') + self.assertEqual(Fore.CYAN, '\033[36m') + self.assertEqual(Fore.WHITE, '\033[37m') + self.assertEqual(Fore.RESET, '\033[39m') + + # Check the light, extended versions. + self.assertEqual(Fore.LIGHTBLACK_EX, '\033[90m') + self.assertEqual(Fore.LIGHTRED_EX, '\033[91m') + self.assertEqual(Fore.LIGHTGREEN_EX, '\033[92m') + self.assertEqual(Fore.LIGHTYELLOW_EX, '\033[93m') + self.assertEqual(Fore.LIGHTBLUE_EX, '\033[94m') + self.assertEqual(Fore.LIGHTMAGENTA_EX, '\033[95m') + self.assertEqual(Fore.LIGHTCYAN_EX, '\033[96m') + self.assertEqual(Fore.LIGHTWHITE_EX, '\033[97m') + + + def testBackAttributes(self): + self.assertEqual(Back.BLACK, '\033[40m') + self.assertEqual(Back.RED, '\033[41m') + self.assertEqual(Back.GREEN, '\033[42m') + self.assertEqual(Back.YELLOW, '\033[43m') + self.assertEqual(Back.BLUE, '\033[44m') + self.assertEqual(Back.MAGENTA, '\033[45m') + self.assertEqual(Back.CYAN, '\033[46m') + self.assertEqual(Back.WHITE, '\033[47m') + self.assertEqual(Back.RESET, '\033[49m') + + # Check the light, extended versions. + self.assertEqual(Back.LIGHTBLACK_EX, '\033[100m') + self.assertEqual(Back.LIGHTRED_EX, '\033[101m') + self.assertEqual(Back.LIGHTGREEN_EX, '\033[102m') + self.assertEqual(Back.LIGHTYELLOW_EX, '\033[103m') + self.assertEqual(Back.LIGHTBLUE_EX, '\033[104m') + self.assertEqual(Back.LIGHTMAGENTA_EX, '\033[105m') + self.assertEqual(Back.LIGHTCYAN_EX, '\033[106m') + self.assertEqual(Back.LIGHTWHITE_EX, '\033[107m') + + + def testStyleAttributes(self): + self.assertEqual(Style.DIM, '\033[2m') + self.assertEqual(Style.NORMAL, '\033[22m') + self.assertEqual(Style.BRIGHT, '\033[1m') + + +if __name__ == '__main__': + main() diff --git a/python/user_packages/Python313/site-packages/colorama/tests/ansitowin32_test.py b/python/user_packages/Python313/site-packages/colorama/tests/ansitowin32_test.py new file mode 100644 index 0000000000000000000000000000000000000000..91ca551f97b4576c680711e826a1855fb944c872 --- /dev/null +++ b/python/user_packages/Python313/site-packages/colorama/tests/ansitowin32_test.py @@ -0,0 +1,294 @@ +# Copyright Jonathan Hartley 2013. BSD 3-Clause license, see LICENSE file. +from io import StringIO, TextIOWrapper +from unittest import TestCase, main +try: + from contextlib import ExitStack +except ImportError: + # python 2 + from contextlib2 import ExitStack + +try: + from unittest.mock import MagicMock, Mock, patch +except ImportError: + from mock import MagicMock, Mock, patch + +from ..ansitowin32 import AnsiToWin32, StreamWrapper +from ..win32 import ENABLE_VIRTUAL_TERMINAL_PROCESSING +from .utils import osname + + +class StreamWrapperTest(TestCase): + + def testIsAProxy(self): + mockStream = Mock() + wrapper = StreamWrapper(mockStream, None) + self.assertTrue( wrapper.random_attr is mockStream.random_attr ) + + def testDelegatesWrite(self): + mockStream = Mock() + mockConverter = Mock() + wrapper = StreamWrapper(mockStream, mockConverter) + wrapper.write('hello') + self.assertTrue(mockConverter.write.call_args, (('hello',), {})) + + def testDelegatesContext(self): + mockConverter = Mock() + s = StringIO() + with StreamWrapper(s, mockConverter) as fp: + fp.write(u'hello') + self.assertTrue(s.closed) + + def testProxyNoContextManager(self): + mockStream = MagicMock() + mockStream.__enter__.side_effect = AttributeError() + mockConverter = Mock() + with self.assertRaises(AttributeError) as excinfo: + with StreamWrapper(mockStream, mockConverter) as wrapper: + wrapper.write('hello') + + def test_closed_shouldnt_raise_on_closed_stream(self): + stream = StringIO() + stream.close() + wrapper = StreamWrapper(stream, None) + self.assertEqual(wrapper.closed, True) + + def test_closed_shouldnt_raise_on_detached_stream(self): + stream = TextIOWrapper(StringIO()) + stream.detach() + wrapper = StreamWrapper(stream, None) + self.assertEqual(wrapper.closed, True) + +class AnsiToWin32Test(TestCase): + + def testInit(self): + mockStdout = Mock() + auto = Mock() + stream = AnsiToWin32(mockStdout, autoreset=auto) + self.assertEqual(stream.wrapped, mockStdout) + self.assertEqual(stream.autoreset, auto) + + @patch('colorama.ansitowin32.winterm', None) + @patch('colorama.ansitowin32.winapi_test', lambda *_: True) + def testStripIsTrueOnWindows(self): + with osname('nt'): + mockStdout = Mock() + stream = AnsiToWin32(mockStdout) + self.assertTrue(stream.strip) + + def testStripIsFalseOffWindows(self): + with osname('posix'): + mockStdout = Mock(closed=False) + stream = AnsiToWin32(mockStdout) + self.assertFalse(stream.strip) + + def testWriteStripsAnsi(self): + mockStdout = Mock() + stream = AnsiToWin32(mockStdout) + stream.wrapped = Mock() + stream.write_and_convert = Mock() + stream.strip = True + + stream.write('abc') + + self.assertFalse(stream.wrapped.write.called) + self.assertEqual(stream.write_and_convert.call_args, (('abc',), {})) + + def testWriteDoesNotStripAnsi(self): + mockStdout = Mock() + stream = AnsiToWin32(mockStdout) + stream.wrapped = Mock() + stream.write_and_convert = Mock() + stream.strip = False + stream.convert = False + + stream.write('abc') + + self.assertFalse(stream.write_and_convert.called) + self.assertEqual(stream.wrapped.write.call_args, (('abc',), {})) + + def assert_autoresets(self, convert, autoreset=True): + stream = AnsiToWin32(Mock()) + stream.convert = convert + stream.reset_all = Mock() + stream.autoreset = autoreset + stream.winterm = Mock() + + stream.write('abc') + + self.assertEqual(stream.reset_all.called, autoreset) + + def testWriteAutoresets(self): + self.assert_autoresets(convert=True) + self.assert_autoresets(convert=False) + self.assert_autoresets(convert=True, autoreset=False) + self.assert_autoresets(convert=False, autoreset=False) + + def testWriteAndConvertWritesPlainText(self): + stream = AnsiToWin32(Mock()) + stream.write_and_convert( 'abc' ) + self.assertEqual( stream.wrapped.write.call_args, (('abc',), {}) ) + + def testWriteAndConvertStripsAllValidAnsi(self): + stream = AnsiToWin32(Mock()) + stream.call_win32 = Mock() + data = [ + 'abc\033[mdef', + 'abc\033[0mdef', + 'abc\033[2mdef', + 'abc\033[02mdef', + 'abc\033[002mdef', + 'abc\033[40mdef', + 'abc\033[040mdef', + 'abc\033[0;1mdef', + 'abc\033[40;50mdef', + 'abc\033[50;30;40mdef', + 'abc\033[Adef', + 'abc\033[0Gdef', + 'abc\033[1;20;128Hdef', + ] + for datum in data: + stream.wrapped.write.reset_mock() + stream.write_and_convert( datum ) + self.assertEqual( + [args[0] for args in stream.wrapped.write.call_args_list], + [ ('abc',), ('def',) ] + ) + + def testWriteAndConvertSkipsEmptySnippets(self): + stream = AnsiToWin32(Mock()) + stream.call_win32 = Mock() + stream.write_and_convert( '\033[40m\033[41m' ) + self.assertFalse( stream.wrapped.write.called ) + + def testWriteAndConvertCallsWin32WithParamsAndCommand(self): + stream = AnsiToWin32(Mock()) + stream.convert = True + stream.call_win32 = Mock() + stream.extract_params = Mock(return_value='params') + data = { + 'abc\033[adef': ('a', 'params'), + 'abc\033[;;bdef': ('b', 'params'), + 'abc\033[0cdef': ('c', 'params'), + 'abc\033[;;0;;Gdef': ('G', 'params'), + 'abc\033[1;20;128Hdef': ('H', 'params'), + } + for datum, expected in data.items(): + stream.call_win32.reset_mock() + stream.write_and_convert( datum ) + self.assertEqual( stream.call_win32.call_args[0], expected ) + + def test_reset_all_shouldnt_raise_on_closed_orig_stdout(self): + stream = StringIO() + converter = AnsiToWin32(stream) + stream.close() + + converter.reset_all() + + def test_wrap_shouldnt_raise_on_closed_orig_stdout(self): + stream = StringIO() + stream.close() + with \ + patch("colorama.ansitowin32.os.name", "nt"), \ + patch("colorama.ansitowin32.winapi_test", lambda: True): + converter = AnsiToWin32(stream) + self.assertTrue(converter.strip) + self.assertFalse(converter.convert) + + def test_wrap_shouldnt_raise_on_missing_closed_attr(self): + with \ + patch("colorama.ansitowin32.os.name", "nt"), \ + patch("colorama.ansitowin32.winapi_test", lambda: True): + converter = AnsiToWin32(object()) + self.assertTrue(converter.strip) + self.assertFalse(converter.convert) + + def testExtractParams(self): + stream = AnsiToWin32(Mock()) + data = { + '': (0,), + ';;': (0,), + '2': (2,), + ';;002;;': (2,), + '0;1': (0, 1), + ';;003;;456;;': (3, 456), + '11;22;33;44;55': (11, 22, 33, 44, 55), + } + for datum, expected in data.items(): + self.assertEqual(stream.extract_params('m', datum), expected) + + def testCallWin32UsesLookup(self): + listener = Mock() + stream = AnsiToWin32(listener) + stream.win32_calls = { + 1: (lambda *_, **__: listener(11),), + 2: (lambda *_, **__: listener(22),), + 3: (lambda *_, **__: listener(33),), + } + stream.call_win32('m', (3, 1, 99, 2)) + self.assertEqual( + [a[0][0] for a in listener.call_args_list], + [33, 11, 22] ) + + def test_osc_codes(self): + mockStdout = Mock() + stream = AnsiToWin32(mockStdout, convert=True) + with patch('colorama.ansitowin32.winterm') as winterm: + data = [ + '\033]0\x07', # missing arguments + '\033]0;foo\x08', # wrong OSC command + '\033]0;colorama_test_title\x07', # should work + '\033]1;colorama_test_title\x07', # wrong set command + '\033]2;colorama_test_title\x07', # should work + '\033]' + ';' * 64 + '\x08', # see issue #247 + ] + for code in data: + stream.write(code) + self.assertEqual(winterm.set_title.call_count, 2) + + def test_native_windows_ansi(self): + with ExitStack() as stack: + def p(a, b): + stack.enter_context(patch(a, b, create=True)) + # Pretend to be on Windows + p("colorama.ansitowin32.os.name", "nt") + p("colorama.ansitowin32.winapi_test", lambda: True) + p("colorama.win32.winapi_test", lambda: True) + p("colorama.winterm.win32.windll", "non-None") + p("colorama.winterm.get_osfhandle", lambda _: 1234) + + # Pretend that our mock stream has native ANSI support + p( + "colorama.winterm.win32.GetConsoleMode", + lambda _: ENABLE_VIRTUAL_TERMINAL_PROCESSING, + ) + SetConsoleMode = Mock() + p("colorama.winterm.win32.SetConsoleMode", SetConsoleMode) + + stdout = Mock() + stdout.closed = False + stdout.isatty.return_value = True + stdout.fileno.return_value = 1 + + # Our fake console says it has native vt support, so AnsiToWin32 should + # enable that support and do nothing else. + stream = AnsiToWin32(stdout) + SetConsoleMode.assert_called_with(1234, ENABLE_VIRTUAL_TERMINAL_PROCESSING) + self.assertFalse(stream.strip) + self.assertFalse(stream.convert) + self.assertFalse(stream.should_wrap()) + + # Now let's pretend we're on an old Windows console, that doesn't have + # native ANSI support. + p("colorama.winterm.win32.GetConsoleMode", lambda _: 0) + SetConsoleMode = Mock() + p("colorama.winterm.win32.SetConsoleMode", SetConsoleMode) + + stream = AnsiToWin32(stdout) + SetConsoleMode.assert_called_with(1234, ENABLE_VIRTUAL_TERMINAL_PROCESSING) + self.assertTrue(stream.strip) + self.assertTrue(stream.convert) + self.assertTrue(stream.should_wrap()) + + +if __name__ == '__main__': + main() diff --git a/python/user_packages/Python313/site-packages/colorama/tests/initialise_test.py b/python/user_packages/Python313/site-packages/colorama/tests/initialise_test.py new file mode 100644 index 0000000000000000000000000000000000000000..89f9b07511c8fee74686d9cc434bf66345a46d6d --- /dev/null +++ b/python/user_packages/Python313/site-packages/colorama/tests/initialise_test.py @@ -0,0 +1,189 @@ +# Copyright Jonathan Hartley 2013. BSD 3-Clause license, see LICENSE file. +import sys +from unittest import TestCase, main, skipUnless + +try: + from unittest.mock import patch, Mock +except ImportError: + from mock import patch, Mock + +from ..ansitowin32 import StreamWrapper +from ..initialise import init, just_fix_windows_console, _wipe_internal_state_for_tests +from .utils import osname, replace_by + +orig_stdout = sys.stdout +orig_stderr = sys.stderr + + +class InitTest(TestCase): + + @skipUnless(sys.stdout.isatty(), "sys.stdout is not a tty") + def setUp(self): + # sanity check + self.assertNotWrapped() + + def tearDown(self): + _wipe_internal_state_for_tests() + sys.stdout = orig_stdout + sys.stderr = orig_stderr + + def assertWrapped(self): + self.assertIsNot(sys.stdout, orig_stdout, 'stdout should be wrapped') + self.assertIsNot(sys.stderr, orig_stderr, 'stderr should be wrapped') + self.assertTrue(isinstance(sys.stdout, StreamWrapper), + 'bad stdout wrapper') + self.assertTrue(isinstance(sys.stderr, StreamWrapper), + 'bad stderr wrapper') + + def assertNotWrapped(self): + self.assertIs(sys.stdout, orig_stdout, 'stdout should not be wrapped') + self.assertIs(sys.stderr, orig_stderr, 'stderr should not be wrapped') + + @patch('colorama.initialise.reset_all') + @patch('colorama.ansitowin32.winapi_test', lambda *_: True) + @patch('colorama.ansitowin32.enable_vt_processing', lambda *_: False) + def testInitWrapsOnWindows(self, _): + with osname("nt"): + init() + self.assertWrapped() + + @patch('colorama.initialise.reset_all') + @patch('colorama.ansitowin32.winapi_test', lambda *_: False) + def testInitDoesntWrapOnEmulatedWindows(self, _): + with osname("nt"): + init() + self.assertNotWrapped() + + def testInitDoesntWrapOnNonWindows(self): + with osname("posix"): + init() + self.assertNotWrapped() + + def testInitDoesntWrapIfNone(self): + with replace_by(None): + init() + # We can't use assertNotWrapped here because replace_by(None) + # changes stdout/stderr already. + self.assertIsNone(sys.stdout) + self.assertIsNone(sys.stderr) + + def testInitAutoresetOnWrapsOnAllPlatforms(self): + with osname("posix"): + init(autoreset=True) + self.assertWrapped() + + def testInitWrapOffDoesntWrapOnWindows(self): + with osname("nt"): + init(wrap=False) + self.assertNotWrapped() + + def testInitWrapOffIncompatibleWithAutoresetOn(self): + self.assertRaises(ValueError, lambda: init(autoreset=True, wrap=False)) + + @patch('colorama.win32.SetConsoleTextAttribute') + @patch('colorama.initialise.AnsiToWin32') + def testAutoResetPassedOn(self, mockATW32, _): + with osname("nt"): + init(autoreset=True) + self.assertEqual(len(mockATW32.call_args_list), 2) + self.assertEqual(mockATW32.call_args_list[1][1]['autoreset'], True) + self.assertEqual(mockATW32.call_args_list[0][1]['autoreset'], True) + + @patch('colorama.initialise.AnsiToWin32') + def testAutoResetChangeable(self, mockATW32): + with osname("nt"): + init() + + init(autoreset=True) + self.assertEqual(len(mockATW32.call_args_list), 4) + self.assertEqual(mockATW32.call_args_list[2][1]['autoreset'], True) + self.assertEqual(mockATW32.call_args_list[3][1]['autoreset'], True) + + init() + self.assertEqual(len(mockATW32.call_args_list), 6) + self.assertEqual( + mockATW32.call_args_list[4][1]['autoreset'], False) + self.assertEqual( + mockATW32.call_args_list[5][1]['autoreset'], False) + + + @patch('colorama.initialise.atexit.register') + def testAtexitRegisteredOnlyOnce(self, mockRegister): + init() + self.assertTrue(mockRegister.called) + mockRegister.reset_mock() + init() + self.assertFalse(mockRegister.called) + + +class JustFixWindowsConsoleTest(TestCase): + def _reset(self): + _wipe_internal_state_for_tests() + sys.stdout = orig_stdout + sys.stderr = orig_stderr + + def tearDown(self): + self._reset() + + @patch("colorama.ansitowin32.winapi_test", lambda: True) + def testJustFixWindowsConsole(self): + if sys.platform != "win32": + # just_fix_windows_console should be a no-op + just_fix_windows_console() + self.assertIs(sys.stdout, orig_stdout) + self.assertIs(sys.stderr, orig_stderr) + else: + def fake_std(): + # Emulate stdout=not a tty, stderr=tty + # to check that we handle both cases correctly + stdout = Mock() + stdout.closed = False + stdout.isatty.return_value = False + stdout.fileno.return_value = 1 + sys.stdout = stdout + + stderr = Mock() + stderr.closed = False + stderr.isatty.return_value = True + stderr.fileno.return_value = 2 + sys.stderr = stderr + + for native_ansi in [False, True]: + with patch( + 'colorama.ansitowin32.enable_vt_processing', + lambda *_: native_ansi + ): + self._reset() + fake_std() + + # Regular single-call test + prev_stdout = sys.stdout + prev_stderr = sys.stderr + just_fix_windows_console() + self.assertIs(sys.stdout, prev_stdout) + if native_ansi: + self.assertIs(sys.stderr, prev_stderr) + else: + self.assertIsNot(sys.stderr, prev_stderr) + + # second call without resetting is always a no-op + prev_stdout = sys.stdout + prev_stderr = sys.stderr + just_fix_windows_console() + self.assertIs(sys.stdout, prev_stdout) + self.assertIs(sys.stderr, prev_stderr) + + self._reset() + fake_std() + + # If init() runs first, just_fix_windows_console should be a no-op + init() + prev_stdout = sys.stdout + prev_stderr = sys.stderr + just_fix_windows_console() + self.assertIs(prev_stdout, sys.stdout) + self.assertIs(prev_stderr, sys.stderr) + + +if __name__ == '__main__': + main() diff --git a/python/user_packages/Python313/site-packages/colorama/tests/isatty_test.py b/python/user_packages/Python313/site-packages/colorama/tests/isatty_test.py new file mode 100644 index 0000000000000000000000000000000000000000..0f84e4befe550d4386d24264648abf1323e682ff --- /dev/null +++ b/python/user_packages/Python313/site-packages/colorama/tests/isatty_test.py @@ -0,0 +1,57 @@ +# Copyright Jonathan Hartley 2013. BSD 3-Clause license, see LICENSE file. +import sys +from unittest import TestCase, main + +from ..ansitowin32 import StreamWrapper, AnsiToWin32 +from .utils import pycharm, replace_by, replace_original_by, StreamTTY, StreamNonTTY + + +def is_a_tty(stream): + return StreamWrapper(stream, None).isatty() + +class IsattyTest(TestCase): + + def test_TTY(self): + tty = StreamTTY() + self.assertTrue(is_a_tty(tty)) + with pycharm(): + self.assertTrue(is_a_tty(tty)) + + def test_nonTTY(self): + non_tty = StreamNonTTY() + self.assertFalse(is_a_tty(non_tty)) + with pycharm(): + self.assertFalse(is_a_tty(non_tty)) + + def test_withPycharm(self): + with pycharm(): + self.assertTrue(is_a_tty(sys.stderr)) + self.assertTrue(is_a_tty(sys.stdout)) + + def test_withPycharmTTYOverride(self): + tty = StreamTTY() + with pycharm(), replace_by(tty): + self.assertTrue(is_a_tty(tty)) + + def test_withPycharmNonTTYOverride(self): + non_tty = StreamNonTTY() + with pycharm(), replace_by(non_tty): + self.assertFalse(is_a_tty(non_tty)) + + def test_withPycharmNoneOverride(self): + with pycharm(): + with replace_by(None), replace_original_by(None): + self.assertFalse(is_a_tty(None)) + self.assertFalse(is_a_tty(StreamNonTTY())) + self.assertTrue(is_a_tty(StreamTTY())) + + def test_withPycharmStreamWrapped(self): + with pycharm(): + self.assertTrue(AnsiToWin32(StreamTTY()).stream.isatty()) + self.assertFalse(AnsiToWin32(StreamNonTTY()).stream.isatty()) + self.assertTrue(AnsiToWin32(sys.stdout).stream.isatty()) + self.assertTrue(AnsiToWin32(sys.stderr).stream.isatty()) + + +if __name__ == '__main__': + main() diff --git a/python/user_packages/Python313/site-packages/colorama/tests/utils.py b/python/user_packages/Python313/site-packages/colorama/tests/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..472fafb4403efb9673d5cc724dafd9cf764aac5b --- /dev/null +++ b/python/user_packages/Python313/site-packages/colorama/tests/utils.py @@ -0,0 +1,49 @@ +# Copyright Jonathan Hartley 2013. BSD 3-Clause license, see LICENSE file. +from contextlib import contextmanager +from io import StringIO +import sys +import os + + +class StreamTTY(StringIO): + def isatty(self): + return True + +class StreamNonTTY(StringIO): + def isatty(self): + return False + +@contextmanager +def osname(name): + orig = os.name + os.name = name + yield + os.name = orig + +@contextmanager +def replace_by(stream): + orig_stdout = sys.stdout + orig_stderr = sys.stderr + sys.stdout = stream + sys.stderr = stream + yield + sys.stdout = orig_stdout + sys.stderr = orig_stderr + +@contextmanager +def replace_original_by(stream): + orig_stdout = sys.__stdout__ + orig_stderr = sys.__stderr__ + sys.__stdout__ = stream + sys.__stderr__ = stream + yield + sys.__stdout__ = orig_stdout + sys.__stderr__ = orig_stderr + +@contextmanager +def pycharm(): + os.environ["PYCHARM_HOSTED"] = "1" + non_tty = StreamNonTTY() + with replace_by(non_tty), replace_original_by(non_tty): + yield + del os.environ["PYCHARM_HOSTED"] diff --git a/python/user_packages/Python313/site-packages/colorama/tests/winterm_test.py b/python/user_packages/Python313/site-packages/colorama/tests/winterm_test.py new file mode 100644 index 0000000000000000000000000000000000000000..d0955f9e608377940f0d548576964f2fcf3caf48 --- /dev/null +++ b/python/user_packages/Python313/site-packages/colorama/tests/winterm_test.py @@ -0,0 +1,131 @@ +# Copyright Jonathan Hartley 2013. BSD 3-Clause license, see LICENSE file. +import sys +from unittest import TestCase, main, skipUnless + +try: + from unittest.mock import Mock, patch +except ImportError: + from mock import Mock, patch + +from ..winterm import WinColor, WinStyle, WinTerm + + +class WinTermTest(TestCase): + + @patch('colorama.winterm.win32') + def testInit(self, mockWin32): + mockAttr = Mock() + mockAttr.wAttributes = 7 + 6 * 16 + 8 + mockWin32.GetConsoleScreenBufferInfo.return_value = mockAttr + term = WinTerm() + self.assertEqual(term._fore, 7) + self.assertEqual(term._back, 6) + self.assertEqual(term._style, 8) + + @skipUnless(sys.platform.startswith("win"), "requires Windows") + def testGetAttrs(self): + term = WinTerm() + + term._fore = 0 + term._back = 0 + term._style = 0 + self.assertEqual(term.get_attrs(), 0) + + term._fore = WinColor.YELLOW + self.assertEqual(term.get_attrs(), WinColor.YELLOW) + + term._back = WinColor.MAGENTA + self.assertEqual( + term.get_attrs(), + WinColor.YELLOW + WinColor.MAGENTA * 16) + + term._style = WinStyle.BRIGHT + self.assertEqual( + term.get_attrs(), + WinColor.YELLOW + WinColor.MAGENTA * 16 + WinStyle.BRIGHT) + + @patch('colorama.winterm.win32') + def testResetAll(self, mockWin32): + mockAttr = Mock() + mockAttr.wAttributes = 1 + 2 * 16 + 8 + mockWin32.GetConsoleScreenBufferInfo.return_value = mockAttr + term = WinTerm() + + term.set_console = Mock() + term._fore = -1 + term._back = -1 + term._style = -1 + + term.reset_all() + + self.assertEqual(term._fore, 1) + self.assertEqual(term._back, 2) + self.assertEqual(term._style, 8) + self.assertEqual(term.set_console.called, True) + + @skipUnless(sys.platform.startswith("win"), "requires Windows") + def testFore(self): + term = WinTerm() + term.set_console = Mock() + term._fore = 0 + + term.fore(5) + + self.assertEqual(term._fore, 5) + self.assertEqual(term.set_console.called, True) + + @skipUnless(sys.platform.startswith("win"), "requires Windows") + def testBack(self): + term = WinTerm() + term.set_console = Mock() + term._back = 0 + + term.back(5) + + self.assertEqual(term._back, 5) + self.assertEqual(term.set_console.called, True) + + @skipUnless(sys.platform.startswith("win"), "requires Windows") + def testStyle(self): + term = WinTerm() + term.set_console = Mock() + term._style = 0 + + term.style(22) + + self.assertEqual(term._style, 22) + self.assertEqual(term.set_console.called, True) + + @patch('colorama.winterm.win32') + def testSetConsole(self, mockWin32): + mockAttr = Mock() + mockAttr.wAttributes = 0 + mockWin32.GetConsoleScreenBufferInfo.return_value = mockAttr + term = WinTerm() + term.windll = Mock() + + term.set_console() + + self.assertEqual( + mockWin32.SetConsoleTextAttribute.call_args, + ((mockWin32.STDOUT, term.get_attrs()), {}) + ) + + @patch('colorama.winterm.win32') + def testSetConsoleOnStderr(self, mockWin32): + mockAttr = Mock() + mockAttr.wAttributes = 0 + mockWin32.GetConsoleScreenBufferInfo.return_value = mockAttr + term = WinTerm() + term.windll = Mock() + + term.set_console(on_stderr=True) + + self.assertEqual( + mockWin32.SetConsoleTextAttribute.call_args, + ((mockWin32.STDERR, term.get_attrs()), {}) + ) + + +if __name__ == '__main__': + main() diff --git a/python/user_packages/Python313/site-packages/cryptography-48.0.0.dist-info/licenses/LICENSE b/python/user_packages/Python313/site-packages/cryptography-48.0.0.dist-info/licenses/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..b11f379efe1504d235b4d2d42685ba5dc6af6e9f --- /dev/null +++ b/python/user_packages/Python313/site-packages/cryptography-48.0.0.dist-info/licenses/LICENSE @@ -0,0 +1,3 @@ +This software is made available under the terms of *either* of the licenses +found in LICENSE.APACHE or LICENSE.BSD. Contributions to cryptography are made +under the terms of *both* these licenses. diff --git a/python/user_packages/Python313/site-packages/cryptography-48.0.0.dist-info/licenses/LICENSE.APACHE b/python/user_packages/Python313/site-packages/cryptography-48.0.0.dist-info/licenses/LICENSE.APACHE new file mode 100644 index 0000000000000000000000000000000000000000..62589edd12a37dd28b6b6fed1e2d728ac9f05c8d --- /dev/null +++ b/python/user_packages/Python313/site-packages/cryptography-48.0.0.dist-info/licenses/LICENSE.APACHE @@ -0,0 +1,202 @@ + + Apache License + Version 2.0, January 2004 + https://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + 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 + + https://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/python/user_packages/Python313/site-packages/cryptography-48.0.0.dist-info/licenses/LICENSE.BSD b/python/user_packages/Python313/site-packages/cryptography-48.0.0.dist-info/licenses/LICENSE.BSD new file mode 100644 index 0000000000000000000000000000000000000000..ec1a29d34d6e419411c75523408aca72f705345c --- /dev/null +++ b/python/user_packages/Python313/site-packages/cryptography-48.0.0.dist-info/licenses/LICENSE.BSD @@ -0,0 +1,27 @@ +Copyright (c) Individual contributors. +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimer. + + 2. 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. + + 3. Neither the name of PyCA Cryptography 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 OWNER 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. diff --git a/python/user_packages/Python313/site-packages/cryptography-48.0.0.dist-info/sboms/cryptography-rust.cyclonedx.json b/python/user_packages/Python313/site-packages/cryptography-48.0.0.dist-info/sboms/cryptography-rust.cyclonedx.json new file mode 100644 index 0000000000000000000000000000000000000000..799b119115b7f3a0f25e7b62eaab741ea9deeef2 --- /dev/null +++ b/python/user_packages/Python313/site-packages/cryptography-48.0.0.dist-info/sboms/cryptography-rust.cyclonedx.json @@ -0,0 +1,1362 @@ +{ + "bomFormat": "CycloneDX", + "specVersion": "1.5", + "version": 1, + "serialNumber": "urn:uuid:9239508a-26c8-47fb-9035-fa65510e2670", + "metadata": { + "timestamp": "2026-05-04T22:45:45.985242700Z", + "tools": [ + { + "vendor": "CycloneDX", + "name": "cargo-cyclonedx", + "version": "0.5.9" + } + ], + "authors": [ + { + "name": "The cryptography developers", + "email": "cryptography-dev@python.org" + } + ], + "component": { + "type": "library", + "bom-ref": "path+file:///D:/a/cryptography/cryptography/wheelhouse/.tmpsrzLM5/cryptography-48.0.0/src/rust#cryptography-rust@0.1.0", + "author": "The cryptography developers ", + "name": "cryptography-rust", + "version": "0.1.0", + "scope": "required", + "licenses": [ + { + "expression": "Apache-2.0 OR BSD-3-Clause" + } + ], + "purl": "pkg:cargo/cryptography-rust@0.1.0?download_url=file://.", + "components": [ + { + "type": "library", + "bom-ref": "path+file:///D:/a/cryptography/cryptography/wheelhouse/.tmpsrzLM5/cryptography-48.0.0/src/rust#cryptography-rust@0.1.0 bin-target-0", + "name": "cryptography_rust", + "version": "0.1.0", + "purl": "pkg:cargo/cryptography-rust@0.1.0?download_url=file://.#src/lib.rs" + } + ] + }, + "properties": [ + { + "name": "cdx:rustc:sbom:target:all_targets", + "value": "true" + } + ] + }, + "components": [ + { + "type": "library", + "bom-ref": "path+file:///D:/a/cryptography/cryptography/wheelhouse/.tmpsrzLM5/cryptography-48.0.0/src/rust/cryptography-cffi#0.1.0", + "author": "The cryptography developers ", + "name": "cryptography-cffi", + "version": "0.1.0", + "scope": "required", + "licenses": [ + { + "expression": "Apache-2.0 OR BSD-3-Clause" + } + ], + "purl": "pkg:cargo/cryptography-cffi@0.1.0?download_url=file://cryptography-cffi" + }, + { + "type": "library", + "bom-ref": "path+file:///D:/a/cryptography/cryptography/wheelhouse/.tmpsrzLM5/cryptography-48.0.0/src/rust/cryptography-crypto#0.1.0", + "author": "The cryptography developers ", + "name": "cryptography-crypto", + "version": "0.1.0", + "scope": "required", + "licenses": [ + { + "expression": "Apache-2.0 OR BSD-3-Clause" + } + ], + "purl": "pkg:cargo/cryptography-crypto@0.1.0?download_url=file://cryptography-crypto" + }, + { + "type": "library", + "bom-ref": "path+file:///D:/a/cryptography/cryptography/wheelhouse/.tmpsrzLM5/cryptography-48.0.0/src/rust/cryptography-keepalive#0.1.0", + "author": "The cryptography developers ", + "name": "cryptography-keepalive", + "version": "0.1.0", + "scope": "required", + "licenses": [ + { + "expression": "Apache-2.0 OR BSD-3-Clause" + } + ], + "purl": "pkg:cargo/cryptography-keepalive@0.1.0?download_url=file://cryptography-keepalive" + }, + { + "type": "library", + "bom-ref": "path+file:///D:/a/cryptography/cryptography/wheelhouse/.tmpsrzLM5/cryptography-48.0.0/src/rust/cryptography-key-parsing#0.1.0", + "author": "The cryptography developers ", + "name": "cryptography-key-parsing", + "version": "0.1.0", + "scope": "required", + "licenses": [ + { + "expression": "Apache-2.0 OR BSD-3-Clause" + } + ], + "purl": "pkg:cargo/cryptography-key-parsing@0.1.0?download_url=file://cryptography-key-parsing" + }, + { + "type": "library", + "bom-ref": "path+file:///D:/a/cryptography/cryptography/wheelhouse/.tmpsrzLM5/cryptography-48.0.0/src/rust/cryptography-openssl#0.1.0", + "author": "The cryptography developers ", + "name": "cryptography-openssl", + "version": "0.1.0", + "scope": "required", + "licenses": [ + { + "expression": "Apache-2.0 OR BSD-3-Clause" + } + ], + "purl": "pkg:cargo/cryptography-openssl@0.1.0?download_url=file://cryptography-openssl" + }, + { + "type": "library", + "bom-ref": "path+file:///D:/a/cryptography/cryptography/wheelhouse/.tmpsrzLM5/cryptography-48.0.0/src/rust/cryptography-x509#0.1.0", + "author": "The cryptography developers ", + "name": "cryptography-x509", + "version": "0.1.0", + "scope": "required", + "licenses": [ + { + "expression": "Apache-2.0 OR BSD-3-Clause" + } + ], + "purl": "pkg:cargo/cryptography-x509@0.1.0?download_url=file://cryptography-x509" + }, + { + "type": "library", + "bom-ref": "path+file:///D:/a/cryptography/cryptography/wheelhouse/.tmpsrzLM5/cryptography-48.0.0/src/rust/cryptography-x509-verification#0.1.0", + "author": "The cryptography developers ", + "name": "cryptography-x509-verification", + "version": "0.1.0", + "scope": "required", + "licenses": [ + { + "expression": "Apache-2.0 OR BSD-3-Clause" + } + ], + "purl": "pkg:cargo/cryptography-x509-verification@0.1.0?download_url=file://cryptography-x509-verification" + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#asn1@0.24.1", + "author": "Alex Gaynor ", + "name": "asn1", + "version": "0.24.1", + "description": "ASN.1 (DER) parser and writer for Rust.", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "c9795210620c0cb3f9a7ce4f882808c38e1ef7b347c90591dceae0886e031fb1" + } + ], + "licenses": [ + { + "expression": "BSD-3-Clause" + } + ], + "purl": "pkg:cargo/asn1@0.24.1", + "externalReferences": [ + { + "type": "vcs", + "url": "https://github.com/alex/rust-asn1" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#asn1_derive@0.24.1", + "author": "Alex Gaynor ", + "name": "asn1_derive", + "version": "0.24.1", + "description": "#[derive] support for asn1", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "909e307f1cc32bb8bccbd98f446e6d1bf03fa30f7b53a4337da7181ad30fa11a" + } + ], + "licenses": [ + { + "expression": "BSD-3-Clause" + } + ], + "purl": "pkg:cargo/asn1_derive@0.24.1", + "externalReferences": [ + { + "type": "vcs", + "url": "https://github.com/alex/rust-asn1" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#base64@0.22.1", + "author": "Marshall Pierce ", + "name": "base64", + "version": "0.22.1", + "description": "encodes and decodes base64 as bytes or utf8", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/base64@0.22.1", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/base64" + }, + { + "type": "vcs", + "url": "https://github.com/marshallpierce/rust-base64" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#bitflags@2.11.1", + "author": "The Rust Project Developers", + "name": "bitflags", + "version": "2.11.1", + "description": "A macro to generate structures which behave like bitflags. ", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "c4512299f36f043ab09a583e57bceb5a5aab7a73db1805848e8fef3c9e8c78b3" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/bitflags@2.11.1", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/bitflags" + }, + { + "type": "website", + "url": "https://github.com/bitflags/bitflags" + }, + { + "type": "vcs", + "url": "https://github.com/bitflags/bitflags" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#cc@1.2.61", + "author": "Alex Crichton ", + "name": "cc", + "version": "1.2.61", + "description": "A build-time dependency for Cargo build scripts to assist in invoking the native C compiler to compile native C code into a static archive to be linked into Rust code. ", + "scope": "excluded", + "hashes": [ + { + "alg": "SHA-256", + "content": "d16d90359e986641506914ba71350897565610e87ce0ad9e6f28569db3dd5c6d" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/cc@1.2.61", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/cc" + }, + { + "type": "website", + "url": "https://github.com/rust-lang/cc-rs" + }, + { + "type": "vcs", + "url": "https://github.com/rust-lang/cc-rs" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#cfg-if@1.0.4", + "author": "Alex Crichton ", + "name": "cfg-if", + "version": "1.0.4", + "description": "A macro to ergonomically define an item depending on a large number of #[cfg] parameters. Structured like an if-else chain, the first matching branch is the item that gets emitted. ", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "9330f8b2ff13f34540b44e946ef35111825727b38d33286ef986142615121801" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/cfg-if@1.0.4", + "externalReferences": [ + { + "type": "vcs", + "url": "https://github.com/rust-lang/cfg-if" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#find-msvc-tools@0.1.9", + "name": "find-msvc-tools", + "version": "0.1.9", + "description": "Find windows-specific tools, read MSVC versions from the registry and from COM interfaces", + "scope": "excluded", + "hashes": [ + { + "alg": "SHA-256", + "content": "5baebc0774151f905a1a2cc41989300b1e6fbb29aff0ceffa1064fdd3088d582" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/find-msvc-tools@0.1.9", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/find-msvc-tools" + }, + { + "type": "vcs", + "url": "https://github.com/rust-lang/cc-rs" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#foreign-types-shared@0.1.1", + "author": "Steven Fackler ", + "name": "foreign-types-shared", + "version": "0.1.1", + "description": "An internal crate used by foreign-types", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "00b0228411908ca8685dba7fc2cdd70ec9990a6e753e89b6ac91a84c40fbaf4b" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/foreign-types-shared@0.1.1", + "externalReferences": [ + { + "type": "vcs", + "url": "https://github.com/sfackler/foreign-types" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#foreign-types@0.3.2", + "author": "Steven Fackler ", + "name": "foreign-types", + "version": "0.3.2", + "description": "A framework for Rust wrappers over C APIs", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "f6f339eb8adc052cd2ca78910fda869aefa38d22d5cb648e6485e4d3fc06f3b1" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/foreign-types@0.3.2", + "externalReferences": [ + { + "type": "vcs", + "url": "https://github.com/sfackler/foreign-types" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#heck@0.5.0", + "name": "heck", + "version": "0.5.0", + "description": "heck is a case conversion library.", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/heck@0.5.0", + "externalReferences": [ + { + "type": "vcs", + "url": "https://github.com/withoutboats/heck" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#itoa@1.0.18", + "author": "David Tolnay ", + "name": "itoa", + "version": "1.0.18", + "description": "Fast integer primitive to string conversion", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/itoa@1.0.18", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/itoa" + }, + { + "type": "vcs", + "url": "https://github.com/dtolnay/itoa" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#libc@0.2.186", + "author": "The Rust Project Developers", + "name": "libc", + "version": "0.2.186", + "description": "Raw FFI bindings to platform libraries like libc.", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "68ab91017fe16c622486840e4c83c9a37afeff978bd239b5293d61ece587de66" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/libc@0.2.186", + "externalReferences": [ + { + "type": "vcs", + "url": "https://github.com/rust-lang/libc" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#once_cell@1.21.4", + "author": "Aleksey Kladov ", + "name": "once_cell", + "version": "1.21.4", + "description": "Single assignment cells and lazy values.", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/once_cell@1.21.4", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/once_cell" + }, + { + "type": "vcs", + "url": "https://github.com/matklad/once_cell" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#openssl-macros@0.1.1", + "name": "openssl-macros", + "version": "0.1.1", + "description": "Internal macros used by the openssl crate.", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "a948666b637a0f465e8564c73e89d4dde00d72d4d473cc972f390fc3dcee7d9c" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/openssl-macros@0.1.1" + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#openssl-sys@0.9.115", + "author": "Alex Crichton , Steven Fackler ", + "name": "openssl-sys", + "version": "0.9.115", + "description": "FFI bindings to OpenSSL", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "158fe5b292746440aa6e7a7e690e55aeb72d41505e2804c23c6973ad0e9c9781" + } + ], + "licenses": [ + { + "expression": "MIT" + } + ], + "purl": "pkg:cargo/openssl-sys@0.9.115", + "externalReferences": [ + { + "type": "other", + "url": "openssl" + }, + { + "type": "vcs", + "url": "https://github.com/rust-openssl/rust-openssl" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#openssl@0.10.79", + "author": "Steven Fackler ", + "name": "openssl", + "version": "0.10.79", + "description": "OpenSSL bindings", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "bf0b434746ee2832f4f0baf10137e1cabb18cbe6912c69e2e33263c45250f542" + } + ], + "licenses": [ + { + "expression": "Apache-2.0" + } + ], + "purl": "pkg:cargo/openssl@0.10.79", + "externalReferences": [ + { + "type": "vcs", + "url": "https://github.com/rust-openssl/rust-openssl" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#pem@3.0.6", + "author": "Jonathan Creekmore ", + "name": "pem", + "version": "3.0.6", + "description": "Parse and encode PEM-encoded data.", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "1d30c53c26bc5b31a98cd02d20f25a7c8567146caf63ed593a9d87b2775291be" + } + ], + "licenses": [ + { + "expression": "MIT" + } + ], + "purl": "pkg:cargo/pem@3.0.6", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/pem/" + }, + { + "type": "website", + "url": "https://github.com/jcreekmore/pem-rs.git" + }, + { + "type": "vcs", + "url": "https://github.com/jcreekmore/pem-rs.git" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#pkg-config@0.3.33", + "author": "Alex Crichton ", + "name": "pkg-config", + "version": "0.3.33", + "description": "A library to run the pkg-config system tool at build time in order to be used in Cargo build scripts. ", + "scope": "excluded", + "hashes": [ + { + "alg": "SHA-256", + "content": "19f132c84eca552bf34cab8ec81f1c1dcc229b811638f9d283dceabe58c5569e" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/pkg-config@0.3.33", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/pkg-config" + }, + { + "type": "vcs", + "url": "https://github.com/rust-lang/pkg-config-rs" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#portable-atomic@1.13.1", + "name": "portable-atomic", + "version": "1.13.1", + "description": "Portable atomic types including support for 128-bit atomics, atomic float, etc. ", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "c33a9471896f1c69cecef8d20cbe2f7accd12527ce60845ff44c153bb2a21b49" + } + ], + "licenses": [ + { + "expression": "Apache-2.0 OR MIT" + } + ], + "purl": "pkg:cargo/portable-atomic@1.13.1", + "externalReferences": [ + { + "type": "vcs", + "url": "https://github.com/taiki-e/portable-atomic" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#proc-macro2@1.0.106", + "author": "David Tolnay , Alex Crichton ", + "name": "proc-macro2", + "version": "1.0.106", + "description": "A substitute implementation of the compiler's `proc_macro` API to decouple token-based libraries from the procedural macro use case.", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "8fd00f0bb2e90d81d1044c2b32617f68fcb9fa3bb7640c23e9c748e53fb30934" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/proc-macro2@1.0.106", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/proc-macro2" + }, + { + "type": "vcs", + "url": "https://github.com/dtolnay/proc-macro2" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#pyo3-build-config@0.28.3", + "author": "PyO3 Project and Contributors ", + "name": "pyo3-build-config", + "version": "0.28.3", + "description": "Build configuration for the PyO3 ecosystem", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "e368e7ddfdeb98c9bca7f8383be1648fd84ab466bf2bc015e94008db6d35611e" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/pyo3-build-config@0.28.3", + "externalReferences": [ + { + "type": "website", + "url": "https://github.com/pyo3/pyo3" + }, + { + "type": "vcs", + "url": "https://github.com/pyo3/pyo3" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#pyo3-ffi@0.28.3", + "author": "PyO3 Project and Contributors ", + "name": "pyo3-ffi", + "version": "0.28.3", + "description": "Python-API bindings for the PyO3 ecosystem", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "7f29e10af80b1f7ccaf7f69eace800a03ecd13e883acfacc1e5d0988605f651e" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/pyo3-ffi@0.28.3", + "externalReferences": [ + { + "type": "website", + "url": "https://github.com/pyo3/pyo3" + }, + { + "type": "other", + "url": "python" + }, + { + "type": "vcs", + "url": "https://github.com/pyo3/pyo3" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#pyo3-macros-backend@0.28.3", + "author": "PyO3 Project and Contributors ", + "name": "pyo3-macros-backend", + "version": "0.28.3", + "description": "Code generation for PyO3 package", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "c4cdc218d835738f81c2338f822078af45b4afdf8b2e33cbb5916f108b813acb" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/pyo3-macros-backend@0.28.3", + "externalReferences": [ + { + "type": "website", + "url": "https://github.com/pyo3/pyo3" + }, + { + "type": "vcs", + "url": "https://github.com/pyo3/pyo3" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#pyo3-macros@0.28.3", + "author": "PyO3 Project and Contributors ", + "name": "pyo3-macros", + "version": "0.28.3", + "description": "Proc macros for PyO3 package", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "df6e520eff47c45997d2fc7dd8214b25dd1310918bbb2642156ef66a67f29813" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/pyo3-macros@0.28.3", + "externalReferences": [ + { + "type": "website", + "url": "https://github.com/pyo3/pyo3" + }, + { + "type": "vcs", + "url": "https://github.com/pyo3/pyo3" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#pyo3@0.28.3", + "author": "PyO3 Project and Contributors ", + "name": "pyo3", + "version": "0.28.3", + "description": "Bindings to Python interpreter", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "91fd8e38a3b50ed1167fb981cd6fd60147e091784c427b8f7183a7ee32c31c12" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/pyo3@0.28.3", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/crate/pyo3/" + }, + { + "type": "website", + "url": "https://github.com/pyo3/pyo3" + }, + { + "type": "vcs", + "url": "https://github.com/pyo3/pyo3" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#quote@1.0.45", + "author": "David Tolnay ", + "name": "quote", + "version": "1.0.45", + "description": "Quasi-quoting macro quote!(...)", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "41f2619966050689382d2b44f664f4bc593e129785a36d6ee376ddf37259b924" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/quote@1.0.45", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/quote/" + }, + { + "type": "vcs", + "url": "https://github.com/dtolnay/quote" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#self_cell@1.2.2", + "author": "Lukas Bergdoll ", + "name": "self_cell", + "version": "1.2.2", + "description": "Safe-to-use proc-macro-free self-referential structs in stable Rust.", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "b12e76d157a900eb52e81bc6e9f3069344290341720e9178cde2407113ac8d89" + } + ], + "licenses": [ + { + "expression": "Apache-2.0 OR GPL-2.0-only" + } + ], + "purl": "pkg:cargo/self_cell@1.2.2", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/self_cell" + }, + { + "type": "vcs", + "url": "https://github.com/Voultapher/self_cell" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#shlex@1.3.0", + "author": "comex , Fenhl , Adrian Taylor , Alex Touchet , Daniel Parks , Garrett Berg ", + "name": "shlex", + "version": "1.3.0", + "description": "Split a string into shell words, like Python's shlex.", + "scope": "excluded", + "hashes": [ + { + "alg": "SHA-256", + "content": "0fda2ff0d084019ba4d7c6f371c95d8fd75ce3524c3cb8fb653a3023f6323e64" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/shlex@1.3.0", + "externalReferences": [ + { + "type": "vcs", + "url": "https://github.com/comex/rust-shlex" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#syn@2.0.117", + "author": "David Tolnay ", + "name": "syn", + "version": "2.0.117", + "description": "Parser for Rust source code", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "e665b8803e7b1d2a727f4023456bbbbe74da67099c585258af0ad9c5013b9b99" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/syn@2.0.117", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/syn" + }, + { + "type": "vcs", + "url": "https://github.com/dtolnay/syn" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#target-lexicon@0.13.5", + "author": "Dan Gohman ", + "name": "target-lexicon", + "version": "0.13.5", + "description": "LLVM target triple types", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "adb6935a6f5c20170eeceb1a3835a49e12e19d792f6dd344ccc76a985ca5a6ca" + } + ], + "licenses": [ + { + "expression": "Apache-2.0 WITH LLVM-exception" + } + ], + "purl": "pkg:cargo/target-lexicon@0.13.5", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/target-lexicon/" + }, + { + "type": "vcs", + "url": "https://github.com/bytecodealliance/target-lexicon" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#unicode-ident@1.0.24", + "author": "David Tolnay ", + "name": "unicode-ident", + "version": "1.0.24", + "description": "Determine whether characters have the XID_Start or XID_Continue properties according to Unicode Standard Annex #31", + "scope": "required", + "hashes": [ + { + "alg": "SHA-256", + "content": "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75" + } + ], + "licenses": [ + { + "expression": "(MIT OR Apache-2.0) AND Unicode-3.0" + } + ], + "purl": "pkg:cargo/unicode-ident@1.0.24", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/unicode-ident" + }, + { + "type": "vcs", + "url": "https://github.com/dtolnay/unicode-ident" + } + ] + }, + { + "type": "library", + "bom-ref": "registry+https://github.com/rust-lang/crates.io-index#vcpkg@0.2.15", + "author": "Jim McGrath ", + "name": "vcpkg", + "version": "0.2.15", + "description": "A library to find native dependencies in a vcpkg tree at build time in order to be used in Cargo build scripts. ", + "scope": "excluded", + "hashes": [ + { + "alg": "SHA-256", + "content": "accd4ea62f7bb7a82fe23066fb0957d48ef677f6eeb8215f372f52e48bb32426" + } + ], + "licenses": [ + { + "expression": "MIT OR Apache-2.0" + } + ], + "purl": "pkg:cargo/vcpkg@0.2.15", + "externalReferences": [ + { + "type": "documentation", + "url": "https://docs.rs/vcpkg" + }, + { + "type": "vcs", + "url": "https://github.com/mcgoo/vcpkg-rs" + } + ] + } + ], + "dependencies": [ + { + "ref": "path+file:///D:/a/cryptography/cryptography/wheelhouse/.tmpsrzLM5/cryptography-48.0.0/src/rust#cryptography-rust@0.1.0", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#asn1@0.24.1", + "registry+https://github.com/rust-lang/crates.io-index#base64@0.22.1", + "registry+https://github.com/rust-lang/crates.io-index#cfg-if@1.0.4", + "path+file:///D:/a/cryptography/cryptography/wheelhouse/.tmpsrzLM5/cryptography-48.0.0/src/rust/cryptography-cffi#0.1.0", + "path+file:///D:/a/cryptography/cryptography/wheelhouse/.tmpsrzLM5/cryptography-48.0.0/src/rust/cryptography-crypto#0.1.0", + "path+file:///D:/a/cryptography/cryptography/wheelhouse/.tmpsrzLM5/cryptography-48.0.0/src/rust/cryptography-keepalive#0.1.0", + "path+file:///D:/a/cryptography/cryptography/wheelhouse/.tmpsrzLM5/cryptography-48.0.0/src/rust/cryptography-key-parsing#0.1.0", + "path+file:///D:/a/cryptography/cryptography/wheelhouse/.tmpsrzLM5/cryptography-48.0.0/src/rust/cryptography-openssl#0.1.0", + "path+file:///D:/a/cryptography/cryptography/wheelhouse/.tmpsrzLM5/cryptography-48.0.0/src/rust/cryptography-x509#0.1.0", + "path+file:///D:/a/cryptography/cryptography/wheelhouse/.tmpsrzLM5/cryptography-48.0.0/src/rust/cryptography-x509-verification#0.1.0", + "registry+https://github.com/rust-lang/crates.io-index#foreign-types-shared@0.1.1", + "registry+https://github.com/rust-lang/crates.io-index#openssl@0.10.79", + "registry+https://github.com/rust-lang/crates.io-index#openssl-sys@0.9.115", + "registry+https://github.com/rust-lang/crates.io-index#pem@3.0.6", + "registry+https://github.com/rust-lang/crates.io-index#pyo3@0.28.3", + "registry+https://github.com/rust-lang/crates.io-index#pyo3-build-config@0.28.3", + "registry+https://github.com/rust-lang/crates.io-index#self_cell@1.2.2" + ] + }, + { + "ref": "path+file:///D:/a/cryptography/cryptography/wheelhouse/.tmpsrzLM5/cryptography-48.0.0/src/rust/cryptography-cffi#0.1.0", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#cc@1.2.61", + "registry+https://github.com/rust-lang/crates.io-index#openssl-sys@0.9.115", + "registry+https://github.com/rust-lang/crates.io-index#pyo3@0.28.3" + ] + }, + { + "ref": "path+file:///D:/a/cryptography/cryptography/wheelhouse/.tmpsrzLM5/cryptography-48.0.0/src/rust/cryptography-crypto#0.1.0", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#openssl@0.10.79" + ] + }, + { + "ref": "path+file:///D:/a/cryptography/cryptography/wheelhouse/.tmpsrzLM5/cryptography-48.0.0/src/rust/cryptography-keepalive#0.1.0", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#pyo3@0.28.3" + ] + }, + { + "ref": "path+file:///D:/a/cryptography/cryptography/wheelhouse/.tmpsrzLM5/cryptography-48.0.0/src/rust/cryptography-key-parsing#0.1.0", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#asn1@0.24.1", + "registry+https://github.com/rust-lang/crates.io-index#cfg-if@1.0.4", + "path+file:///D:/a/cryptography/cryptography/wheelhouse/.tmpsrzLM5/cryptography-48.0.0/src/rust/cryptography-crypto#0.1.0", + "path+file:///D:/a/cryptography/cryptography/wheelhouse/.tmpsrzLM5/cryptography-48.0.0/src/rust/cryptography-openssl#0.1.0", + "path+file:///D:/a/cryptography/cryptography/wheelhouse/.tmpsrzLM5/cryptography-48.0.0/src/rust/cryptography-x509#0.1.0", + "registry+https://github.com/rust-lang/crates.io-index#openssl@0.10.79", + "registry+https://github.com/rust-lang/crates.io-index#openssl-sys@0.9.115", + "registry+https://github.com/rust-lang/crates.io-index#pem@3.0.6" + ] + }, + { + "ref": "path+file:///D:/a/cryptography/cryptography/wheelhouse/.tmpsrzLM5/cryptography-48.0.0/src/rust/cryptography-openssl#0.1.0", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#cfg-if@1.0.4", + "registry+https://github.com/rust-lang/crates.io-index#foreign-types@0.3.2", + "registry+https://github.com/rust-lang/crates.io-index#foreign-types-shared@0.1.1", + "registry+https://github.com/rust-lang/crates.io-index#openssl@0.10.79", + "registry+https://github.com/rust-lang/crates.io-index#openssl-sys@0.9.115" + ] + }, + { + "ref": "path+file:///D:/a/cryptography/cryptography/wheelhouse/.tmpsrzLM5/cryptography-48.0.0/src/rust/cryptography-x509#0.1.0", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#asn1@0.24.1" + ] + }, + { + "ref": "path+file:///D:/a/cryptography/cryptography/wheelhouse/.tmpsrzLM5/cryptography-48.0.0/src/rust/cryptography-x509-verification#0.1.0", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#asn1@0.24.1", + "path+file:///D:/a/cryptography/cryptography/wheelhouse/.tmpsrzLM5/cryptography-48.0.0/src/rust/cryptography-x509#0.1.0" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#asn1@0.24.1", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#asn1_derive@0.24.1", + "registry+https://github.com/rust-lang/crates.io-index#itoa@1.0.18" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#asn1_derive@0.24.1", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#proc-macro2@1.0.106", + "registry+https://github.com/rust-lang/crates.io-index#quote@1.0.45", + "registry+https://github.com/rust-lang/crates.io-index#syn@2.0.117" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#base64@0.22.1" + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#bitflags@2.11.1" + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#cc@1.2.61", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#find-msvc-tools@0.1.9", + "registry+https://github.com/rust-lang/crates.io-index#shlex@1.3.0" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#cfg-if@1.0.4" + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#find-msvc-tools@0.1.9" + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#foreign-types-shared@0.1.1" + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#foreign-types@0.3.2", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#foreign-types-shared@0.1.1" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#heck@0.5.0" + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#itoa@1.0.18" + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#libc@0.2.186" + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#once_cell@1.21.4" + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#openssl-macros@0.1.1", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#proc-macro2@1.0.106", + "registry+https://github.com/rust-lang/crates.io-index#quote@1.0.45", + "registry+https://github.com/rust-lang/crates.io-index#syn@2.0.117" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#openssl-sys@0.9.115", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#cc@1.2.61", + "registry+https://github.com/rust-lang/crates.io-index#libc@0.2.186", + "registry+https://github.com/rust-lang/crates.io-index#pkg-config@0.3.33", + "registry+https://github.com/rust-lang/crates.io-index#vcpkg@0.2.15" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#openssl@0.10.79", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#bitflags@2.11.1", + "registry+https://github.com/rust-lang/crates.io-index#cfg-if@1.0.4", + "registry+https://github.com/rust-lang/crates.io-index#foreign-types@0.3.2", + "registry+https://github.com/rust-lang/crates.io-index#libc@0.2.186", + "registry+https://github.com/rust-lang/crates.io-index#openssl-macros@0.1.1", + "registry+https://github.com/rust-lang/crates.io-index#openssl-sys@0.9.115" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#pem@3.0.6", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#base64@0.22.1" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#pkg-config@0.3.33" + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#portable-atomic@1.13.1" + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#proc-macro2@1.0.106", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#unicode-ident@1.0.24" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#pyo3-build-config@0.28.3", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#target-lexicon@0.13.5" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#pyo3-ffi@0.28.3", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#libc@0.2.186", + "registry+https://github.com/rust-lang/crates.io-index#pyo3-build-config@0.28.3" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#pyo3-macros-backend@0.28.3", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#heck@0.5.0", + "registry+https://github.com/rust-lang/crates.io-index#proc-macro2@1.0.106", + "registry+https://github.com/rust-lang/crates.io-index#pyo3-build-config@0.28.3", + "registry+https://github.com/rust-lang/crates.io-index#quote@1.0.45", + "registry+https://github.com/rust-lang/crates.io-index#syn@2.0.117" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#pyo3-macros@0.28.3", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#proc-macro2@1.0.106", + "registry+https://github.com/rust-lang/crates.io-index#pyo3-macros-backend@0.28.3", + "registry+https://github.com/rust-lang/crates.io-index#quote@1.0.45", + "registry+https://github.com/rust-lang/crates.io-index#syn@2.0.117" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#pyo3@0.28.3", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#libc@0.2.186", + "registry+https://github.com/rust-lang/crates.io-index#once_cell@1.21.4", + "registry+https://github.com/rust-lang/crates.io-index#portable-atomic@1.13.1", + "registry+https://github.com/rust-lang/crates.io-index#pyo3-build-config@0.28.3", + "registry+https://github.com/rust-lang/crates.io-index#pyo3-ffi@0.28.3", + "registry+https://github.com/rust-lang/crates.io-index#pyo3-macros@0.28.3" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#quote@1.0.45", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#proc-macro2@1.0.106" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#self_cell@1.2.2" + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#shlex@1.3.0" + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#syn@2.0.117", + "dependsOn": [ + "registry+https://github.com/rust-lang/crates.io-index#proc-macro2@1.0.106", + "registry+https://github.com/rust-lang/crates.io-index#quote@1.0.45", + "registry+https://github.com/rust-lang/crates.io-index#unicode-ident@1.0.24" + ] + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#target-lexicon@0.13.5" + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#unicode-ident@1.0.24" + }, + { + "ref": "registry+https://github.com/rust-lang/crates.io-index#vcpkg@0.2.15" + } + ] +} \ No newline at end of file diff --git a/python/user_packages/Python313/site-packages/cryptography-48.0.0.dist-info/sboms/sbom.json b/python/user_packages/Python313/site-packages/cryptography-48.0.0.dist-info/sboms/sbom.json new file mode 100644 index 0000000000000000000000000000000000000000..1fa8c3fa3c2b6eeeb785b90367a06eefa89c9cd3 --- /dev/null +++ b/python/user_packages/Python313/site-packages/cryptography-48.0.0.dist-info/sboms/sbom.json @@ -0,0 +1,43 @@ +{ + "bomFormat": "CycloneDX", + "specVersion": "1.5", + "version": 1, + "serialNumber": "urn:uuid:d28eacb5-bc17-4ccb-953b-1bf4fa4d4845", + "metadata": { + "timestamp": "2026-05-01T00:40:11Z" + }, + "components": [ + { + "type": "library", + "name": "openssl", + "version": "4.0.0", + "purl": "pkg:generic/openssl@4.0.0?download_url=https://github.com/openssl/openssl/releases/download/openssl-4.0.0/openssl-4.0.0.tar.gz", + "hashes": [ + { + "alg": "SHA-256", + "content": "c32cf49a959c4f345f9606982dd36e7d28f7c58b19c2e25d75624d2b3d2f79ac" + } + ], + "externalReferences": [ + { + "type": "distribution", + "url": "https://github.com/openssl/openssl/releases/download/openssl-4.0.0/openssl-4.0.0.tar.gz" + } + ], + "properties": [ + { + "name": "build:operating-system", + "value": "windows" + }, + { + "name": "build:architecture", + "value": "win64" + }, + { + "name": "build:flags", + "value": "no-zlib no-shared no-module no-comp no-apps no-docs no-sm2-precomp no-atexit" + } + ] + } + ] +} diff --git a/python/user_packages/Python313/site-packages/cryptography/__pycache__/__about__.cpython-313.pyc b/python/user_packages/Python313/site-packages/cryptography/__pycache__/__about__.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..56a52b99c4cb100756d56fa76b35d49572a6e695 Binary files /dev/null and b/python/user_packages/Python313/site-packages/cryptography/__pycache__/__about__.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/cryptography/__pycache__/__init__.cpython-313.pyc b/python/user_packages/Python313/site-packages/cryptography/__pycache__/__init__.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8b2cde36ace2011866256694a32c61a4f12c268c Binary files /dev/null and b/python/user_packages/Python313/site-packages/cryptography/__pycache__/__init__.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/cryptography/__pycache__/exceptions.cpython-313.pyc b/python/user_packages/Python313/site-packages/cryptography/__pycache__/exceptions.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5f051977f8a7462f6ff38df8bf31c73b2462ed3c Binary files /dev/null and b/python/user_packages/Python313/site-packages/cryptography/__pycache__/exceptions.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/cryptography/__pycache__/fernet.cpython-313.pyc b/python/user_packages/Python313/site-packages/cryptography/__pycache__/fernet.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..bb8071cf208b0a22387551d6c856b6c2b6cae210 Binary files /dev/null and b/python/user_packages/Python313/site-packages/cryptography/__pycache__/fernet.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/cryptography/__pycache__/utils.cpython-313.pyc b/python/user_packages/Python313/site-packages/cryptography/__pycache__/utils.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..04ae815e9940aaac128f29f108c611a4a9910b32 Binary files /dev/null and b/python/user_packages/Python313/site-packages/cryptography/__pycache__/utils.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/cryptography/hazmat/__init__.py b/python/user_packages/Python313/site-packages/cryptography/hazmat/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..b9f1187011bdaa0720bc462564582393700f3d4a --- /dev/null +++ b/python/user_packages/Python313/site-packages/cryptography/hazmat/__init__.py @@ -0,0 +1,13 @@ +# This file is dual licensed under the terms of the Apache License, Version +# 2.0, and the BSD License. See the LICENSE file in the root of this repository +# for complete details. + +from __future__ import annotations + +""" +Hazardous Materials + +This is a "Hazardous Materials" module. You should ONLY use it if you're +100% absolutely sure that you know what you're doing because this module +is full of land mines, dragons, and dinosaurs with laser guns. +""" diff --git a/python/user_packages/Python313/site-packages/cryptography/hazmat/__pycache__/__init__.cpython-313.pyc b/python/user_packages/Python313/site-packages/cryptography/hazmat/__pycache__/__init__.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b77f4942bd1a67c427fabf04248958d43811701c Binary files /dev/null and b/python/user_packages/Python313/site-packages/cryptography/hazmat/__pycache__/__init__.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/cryptography/hazmat/__pycache__/_oid.cpython-313.pyc b/python/user_packages/Python313/site-packages/cryptography/hazmat/__pycache__/_oid.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..355e51d468dea7a69296e9dd19095e2f40632d84 Binary files /dev/null and b/python/user_packages/Python313/site-packages/cryptography/hazmat/__pycache__/_oid.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/cryptography/hazmat/_oid.py b/python/user_packages/Python313/site-packages/cryptography/hazmat/_oid.py new file mode 100644 index 0000000000000000000000000000000000000000..4bf138d4f80b8e83e0657577e338270df18fcdcd --- /dev/null +++ b/python/user_packages/Python313/site-packages/cryptography/hazmat/_oid.py @@ -0,0 +1,356 @@ +# This file is dual licensed under the terms of the Apache License, Version +# 2.0, and the BSD License. See the LICENSE file in the root of this repository +# for complete details. + +from __future__ import annotations + +from cryptography.hazmat.bindings._rust import ( + ObjectIdentifier as ObjectIdentifier, +) +from cryptography.hazmat.primitives import hashes + + +class ExtensionOID: + SUBJECT_DIRECTORY_ATTRIBUTES = ObjectIdentifier("2.5.29.9") + SUBJECT_KEY_IDENTIFIER = ObjectIdentifier("2.5.29.14") + KEY_USAGE = ObjectIdentifier("2.5.29.15") + PRIVATE_KEY_USAGE_PERIOD = ObjectIdentifier("2.5.29.16") + SUBJECT_ALTERNATIVE_NAME = ObjectIdentifier("2.5.29.17") + ISSUER_ALTERNATIVE_NAME = ObjectIdentifier("2.5.29.18") + BASIC_CONSTRAINTS = ObjectIdentifier("2.5.29.19") + NAME_CONSTRAINTS = ObjectIdentifier("2.5.29.30") + CRL_DISTRIBUTION_POINTS = ObjectIdentifier("2.5.29.31") + CERTIFICATE_POLICIES = ObjectIdentifier("2.5.29.32") + POLICY_MAPPINGS = ObjectIdentifier("2.5.29.33") + AUTHORITY_KEY_IDENTIFIER = ObjectIdentifier("2.5.29.35") + POLICY_CONSTRAINTS = ObjectIdentifier("2.5.29.36") + EXTENDED_KEY_USAGE = ObjectIdentifier("2.5.29.37") + FRESHEST_CRL = ObjectIdentifier("2.5.29.46") + INHIBIT_ANY_POLICY = ObjectIdentifier("2.5.29.54") + ISSUING_DISTRIBUTION_POINT = ObjectIdentifier("2.5.29.28") + AUTHORITY_INFORMATION_ACCESS = ObjectIdentifier("1.3.6.1.5.5.7.1.1") + SUBJECT_INFORMATION_ACCESS = ObjectIdentifier("1.3.6.1.5.5.7.1.11") + OCSP_NO_CHECK = ObjectIdentifier("1.3.6.1.5.5.7.48.1.5") + TLS_FEATURE = ObjectIdentifier("1.3.6.1.5.5.7.1.24") + CRL_NUMBER = ObjectIdentifier("2.5.29.20") + DELTA_CRL_INDICATOR = ObjectIdentifier("2.5.29.27") + PRECERT_SIGNED_CERTIFICATE_TIMESTAMPS = ObjectIdentifier( + "1.3.6.1.4.1.11129.2.4.2" + ) + PRECERT_POISON = ObjectIdentifier("1.3.6.1.4.1.11129.2.4.3") + SIGNED_CERTIFICATE_TIMESTAMPS = ObjectIdentifier("1.3.6.1.4.1.11129.2.4.5") + MS_CERTIFICATE_TEMPLATE = ObjectIdentifier("1.3.6.1.4.1.311.21.7") + ADMISSIONS = ObjectIdentifier("1.3.36.8.3.3") + + +class OCSPExtensionOID: + NONCE = ObjectIdentifier("1.3.6.1.5.5.7.48.1.2") + ACCEPTABLE_RESPONSES = ObjectIdentifier("1.3.6.1.5.5.7.48.1.4") + + +class CRLEntryExtensionOID: + CERTIFICATE_ISSUER = ObjectIdentifier("2.5.29.29") + CRL_REASON = ObjectIdentifier("2.5.29.21") + INVALIDITY_DATE = ObjectIdentifier("2.5.29.24") + + +class NameOID: + COMMON_NAME = ObjectIdentifier("2.5.4.3") + COUNTRY_NAME = ObjectIdentifier("2.5.4.6") + LOCALITY_NAME = ObjectIdentifier("2.5.4.7") + STATE_OR_PROVINCE_NAME = ObjectIdentifier("2.5.4.8") + STREET_ADDRESS = ObjectIdentifier("2.5.4.9") + ORGANIZATION_IDENTIFIER = ObjectIdentifier("2.5.4.97") + ORGANIZATION_NAME = ObjectIdentifier("2.5.4.10") + ORGANIZATIONAL_UNIT_NAME = ObjectIdentifier("2.5.4.11") + SERIAL_NUMBER = ObjectIdentifier("2.5.4.5") + SURNAME = ObjectIdentifier("2.5.4.4") + GIVEN_NAME = ObjectIdentifier("2.5.4.42") + TITLE = ObjectIdentifier("2.5.4.12") + INITIALS = ObjectIdentifier("2.5.4.43") + GENERATION_QUALIFIER = ObjectIdentifier("2.5.4.44") + X500_UNIQUE_IDENTIFIER = ObjectIdentifier("2.5.4.45") + DN_QUALIFIER = ObjectIdentifier("2.5.4.46") + PSEUDONYM = ObjectIdentifier("2.5.4.65") + USER_ID = ObjectIdentifier("0.9.2342.19200300.100.1.1") + DOMAIN_COMPONENT = ObjectIdentifier("0.9.2342.19200300.100.1.25") + EMAIL_ADDRESS = ObjectIdentifier("1.2.840.113549.1.9.1") + JURISDICTION_COUNTRY_NAME = ObjectIdentifier("1.3.6.1.4.1.311.60.2.1.3") + JURISDICTION_LOCALITY_NAME = ObjectIdentifier("1.3.6.1.4.1.311.60.2.1.1") + JURISDICTION_STATE_OR_PROVINCE_NAME = ObjectIdentifier( + "1.3.6.1.4.1.311.60.2.1.2" + ) + BUSINESS_CATEGORY = ObjectIdentifier("2.5.4.15") + POSTAL_ADDRESS = ObjectIdentifier("2.5.4.16") + POSTAL_CODE = ObjectIdentifier("2.5.4.17") + INN = ObjectIdentifier("1.2.643.3.131.1.1") + OGRN = ObjectIdentifier("1.2.643.100.1") + SNILS = ObjectIdentifier("1.2.643.100.3") + UNSTRUCTURED_NAME = ObjectIdentifier("1.2.840.113549.1.9.2") + + +class SignatureAlgorithmOID: + RSA_WITH_MD5 = ObjectIdentifier("1.2.840.113549.1.1.4") + RSA_WITH_SHA1 = ObjectIdentifier("1.2.840.113549.1.1.5") + # This is an alternate OID for RSA with SHA1 that is occasionally seen + _RSA_WITH_SHA1 = ObjectIdentifier("1.3.14.3.2.29") + RSA_WITH_SHA224 = ObjectIdentifier("1.2.840.113549.1.1.14") + RSA_WITH_SHA256 = ObjectIdentifier("1.2.840.113549.1.1.11") + RSA_WITH_SHA384 = ObjectIdentifier("1.2.840.113549.1.1.12") + RSA_WITH_SHA512 = ObjectIdentifier("1.2.840.113549.1.1.13") + RSA_WITH_SHA3_224 = ObjectIdentifier("2.16.840.1.101.3.4.3.13") + RSA_WITH_SHA3_256 = ObjectIdentifier("2.16.840.1.101.3.4.3.14") + RSA_WITH_SHA3_384 = ObjectIdentifier("2.16.840.1.101.3.4.3.15") + RSA_WITH_SHA3_512 = ObjectIdentifier("2.16.840.1.101.3.4.3.16") + RSASSA_PSS = ObjectIdentifier("1.2.840.113549.1.1.10") + ECDSA_WITH_SHA1 = ObjectIdentifier("1.2.840.10045.4.1") + ECDSA_WITH_SHA224 = ObjectIdentifier("1.2.840.10045.4.3.1") + ECDSA_WITH_SHA256 = ObjectIdentifier("1.2.840.10045.4.3.2") + ECDSA_WITH_SHA384 = ObjectIdentifier("1.2.840.10045.4.3.3") + ECDSA_WITH_SHA512 = ObjectIdentifier("1.2.840.10045.4.3.4") + ECDSA_WITH_SHA3_224 = ObjectIdentifier("2.16.840.1.101.3.4.3.9") + ECDSA_WITH_SHA3_256 = ObjectIdentifier("2.16.840.1.101.3.4.3.10") + ECDSA_WITH_SHA3_384 = ObjectIdentifier("2.16.840.1.101.3.4.3.11") + ECDSA_WITH_SHA3_512 = ObjectIdentifier("2.16.840.1.101.3.4.3.12") + DSA_WITH_SHA1 = ObjectIdentifier("1.2.840.10040.4.3") + DSA_WITH_SHA224 = ObjectIdentifier("2.16.840.1.101.3.4.3.1") + DSA_WITH_SHA256 = ObjectIdentifier("2.16.840.1.101.3.4.3.2") + DSA_WITH_SHA384 = ObjectIdentifier("2.16.840.1.101.3.4.3.3") + DSA_WITH_SHA512 = ObjectIdentifier("2.16.840.1.101.3.4.3.4") + ED25519 = ObjectIdentifier("1.3.101.112") + ED448 = ObjectIdentifier("1.3.101.113") + GOSTR3411_94_WITH_3410_2001 = ObjectIdentifier("1.2.643.2.2.3") + GOSTR3410_2012_WITH_3411_2012_256 = ObjectIdentifier("1.2.643.7.1.1.3.2") + GOSTR3410_2012_WITH_3411_2012_512 = ObjectIdentifier("1.2.643.7.1.1.3.3") + + +_SIG_OIDS_TO_HASH: dict[ObjectIdentifier, hashes.HashAlgorithm | None] = { + SignatureAlgorithmOID.RSA_WITH_MD5: hashes.MD5(), + SignatureAlgorithmOID.RSA_WITH_SHA1: hashes.SHA1(), + SignatureAlgorithmOID._RSA_WITH_SHA1: hashes.SHA1(), + SignatureAlgorithmOID.RSA_WITH_SHA224: hashes.SHA224(), + SignatureAlgorithmOID.RSA_WITH_SHA256: hashes.SHA256(), + SignatureAlgorithmOID.RSA_WITH_SHA384: hashes.SHA384(), + SignatureAlgorithmOID.RSA_WITH_SHA512: hashes.SHA512(), + SignatureAlgorithmOID.RSA_WITH_SHA3_224: hashes.SHA3_224(), + SignatureAlgorithmOID.RSA_WITH_SHA3_256: hashes.SHA3_256(), + SignatureAlgorithmOID.RSA_WITH_SHA3_384: hashes.SHA3_384(), + SignatureAlgorithmOID.RSA_WITH_SHA3_512: hashes.SHA3_512(), + SignatureAlgorithmOID.ECDSA_WITH_SHA1: hashes.SHA1(), + SignatureAlgorithmOID.ECDSA_WITH_SHA224: hashes.SHA224(), + SignatureAlgorithmOID.ECDSA_WITH_SHA256: hashes.SHA256(), + SignatureAlgorithmOID.ECDSA_WITH_SHA384: hashes.SHA384(), + SignatureAlgorithmOID.ECDSA_WITH_SHA512: hashes.SHA512(), + SignatureAlgorithmOID.ECDSA_WITH_SHA3_224: hashes.SHA3_224(), + SignatureAlgorithmOID.ECDSA_WITH_SHA3_256: hashes.SHA3_256(), + SignatureAlgorithmOID.ECDSA_WITH_SHA3_384: hashes.SHA3_384(), + SignatureAlgorithmOID.ECDSA_WITH_SHA3_512: hashes.SHA3_512(), + SignatureAlgorithmOID.DSA_WITH_SHA1: hashes.SHA1(), + SignatureAlgorithmOID.DSA_WITH_SHA224: hashes.SHA224(), + SignatureAlgorithmOID.DSA_WITH_SHA256: hashes.SHA256(), + SignatureAlgorithmOID.ED25519: None, + SignatureAlgorithmOID.ED448: None, + SignatureAlgorithmOID.GOSTR3411_94_WITH_3410_2001: None, + SignatureAlgorithmOID.GOSTR3410_2012_WITH_3411_2012_256: None, + SignatureAlgorithmOID.GOSTR3410_2012_WITH_3411_2012_512: None, +} + + +class HashAlgorithmOID: + SHA1 = ObjectIdentifier("1.3.14.3.2.26") + SHA224 = ObjectIdentifier("2.16.840.1.101.3.4.2.4") + SHA256 = ObjectIdentifier("2.16.840.1.101.3.4.2.1") + SHA384 = ObjectIdentifier("2.16.840.1.101.3.4.2.2") + SHA512 = ObjectIdentifier("2.16.840.1.101.3.4.2.3") + SHA3_224 = ObjectIdentifier("1.3.6.1.4.1.37476.3.2.1.99.7.224") + SHA3_256 = ObjectIdentifier("1.3.6.1.4.1.37476.3.2.1.99.7.256") + SHA3_384 = ObjectIdentifier("1.3.6.1.4.1.37476.3.2.1.99.7.384") + SHA3_512 = ObjectIdentifier("1.3.6.1.4.1.37476.3.2.1.99.7.512") + SHA3_224_NIST = ObjectIdentifier("2.16.840.1.101.3.4.2.7") + SHA3_256_NIST = ObjectIdentifier("2.16.840.1.101.3.4.2.8") + SHA3_384_NIST = ObjectIdentifier("2.16.840.1.101.3.4.2.9") + SHA3_512_NIST = ObjectIdentifier("2.16.840.1.101.3.4.2.10") + + +class PublicKeyAlgorithmOID: + DSA = ObjectIdentifier("1.2.840.10040.4.1") + EC_PUBLIC_KEY = ObjectIdentifier("1.2.840.10045.2.1") + RSAES_PKCS1_v1_5 = ObjectIdentifier("1.2.840.113549.1.1.1") + RSASSA_PSS = ObjectIdentifier("1.2.840.113549.1.1.10") + X25519 = ObjectIdentifier("1.3.101.110") + X448 = ObjectIdentifier("1.3.101.111") + ED25519 = ObjectIdentifier("1.3.101.112") + ED448 = ObjectIdentifier("1.3.101.113") + + +class ExtendedKeyUsageOID: + SERVER_AUTH = ObjectIdentifier("1.3.6.1.5.5.7.3.1") + CLIENT_AUTH = ObjectIdentifier("1.3.6.1.5.5.7.3.2") + CODE_SIGNING = ObjectIdentifier("1.3.6.1.5.5.7.3.3") + EMAIL_PROTECTION = ObjectIdentifier("1.3.6.1.5.5.7.3.4") + TIME_STAMPING = ObjectIdentifier("1.3.6.1.5.5.7.3.8") + OCSP_SIGNING = ObjectIdentifier("1.3.6.1.5.5.7.3.9") + ANY_EXTENDED_KEY_USAGE = ObjectIdentifier("2.5.29.37.0") + SMARTCARD_LOGON = ObjectIdentifier("1.3.6.1.4.1.311.20.2.2") + KERBEROS_PKINIT_KDC = ObjectIdentifier("1.3.6.1.5.2.3.5") + IPSEC_IKE = ObjectIdentifier("1.3.6.1.5.5.7.3.17") + BUNDLE_SECURITY = ObjectIdentifier("1.3.6.1.5.5.7.3.35") + CERTIFICATE_TRANSPARENCY = ObjectIdentifier("1.3.6.1.4.1.11129.2.4.4") + + +class OtherNameFormOID: + PERMANENT_IDENTIFIER = ObjectIdentifier("1.3.6.1.5.5.7.8.3") + HW_MODULE_NAME = ObjectIdentifier("1.3.6.1.5.5.7.8.4") + DNS_SRV = ObjectIdentifier("1.3.6.1.5.5.7.8.7") + NAI_REALM = ObjectIdentifier("1.3.6.1.5.5.7.8.8") + SMTP_UTF8_MAILBOX = ObjectIdentifier("1.3.6.1.5.5.7.8.9") + ACP_NODE_NAME = ObjectIdentifier("1.3.6.1.5.5.7.8.10") + BUNDLE_EID = ObjectIdentifier("1.3.6.1.5.5.7.8.11") + + +class AuthorityInformationAccessOID: + CA_ISSUERS = ObjectIdentifier("1.3.6.1.5.5.7.48.2") + OCSP = ObjectIdentifier("1.3.6.1.5.5.7.48.1") + + +class SubjectInformationAccessOID: + CA_REPOSITORY = ObjectIdentifier("1.3.6.1.5.5.7.48.5") + + +class CertificatePoliciesOID: + CPS_QUALIFIER = ObjectIdentifier("1.3.6.1.5.5.7.2.1") + CPS_USER_NOTICE = ObjectIdentifier("1.3.6.1.5.5.7.2.2") + ANY_POLICY = ObjectIdentifier("2.5.29.32.0") + + +class AttributeOID: + CHALLENGE_PASSWORD = ObjectIdentifier("1.2.840.113549.1.9.7") + UNSTRUCTURED_NAME = ObjectIdentifier("1.2.840.113549.1.9.2") + + +_OID_NAMES = { + NameOID.COMMON_NAME: "commonName", + NameOID.COUNTRY_NAME: "countryName", + NameOID.LOCALITY_NAME: "localityName", + NameOID.STATE_OR_PROVINCE_NAME: "stateOrProvinceName", + NameOID.STREET_ADDRESS: "streetAddress", + NameOID.ORGANIZATION_NAME: "organizationName", + NameOID.ORGANIZATIONAL_UNIT_NAME: "organizationalUnitName", + NameOID.SERIAL_NUMBER: "serialNumber", + NameOID.SURNAME: "surname", + NameOID.GIVEN_NAME: "givenName", + NameOID.TITLE: "title", + NameOID.GENERATION_QUALIFIER: "generationQualifier", + NameOID.X500_UNIQUE_IDENTIFIER: "x500UniqueIdentifier", + NameOID.DN_QUALIFIER: "dnQualifier", + NameOID.PSEUDONYM: "pseudonym", + NameOID.USER_ID: "userID", + NameOID.DOMAIN_COMPONENT: "domainComponent", + NameOID.EMAIL_ADDRESS: "emailAddress", + NameOID.JURISDICTION_COUNTRY_NAME: "jurisdictionCountryName", + NameOID.JURISDICTION_LOCALITY_NAME: "jurisdictionLocalityName", + NameOID.JURISDICTION_STATE_OR_PROVINCE_NAME: ( + "jurisdictionStateOrProvinceName" + ), + NameOID.BUSINESS_CATEGORY: "businessCategory", + NameOID.POSTAL_ADDRESS: "postalAddress", + NameOID.POSTAL_CODE: "postalCode", + NameOID.INN: "INN", + NameOID.OGRN: "OGRN", + NameOID.SNILS: "SNILS", + NameOID.UNSTRUCTURED_NAME: "unstructuredName", + SignatureAlgorithmOID.RSA_WITH_MD5: "md5WithRSAEncryption", + SignatureAlgorithmOID.RSA_WITH_SHA1: "sha1WithRSAEncryption", + SignatureAlgorithmOID.RSA_WITH_SHA224: "sha224WithRSAEncryption", + SignatureAlgorithmOID.RSA_WITH_SHA256: "sha256WithRSAEncryption", + SignatureAlgorithmOID.RSA_WITH_SHA384: "sha384WithRSAEncryption", + SignatureAlgorithmOID.RSA_WITH_SHA512: "sha512WithRSAEncryption", + SignatureAlgorithmOID.RSASSA_PSS: "rsassaPss", + SignatureAlgorithmOID.ECDSA_WITH_SHA1: "ecdsa-with-SHA1", + SignatureAlgorithmOID.ECDSA_WITH_SHA224: "ecdsa-with-SHA224", + SignatureAlgorithmOID.ECDSA_WITH_SHA256: "ecdsa-with-SHA256", + SignatureAlgorithmOID.ECDSA_WITH_SHA384: "ecdsa-with-SHA384", + SignatureAlgorithmOID.ECDSA_WITH_SHA512: "ecdsa-with-SHA512", + SignatureAlgorithmOID.DSA_WITH_SHA1: "dsa-with-sha1", + SignatureAlgorithmOID.DSA_WITH_SHA224: "dsa-with-sha224", + SignatureAlgorithmOID.DSA_WITH_SHA256: "dsa-with-sha256", + SignatureAlgorithmOID.ED25519: "ed25519", + SignatureAlgorithmOID.ED448: "ed448", + SignatureAlgorithmOID.GOSTR3411_94_WITH_3410_2001: ( + "GOST R 34.11-94 with GOST R 34.10-2001" + ), + SignatureAlgorithmOID.GOSTR3410_2012_WITH_3411_2012_256: ( + "GOST R 34.10-2012 with GOST R 34.11-2012 (256 bit)" + ), + SignatureAlgorithmOID.GOSTR3410_2012_WITH_3411_2012_512: ( + "GOST R 34.10-2012 with GOST R 34.11-2012 (512 bit)" + ), + HashAlgorithmOID.SHA1: "sha1", + HashAlgorithmOID.SHA224: "sha224", + HashAlgorithmOID.SHA256: "sha256", + HashAlgorithmOID.SHA384: "sha384", + HashAlgorithmOID.SHA512: "sha512", + HashAlgorithmOID.SHA3_224: "sha3_224", + HashAlgorithmOID.SHA3_256: "sha3_256", + HashAlgorithmOID.SHA3_384: "sha3_384", + HashAlgorithmOID.SHA3_512: "sha3_512", + HashAlgorithmOID.SHA3_224_NIST: "sha3_224", + HashAlgorithmOID.SHA3_256_NIST: "sha3_256", + HashAlgorithmOID.SHA3_384_NIST: "sha3_384", + HashAlgorithmOID.SHA3_512_NIST: "sha3_512", + PublicKeyAlgorithmOID.DSA: "dsaEncryption", + PublicKeyAlgorithmOID.EC_PUBLIC_KEY: "id-ecPublicKey", + PublicKeyAlgorithmOID.RSAES_PKCS1_v1_5: "rsaEncryption", + PublicKeyAlgorithmOID.X25519: "X25519", + PublicKeyAlgorithmOID.X448: "X448", + ExtendedKeyUsageOID.SERVER_AUTH: "serverAuth", + ExtendedKeyUsageOID.CLIENT_AUTH: "clientAuth", + ExtendedKeyUsageOID.CODE_SIGNING: "codeSigning", + ExtendedKeyUsageOID.EMAIL_PROTECTION: "emailProtection", + ExtendedKeyUsageOID.TIME_STAMPING: "timeStamping", + ExtendedKeyUsageOID.OCSP_SIGNING: "OCSPSigning", + ExtendedKeyUsageOID.SMARTCARD_LOGON: "msSmartcardLogin", + ExtendedKeyUsageOID.KERBEROS_PKINIT_KDC: "pkInitKDC", + ExtensionOID.SUBJECT_DIRECTORY_ATTRIBUTES: "subjectDirectoryAttributes", + ExtensionOID.SUBJECT_KEY_IDENTIFIER: "subjectKeyIdentifier", + ExtensionOID.KEY_USAGE: "keyUsage", + ExtensionOID.PRIVATE_KEY_USAGE_PERIOD: "privateKeyUsagePeriod", + ExtensionOID.SUBJECT_ALTERNATIVE_NAME: "subjectAltName", + ExtensionOID.ISSUER_ALTERNATIVE_NAME: "issuerAltName", + ExtensionOID.BASIC_CONSTRAINTS: "basicConstraints", + ExtensionOID.PRECERT_SIGNED_CERTIFICATE_TIMESTAMPS: ( + "signedCertificateTimestampList" + ), + ExtensionOID.SIGNED_CERTIFICATE_TIMESTAMPS: ( + "signedCertificateTimestampList" + ), + ExtensionOID.PRECERT_POISON: "ctPoison", + ExtensionOID.MS_CERTIFICATE_TEMPLATE: "msCertificateTemplate", + ExtensionOID.ADMISSIONS: "Admissions", + CRLEntryExtensionOID.CRL_REASON: "cRLReason", + CRLEntryExtensionOID.INVALIDITY_DATE: "invalidityDate", + CRLEntryExtensionOID.CERTIFICATE_ISSUER: "certificateIssuer", + ExtensionOID.NAME_CONSTRAINTS: "nameConstraints", + ExtensionOID.CRL_DISTRIBUTION_POINTS: "cRLDistributionPoints", + ExtensionOID.CERTIFICATE_POLICIES: "certificatePolicies", + ExtensionOID.POLICY_MAPPINGS: "policyMappings", + ExtensionOID.AUTHORITY_KEY_IDENTIFIER: "authorityKeyIdentifier", + ExtensionOID.POLICY_CONSTRAINTS: "policyConstraints", + ExtensionOID.EXTENDED_KEY_USAGE: "extendedKeyUsage", + ExtensionOID.FRESHEST_CRL: "freshestCRL", + ExtensionOID.INHIBIT_ANY_POLICY: "inhibitAnyPolicy", + ExtensionOID.ISSUING_DISTRIBUTION_POINT: "issuingDistributionPoint", + ExtensionOID.AUTHORITY_INFORMATION_ACCESS: "authorityInfoAccess", + ExtensionOID.SUBJECT_INFORMATION_ACCESS: "subjectInfoAccess", + ExtensionOID.OCSP_NO_CHECK: "OCSPNoCheck", + ExtensionOID.CRL_NUMBER: "cRLNumber", + ExtensionOID.DELTA_CRL_INDICATOR: "deltaCRLIndicator", + ExtensionOID.TLS_FEATURE: "TLSFeature", + AuthorityInformationAccessOID.OCSP: "OCSP", + AuthorityInformationAccessOID.CA_ISSUERS: "caIssuers", + SubjectInformationAccessOID.CA_REPOSITORY: "caRepository", + CertificatePoliciesOID.CPS_QUALIFIER: "id-qt-cps", + CertificatePoliciesOID.CPS_USER_NOTICE: "id-qt-unotice", + OCSPExtensionOID.NONCE: "OCSPNonce", + AttributeOID.CHALLENGE_PASSWORD: "challengePassword", +} diff --git a/python/user_packages/Python313/site-packages/cryptography/hazmat/asn1/__init__.py b/python/user_packages/Python313/site-packages/cryptography/hazmat/asn1/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..ac3d4bd8590b56f20ac1d9e8cd68221f47cce16b --- /dev/null +++ b/python/user_packages/Python313/site-packages/cryptography/hazmat/asn1/__init__.py @@ -0,0 +1,43 @@ +# This file is dual licensed under the terms of the Apache License, Version +# 2.0, and the BSD License. See the LICENSE file in the root of this repository +# for complete details. + +from cryptography.hazmat.asn1.asn1 import ( + TLV, + BitString, + Default, + Explicit, + GeneralizedTime, + IA5String, + Implicit, + Null, + PrintableString, + SetOf, + Size, + UTCTime, + Variant, + decode_der, + encode_der, + sequence, + set, +) + +__all__ = [ + "TLV", + "BitString", + "Default", + "Explicit", + "GeneralizedTime", + "IA5String", + "Implicit", + "Null", + "PrintableString", + "SetOf", + "Size", + "UTCTime", + "Variant", + "decode_der", + "encode_der", + "sequence", + "set", +] diff --git a/python/user_packages/Python313/site-packages/cryptography/hazmat/asn1/__pycache__/__init__.cpython-313.pyc b/python/user_packages/Python313/site-packages/cryptography/hazmat/asn1/__pycache__/__init__.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5d328dfbbe274087363326272f2cd10a1bfe9519 Binary files /dev/null and b/python/user_packages/Python313/site-packages/cryptography/hazmat/asn1/__pycache__/__init__.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/cryptography/hazmat/asn1/__pycache__/asn1.cpython-313.pyc b/python/user_packages/Python313/site-packages/cryptography/hazmat/asn1/__pycache__/asn1.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ea7a9688f462adde0976e501d332750ef176cc47 Binary files /dev/null and b/python/user_packages/Python313/site-packages/cryptography/hazmat/asn1/__pycache__/asn1.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/cryptography/hazmat/asn1/asn1.py b/python/user_packages/Python313/site-packages/cryptography/hazmat/asn1/asn1.py new file mode 100644 index 0000000000000000000000000000000000000000..aa18d7e5aa5206a78745ba549ed2a7b2fc8563fe --- /dev/null +++ b/python/user_packages/Python313/site-packages/cryptography/hazmat/asn1/asn1.py @@ -0,0 +1,419 @@ +# This file is dual licensed under the terms of the Apache License, Version +# 2.0, and the BSD License. See the LICENSE file in the root of this repository +# for complete details. + +from __future__ import annotations + +import builtins +import dataclasses +import sys +import types +import typing + +if sys.version_info < (3, 11): + import typing_extensions + + LiteralString = typing_extensions.LiteralString +else: + LiteralString = typing.LiteralString + +from cryptography.hazmat.bindings._rust import declarative_asn1 + +if sys.version_info < (3, 10): + NoneType = type(None) +else: + NoneType = types.NoneType # type: ignore[nonetype-type] + +T = typing.TypeVar("T", covariant=True) +U = typing.TypeVar("U") +Tag = typing.TypeVar("Tag", bound=LiteralString) + + +@dataclasses.dataclass(frozen=True) +class Variant(typing.Generic[U, Tag]): + """ + A tagged variant for CHOICE fields with the same underlying type. + + Use this when you have multiple CHOICE alternatives with the same type + and need to distinguish between them: + + foo: ( + Annotated[Variant[int, typing.Literal["IntA"]], Implicit(0)] + | Annotated[Variant[int, typing.Literal["IntB"]], Implicit(1)] + ) + + Usage: + example = Example(foo=Variant(5, "IntA")) + decoded.foo.value # The int value + decoded.foo.tag # "IntA" or "IntB" + """ + + value: U + tag: str + + +decode_der = declarative_asn1.decode_der +encode_der = declarative_asn1.encode_der + + +def _is_union(field_type: type) -> bool: + # NOTE: types.UnionType for `T | U`, typing.Union for `Union[T, U]`. + # TODO: Drop the `hasattr()` once the minimum supported Python version + # is >= 3.10. + union_types = ( + (types.UnionType, typing.Union) + if hasattr(types, "UnionType") + else (typing.Union,) + ) + return typing.get_origin(field_type) in union_types + + +def _extract_annotation( + metadata: tuple, field_name: str +) -> declarative_asn1.Annotation: + default = None + encoding = None + size = None + for raw_annotation in metadata: + if isinstance(raw_annotation, Default): + if default is not None: + raise TypeError( + f"multiple DEFAULT annotations found in field " + f"'{field_name}'" + ) + default = raw_annotation.value + elif isinstance(raw_annotation, declarative_asn1.Encoding): + if encoding is not None: + raise TypeError( + f"multiple IMPLICIT/EXPLICIT annotations found in field " + f"'{field_name}'" + ) + encoding = raw_annotation + elif isinstance(raw_annotation, declarative_asn1.Size): + if size is not None: + raise TypeError( + f"multiple SIZE annotations found in field '{field_name}'" + ) + size = raw_annotation + else: + raise TypeError(f"unsupported annotation: {raw_annotation}") + + return declarative_asn1.Annotation( + default=default, encoding=encoding, size=size + ) + + +def _normalize_field_type( + field_type: typing.Any, field_name: str +) -> declarative_asn1.AnnotatedType: + # Strip the `Annotated[...]` off, and populate the annotation + # from it if it exists. + if typing.get_origin(field_type) is typing.Annotated: + annotation = _extract_annotation(field_type.__metadata__, field_name) + field_type, *_ = typing.get_args(field_type) + else: + annotation = declarative_asn1.Annotation() + + if annotation.size is not None and ( + typing.get_origin(field_type) not in (builtins.list, SetOf) + and field_type + not in ( + builtins.bytes, + builtins.str, + BitString, + IA5String, + PrintableString, + ) + ): + raise TypeError( + f"field '{field_name}' has a SIZE annotation, but SIZE " + "annotations are only supported for fields of types: " + "[SEQUENCE OF, SET OF, BIT STRING, OCTET STRING, UTF8String, " + "PrintableString, IA5String]" + ) + + if field_type is TLV: + if isinstance(annotation.encoding, Implicit): + raise TypeError( + f"field '{field_name}' has an IMPLICIT annotation, but " + "IMPLICIT annotations are not supported for TLV types." + ) + elif annotation.default is not None: + raise TypeError( + f"field '{field_name}' has a DEFAULT annotation, but " + "DEFAULT annotations are not supported for TLV types." + ) + + if hasattr(field_type, "__asn1_root__"): + root_type = field_type.__asn1_root__ + if not isinstance( + root_type, + (declarative_asn1.Type.Sequence, declarative_asn1.Type.Set), + ): + raise TypeError(f"unsupported root type: {root_type}") + return declarative_asn1.AnnotatedType( + typing.cast(declarative_asn1.Type, root_type), annotation + ) + elif _is_union(field_type): + union_args = typing.get_args(field_type) + if len(union_args) == 2 and NoneType in union_args: + # A Union between a type and None is an OPTIONAL + optional_type = ( + union_args[0] if union_args[1] is type(None) else union_args[1] + ) + if optional_type is TLV: + raise TypeError( + "optional TLV types (`TLV | None`) are not " + "currently supported" + ) + annotated_type = _normalize_field_type(optional_type, field_name) + + if not annotated_type.annotation.is_empty(): + raise TypeError( + "optional (`X | None`) types cannot have `X` " + "annotated: annotations must apply to the union " + "(i.e: `Annotated[X | None, annotation]`)" + ) + + if annotation.default is not None: + raise TypeError( + "optional (`X | None`) types should not have a DEFAULT " + "annotation" + ) + + rust_field_type = declarative_asn1.Type.Option(annotated_type) + + else: + # Otherwise, the Union is a CHOICE + if isinstance(annotation.encoding, Implicit): + # CHOICEs cannot be IMPLICIT. See X.680 section 31.2.9. + raise TypeError( + "CHOICE (`X | Y | ...`) types should not have an IMPLICIT " + "annotation" + ) + variants = [ + _type_to_variant(arg, field_name) + for arg in union_args + if arg is not type(None) + ] + + # Union types should either be all Variants + # (`Variant[..] | Variant[..] | etc`) or all non Variants + are_union_types_tagged = variants[0].tag_name is not None + if any( + (v.tag_name is not None) != are_union_types_tagged + for v in variants + ): + raise TypeError( + "When using `asn1.Variant` in a union, all the other " + "types in the union must also be `asn1.Variant`" + ) + + if are_union_types_tagged: + tags = {v.tag_name for v in variants} + if len(variants) != len(tags): + raise TypeError( + "When using `asn1.Variant` in a union, the tags used " + "must be unique" + ) + + rust_choice_type = declarative_asn1.Type.Choice(variants) + # If None is part of the union types, this is an OPTIONAL CHOICE + rust_field_type = ( + declarative_asn1.Type.Option( + declarative_asn1.AnnotatedType( + rust_choice_type, declarative_asn1.Annotation() + ) + ) + if NoneType in union_args + else rust_choice_type + ) + + elif typing.get_origin(field_type) is builtins.list: + inner_type = _normalize_field_type( + typing.get_args(field_type)[0], field_name + ) + rust_field_type = declarative_asn1.Type.SequenceOf(inner_type) + elif typing.get_origin(field_type) is SetOf: + inner_type = _normalize_field_type( + typing.get_args(field_type)[0], field_name + ) + rust_field_type = declarative_asn1.Type.SetOf(inner_type) + else: + rust_field_type = declarative_asn1.non_root_python_to_rust(field_type) + + return declarative_asn1.AnnotatedType(rust_field_type, annotation) + + +# Convert a type to a Variant. Used with types inside Union +# annotations (T1, T2, etc in `Union[T1, T2, ...]`). +def _type_to_variant( + t: typing.Any, field_name: str +) -> declarative_asn1.Variant: + is_annotated = typing.get_origin(t) is typing.Annotated + inner_type = typing.get_args(t)[0] if is_annotated else t + + # Check if this is a Variant[T, Tag] type + if typing.get_origin(inner_type) is Variant: + value_type, tag_literal = typing.get_args(inner_type) + if typing.get_origin(tag_literal) is not typing.Literal: + raise TypeError( + "When using `asn1.Variant` in a type annotation, the second " + "type parameter must be a `typing.Literal` type. E.g: " + '`Variant[int, typing.Literal["MyInt"]]`.' + ) + tag_name = typing.get_args(tag_literal)[0] + + if hasattr(value_type, "__asn1_root__"): + rust_type = value_type.__asn1_root__ + else: + rust_type = declarative_asn1.non_root_python_to_rust(value_type) + + if is_annotated: + ann_type = declarative_asn1.AnnotatedType( + rust_type, + _extract_annotation(t.__metadata__, field_name), + ) + else: + ann_type = declarative_asn1.AnnotatedType( + rust_type, + declarative_asn1.Annotation(), + ) + + return declarative_asn1.Variant(Variant, ann_type, tag_name) + else: + # Plain type (not a tagged Variant) + return declarative_asn1.Variant( + inner_type, + _normalize_field_type(t, field_name), + None, + ) + + +def _annotate_fields( + raw_fields: dict[str, type], +) -> dict[str, declarative_asn1.AnnotatedType]: + fields = {} + for field_name, field_type in raw_fields.items(): + # Recursively normalize the field type into something that the + # Rust code can understand. + annotated_field_type = _normalize_field_type(field_type, field_name) + fields[field_name] = annotated_field_type + + return fields + + +def _register_asn1_sequence(cls: type[U]) -> None: + raw_fields = typing.get_type_hints(cls, include_extras=True) + root = declarative_asn1.Type.Sequence(cls, _annotate_fields(raw_fields)) + + setattr(cls, "__asn1_root__", root) + + +def _register_asn1_set(cls: type[U]) -> None: + raw_fields = typing.get_type_hints(cls, include_extras=True) + root = declarative_asn1.Type.Set(cls, _annotate_fields(raw_fields)) + + setattr(cls, "__asn1_root__", root) + + +# Due to https://github.com/python/mypy/issues/19731, we can't define an alias +# for `dataclass_transform` that conditionally points to `typing` or +# `typing_extensions` depending on the Python version. We work around it by +# making the whole decorated class conditional on the Python version. +if sys.version_info < (3, 11): + + @typing_extensions.dataclass_transform(kw_only_default=True) + def sequence(cls: type[U]) -> type[U]: + # We use `dataclasses.dataclass` to add an __init__ method + # to the class with keyword-only parameters. + if sys.version_info >= (3, 10): + dataclass_cls = dataclasses.dataclass( + repr=False, + eq=False, + # `match_args` was added in Python 3.10 and defaults + # to True + match_args=False, + # `kw_only` was added in Python 3.10 and defaults to + # False + kw_only=True, + )(cls) + else: + dataclass_cls = dataclasses.dataclass( + repr=False, + eq=False, + )(cls) + _register_asn1_sequence(dataclass_cls) + return dataclass_cls + + @typing_extensions.dataclass_transform(kw_only_default=True) + def set(cls: type[U]) -> type[U]: + # We use `dataclasses.dataclass` to add an __init__ method + # to the class with keyword-only parameters. + if sys.version_info >= (3, 10): + dataclass_cls = dataclasses.dataclass( + repr=False, + eq=False, + # `match_args` was added in Python 3.10 and defaults + # to True + match_args=False, + # `kw_only` was added in Python 3.10 and defaults to + # False + kw_only=True, + )(cls) + else: + dataclass_cls = dataclasses.dataclass( + repr=False, + eq=False, + )(cls) + _register_asn1_set(dataclass_cls) + return dataclass_cls + +else: + + @typing.dataclass_transform(kw_only_default=True) + def sequence(cls: type[U]) -> type[U]: + # Only add an __init__ method, with keyword-only + # parameters. + dataclass_cls = dataclasses.dataclass( + repr=False, + eq=False, + match_args=False, + kw_only=True, + )(cls) + _register_asn1_sequence(dataclass_cls) + return dataclass_cls + + @typing.dataclass_transform(kw_only_default=True) + def set(cls: type[U]) -> type[U]: + # Only add an __init__ method, with keyword-only + # parameters. + dataclass_cls = dataclasses.dataclass( + repr=False, + eq=False, + match_args=False, + kw_only=True, + )(cls) + _register_asn1_set(dataclass_cls) + return dataclass_cls + + +# TODO: replace with `Default[U]` once the min Python version is >= 3.12 +@dataclasses.dataclass(frozen=True) +class Default(typing.Generic[U]): + value: U + + +SetOf = declarative_asn1.SetOf + +Explicit = declarative_asn1.Encoding.Explicit +Implicit = declarative_asn1.Encoding.Implicit +Size = declarative_asn1.Size + +PrintableString = declarative_asn1.PrintableString +IA5String = declarative_asn1.IA5String +UTCTime = declarative_asn1.UTCTime +GeneralizedTime = declarative_asn1.GeneralizedTime +BitString = declarative_asn1.BitString +TLV = declarative_asn1.Tlv +Null = declarative_asn1.Null diff --git a/python/user_packages/Python313/site-packages/cryptography/hazmat/backends/__init__.py b/python/user_packages/Python313/site-packages/cryptography/hazmat/backends/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..b4400aa037451d10d6bcadd455dcf98f9b72e221 --- /dev/null +++ b/python/user_packages/Python313/site-packages/cryptography/hazmat/backends/__init__.py @@ -0,0 +1,13 @@ +# This file is dual licensed under the terms of the Apache License, Version +# 2.0, and the BSD License. See the LICENSE file in the root of this repository +# for complete details. + +from __future__ import annotations + +from typing import Any + + +def default_backend() -> Any: + from cryptography.hazmat.backends.openssl.backend import backend + + return backend diff --git a/python/user_packages/Python313/site-packages/cryptography/hazmat/backends/__pycache__/__init__.cpython-313.pyc b/python/user_packages/Python313/site-packages/cryptography/hazmat/backends/__pycache__/__init__.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7547bd8615b016e3a801e2cbee25e324f4abc050 Binary files /dev/null and b/python/user_packages/Python313/site-packages/cryptography/hazmat/backends/__pycache__/__init__.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/cryptography/hazmat/backends/openssl/__init__.py b/python/user_packages/Python313/site-packages/cryptography/hazmat/backends/openssl/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..51b04476cbb7f4a98051f2fc55bcc1aa35e22d05 --- /dev/null +++ b/python/user_packages/Python313/site-packages/cryptography/hazmat/backends/openssl/__init__.py @@ -0,0 +1,9 @@ +# This file is dual licensed under the terms of the Apache License, Version +# 2.0, and the BSD License. See the LICENSE file in the root of this repository +# for complete details. + +from __future__ import annotations + +from cryptography.hazmat.backends.openssl.backend import backend + +__all__ = ["backend"] diff --git a/python/user_packages/Python313/site-packages/cryptography/hazmat/backends/openssl/__pycache__/__init__.cpython-313.pyc b/python/user_packages/Python313/site-packages/cryptography/hazmat/backends/openssl/__pycache__/__init__.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0ebb7251d742c2dcfc826cb5b5af2c5540c10233 Binary files /dev/null and b/python/user_packages/Python313/site-packages/cryptography/hazmat/backends/openssl/__pycache__/__init__.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/cryptography/hazmat/backends/openssl/__pycache__/backend.cpython-313.pyc b/python/user_packages/Python313/site-packages/cryptography/hazmat/backends/openssl/__pycache__/backend.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..891c0eeee254ed3b87bc66392c8fdc87cc6b8516 Binary files /dev/null and b/python/user_packages/Python313/site-packages/cryptography/hazmat/backends/openssl/__pycache__/backend.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/cryptography/hazmat/backends/openssl/backend.py b/python/user_packages/Python313/site-packages/cryptography/hazmat/backends/openssl/backend.py new file mode 100644 index 0000000000000000000000000000000000000000..ad64a2afd3688dcb6de74c939137a311e978aecc --- /dev/null +++ b/python/user_packages/Python313/site-packages/cryptography/hazmat/backends/openssl/backend.py @@ -0,0 +1,312 @@ +# This file is dual licensed under the terms of the Apache License, Version +# 2.0, and the BSD License. See the LICENSE file in the root of this repository +# for complete details. + +from __future__ import annotations + +from cryptography.hazmat.bindings._rust import openssl as rust_openssl +from cryptography.hazmat.bindings.openssl import binding +from cryptography.hazmat.primitives import hashes +from cryptography.hazmat.primitives._asymmetric import AsymmetricPadding +from cryptography.hazmat.primitives.asymmetric import ec +from cryptography.hazmat.primitives.asymmetric import utils as asym_utils +from cryptography.hazmat.primitives.asymmetric.padding import ( + MGF1, + OAEP, + PSS, + PKCS1v15, +) +from cryptography.hazmat.primitives.ciphers import ( + CipherAlgorithm, +) +from cryptography.hazmat.primitives.ciphers.algorithms import ( + AES, +) +from cryptography.hazmat.primitives.ciphers.modes import ( + CBC, + Mode, +) + + +class Backend: + """ + OpenSSL API binding interfaces. + """ + + name = "openssl" + + # TripleDES encryption is disallowed/deprecated throughout 2023 in + # FIPS 140-3. To keep it simple we denylist any use of TripleDES (TDEA). + _fips_ciphers = (AES,) + # Sometimes SHA1 is still permissible. That logic is contained + # within the various *_supported methods. + _fips_hashes = ( + hashes.SHA224, + hashes.SHA256, + hashes.SHA384, + hashes.SHA512, + hashes.SHA512_224, + hashes.SHA512_256, + hashes.SHA3_224, + hashes.SHA3_256, + hashes.SHA3_384, + hashes.SHA3_512, + hashes.SHAKE128, + hashes.SHAKE256, + ) + _fips_ecdh_curves = ( + ec.SECP224R1, + ec.SECP256R1, + ec.SECP384R1, + ec.SECP521R1, + ) + _fips_rsa_min_key_size = 2048 + _fips_rsa_min_public_exponent = 65537 + _fips_dsa_min_modulus = 1 << 2048 + _fips_dh_min_key_size = 2048 + _fips_dh_min_modulus = 1 << _fips_dh_min_key_size + + def __init__(self) -> None: + self._binding = binding.Binding() + self._ffi = self._binding.ffi + self._lib = self._binding.lib + self._fips_enabled = rust_openssl.is_fips_enabled() + + def __repr__(self) -> str: + return ( + f"" + ) + + def openssl_assert(self, ok: bool) -> None: + return binding._openssl_assert(ok) + + def _enable_fips(self) -> None: + # This function enables FIPS mode for OpenSSL 3.0.0 on installs that + # have the FIPS provider installed properly. + rust_openssl.enable_fips(rust_openssl._providers) + assert rust_openssl.is_fips_enabled() + self._fips_enabled = rust_openssl.is_fips_enabled() + + def openssl_version_text(self) -> str: + """ + Friendly string name of the loaded OpenSSL library. This is not + necessarily the same version as it was compiled against. + + Example: OpenSSL 3.2.1 30 Jan 2024 + """ + return rust_openssl.openssl_version_text() + + def openssl_version_number(self) -> int: + return rust_openssl.openssl_version() + + def hash_supported(self, algorithm: hashes.HashAlgorithm) -> bool: + if self._fips_enabled and not isinstance(algorithm, self._fips_hashes): + return False + + return rust_openssl.hashes.hash_supported(algorithm) + + def signature_hash_supported( + self, algorithm: hashes.HashAlgorithm + ) -> bool: + # Dedicated check for hashing algorithm use in message digest for + # signatures, e.g. RSA PKCS#1 v1.5 SHA1 (sha1WithRSAEncryption). + if self._fips_enabled and isinstance(algorithm, hashes.SHA1): + return False + return self.hash_supported(algorithm) + + def scrypt_supported(self) -> bool: + if self._fips_enabled: + return False + else: + return hasattr(rust_openssl.kdf.Scrypt, "derive") + + def argon2_supported(self) -> bool: + if self._fips_enabled: + return False + else: + return hasattr(rust_openssl.kdf.Argon2id, "derive") + + def hmac_supported(self, algorithm: hashes.HashAlgorithm) -> bool: + # FIPS mode still allows SHA1 for HMAC + if self._fips_enabled and isinstance(algorithm, hashes.SHA1): + return True + if rust_openssl.CRYPTOGRAPHY_IS_AWSLC: + return isinstance( + algorithm, + ( + hashes.MD5, + hashes.SHA1, + hashes.SHA224, + hashes.SHA256, + hashes.SHA384, + hashes.SHA512, + hashes.SHA512_224, + hashes.SHA512_256, + ), + ) + return self.hash_supported(algorithm) + + def cipher_supported(self, cipher: CipherAlgorithm, mode: Mode) -> bool: + if self._fips_enabled: + # FIPS mode requires AES. TripleDES is disallowed/deprecated in + # FIPS 140-3. + if not isinstance(cipher, self._fips_ciphers): + return False + + return rust_openssl.ciphers.cipher_supported(cipher, mode) + + def pbkdf2_hmac_supported(self, algorithm: hashes.HashAlgorithm) -> bool: + return self.hmac_supported(algorithm) + + def _consume_errors(self) -> list[rust_openssl.OpenSSLError]: + return rust_openssl.capture_error_stack() + + def _oaep_hash_supported(self, algorithm: hashes.HashAlgorithm) -> bool: + if self._fips_enabled and isinstance(algorithm, hashes.SHA1): + return False + + return isinstance( + algorithm, + ( + hashes.SHA1, + hashes.SHA224, + hashes.SHA256, + hashes.SHA384, + hashes.SHA512, + ), + ) + + def rsa_padding_supported(self, padding: AsymmetricPadding) -> bool: + if isinstance(padding, PKCS1v15): + return True + elif isinstance(padding, PSS) and isinstance(padding._mgf, MGF1): + # FIPS 186-4 only allows salt length == digest length for PSS + # It is technically acceptable to set an explicit salt length + # equal to the digest length and this will incorrectly fail, but + # since we don't do that in the tests and this method is + # private, we'll ignore that until we need to do otherwise. + if ( + self._fips_enabled + and padding._salt_length != PSS.DIGEST_LENGTH + ): + return False + return self.hash_supported(padding._mgf._algorithm) + elif isinstance(padding, OAEP) and isinstance(padding._mgf, MGF1): + return self._oaep_hash_supported( + padding._mgf._algorithm + ) and self._oaep_hash_supported(padding._algorithm) + else: + return False + + def rsa_encryption_supported(self, padding: AsymmetricPadding) -> bool: + if self._fips_enabled and isinstance(padding, PKCS1v15): + return False + else: + return self.rsa_padding_supported(padding) + + def dsa_supported(self) -> bool: + return ( + not rust_openssl.CRYPTOGRAPHY_IS_BORINGSSL + and not self._fips_enabled + ) + + def dsa_hash_supported(self, algorithm: hashes.HashAlgorithm) -> bool: + if not self.dsa_supported(): + return False + return self.signature_hash_supported(algorithm) + + def cmac_algorithm_supported(self, algorithm) -> bool: + return self.cipher_supported( + algorithm, CBC(b"\x00" * algorithm.block_size) + ) + + def elliptic_curve_supported(self, curve: ec.EllipticCurve) -> bool: + if self._fips_enabled and not isinstance( + curve, self._fips_ecdh_curves + ): + return False + + return rust_openssl.ec.curve_supported(curve) + + def elliptic_curve_signature_algorithm_supported( + self, + signature_algorithm: ec.EllipticCurveSignatureAlgorithm, + curve: ec.EllipticCurve, + ) -> bool: + # We only support ECDSA right now. + if not isinstance(signature_algorithm, ec.ECDSA): + return False + + return self.elliptic_curve_supported(curve) and ( + isinstance(signature_algorithm.algorithm, asym_utils.Prehashed) + or self.hash_supported(signature_algorithm.algorithm) + ) + + def elliptic_curve_exchange_algorithm_supported( + self, algorithm: ec.ECDH, curve: ec.EllipticCurve + ) -> bool: + return self.elliptic_curve_supported(curve) and isinstance( + algorithm, ec.ECDH + ) + + def dh_supported(self) -> bool: + return ( + not rust_openssl.CRYPTOGRAPHY_IS_BORINGSSL + and not rust_openssl.CRYPTOGRAPHY_IS_AWSLC + ) + + def dh_x942_serialization_supported(self) -> bool: + return self._lib.Cryptography_HAS_EVP_PKEY_DHX == 1 + + def x25519_supported(self) -> bool: + return not self._fips_enabled + + def x448_supported(self) -> bool: + if self._fips_enabled: + return False + return ( + not rust_openssl.CRYPTOGRAPHY_IS_LIBRESSL + and not rust_openssl.CRYPTOGRAPHY_IS_BORINGSSL + and not rust_openssl.CRYPTOGRAPHY_IS_AWSLC + ) + + def mlkem_supported(self) -> bool: + return ( + rust_openssl.CRYPTOGRAPHY_IS_AWSLC + or rust_openssl.CRYPTOGRAPHY_IS_BORINGSSL + or rust_openssl.CRYPTOGRAPHY_OPENSSL_350_OR_GREATER + ) + + def mldsa_supported(self) -> bool: + return ( + rust_openssl.CRYPTOGRAPHY_IS_AWSLC + or rust_openssl.CRYPTOGRAPHY_IS_BORINGSSL + or rust_openssl.CRYPTOGRAPHY_OPENSSL_350_OR_GREATER + ) + + def ed25519_supported(self) -> bool: + return True + + def ed448_supported(self) -> bool: + return ( + not rust_openssl.CRYPTOGRAPHY_IS_LIBRESSL + and not rust_openssl.CRYPTOGRAPHY_IS_BORINGSSL + and not rust_openssl.CRYPTOGRAPHY_IS_AWSLC + ) + + def ecdsa_deterministic_supported(self) -> bool: + return ( + rust_openssl.CRYPTOGRAPHY_OPENSSL_320_OR_GREATER + and not self._fips_enabled + ) + + def poly1305_supported(self) -> bool: + return not self._fips_enabled + + def pkcs7_supported(self) -> bool: + return True + + +backend = Backend() diff --git a/python/user_packages/Python313/site-packages/cryptography/hazmat/bindings/__init__.py b/python/user_packages/Python313/site-packages/cryptography/hazmat/bindings/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..b509336233c2fafe4185a49da5909c8bbb38dfd7 --- /dev/null +++ b/python/user_packages/Python313/site-packages/cryptography/hazmat/bindings/__init__.py @@ -0,0 +1,3 @@ +# This file is dual licensed under the terms of the Apache License, Version +# 2.0, and the BSD License. See the LICENSE file in the root of this repository +# for complete details. diff --git a/python/user_packages/Python313/site-packages/cryptography/hazmat/bindings/__pycache__/__init__.cpython-313.pyc b/python/user_packages/Python313/site-packages/cryptography/hazmat/bindings/__pycache__/__init__.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4ec79709e82c46ad09d2f2072618f1bb573080b2 Binary files /dev/null and b/python/user_packages/Python313/site-packages/cryptography/hazmat/bindings/__pycache__/__init__.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/cryptography/hazmat/bindings/_rust/__init__.pyi b/python/user_packages/Python313/site-packages/cryptography/hazmat/bindings/_rust/__init__.pyi new file mode 100644 index 0000000000000000000000000000000000000000..c3148f12bd0422e88b6abddc98016534d512a14c --- /dev/null +++ b/python/user_packages/Python313/site-packages/cryptography/hazmat/bindings/_rust/__init__.pyi @@ -0,0 +1,67 @@ +# This file is dual licensed under the terms of the Apache License, Version +# 2.0, and the BSD License. See the LICENSE file in the root of this repository +# for complete details. + +import typing + +from cryptography.hazmat.primitives import padding +from cryptography.hazmat.primitives._serialization import ( + KeySerializationEncryptionBuilder, +) +from cryptography.utils import Buffer + +class PKCS7PaddingContext(padding.PaddingContext): + def __init__(self, block_size: int) -> None: ... + def update(self, data: Buffer) -> bytes: ... + def finalize(self) -> bytes: ... + +class ANSIX923PaddingContext(padding.PaddingContext): + def __init__(self, block_size: int) -> None: ... + def update(self, data: Buffer) -> bytes: ... + def finalize(self) -> bytes: ... + +class PKCS7UnpaddingContext(padding.PaddingContext): + def __init__(self, block_size: int) -> None: ... + def update(self, data: Buffer) -> bytes: ... + def finalize(self) -> bytes: ... + +class ANSIX923UnpaddingContext(padding.PaddingContext): + def __init__(self, block_size: int) -> None: ... + def update(self, data: Buffer) -> bytes: ... + def finalize(self) -> bytes: ... + +class Encoding: + PEM: typing.ClassVar[Encoding] + DER: typing.ClassVar[Encoding] + OpenSSH: typing.ClassVar[Encoding] + Raw: typing.ClassVar[Encoding] + X962: typing.ClassVar[Encoding] + SMIME: typing.ClassVar[Encoding] + +class PrivateFormat: + PKCS8: typing.ClassVar[PrivateFormat] + TraditionalOpenSSL: typing.ClassVar[PrivateFormat] + Raw: typing.ClassVar[PrivateFormat] + OpenSSH: typing.ClassVar[PrivateFormat] + PKCS12: typing.ClassVar[PrivateFormat] + def encryption_builder(self) -> KeySerializationEncryptionBuilder: ... + +class PublicFormat: + SubjectPublicKeyInfo: typing.ClassVar[PublicFormat] + PKCS1: typing.ClassVar[PublicFormat] + OpenSSH: typing.ClassVar[PublicFormat] + Raw: typing.ClassVar[PublicFormat] + CompressedPoint: typing.ClassVar[PublicFormat] + UncompressedPoint: typing.ClassVar[PublicFormat] + +class ParameterFormat: + PKCS3: typing.ClassVar[ParameterFormat] + +class ObjectIdentifier: + def __init__(self, value: str) -> None: ... + @property + def dotted_string(self) -> str: ... + @property + def _name(self) -> str: ... + +T = typing.TypeVar("T") diff --git a/python/user_packages/Python313/site-packages/cryptography/hazmat/bindings/_rust/_openssl.pyi b/python/user_packages/Python313/site-packages/cryptography/hazmat/bindings/_rust/_openssl.pyi new file mode 100644 index 0000000000000000000000000000000000000000..3d4ea4eb2061c7c16a2e31af216367133e55c790 --- /dev/null +++ b/python/user_packages/Python313/site-packages/cryptography/hazmat/bindings/_rust/_openssl.pyi @@ -0,0 +1,8 @@ +# This file is dual licensed under the terms of the Apache License, Version +# 2.0, and the BSD License. See the LICENSE file in the root of this repository +# for complete details. + +import typing + +lib: typing.Any +ffi: typing.Any diff --git a/python/user_packages/Python313/site-packages/cryptography/hazmat/bindings/_rust/asn1.pyi b/python/user_packages/Python313/site-packages/cryptography/hazmat/bindings/_rust/asn1.pyi new file mode 100644 index 0000000000000000000000000000000000000000..3b5f208ecf09aa661854e6983507b0e7b1ef15cb --- /dev/null +++ b/python/user_packages/Python313/site-packages/cryptography/hazmat/bindings/_rust/asn1.pyi @@ -0,0 +1,7 @@ +# This file is dual licensed under the terms of the Apache License, Version +# 2.0, and the BSD License. See the LICENSE file in the root of this repository +# for complete details. + +def decode_dss_signature(signature: bytes) -> tuple[int, int]: ... +def encode_dss_signature(r: int, s: int) -> bytes: ... +def parse_spki_for_data(data: bytes) -> bytes: ... diff --git a/python/user_packages/Python313/site-packages/cryptography/hazmat/bindings/_rust/declarative_asn1.pyi b/python/user_packages/Python313/site-packages/cryptography/hazmat/bindings/_rust/declarative_asn1.pyi new file mode 100644 index 0000000000000000000000000000000000000000..a4c0cb6d66cd2c62f44965134399405468a63c0e --- /dev/null +++ b/python/user_packages/Python313/site-packages/cryptography/hazmat/bindings/_rust/declarative_asn1.pyi @@ -0,0 +1,127 @@ +# This file is dual licensed under the terms of the Apache License, Version +# 2.0, and the BSD License. See the LICENSE file in the root of this repository +# for complete details. + +import datetime +import typing + +def decode_der(cls: type, value: bytes) -> typing.Any: ... +def encode_der(value: typing.Any) -> bytes: ... +def non_root_python_to_rust(cls: type) -> Type: ... + +# Type is a Rust enum with tuple variants. For now, we express the type +# annotations like this: +class Type: + Sequence: typing.ClassVar[type] + SequenceOf: typing.ClassVar[type] + Set: typing.ClassVar[type] + SetOf: typing.ClassVar[type] + Option: typing.ClassVar[type] + Choice: typing.ClassVar[type] + PyBool: typing.ClassVar[type] + PyInt: typing.ClassVar[type] + PyBytes: typing.ClassVar[type] + PyStr: typing.ClassVar[type] + +class Annotation: + default: typing.Any | None + encoding: Encoding | None + size: Size | None + def __new__( + cls, + default: typing.Any | None = None, + encoding: Encoding | None = None, + size: Size | None = None, + ) -> Annotation: ... + def is_empty(self) -> bool: ... + +# Encoding is a Rust enum with tuple variants. For now, we express the type +# annotations like this: +class Encoding: + Implicit: typing.ClassVar[type] + Explicit: typing.ClassVar[type] + +class Size: + min: int + max: int | None + + def __new__(cls, min: int, max: int | None) -> Size: ... + @staticmethod + def exact(n: int) -> Size: ... + +class AnnotatedType: + inner: Type + annotation: Annotation + + def __new__(cls, inner: Type, annotation: Annotation) -> AnnotatedType: ... + +class AnnotatedTypeObject: + annotated_type: AnnotatedType + value: typing.Any + + def __new__( + cls, annotated_type: AnnotatedType, value: typing.Any + ) -> AnnotatedTypeObject: ... + +class Variant: + python_class: type + ann_type: AnnotatedType + tag_name: str | None + + def __new__( + cls, + python_class: type, + ann_type: AnnotatedType, + tag_name: str | None, + ) -> Variant: ... + +class PrintableString: + def __new__(cls, inner: str) -> PrintableString: ... + def __repr__(self) -> str: ... + def __eq__(self, other: object) -> bool: ... + def as_str(self) -> str: ... + +class IA5String: + def __new__(cls, inner: str) -> IA5String: ... + def __repr__(self) -> str: ... + def __eq__(self, other: object) -> bool: ... + def as_str(self) -> str: ... + +class UTCTime: + def __new__(cls, inner: datetime.datetime) -> UTCTime: ... + def __repr__(self) -> str: ... + def __eq__(self, other: object) -> bool: ... + def as_datetime(self) -> datetime.datetime: ... + +class GeneralizedTime: + def __new__(cls, inner: datetime.datetime) -> GeneralizedTime: ... + def __repr__(self) -> str: ... + def __eq__(self, other: object) -> bool: ... + def as_datetime(self) -> datetime.datetime: ... + +class BitString: + def __new__(cls, data: bytes, padding_bits: int) -> BitString: ... + def __repr__(self) -> str: ... + def __eq__(self, other: object) -> bool: ... + def as_bytes(self) -> bytes: ... + def padding_bits(self) -> int: ... + +class Tlv: + @property + def tag_bytes(self) -> bytes: ... + @property + def data(self) -> memoryview: ... + def parse(self, cls: type): ... + +T = typing.TypeVar("T") + +class SetOf(typing.Generic[T]): + def __new__(cls, inner: list[T]) -> SetOf[T]: ... + def as_list(self) -> list[T]: ... + def __eq__(self, other: object) -> bool: ... + def __repr__(self) -> str: ... + +class Null: + def __new__(cls) -> Null: ... + def __repr__(self) -> str: ... + def __eq__(self, other: object) -> bool: ... diff --git a/python/user_packages/Python313/site-packages/cryptography/hazmat/bindings/_rust/exceptions.pyi b/python/user_packages/Python313/site-packages/cryptography/hazmat/bindings/_rust/exceptions.pyi new file mode 100644 index 0000000000000000000000000000000000000000..09f46b1e817f806873c4a4bdd7b8466046b5f64d --- /dev/null +++ b/python/user_packages/Python313/site-packages/cryptography/hazmat/bindings/_rust/exceptions.pyi @@ -0,0 +1,17 @@ +# This file is dual licensed under the terms of the Apache License, Version +# 2.0, and the BSD License. See the LICENSE file in the root of this repository +# for complete details. + +class _Reasons: + BACKEND_MISSING_INTERFACE: _Reasons + UNSUPPORTED_HASH: _Reasons + UNSUPPORTED_CIPHER: _Reasons + UNSUPPORTED_PADDING: _Reasons + UNSUPPORTED_MGF: _Reasons + UNSUPPORTED_PUBLIC_KEY_ALGORITHM: _Reasons + UNSUPPORTED_ELLIPTIC_CURVE: _Reasons + UNSUPPORTED_SERIALIZATION: _Reasons + UNSUPPORTED_X509: _Reasons + UNSUPPORTED_EXCHANGE_ALGORITHM: _Reasons + UNSUPPORTED_DIFFIE_HELLMAN: _Reasons + UNSUPPORTED_MAC: _Reasons diff --git a/python/user_packages/Python313/site-packages/cryptography/hazmat/bindings/_rust/ocsp.pyi b/python/user_packages/Python313/site-packages/cryptography/hazmat/bindings/_rust/ocsp.pyi new file mode 100644 index 0000000000000000000000000000000000000000..103e96c1f117ed06924569fadb6a2b680fbd5456 --- /dev/null +++ b/python/user_packages/Python313/site-packages/cryptography/hazmat/bindings/_rust/ocsp.pyi @@ -0,0 +1,117 @@ +# This file is dual licensed under the terms of the Apache License, Version +# 2.0, and the BSD License. See the LICENSE file in the root of this repository +# for complete details. + +import datetime +from collections.abc import Iterator + +from cryptography import x509 +from cryptography.hazmat.primitives import hashes, serialization +from cryptography.hazmat.primitives.asymmetric.types import PrivateKeyTypes +from cryptography.x509 import ocsp + +class OCSPRequest: + @property + def issuer_key_hash(self) -> bytes: ... + @property + def issuer_name_hash(self) -> bytes: ... + @property + def hash_algorithm(self) -> hashes.HashAlgorithm: ... + @property + def serial_number(self) -> int: ... + def public_bytes(self, encoding: serialization.Encoding) -> bytes: ... + @property + def extensions(self) -> x509.Extensions: ... + +class OCSPResponse: + @property + def responses(self) -> Iterator[OCSPSingleResponse]: ... + @property + def response_status(self) -> ocsp.OCSPResponseStatus: ... + @property + def signature_algorithm_oid(self) -> x509.ObjectIdentifier: ... + @property + def signature_hash_algorithm( + self, + ) -> hashes.HashAlgorithm | None: ... + @property + def signature(self) -> bytes: ... + @property + def tbs_response_bytes(self) -> bytes: ... + @property + def certificates(self) -> list[x509.Certificate]: ... + @property + def responder_key_hash(self) -> bytes | None: ... + @property + def responder_name(self) -> x509.Name | None: ... + @property + def produced_at(self) -> datetime.datetime: ... + @property + def produced_at_utc(self) -> datetime.datetime: ... + @property + def certificate_status(self) -> ocsp.OCSPCertStatus: ... + @property + def revocation_time(self) -> datetime.datetime | None: ... + @property + def revocation_time_utc(self) -> datetime.datetime | None: ... + @property + def revocation_reason(self) -> x509.ReasonFlags | None: ... + @property + def this_update(self) -> datetime.datetime: ... + @property + def this_update_utc(self) -> datetime.datetime: ... + @property + def next_update(self) -> datetime.datetime | None: ... + @property + def next_update_utc(self) -> datetime.datetime | None: ... + @property + def issuer_key_hash(self) -> bytes: ... + @property + def issuer_name_hash(self) -> bytes: ... + @property + def hash_algorithm(self) -> hashes.HashAlgorithm: ... + @property + def serial_number(self) -> int: ... + @property + def extensions(self) -> x509.Extensions: ... + @property + def single_extensions(self) -> x509.Extensions: ... + def public_bytes(self, encoding: serialization.Encoding) -> bytes: ... + +class OCSPSingleResponse: + @property + def certificate_status(self) -> ocsp.OCSPCertStatus: ... + @property + def revocation_time(self) -> datetime.datetime | None: ... + @property + def revocation_time_utc(self) -> datetime.datetime | None: ... + @property + def revocation_reason(self) -> x509.ReasonFlags | None: ... + @property + def this_update(self) -> datetime.datetime: ... + @property + def this_update_utc(self) -> datetime.datetime: ... + @property + def next_update(self) -> datetime.datetime | None: ... + @property + def next_update_utc(self) -> datetime.datetime | None: ... + @property + def issuer_key_hash(self) -> bytes: ... + @property + def issuer_name_hash(self) -> bytes: ... + @property + def hash_algorithm(self) -> hashes.HashAlgorithm: ... + @property + def serial_number(self) -> int: ... + +def load_der_ocsp_request(data: bytes) -> ocsp.OCSPRequest: ... +def load_der_ocsp_response(data: bytes) -> ocsp.OCSPResponse: ... +def create_ocsp_request( + builder: ocsp.OCSPRequestBuilder, +) -> ocsp.OCSPRequest: ... +def create_ocsp_response( + status: ocsp.OCSPResponseStatus, + builder: ocsp.OCSPResponseBuilder | None, + private_key: PrivateKeyTypes | None, + hash_algorithm: hashes.HashAlgorithm | None, +) -> ocsp.OCSPResponse: ... diff --git a/python/user_packages/Python313/site-packages/cryptography/hazmat/bindings/_rust/openssl/__init__.pyi b/python/user_packages/Python313/site-packages/cryptography/hazmat/bindings/_rust/openssl/__init__.pyi new file mode 100644 index 0000000000000000000000000000000000000000..404a300a52e176d6b0e9ca123894775b27371eaa --- /dev/null +++ b/python/user_packages/Python313/site-packages/cryptography/hazmat/bindings/_rust/openssl/__init__.pyi @@ -0,0 +1,80 @@ +# This file is dual licensed under the terms of the Apache License, Version +# 2.0, and the BSD License. See the LICENSE file in the root of this repository +# for complete details. + +import typing + +from cryptography.hazmat.bindings._rust.openssl import ( + aead, + ciphers, + cmac, + dh, + dsa, + ec, + ed448, + ed25519, + hashes, + hmac, + hpke, + kdf, + keys, + mldsa, + mlkem, + poly1305, + rsa, + x448, + x25519, +) + +__all__ = [ + "aead", + "ciphers", + "cmac", + "dh", + "dsa", + "ec", + "ed448", + "ed25519", + "hashes", + "hmac", + "hpke", + "kdf", + "keys", + "mldsa", + "mlkem", + "openssl_version", + "openssl_version_text", + "poly1305", + "raise_openssl_error", + "rsa", + "x448", + "x25519", +] + +CRYPTOGRAPHY_IS_LIBRESSL: bool +CRYPTOGRAPHY_IS_BORINGSSL: bool +CRYPTOGRAPHY_IS_AWSLC: bool +CRYPTOGRAPHY_OPENSSL_309_OR_GREATER: bool +CRYPTOGRAPHY_OPENSSL_320_OR_GREATER: bool +CRYPTOGRAPHY_OPENSSL_330_OR_GREATER: bool +CRYPTOGRAPHY_OPENSSL_350_OR_GREATER: bool + +class Providers: ... + +_legacy_provider_loaded: bool +_providers: Providers + +def openssl_version() -> int: ... +def openssl_version_text() -> str: ... +def raise_openssl_error() -> typing.NoReturn: ... +def capture_error_stack() -> list[OpenSSLError]: ... +def is_fips_enabled() -> bool: ... +def enable_fips(providers: Providers) -> None: ... + +class OpenSSLError: + @property + def lib(self) -> int: ... + @property + def reason(self) -> int: ... + @property + def reason_text(self) -> bytes: ... diff --git a/python/user_packages/Python313/site-packages/cryptography/hazmat/bindings/_rust/openssl/aead.pyi b/python/user_packages/Python313/site-packages/cryptography/hazmat/bindings/_rust/openssl/aead.pyi new file mode 100644 index 0000000000000000000000000000000000000000..eb44608a78d8e53be8f44e2789bcc417a27916fc --- /dev/null +++ b/python/user_packages/Python313/site-packages/cryptography/hazmat/bindings/_rust/openssl/aead.pyi @@ -0,0 +1,189 @@ +# This file is dual licensed under the terms of the Apache License, Version +# 2.0, and the BSD License. See the LICENSE file in the root of this repository +# for complete details. + +from collections.abc import Sequence + +from cryptography.utils import Buffer + +class AESGCM: + def __init__(self, key: Buffer) -> None: ... + @staticmethod + def generate_key(bit_length: int) -> bytes: ... + def encrypt( + self, + nonce: Buffer, + data: Buffer, + associated_data: Buffer | None, + ) -> bytes: ... + def decrypt( + self, + nonce: Buffer, + data: Buffer, + associated_data: Buffer | None, + ) -> bytes: ... + def encrypt_into( + self, + nonce: Buffer, + data: Buffer, + associated_data: Buffer | None, + buf: Buffer, + ) -> int: ... + def decrypt_into( + self, + nonce: Buffer, + data: Buffer, + associated_data: Buffer | None, + buf: Buffer, + ) -> int: ... + +class ChaCha20Poly1305: + def __init__(self, key: Buffer) -> None: ... + @staticmethod + def generate_key() -> bytes: ... + def encrypt( + self, + nonce: Buffer, + data: Buffer, + associated_data: Buffer | None, + ) -> bytes: ... + def encrypt_into( + self, + nonce: Buffer, + data: Buffer, + associated_data: Buffer | None, + buf: Buffer, + ) -> int: ... + def decrypt( + self, + nonce: Buffer, + data: Buffer, + associated_data: Buffer | None, + ) -> bytes: ... + def decrypt_into( + self, + nonce: Buffer, + data: Buffer, + associated_data: Buffer | None, + buf: Buffer, + ) -> int: ... + +class AESCCM: + def __init__(self, key: Buffer, tag_length: int = 16) -> None: ... + @staticmethod + def generate_key(bit_length: int) -> bytes: ... + def encrypt( + self, + nonce: Buffer, + data: Buffer, + associated_data: Buffer | None, + ) -> bytes: ... + def encrypt_into( + self, + nonce: Buffer, + data: Buffer, + associated_data: Buffer | None, + buf: Buffer, + ) -> int: ... + def decrypt( + self, + nonce: Buffer, + data: Buffer, + associated_data: Buffer | None, + ) -> bytes: ... + def decrypt_into( + self, + nonce: Buffer, + data: Buffer, + associated_data: Buffer | None, + buf: Buffer, + ) -> int: ... + +class AESSIV: + def __init__(self, key: Buffer) -> None: ... + @staticmethod + def generate_key(bit_length: int) -> bytes: ... + def encrypt( + self, + data: Buffer, + associated_data: Sequence[Buffer] | None, + ) -> bytes: ... + def encrypt_into( + self, + data: Buffer, + associated_data: Sequence[Buffer] | None, + buf: Buffer, + ) -> int: ... + def decrypt( + self, + data: Buffer, + associated_data: Sequence[Buffer] | None, + ) -> bytes: ... + def decrypt_into( + self, + data: Buffer, + associated_data: Sequence[Buffer] | None, + buf: Buffer, + ) -> int: ... + +class AESOCB3: + def __init__(self, key: Buffer) -> None: ... + @staticmethod + def generate_key(bit_length: int) -> bytes: ... + def encrypt( + self, + nonce: Buffer, + data: Buffer, + associated_data: Buffer | None, + ) -> bytes: ... + def encrypt_into( + self, + nonce: Buffer, + data: Buffer, + associated_data: Buffer | None, + buf: Buffer, + ) -> int: ... + def decrypt( + self, + nonce: Buffer, + data: Buffer, + associated_data: Buffer | None, + ) -> bytes: ... + def decrypt_into( + self, + nonce: Buffer, + data: Buffer, + associated_data: Buffer | None, + buf: Buffer, + ) -> int: ... + +class AESGCMSIV: + def __init__(self, key: Buffer) -> None: ... + @staticmethod + def generate_key(bit_length: int) -> bytes: ... + def encrypt( + self, + nonce: Buffer, + data: Buffer, + associated_data: Buffer | None, + ) -> bytes: ... + def encrypt_into( + self, + nonce: Buffer, + data: Buffer, + associated_data: Buffer | None, + buf: Buffer, + ) -> int: ... + def decrypt( + self, + nonce: Buffer, + data: Buffer, + associated_data: Buffer | None, + ) -> bytes: ... + def decrypt_into( + self, + nonce: Buffer, + data: Buffer, + associated_data: Buffer | None, + buf: Buffer, + ) -> int: ... diff --git a/python/user_packages/Python313/site-packages/cryptography/hazmat/bindings/_rust/openssl/ciphers.pyi b/python/user_packages/Python313/site-packages/cryptography/hazmat/bindings/_rust/openssl/ciphers.pyi new file mode 100644 index 0000000000000000000000000000000000000000..a48fb017ff562b3d26fa849ebf0c0f9dafb36aaf --- /dev/null +++ b/python/user_packages/Python313/site-packages/cryptography/hazmat/bindings/_rust/openssl/ciphers.pyi @@ -0,0 +1,38 @@ +# This file is dual licensed under the terms of the Apache License, Version +# 2.0, and the BSD License. See the LICENSE file in the root of this repository +# for complete details. + +import typing + +from cryptography.hazmat.primitives import ciphers +from cryptography.hazmat.primitives.ciphers import modes + +@typing.overload +def create_encryption_ctx( + algorithm: ciphers.CipherAlgorithm, mode: modes.ModeWithAuthenticationTag +) -> ciphers.AEADEncryptionContext: ... +@typing.overload +def create_encryption_ctx( + algorithm: ciphers.CipherAlgorithm, mode: modes.Mode | None +) -> ciphers.CipherContext: ... +@typing.overload +def create_decryption_ctx( + algorithm: ciphers.CipherAlgorithm, mode: modes.ModeWithAuthenticationTag +) -> ciphers.AEADDecryptionContext: ... +@typing.overload +def create_decryption_ctx( + algorithm: ciphers.CipherAlgorithm, mode: modes.Mode | None +) -> ciphers.CipherContext: ... +def cipher_supported( + algorithm: ciphers.CipherAlgorithm, mode: modes.Mode +) -> bool: ... +def _advance( + ctx: ciphers.AEADEncryptionContext | ciphers.AEADDecryptionContext, n: int +) -> None: ... +def _advance_aad( + ctx: ciphers.AEADEncryptionContext | ciphers.AEADDecryptionContext, n: int +) -> None: ... + +class CipherContext: ... +class AEADEncryptionContext: ... +class AEADDecryptionContext: ... diff --git a/python/user_packages/Python313/site-packages/cryptography/hazmat/bindings/_rust/openssl/cmac.pyi b/python/user_packages/Python313/site-packages/cryptography/hazmat/bindings/_rust/openssl/cmac.pyi new file mode 100644 index 0000000000000000000000000000000000000000..9c03508bc89bf087e24c684802eeec344d76bb9e --- /dev/null +++ b/python/user_packages/Python313/site-packages/cryptography/hazmat/bindings/_rust/openssl/cmac.pyi @@ -0,0 +1,18 @@ +# This file is dual licensed under the terms of the Apache License, Version +# 2.0, and the BSD License. See the LICENSE file in the root of this repository +# for complete details. + +import typing + +from cryptography.hazmat.primitives import ciphers + +class CMAC: + def __init__( + self, + algorithm: ciphers.BlockCipherAlgorithm, + backend: typing.Any = None, + ) -> None: ... + def update(self, data: bytes) -> None: ... + def finalize(self) -> bytes: ... + def verify(self, signature: bytes) -> None: ... + def copy(self) -> CMAC: ... diff --git a/python/user_packages/Python313/site-packages/cryptography/hazmat/bindings/_rust/openssl/dh.pyi b/python/user_packages/Python313/site-packages/cryptography/hazmat/bindings/_rust/openssl/dh.pyi new file mode 100644 index 0000000000000000000000000000000000000000..08733d745c3ddc994f358193dd4b79ce359583d8 --- /dev/null +++ b/python/user_packages/Python313/site-packages/cryptography/hazmat/bindings/_rust/openssl/dh.pyi @@ -0,0 +1,51 @@ +# This file is dual licensed under the terms of the Apache License, Version +# 2.0, and the BSD License. See the LICENSE file in the root of this repository +# for complete details. + +import typing + +from cryptography.hazmat.primitives.asymmetric import dh + +MIN_MODULUS_SIZE: int + +class DHPrivateKey: ... +class DHPublicKey: ... +class DHParameters: ... + +class DHPrivateNumbers: + def __init__(self, x: int, public_numbers: DHPublicNumbers) -> None: ... + def private_key(self, backend: typing.Any = None) -> dh.DHPrivateKey: ... + @property + def x(self) -> int: ... + @property + def public_numbers(self) -> DHPublicNumbers: ... + +class DHPublicNumbers: + def __init__( + self, y: int, parameter_numbers: DHParameterNumbers + ) -> None: ... + def public_key(self, backend: typing.Any = None) -> dh.DHPublicKey: ... + @property + def y(self) -> int: ... + @property + def parameter_numbers(self) -> DHParameterNumbers: ... + +class DHParameterNumbers: + def __init__(self, p: int, g: int, q: int | None = None) -> None: ... + def parameters(self, backend: typing.Any = None) -> dh.DHParameters: ... + @property + def p(self) -> int: ... + @property + def g(self) -> int: ... + @property + def q(self) -> int | None: ... + +def generate_parameters( + generator: int, key_size: int, backend: typing.Any = None +) -> dh.DHParameters: ... +def from_pem_parameters( + data: bytes, backend: typing.Any = None +) -> dh.DHParameters: ... +def from_der_parameters( + data: bytes, backend: typing.Any = None +) -> dh.DHParameters: ... diff --git a/python/user_packages/Python313/site-packages/cryptography/hazmat/bindings/_rust/openssl/dsa.pyi b/python/user_packages/Python313/site-packages/cryptography/hazmat/bindings/_rust/openssl/dsa.pyi new file mode 100644 index 0000000000000000000000000000000000000000..0922a4c4041a90b1e884f56522f82bced398c80e --- /dev/null +++ b/python/user_packages/Python313/site-packages/cryptography/hazmat/bindings/_rust/openssl/dsa.pyi @@ -0,0 +1,41 @@ +# This file is dual licensed under the terms of the Apache License, Version +# 2.0, and the BSD License. See the LICENSE file in the root of this repository +# for complete details. + +import typing + +from cryptography.hazmat.primitives.asymmetric import dsa + +class DSAPrivateKey: ... +class DSAPublicKey: ... +class DSAParameters: ... + +class DSAPrivateNumbers: + def __init__(self, x: int, public_numbers: DSAPublicNumbers) -> None: ... + @property + def x(self) -> int: ... + @property + def public_numbers(self) -> DSAPublicNumbers: ... + def private_key(self, backend: typing.Any = None) -> dsa.DSAPrivateKey: ... + +class DSAPublicNumbers: + def __init__( + self, y: int, parameter_numbers: DSAParameterNumbers + ) -> None: ... + @property + def y(self) -> int: ... + @property + def parameter_numbers(self) -> DSAParameterNumbers: ... + def public_key(self, backend: typing.Any = None) -> dsa.DSAPublicKey: ... + +class DSAParameterNumbers: + def __init__(self, p: int, q: int, g: int) -> None: ... + @property + def p(self) -> int: ... + @property + def q(self) -> int: ... + @property + def g(self) -> int: ... + def parameters(self, backend: typing.Any = None) -> dsa.DSAParameters: ... + +def generate_parameters(key_size: int) -> dsa.DSAParameters: ... diff --git a/python/user_packages/Python313/site-packages/cryptography/hazmat/bindings/_rust/openssl/ec.pyi b/python/user_packages/Python313/site-packages/cryptography/hazmat/bindings/_rust/openssl/ec.pyi new file mode 100644 index 0000000000000000000000000000000000000000..5c3b7bf6e4a9bafac1423bd3936ebc347885a950 --- /dev/null +++ b/python/user_packages/Python313/site-packages/cryptography/hazmat/bindings/_rust/openssl/ec.pyi @@ -0,0 +1,52 @@ +# This file is dual licensed under the terms of the Apache License, Version +# 2.0, and the BSD License. See the LICENSE file in the root of this repository +# for complete details. + +import typing + +from cryptography.hazmat.primitives.asymmetric import ec + +class ECPrivateKey: ... +class ECPublicKey: ... + +class EllipticCurvePrivateNumbers: + def __init__( + self, private_value: int, public_numbers: EllipticCurvePublicNumbers + ) -> None: ... + def private_key( + self, backend: typing.Any = None + ) -> ec.EllipticCurvePrivateKey: ... + @property + def private_value(self) -> int: ... + @property + def public_numbers(self) -> EllipticCurvePublicNumbers: ... + +class EllipticCurvePublicNumbers: + def __init__(self, x: int, y: int, curve: ec.EllipticCurve) -> None: ... + def public_key( + self, backend: typing.Any = None + ) -> ec.EllipticCurvePublicKey: ... + @property + def x(self) -> int: ... + @property + def y(self) -> int: ... + @property + def curve(self) -> ec.EllipticCurve: ... + def __eq__(self, other: object) -> bool: ... + +def curve_supported(curve: ec.EllipticCurve) -> bool: ... +def generate_private_key( + curve: ec.EllipticCurve, backend: typing.Any = None +) -> ec.EllipticCurvePrivateKey: ... +def from_private_numbers( + numbers: ec.EllipticCurvePrivateNumbers, +) -> ec.EllipticCurvePrivateKey: ... +def from_public_numbers( + numbers: ec.EllipticCurvePublicNumbers, +) -> ec.EllipticCurvePublicKey: ... +def from_public_bytes( + curve: ec.EllipticCurve, data: bytes +) -> ec.EllipticCurvePublicKey: ... +def derive_private_key( + private_value: int, curve: ec.EllipticCurve +) -> ec.EllipticCurvePrivateKey: ... diff --git a/python/user_packages/Python313/site-packages/cryptography/hazmat/bindings/_rust/openssl/ed25519.pyi b/python/user_packages/Python313/site-packages/cryptography/hazmat/bindings/_rust/openssl/ed25519.pyi new file mode 100644 index 0000000000000000000000000000000000000000..f85b3d1b2361832095a00ba9b67675ad365339dd --- /dev/null +++ b/python/user_packages/Python313/site-packages/cryptography/hazmat/bindings/_rust/openssl/ed25519.pyi @@ -0,0 +1,13 @@ +# This file is dual licensed under the terms of the Apache License, Version +# 2.0, and the BSD License. See the LICENSE file in the root of this repository +# for complete details. + +from cryptography.hazmat.primitives.asymmetric import ed25519 +from cryptography.utils import Buffer + +class Ed25519PrivateKey: ... +class Ed25519PublicKey: ... + +def generate_key() -> ed25519.Ed25519PrivateKey: ... +def from_private_bytes(data: Buffer) -> ed25519.Ed25519PrivateKey: ... +def from_public_bytes(data: bytes) -> ed25519.Ed25519PublicKey: ... diff --git a/python/user_packages/Python313/site-packages/cryptography/hazmat/bindings/_rust/openssl/ed448.pyi b/python/user_packages/Python313/site-packages/cryptography/hazmat/bindings/_rust/openssl/ed448.pyi new file mode 100644 index 0000000000000000000000000000000000000000..c8ca0ecb156b9d9a7e69cf10bf71f187362f3315 --- /dev/null +++ b/python/user_packages/Python313/site-packages/cryptography/hazmat/bindings/_rust/openssl/ed448.pyi @@ -0,0 +1,13 @@ +# This file is dual licensed under the terms of the Apache License, Version +# 2.0, and the BSD License. See the LICENSE file in the root of this repository +# for complete details. + +from cryptography.hazmat.primitives.asymmetric import ed448 +from cryptography.utils import Buffer + +class Ed448PrivateKey: ... +class Ed448PublicKey: ... + +def generate_key() -> ed448.Ed448PrivateKey: ... +def from_private_bytes(data: Buffer) -> ed448.Ed448PrivateKey: ... +def from_public_bytes(data: bytes) -> ed448.Ed448PublicKey: ... diff --git a/python/user_packages/Python313/site-packages/cryptography/hazmat/bindings/_rust/openssl/hashes.pyi b/python/user_packages/Python313/site-packages/cryptography/hazmat/bindings/_rust/openssl/hashes.pyi new file mode 100644 index 0000000000000000000000000000000000000000..106b531c66a17cc2ceb3effc9863b8cc614a1351 --- /dev/null +++ b/python/user_packages/Python313/site-packages/cryptography/hazmat/bindings/_rust/openssl/hashes.pyi @@ -0,0 +1,30 @@ +# This file is dual licensed under the terms of the Apache License, Version +# 2.0, and the BSD License. See the LICENSE file in the root of this repository +# for complete details. + +import typing + +from cryptography.hazmat.primitives import hashes +from cryptography.utils import Buffer + +class Hash(hashes.HashContext): + def __init__( + self, algorithm: hashes.HashAlgorithm, backend: typing.Any = None + ) -> None: ... + @property + def algorithm(self) -> hashes.HashAlgorithm: ... + def update(self, data: Buffer) -> None: ... + def finalize(self) -> bytes: ... + def copy(self) -> Hash: ... + @staticmethod + def hash(algorithm: hashes.HashAlgorithm, data: Buffer) -> bytes: ... + +def hash_supported(algorithm: hashes.HashAlgorithm) -> bool: ... + +class XOFHash: + def __init__(self, algorithm: hashes.ExtendableOutputFunction) -> None: ... + @property + def algorithm(self) -> hashes.ExtendableOutputFunction: ... + def update(self, data: Buffer) -> None: ... + def squeeze(self, length: int) -> bytes: ... + def copy(self) -> XOFHash: ... diff --git a/python/user_packages/Python313/site-packages/cryptography/hazmat/bindings/_rust/openssl/hmac.pyi b/python/user_packages/Python313/site-packages/cryptography/hazmat/bindings/_rust/openssl/hmac.pyi new file mode 100644 index 0000000000000000000000000000000000000000..3883d1b1a920b0f118a6e9c6084f9532a5484bec --- /dev/null +++ b/python/user_packages/Python313/site-packages/cryptography/hazmat/bindings/_rust/openssl/hmac.pyi @@ -0,0 +1,22 @@ +# This file is dual licensed under the terms of the Apache License, Version +# 2.0, and the BSD License. See the LICENSE file in the root of this repository +# for complete details. + +import typing + +from cryptography.hazmat.primitives import hashes +from cryptography.utils import Buffer + +class HMAC(hashes.HashContext): + def __init__( + self, + key: Buffer, + algorithm: hashes.HashAlgorithm, + backend: typing.Any = None, + ) -> None: ... + @property + def algorithm(self) -> hashes.HashAlgorithm: ... + def update(self, data: Buffer) -> None: ... + def finalize(self) -> bytes: ... + def verify(self, signature: bytes) -> None: ... + def copy(self) -> HMAC: ... diff --git a/python/user_packages/Python313/site-packages/cryptography/hazmat/bindings/_rust/openssl/hpke.pyi b/python/user_packages/Python313/site-packages/cryptography/hazmat/bindings/_rust/openssl/hpke.pyi new file mode 100644 index 0000000000000000000000000000000000000000..a9d8a1167efc6a72c686b038a52d9fe9f1e8aa37 --- /dev/null +++ b/python/user_packages/Python313/site-packages/cryptography/hazmat/bindings/_rust/openssl/hpke.pyi @@ -0,0 +1,108 @@ +# This file is dual licensed under the terms of the Apache License, Version +# 2.0, and the BSD License. See the LICENSE file in the root of this repository +# for complete details. + +from cryptography.hazmat.primitives.asymmetric import ec, mlkem, x25519 +from cryptography.utils import Buffer + +class KEM: + X25519: KEM + P256: KEM + P384: KEM + P521: KEM + MLKEM768: KEM + MLKEM1024: KEM + MLKEM768_X25519: KEM + MLKEM1024_P384: KEM + +class KDF: + HKDF_SHA256: KDF + HKDF_SHA384: KDF + HKDF_SHA512: KDF + SHAKE128: KDF + SHAKE256: KDF + +class AEAD: + AES_128_GCM: AEAD + AES_256_GCM: AEAD + CHACHA20_POLY1305: AEAD + +class MLKEM768X25519PrivateKey: + def __init__( + self, + mlkem_key: mlkem.MLKEM768PrivateKey, + x25519_key: x25519.X25519PrivateKey, + ) -> None: ... + def public_key(self) -> MLKEM768X25519PublicKey: ... + +class MLKEM768X25519PublicKey: + def __init__( + self, + mlkem_key: mlkem.MLKEM768PublicKey, + x25519_key: x25519.X25519PublicKey, + ) -> None: ... + +class MLKEM1024P384PrivateKey: + def __init__( + self, + mlkem_key: mlkem.MLKEM1024PrivateKey, + p384_key: ec.EllipticCurvePrivateKey, + ) -> None: ... + def public_key(self) -> MLKEM1024P384PublicKey: ... + +class MLKEM1024P384PublicKey: + def __init__( + self, + mlkem_key: mlkem.MLKEM1024PublicKey, + p384_key: ec.EllipticCurvePublicKey, + ) -> None: ... + +class Suite: + def __init__(self, kem: KEM, kdf: KDF, aead: AEAD) -> None: ... + def encrypt( + self, + plaintext: Buffer, + public_key: x25519.X25519PublicKey + | ec.EllipticCurvePublicKey + | mlkem.MLKEM768PublicKey + | mlkem.MLKEM1024PublicKey + | MLKEM768X25519PublicKey + | MLKEM1024P384PublicKey, + info: Buffer | None = None, + ) -> bytes: ... + def decrypt( + self, + ciphertext: Buffer, + private_key: x25519.X25519PrivateKey + | ec.EllipticCurvePrivateKey + | mlkem.MLKEM768PrivateKey + | mlkem.MLKEM1024PrivateKey + | MLKEM768X25519PrivateKey + | MLKEM1024P384PrivateKey, + info: Buffer | None = None, + ) -> bytes: ... + +def _encrypt_with_aad( + suite: Suite, + plaintext: Buffer, + public_key: x25519.X25519PublicKey + | ec.EllipticCurvePublicKey + | mlkem.MLKEM768PublicKey + | mlkem.MLKEM1024PublicKey + | MLKEM768X25519PublicKey + | MLKEM1024P384PublicKey, + info: Buffer | None = None, + aad: Buffer | None = None, +) -> bytes: ... +def _decrypt_with_aad( + suite: Suite, + ciphertext: Buffer, + private_key: x25519.X25519PrivateKey + | ec.EllipticCurvePrivateKey + | mlkem.MLKEM768PrivateKey + | mlkem.MLKEM1024PrivateKey + | MLKEM768X25519PrivateKey + | MLKEM1024P384PrivateKey, + info: Buffer | None = None, + aad: Buffer | None = None, +) -> bytes: ... diff --git a/python/user_packages/Python313/site-packages/cryptography/hazmat/bindings/_rust/openssl/kdf.pyi b/python/user_packages/Python313/site-packages/cryptography/hazmat/bindings/_rust/openssl/kdf.pyi new file mode 100644 index 0000000000000000000000000000000000000000..bb37b9698a7d0cb62304d7ca031da82bc474612a --- /dev/null +++ b/python/user_packages/Python313/site-packages/cryptography/hazmat/bindings/_rust/openssl/kdf.pyi @@ -0,0 +1,205 @@ +# This file is dual licensed under the terms of the Apache License, Version +# 2.0, and the BSD License. See the LICENSE file in the root of this repository +# for complete details. + +import typing + +from cryptography.hazmat.primitives.hashes import HashAlgorithm +from cryptography.hazmat.primitives.kdf.kbkdf import CounterLocation, Mode +from cryptography.utils import Buffer + +class PBKDF2HMAC: + def __init__( + self, + algorithm: HashAlgorithm, + length: int, + salt: bytes, + iterations: int, + backend: typing.Any = None, + ) -> None: ... + def derive(self, key_material: Buffer) -> bytes: ... + def derive_into(self, key_material: Buffer, buffer: Buffer) -> int: ... + def verify(self, key_material: bytes, expected_key: bytes) -> None: ... + +class Scrypt: + def __init__( + self, + salt: bytes, + length: int, + n: int, + r: int, + p: int, + backend: typing.Any = None, + ) -> None: ... + def derive(self, key_material: Buffer) -> bytes: ... + def derive_into(self, key_material: Buffer, buffer: Buffer) -> int: ... + def verify(self, key_material: bytes, expected_key: bytes) -> None: ... + +class Argon2d: + def __init__( + self, + *, + salt: bytes, + length: int, + iterations: int, + lanes: int, + memory_cost: int, + ad: bytes | None = None, + secret: bytes | None = None, + ) -> None: ... + def derive(self, key_material: bytes) -> bytes: ... + def derive_into(self, key_material: bytes, buffer: Buffer) -> int: ... + def verify(self, key_material: bytes, expected_key: bytes) -> None: ... + def derive_phc_encoded(self, key_material: bytes) -> str: ... + @classmethod + def verify_phc_encoded( + cls, key_material: bytes, phc_encoded: str, secret: bytes | None = None + ) -> None: ... + +class Argon2i: + def __init__( + self, + *, + salt: bytes, + length: int, + iterations: int, + lanes: int, + memory_cost: int, + ad: bytes | None = None, + secret: bytes | None = None, + ) -> None: ... + def derive(self, key_material: bytes) -> bytes: ... + def derive_into(self, key_material: bytes, buffer: Buffer) -> int: ... + def verify(self, key_material: bytes, expected_key: bytes) -> None: ... + def derive_phc_encoded(self, key_material: bytes) -> str: ... + @classmethod + def verify_phc_encoded( + cls, key_material: bytes, phc_encoded: str, secret: bytes | None = None + ) -> None: ... + +class Argon2id: + def __init__( + self, + *, + salt: bytes, + length: int, + iterations: int, + lanes: int, + memory_cost: int, + ad: bytes | None = None, + secret: bytes | None = None, + ) -> None: ... + def derive(self, key_material: bytes) -> bytes: ... + def derive_into(self, key_material: bytes, buffer: Buffer) -> int: ... + def verify(self, key_material: bytes, expected_key: bytes) -> None: ... + def derive_phc_encoded(self, key_material: bytes) -> str: ... + @classmethod + def verify_phc_encoded( + cls, key_material: bytes, phc_encoded: str, secret: bytes | None = None + ) -> None: ... + +class HKDF: + def __init__( + self, + algorithm: HashAlgorithm, + length: int, + salt: bytes | None, + info: bytes | None, + backend: typing.Any = None, + ): ... + @staticmethod + def extract( + algorithm: HashAlgorithm, salt: bytes | None, key_material: Buffer + ) -> bytes: ... + def derive(self, key_material: Buffer) -> bytes: ... + def derive_into(self, key_material: Buffer, buffer: Buffer) -> int: ... + def verify(self, key_material: bytes, expected_key: bytes) -> None: ... + +class HKDFExpand: + def __init__( + self, + algorithm: HashAlgorithm, + length: int, + info: bytes | None, + backend: typing.Any = None, + ): ... + def derive(self, key_material: Buffer) -> bytes: ... + def derive_into(self, key_material: Buffer, buffer: Buffer) -> int: ... + def verify(self, key_material: bytes, expected_key: bytes) -> None: ... + +class X963KDF: + def __init__( + self, + algorithm: HashAlgorithm, + length: int, + sharedinfo: bytes | None, + backend: typing.Any = None, + ) -> None: ... + def derive(self, key_material: Buffer) -> bytes: ... + def derive_into(self, key_material: Buffer, buffer: Buffer) -> int: ... + def verify(self, key_material: bytes, expected_key: bytes) -> None: ... + +class ConcatKDFHash: + def __init__( + self, + algorithm: HashAlgorithm, + length: int, + otherinfo: bytes | None, + backend: typing.Any = None, + ) -> None: ... + def derive(self, key_material: Buffer) -> bytes: ... + def derive_into(self, key_material: Buffer, buffer: Buffer) -> int: ... + def verify(self, key_material: bytes, expected_key: bytes) -> None: ... + +class ConcatKDFHMAC: + def __init__( + self, + algorithm: HashAlgorithm, + length: int, + salt: bytes | None, + otherinfo: bytes | None, + backend: typing.Any = None, + ) -> None: ... + def derive(self, key_material: Buffer) -> bytes: ... + def derive_into(self, key_material: Buffer, buffer: Buffer) -> int: ... + def verify(self, key_material: bytes, expected_key: bytes) -> None: ... + +class KBKDFHMAC: + def __init__( + self, + algorithm: HashAlgorithm, + mode: Mode, + length: int, + rlen: int, + llen: int | None, + location: CounterLocation, + label: bytes | None, + context: bytes | None, + fixed: bytes | None, + backend: typing.Any = None, + *, + break_location: int | None = None, + ) -> None: ... + def derive(self, key_material: Buffer) -> bytes: ... + def derive_into(self, key_material: Buffer, buffer: Buffer) -> int: ... + def verify(self, key_material: bytes, expected_key: bytes) -> None: ... + +class KBKDFCMAC: + def __init__( + self, + algorithm: typing.Any, + mode: Mode, + length: int, + rlen: int, + llen: int | None, + location: CounterLocation, + label: bytes | None, + context: bytes | None, + fixed: bytes | None, + backend: typing.Any = None, + *, + break_location: int | None = None, + ) -> None: ... + def derive(self, key_material: Buffer) -> bytes: ... + def derive_into(self, key_material: Buffer, buffer: Buffer) -> int: ... + def verify(self, key_material: bytes, expected_key: bytes) -> None: ... diff --git a/python/user_packages/Python313/site-packages/cryptography/hazmat/bindings/_rust/openssl/keys.pyi b/python/user_packages/Python313/site-packages/cryptography/hazmat/bindings/_rust/openssl/keys.pyi new file mode 100644 index 0000000000000000000000000000000000000000..404057e037408dd1979afc482768430b8b478646 --- /dev/null +++ b/python/user_packages/Python313/site-packages/cryptography/hazmat/bindings/_rust/openssl/keys.pyi @@ -0,0 +1,34 @@ +# This file is dual licensed under the terms of the Apache License, Version +# 2.0, and the BSD License. See the LICENSE file in the root of this repository +# for complete details. + +import typing + +from cryptography.hazmat.primitives.asymmetric.types import ( + PrivateKeyTypes, + PublicKeyTypes, +) +from cryptography.utils import Buffer + +def load_der_private_key( + data: Buffer, + password: bytes | None, + backend: typing.Any = None, + *, + unsafe_skip_rsa_key_validation: bool = False, +) -> PrivateKeyTypes: ... +def load_pem_private_key( + data: Buffer, + password: bytes | None, + backend: typing.Any = None, + *, + unsafe_skip_rsa_key_validation: bool = False, +) -> PrivateKeyTypes: ... +def load_der_public_key( + data: bytes, + backend: typing.Any = None, +) -> PublicKeyTypes: ... +def load_pem_public_key( + data: bytes, + backend: typing.Any = None, +) -> PublicKeyTypes: ... diff --git a/python/user_packages/Python313/site-packages/cryptography/hazmat/bindings/_rust/openssl/mldsa.pyi b/python/user_packages/Python313/site-packages/cryptography/hazmat/bindings/_rust/openssl/mldsa.pyi new file mode 100644 index 0000000000000000000000000000000000000000..232469a090387544cee2198fccd264785bad652f --- /dev/null +++ b/python/user_packages/Python313/site-packages/cryptography/hazmat/bindings/_rust/openssl/mldsa.pyi @@ -0,0 +1,23 @@ +# This file is dual licensed under the terms of the Apache License, Version +# 2.0, and the BSD License. See the LICENSE file in the root of this repository +# for complete details. + +from cryptography.hazmat.primitives.asymmetric import mldsa +from cryptography.utils import Buffer + +class MLDSA44PrivateKey: ... +class MLDSA44PublicKey: ... +class MLDSA65PrivateKey: ... +class MLDSA65PublicKey: ... +class MLDSA87PrivateKey: ... +class MLDSA87PublicKey: ... + +def generate_mldsa44_key() -> mldsa.MLDSA44PrivateKey: ... +def from_mldsa44_public_bytes(data: bytes) -> mldsa.MLDSA44PublicKey: ... +def from_mldsa44_seed_bytes(data: Buffer) -> mldsa.MLDSA44PrivateKey: ... +def generate_mldsa65_key() -> mldsa.MLDSA65PrivateKey: ... +def from_mldsa65_public_bytes(data: bytes) -> mldsa.MLDSA65PublicKey: ... +def from_mldsa65_seed_bytes(data: Buffer) -> mldsa.MLDSA65PrivateKey: ... +def generate_mldsa87_key() -> mldsa.MLDSA87PrivateKey: ... +def from_mldsa87_public_bytes(data: bytes) -> mldsa.MLDSA87PublicKey: ... +def from_mldsa87_seed_bytes(data: Buffer) -> mldsa.MLDSA87PrivateKey: ... diff --git a/python/user_packages/Python313/site-packages/cryptography/hazmat/bindings/_rust/openssl/mlkem.pyi b/python/user_packages/Python313/site-packages/cryptography/hazmat/bindings/_rust/openssl/mlkem.pyi new file mode 100644 index 0000000000000000000000000000000000000000..768a340a3831aa7367751a28658b0b0841c8a7ca --- /dev/null +++ b/python/user_packages/Python313/site-packages/cryptography/hazmat/bindings/_rust/openssl/mlkem.pyi @@ -0,0 +1,18 @@ +# This file is dual licensed under the terms of the Apache License, Version +# 2.0, and the BSD License. See the LICENSE file in the root of this repository +# for complete details. + +from cryptography.hazmat.primitives.asymmetric import mlkem +from cryptography.utils import Buffer + +class MLKEM768PrivateKey: ... +class MLKEM768PublicKey: ... +class MLKEM1024PrivateKey: ... +class MLKEM1024PublicKey: ... + +def generate_mlkem768_key() -> mlkem.MLKEM768PrivateKey: ... +def from_mlkem768_seed_bytes(data: Buffer) -> mlkem.MLKEM768PrivateKey: ... +def from_mlkem768_public_bytes(data: Buffer) -> mlkem.MLKEM768PublicKey: ... +def generate_mlkem1024_key() -> mlkem.MLKEM1024PrivateKey: ... +def from_mlkem1024_seed_bytes(data: Buffer) -> mlkem.MLKEM1024PrivateKey: ... +def from_mlkem1024_public_bytes(data: Buffer) -> mlkem.MLKEM1024PublicKey: ... diff --git a/python/user_packages/Python313/site-packages/cryptography/hazmat/bindings/_rust/openssl/poly1305.pyi b/python/user_packages/Python313/site-packages/cryptography/hazmat/bindings/_rust/openssl/poly1305.pyi new file mode 100644 index 0000000000000000000000000000000000000000..45a2a39f689071b5d544d8495bfd5bd57d4ab6e4 --- /dev/null +++ b/python/user_packages/Python313/site-packages/cryptography/hazmat/bindings/_rust/openssl/poly1305.pyi @@ -0,0 +1,15 @@ +# This file is dual licensed under the terms of the Apache License, Version +# 2.0, and the BSD License. See the LICENSE file in the root of this repository +# for complete details. + +from cryptography.utils import Buffer + +class Poly1305: + def __init__(self, key: Buffer) -> None: ... + @staticmethod + def generate_tag(key: Buffer, data: Buffer) -> bytes: ... + @staticmethod + def verify_tag(key: Buffer, data: Buffer, tag: bytes) -> None: ... + def update(self, data: Buffer) -> None: ... + def finalize(self) -> bytes: ... + def verify(self, tag: bytes) -> None: ... diff --git a/python/user_packages/Python313/site-packages/cryptography/hazmat/bindings/_rust/openssl/rsa.pyi b/python/user_packages/Python313/site-packages/cryptography/hazmat/bindings/_rust/openssl/rsa.pyi new file mode 100644 index 0000000000000000000000000000000000000000..ef7752ddb79db62489bcf71df933fdefd83c0f9d --- /dev/null +++ b/python/user_packages/Python313/site-packages/cryptography/hazmat/bindings/_rust/openssl/rsa.pyi @@ -0,0 +1,55 @@ +# This file is dual licensed under the terms of the Apache License, Version +# 2.0, and the BSD License. See the LICENSE file in the root of this repository +# for complete details. + +import typing + +from cryptography.hazmat.primitives.asymmetric import rsa + +class RSAPrivateKey: ... +class RSAPublicKey: ... + +class RSAPrivateNumbers: + def __init__( + self, + p: int, + q: int, + d: int, + dmp1: int, + dmq1: int, + iqmp: int, + public_numbers: RSAPublicNumbers, + ) -> None: ... + @property + def p(self) -> int: ... + @property + def q(self) -> int: ... + @property + def d(self) -> int: ... + @property + def dmp1(self) -> int: ... + @property + def dmq1(self) -> int: ... + @property + def iqmp(self) -> int: ... + @property + def public_numbers(self) -> RSAPublicNumbers: ... + def private_key( + self, + backend: typing.Any = None, + *, + unsafe_skip_rsa_key_validation: bool = False, + ) -> rsa.RSAPrivateKey: ... + +class RSAPublicNumbers: + def __init__(self, e: int, n: int) -> None: ... + @property + def n(self) -> int: ... + @property + def e(self) -> int: ... + def public_key(self, backend: typing.Any = None) -> rsa.RSAPublicKey: ... + +def generate_private_key( + public_exponent: int, + key_size: int, +) -> rsa.RSAPrivateKey: ... diff --git a/python/user_packages/Python313/site-packages/cryptography/hazmat/bindings/_rust/openssl/x25519.pyi b/python/user_packages/Python313/site-packages/cryptography/hazmat/bindings/_rust/openssl/x25519.pyi new file mode 100644 index 0000000000000000000000000000000000000000..38d2adddb1017030139f2cb2411dc43101a7448e --- /dev/null +++ b/python/user_packages/Python313/site-packages/cryptography/hazmat/bindings/_rust/openssl/x25519.pyi @@ -0,0 +1,13 @@ +# This file is dual licensed under the terms of the Apache License, Version +# 2.0, and the BSD License. See the LICENSE file in the root of this repository +# for complete details. + +from cryptography.hazmat.primitives.asymmetric import x25519 +from cryptography.utils import Buffer + +class X25519PrivateKey: ... +class X25519PublicKey: ... + +def generate_key() -> x25519.X25519PrivateKey: ... +def from_private_bytes(data: Buffer) -> x25519.X25519PrivateKey: ... +def from_public_bytes(data: bytes) -> x25519.X25519PublicKey: ... diff --git a/python/user_packages/Python313/site-packages/cryptography/hazmat/bindings/_rust/openssl/x448.pyi b/python/user_packages/Python313/site-packages/cryptography/hazmat/bindings/_rust/openssl/x448.pyi new file mode 100644 index 0000000000000000000000000000000000000000..3ac098091af514639889486723710f851cd93e6b --- /dev/null +++ b/python/user_packages/Python313/site-packages/cryptography/hazmat/bindings/_rust/openssl/x448.pyi @@ -0,0 +1,13 @@ +# This file is dual licensed under the terms of the Apache License, Version +# 2.0, and the BSD License. See the LICENSE file in the root of this repository +# for complete details. + +from cryptography.hazmat.primitives.asymmetric import x448 +from cryptography.utils import Buffer + +class X448PrivateKey: ... +class X448PublicKey: ... + +def generate_key() -> x448.X448PrivateKey: ... +def from_private_bytes(data: Buffer) -> x448.X448PrivateKey: ... +def from_public_bytes(data: bytes) -> x448.X448PublicKey: ... diff --git a/python/user_packages/Python313/site-packages/cryptography/hazmat/bindings/_rust/pkcs12.pyi b/python/user_packages/Python313/site-packages/cryptography/hazmat/bindings/_rust/pkcs12.pyi new file mode 100644 index 0000000000000000000000000000000000000000..b25becb6bdef7ce259dcb40f34aa9386774437ca --- /dev/null +++ b/python/user_packages/Python313/site-packages/cryptography/hazmat/bindings/_rust/pkcs12.pyi @@ -0,0 +1,52 @@ +# This file is dual licensed under the terms of the Apache License, Version +# 2.0, and the BSD License. See the LICENSE file in the root of this repository +# for complete details. + +import typing +from collections.abc import Iterable + +from cryptography import x509 +from cryptography.hazmat.primitives.asymmetric.types import PrivateKeyTypes +from cryptography.hazmat.primitives.serialization import ( + KeySerializationEncryption, +) +from cryptography.hazmat.primitives.serialization.pkcs12 import ( + PKCS12KeyAndCertificates, + PKCS12PrivateKeyTypes, +) +from cryptography.utils import Buffer + +class PKCS12Certificate: + def __init__( + self, cert: x509.Certificate, friendly_name: bytes | None + ) -> None: ... + @property + def friendly_name(self) -> bytes | None: ... + @property + def certificate(self) -> x509.Certificate: ... + +def load_key_and_certificates( + data: Buffer, + password: Buffer | None, + backend: typing.Any = None, +) -> tuple[ + PrivateKeyTypes | None, + x509.Certificate | None, + list[x509.Certificate], +]: ... +def load_pkcs12( + data: bytes, + password: bytes | None, + backend: typing.Any = None, +) -> PKCS12KeyAndCertificates: ... +def serialize_java_truststore( + certs: Iterable[PKCS12Certificate], + encryption_algorithm: KeySerializationEncryption, +) -> bytes: ... +def serialize_key_and_certificates( + name: bytes | None, + key: PKCS12PrivateKeyTypes | None, + cert: x509.Certificate | None, + cas: Iterable[x509.Certificate | PKCS12Certificate] | None, + encryption_algorithm: KeySerializationEncryption, +) -> bytes: ... diff --git a/python/user_packages/Python313/site-packages/cryptography/hazmat/bindings/_rust/pkcs7.pyi b/python/user_packages/Python313/site-packages/cryptography/hazmat/bindings/_rust/pkcs7.pyi new file mode 100644 index 0000000000000000000000000000000000000000..358b135865a89a6675706e0fd880d3eabdb081b5 --- /dev/null +++ b/python/user_packages/Python313/site-packages/cryptography/hazmat/bindings/_rust/pkcs7.pyi @@ -0,0 +1,50 @@ +# This file is dual licensed under the terms of the Apache License, Version +# 2.0, and the BSD License. See the LICENSE file in the root of this repository +# for complete details. + +from collections.abc import Iterable + +from cryptography import x509 +from cryptography.hazmat.primitives import serialization +from cryptography.hazmat.primitives.asymmetric import rsa +from cryptography.hazmat.primitives.serialization import pkcs7 + +def serialize_certificates( + certs: list[x509.Certificate], + encoding: serialization.Encoding, +) -> bytes: ... +def encrypt_and_serialize( + builder: pkcs7.PKCS7EnvelopeBuilder, + content_encryption_algorithm: pkcs7.ContentEncryptionAlgorithm, + encoding: serialization.Encoding, + options: Iterable[pkcs7.PKCS7Options], +) -> bytes: ... +def sign_and_serialize( + builder: pkcs7.PKCS7SignatureBuilder, + encoding: serialization.Encoding, + options: Iterable[pkcs7.PKCS7Options], +) -> bytes: ... +def decrypt_der( + data: bytes, + certificate: x509.Certificate, + private_key: rsa.RSAPrivateKey, + options: Iterable[pkcs7.PKCS7Options], +) -> bytes: ... +def decrypt_pem( + data: bytes, + certificate: x509.Certificate, + private_key: rsa.RSAPrivateKey, + options: Iterable[pkcs7.PKCS7Options], +) -> bytes: ... +def decrypt_smime( + data: bytes, + certificate: x509.Certificate, + private_key: rsa.RSAPrivateKey, + options: Iterable[pkcs7.PKCS7Options], +) -> bytes: ... +def load_pem_pkcs7_certificates( + data: bytes, +) -> list[x509.Certificate]: ... +def load_der_pkcs7_certificates( + data: bytes, +) -> list[x509.Certificate]: ... diff --git a/python/user_packages/Python313/site-packages/cryptography/hazmat/bindings/_rust/test_support.pyi b/python/user_packages/Python313/site-packages/cryptography/hazmat/bindings/_rust/test_support.pyi new file mode 100644 index 0000000000000000000000000000000000000000..c6c6d0bbe12916b4299d08398493c5da8f762ae7 --- /dev/null +++ b/python/user_packages/Python313/site-packages/cryptography/hazmat/bindings/_rust/test_support.pyi @@ -0,0 +1,23 @@ +# This file is dual licensed under the terms of the Apache License, Version +# 2.0, and the BSD License. See the LICENSE file in the root of this repository +# for complete details. + +from cryptography import x509 +from cryptography.hazmat.primitives import serialization +from cryptography.hazmat.primitives.serialization import pkcs7 +from cryptography.utils import Buffer + +class TestCertificate: + not_after_tag: int + not_before_tag: int + issuer_value_tags: list[int] + subject_value_tags: list[int] + +def test_parse_certificate(data: bytes) -> TestCertificate: ... +def pkcs7_verify( + encoding: serialization.Encoding, + sig: bytes, + msg: Buffer | None, + certs: list[x509.Certificate], + options: list[pkcs7.PKCS7Options], +) -> None: ... diff --git a/python/user_packages/Python313/site-packages/cryptography/hazmat/bindings/_rust/x509.pyi b/python/user_packages/Python313/site-packages/cryptography/hazmat/bindings/_rust/x509.pyi new file mode 100644 index 0000000000000000000000000000000000000000..196a3c60f7edf6887a75ed45f7eabd330f4efc1a --- /dev/null +++ b/python/user_packages/Python313/site-packages/cryptography/hazmat/bindings/_rust/x509.pyi @@ -0,0 +1,312 @@ +# This file is dual licensed under the terms of the Apache License, Version +# 2.0, and the BSD License. See the LICENSE file in the root of this repository +# for complete details. + +import datetime +import typing +from collections.abc import Iterator + +from cryptography import x509 +from cryptography.hazmat.primitives import hashes, serialization +from cryptography.hazmat.primitives.asymmetric.ec import ECDSA +from cryptography.hazmat.primitives.asymmetric.padding import PSS, PKCS1v15 +from cryptography.hazmat.primitives.asymmetric.types import ( + CertificateIssuerPublicKeyTypes, + CertificatePublicKeyTypes, + PrivateKeyTypes, +) +from cryptography.x509 import certificate_transparency + +def load_pem_x509_certificate( + data: bytes, backend: typing.Any = None +) -> x509.Certificate: ... +def load_der_x509_certificate( + data: bytes, backend: typing.Any = None +) -> x509.Certificate: ... +def load_pem_x509_certificates( + data: bytes, +) -> list[x509.Certificate]: ... +def load_pem_x509_crl( + data: bytes, backend: typing.Any = None +) -> x509.CertificateRevocationList: ... +def load_der_x509_crl( + data: bytes, backend: typing.Any = None +) -> x509.CertificateRevocationList: ... +def load_pem_x509_csr( + data: bytes, backend: typing.Any = None +) -> x509.CertificateSigningRequest: ... +def load_der_x509_csr( + data: bytes, backend: typing.Any = None +) -> x509.CertificateSigningRequest: ... +def encode_name_bytes(name: x509.Name) -> bytes: ... +def encode_extension_value(extension: x509.ExtensionType) -> bytes: ... +def create_x509_certificate( + builder: x509.CertificateBuilder, + private_key: PrivateKeyTypes, + hash_algorithm: hashes.HashAlgorithm | None, + rsa_padding: PKCS1v15 | PSS | None, + ecdsa_deterministic: bool | None, +) -> x509.Certificate: ... +def create_x509_csr( + builder: x509.CertificateSigningRequestBuilder, + private_key: PrivateKeyTypes, + hash_algorithm: hashes.HashAlgorithm | None, + rsa_padding: PKCS1v15 | PSS | None, + ecdsa_deterministic: bool | None, +) -> x509.CertificateSigningRequest: ... +def create_revoked_certificate( + builder: x509.RevokedCertificateBuilder, +) -> x509.RevokedCertificate: ... +def create_x509_crl( + builder: x509.CertificateRevocationListBuilder, + private_key: PrivateKeyTypes, + hash_algorithm: hashes.HashAlgorithm | None, + rsa_padding: PKCS1v15 | PSS | None, + ecdsa_deterministic: bool | None, +) -> x509.CertificateRevocationList: ... + +class Sct: + @property + def version(self) -> certificate_transparency.Version: ... + @property + def log_id(self) -> bytes: ... + @property + def timestamp(self) -> datetime.datetime: ... + @property + def entry_type(self) -> certificate_transparency.LogEntryType: ... + @property + def signature_hash_algorithm(self) -> hashes.HashAlgorithm: ... + @property + def signature_algorithm( + self, + ) -> certificate_transparency.SignatureAlgorithm: ... + @property + def signature(self) -> bytes: ... + @property + def extension_bytes(self) -> bytes: ... + +class Certificate: + def fingerprint(self, algorithm: hashes.HashAlgorithm) -> bytes: ... + @property + def serial_number(self) -> int: ... + @property + def version(self) -> x509.Version: ... + def public_key(self) -> CertificatePublicKeyTypes: ... + @property + def public_key_algorithm_oid(self) -> x509.ObjectIdentifier: ... + @property + def not_valid_before(self) -> datetime.datetime: ... + @property + def not_valid_before_utc(self) -> datetime.datetime: ... + @property + def not_valid_after(self) -> datetime.datetime: ... + @property + def not_valid_after_utc(self) -> datetime.datetime: ... + @property + def issuer(self) -> x509.Name: ... + @property + def subject(self) -> x509.Name: ... + @property + def signature_hash_algorithm( + self, + ) -> hashes.HashAlgorithm | None: ... + @property + def signature_algorithm_oid(self) -> x509.ObjectIdentifier: ... + @property + def signature_algorithm_parameters( + self, + ) -> PSS | PKCS1v15 | ECDSA | None: ... + @property + def extensions(self) -> x509.Extensions: ... + @property + def signature(self) -> bytes: ... + @property + def tbs_certificate_bytes(self) -> bytes: ... + @property + def tbs_precertificate_bytes(self) -> bytes: ... + def __eq__(self, other: object) -> bool: ... + def __hash__(self) -> int: ... + def public_bytes(self, encoding: serialization.Encoding) -> bytes: ... + def verify_directly_issued_by(self, issuer: Certificate) -> None: ... + +class RevokedCertificate: + @property + def serial_number(self) -> int: ... + @property + def revocation_date(self) -> datetime.datetime: ... + @property + def revocation_date_utc(self) -> datetime.datetime: ... + @property + def extensions(self) -> x509.Extensions: ... + +class CertificateRevocationList: + def public_bytes(self, encoding: serialization.Encoding) -> bytes: ... + def fingerprint(self, algorithm: hashes.HashAlgorithm) -> bytes: ... + def get_revoked_certificate_by_serial_number( + self, serial_number: int + ) -> x509.RevokedCertificate | None: ... + @property + def signature_hash_algorithm( + self, + ) -> hashes.HashAlgorithm | None: ... + @property + def signature_algorithm_oid(self) -> x509.ObjectIdentifier: ... + @property + def signature_algorithm_parameters( + self, + ) -> PSS | PKCS1v15 | ECDSA | None: ... + @property + def issuer(self) -> x509.Name: ... + @property + def next_update(self) -> datetime.datetime | None: ... + @property + def next_update_utc(self) -> datetime.datetime | None: ... + @property + def last_update(self) -> datetime.datetime: ... + @property + def last_update_utc(self) -> datetime.datetime: ... + @property + def extensions(self) -> x509.Extensions: ... + @property + def signature(self) -> bytes: ... + @property + def tbs_certlist_bytes(self) -> bytes: ... + def __eq__(self, other: object) -> bool: ... + def __len__(self) -> int: ... + @typing.overload + def __getitem__(self, idx: int) -> x509.RevokedCertificate: ... + @typing.overload + def __getitem__(self, idx: slice) -> list[x509.RevokedCertificate]: ... + def __iter__(self) -> Iterator[x509.RevokedCertificate]: ... + def is_signature_valid( + self, public_key: CertificateIssuerPublicKeyTypes + ) -> bool: ... + +class CertificateSigningRequest: + def __eq__(self, other: object) -> bool: ... + def __hash__(self) -> int: ... + def public_key(self) -> CertificatePublicKeyTypes: ... + @property + def subject(self) -> x509.Name: ... + @property + def signature_hash_algorithm( + self, + ) -> hashes.HashAlgorithm | None: ... + @property + def signature_algorithm_oid(self) -> x509.ObjectIdentifier: ... + @property + def signature_algorithm_parameters( + self, + ) -> PSS | PKCS1v15 | ECDSA | None: ... + @property + def extensions(self) -> x509.Extensions: ... + @property + def attributes(self) -> x509.Attributes: ... + def public_bytes(self, encoding: serialization.Encoding) -> bytes: ... + @property + def signature(self) -> bytes: ... + @property + def tbs_certrequest_bytes(self) -> bytes: ... + @property + def is_signature_valid(self) -> bool: ... + +class PolicyBuilder: + def time(self, time: datetime.datetime) -> PolicyBuilder: ... + def store(self, store: Store) -> PolicyBuilder: ... + def max_chain_depth(self, max_chain_depth: int) -> PolicyBuilder: ... + def extension_policies( + self, *, ca_policy: ExtensionPolicy, ee_policy: ExtensionPolicy + ) -> PolicyBuilder: ... + def build_client_verifier(self) -> ClientVerifier: ... + def build_server_verifier( + self, subject: x509.verification.Subject + ) -> ServerVerifier: ... + +class Policy: + @property + def max_chain_depth(self) -> int: ... + @property + def subject(self) -> x509.verification.Subject | None: ... + @property + def validation_time(self) -> datetime.datetime: ... + @property + def extended_key_usage(self) -> x509.ObjectIdentifier: ... + @property + def minimum_rsa_modulus(self) -> int: ... + +class Criticality: + CRITICAL: Criticality + AGNOSTIC: Criticality + NON_CRITICAL: Criticality + +T = typing.TypeVar("T", contravariant=True, bound=x509.ExtensionType) + +MaybeExtensionValidatorCallback = typing.Callable[ + [ + Policy, + x509.Certificate, + T | None, + ], + None, +] + +PresentExtensionValidatorCallback = typing.Callable[ + [Policy, x509.Certificate, T], + None, +] + +class ExtensionPolicy: + @staticmethod + def permit_all() -> ExtensionPolicy: ... + @staticmethod + def webpki_defaults_ca() -> ExtensionPolicy: ... + @staticmethod + def webpki_defaults_ee() -> ExtensionPolicy: ... + def require_not_present( + self, extension_type: type[x509.ExtensionType] + ) -> ExtensionPolicy: ... + def may_be_present( + self, + extension_type: type[T], + criticality: Criticality, + validator: MaybeExtensionValidatorCallback[T] | None, + ) -> ExtensionPolicy: ... + def require_present( + self, + extension_type: type[T], + criticality: Criticality, + validator: PresentExtensionValidatorCallback[T] | None, + ) -> ExtensionPolicy: ... + +class VerifiedClient: + @property + def subjects(self) -> list[x509.GeneralName] | None: ... + @property + def chain(self) -> list[x509.Certificate]: ... + +class ClientVerifier: + @property + def policy(self) -> Policy: ... + @property + def store(self) -> Store: ... + def verify( + self, + leaf: x509.Certificate, + intermediates: list[x509.Certificate], + ) -> VerifiedClient: ... + +class ServerVerifier: + @property + def policy(self) -> Policy: ... + @property + def store(self) -> Store: ... + def verify( + self, + leaf: x509.Certificate, + intermediates: list[x509.Certificate], + ) -> list[x509.Certificate]: ... + +class Store: + def __init__(self, certs: list[x509.Certificate]) -> None: ... + +class VerificationError(Exception): ... diff --git a/python/user_packages/Python313/site-packages/cryptography/hazmat/bindings/openssl/__init__.py b/python/user_packages/Python313/site-packages/cryptography/hazmat/bindings/openssl/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..b509336233c2fafe4185a49da5909c8bbb38dfd7 --- /dev/null +++ b/python/user_packages/Python313/site-packages/cryptography/hazmat/bindings/openssl/__init__.py @@ -0,0 +1,3 @@ +# This file is dual licensed under the terms of the Apache License, Version +# 2.0, and the BSD License. See the LICENSE file in the root of this repository +# for complete details. diff --git a/python/user_packages/Python313/site-packages/cryptography/hazmat/bindings/openssl/__pycache__/__init__.cpython-313.pyc b/python/user_packages/Python313/site-packages/cryptography/hazmat/bindings/openssl/__pycache__/__init__.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0f5e2ef4718349aa79374a5537ecc951dc564711 Binary files /dev/null and b/python/user_packages/Python313/site-packages/cryptography/hazmat/bindings/openssl/__pycache__/__init__.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/cryptography/hazmat/bindings/openssl/__pycache__/_conditional.cpython-313.pyc b/python/user_packages/Python313/site-packages/cryptography/hazmat/bindings/openssl/__pycache__/_conditional.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4ab5e716373fa9f3af90d1e0d7d602373d755d37 Binary files /dev/null and b/python/user_packages/Python313/site-packages/cryptography/hazmat/bindings/openssl/__pycache__/_conditional.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/cryptography/hazmat/bindings/openssl/__pycache__/binding.cpython-313.pyc b/python/user_packages/Python313/site-packages/cryptography/hazmat/bindings/openssl/__pycache__/binding.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2be8d51633f187b21cbc84efc92ccdc0f1439b50 Binary files /dev/null and b/python/user_packages/Python313/site-packages/cryptography/hazmat/bindings/openssl/__pycache__/binding.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/cryptography/hazmat/bindings/openssl/_conditional.py b/python/user_packages/Python313/site-packages/cryptography/hazmat/bindings/openssl/_conditional.py new file mode 100644 index 0000000000000000000000000000000000000000..1e447a59e9e9f2eac4069cef1b7025388636be5d --- /dev/null +++ b/python/user_packages/Python313/site-packages/cryptography/hazmat/bindings/openssl/_conditional.py @@ -0,0 +1,199 @@ +# This file is dual licensed under the terms of the Apache License, Version +# 2.0, and the BSD License. See the LICENSE file in the root of this repository +# for complete details. + +from __future__ import annotations + + +def cryptography_has_set_cert_cb() -> list[str]: + return [ + "SSL_CTX_set_cert_cb", + "SSL_set_cert_cb", + ] + + +def cryptography_has_ssl_st() -> list[str]: + return [ + "SSL_ST_BEFORE", + "SSL_ST_OK", + "SSL_ST_INIT", + "SSL_ST_RENEGOTIATE", + ] + + +def cryptography_has_tls_st() -> list[str]: + return [ + "TLS_ST_BEFORE", + "TLS_ST_OK", + ] + + +def cryptography_has_ssl_sigalgs() -> list[str]: + return [ + "SSL_CTX_set1_sigalgs_list", + ] + + +def cryptography_has_psk() -> list[str]: + return [ + "SSL_CTX_use_psk_identity_hint", + "SSL_CTX_set_psk_server_callback", + "SSL_CTX_set_psk_client_callback", + ] + + +def cryptography_has_psk_tlsv13() -> list[str]: + return [ + "SSL_CTX_set_psk_find_session_callback", + "SSL_CTX_set_psk_use_session_callback", + "Cryptography_SSL_SESSION_new", + "SSL_CIPHER_find", + "SSL_SESSION_set1_master_key", + "SSL_SESSION_set_cipher", + "SSL_SESSION_set_protocol_version", + ] + + +def cryptography_has_custom_ext() -> list[str]: + return [ + "SSL_CTX_add_client_custom_ext", + "SSL_CTX_add_server_custom_ext", + "SSL_extension_supported", + ] + + +def cryptography_has_tlsv13_functions() -> list[str]: + return [ + "SSL_CTX_set_ciphersuites", + ] + + +def cryptography_has_tlsv13_hs_functions() -> list[str]: + return [ + "SSL_VERIFY_POST_HANDSHAKE", + "SSL_verify_client_post_handshake", + "SSL_CTX_set_post_handshake_auth", + "SSL_set_post_handshake_auth", + "SSL_SESSION_get_max_early_data", + "SSL_write_early_data", + "SSL_read_early_data", + "SSL_CTX_set_max_early_data", + ] + + +def cryptography_has_ssl_verify_client_post_handshake() -> list[str]: + return [ + "SSL_verify_client_post_handshake", + ] + + +def cryptography_has_engine() -> list[str]: + return [ + "ENGINE_by_id", + "ENGINE_init", + "ENGINE_finish", + "ENGINE_get_default_RAND", + "ENGINE_set_default_RAND", + "ENGINE_unregister_RAND", + "ENGINE_ctrl_cmd", + "ENGINE_free", + "ENGINE_get_name", + "ENGINE_ctrl_cmd_string", + "ENGINE_load_builtin_engines", + "ENGINE_load_private_key", + "ENGINE_load_public_key", + "SSL_CTX_set_client_cert_engine", + ] + + +def cryptography_has_verified_chain() -> list[str]: + return [ + "SSL_get0_verified_chain", + ] + + +def cryptography_has_srtp() -> list[str]: + return [ + "SSL_CTX_set_tlsext_use_srtp", + "SSL_set_tlsext_use_srtp", + "SSL_get_selected_srtp_profile", + ] + + +def cryptography_has_dtls_get_data_mtu() -> list[str]: + return [ + "DTLS_get_data_mtu", + ] + + +def cryptography_has_ssl_cookie() -> list[str]: + return [ + "SSL_OP_COOKIE_EXCHANGE", + "DTLS1_COOKIE_LENGTH", + "DTLSv1_listen", + "SSL_CTX_set_cookie_generate_cb", + "SSL_CTX_set_cookie_verify_cb", + ] + + +def cryptography_has_prime_checks() -> list[str]: + return [ + "BN_prime_checks_for_size", + ] + + +def cryptography_has_unexpected_eof_while_reading() -> list[str]: + return ["SSL_R_UNEXPECTED_EOF_WHILE_READING"] + + +def cryptography_has_ssl_op_ignore_unexpected_eof() -> list[str]: + return [ + "SSL_OP_IGNORE_UNEXPECTED_EOF", + ] + + +def cryptography_has_get_extms_support() -> list[str]: + return ["SSL_get_extms_support"] + + +def cryptography_has_ssl_get0_group_name() -> list[str]: + return ["SSL_get0_group_name"] + + +# This is a mapping of +# {condition: function-returning-names-dependent-on-that-condition} so we can +# loop over them and delete unsupported names at runtime. It will be removed +# when cffi supports #if in cdef. We use functions instead of just a dict of +# lists so we can use coverage to measure which are used. +CONDITIONAL_NAMES = { + "Cryptography_HAS_SET_CERT_CB": cryptography_has_set_cert_cb, + "Cryptography_HAS_SSL_ST": cryptography_has_ssl_st, + "Cryptography_HAS_TLS_ST": cryptography_has_tls_st, + "Cryptography_HAS_SIGALGS": cryptography_has_ssl_sigalgs, + "Cryptography_HAS_PSK": cryptography_has_psk, + "Cryptography_HAS_PSK_TLSv1_3": cryptography_has_psk_tlsv13, + "Cryptography_HAS_CUSTOM_EXT": cryptography_has_custom_ext, + "Cryptography_HAS_TLSv1_3_FUNCTIONS": cryptography_has_tlsv13_functions, + "Cryptography_HAS_TLSv1_3_HS_FUNCTIONS": ( + cryptography_has_tlsv13_hs_functions + ), + "Cryptography_HAS_SSL_VERIFY_CLIENT_POST_HANDSHAKE": ( + cryptography_has_ssl_verify_client_post_handshake + ), + "Cryptography_HAS_ENGINE": cryptography_has_engine, + "Cryptography_HAS_VERIFIED_CHAIN": cryptography_has_verified_chain, + "Cryptography_HAS_SRTP": cryptography_has_srtp, + "Cryptography_HAS_DTLS_GET_DATA_MTU": cryptography_has_dtls_get_data_mtu, + "Cryptography_HAS_SSL_COOKIE": cryptography_has_ssl_cookie, + "Cryptography_HAS_PRIME_CHECKS": cryptography_has_prime_checks, + "Cryptography_HAS_UNEXPECTED_EOF_WHILE_READING": ( + cryptography_has_unexpected_eof_while_reading + ), + "Cryptography_HAS_SSL_OP_IGNORE_UNEXPECTED_EOF": ( + cryptography_has_ssl_op_ignore_unexpected_eof + ), + "Cryptography_HAS_GET_EXTMS_SUPPORT": cryptography_has_get_extms_support, + "Cryptography_HAS_SSL_GET0_GROUP_NAME": ( + cryptography_has_ssl_get0_group_name + ), +} diff --git a/python/user_packages/Python313/site-packages/cryptography/hazmat/bindings/openssl/binding.py b/python/user_packages/Python313/site-packages/cryptography/hazmat/bindings/openssl/binding.py new file mode 100644 index 0000000000000000000000000000000000000000..6a0cafdba0070423d85adf31441b0be3abd26ea5 --- /dev/null +++ b/python/user_packages/Python313/site-packages/cryptography/hazmat/bindings/openssl/binding.py @@ -0,0 +1,122 @@ +# This file is dual licensed under the terms of the Apache License, Version +# 2.0, and the BSD License. See the LICENSE file in the root of this repository +# for complete details. + +from __future__ import annotations + +import os +import sys +import threading +import types +import typing +import warnings +from collections.abc import Callable + +import cryptography +from cryptography.exceptions import InternalError +from cryptography.hazmat.bindings._rust import _openssl, openssl +from cryptography.hazmat.bindings.openssl._conditional import CONDITIONAL_NAMES + + +def _openssl_assert(ok: bool) -> None: + if not ok: + errors = openssl.capture_error_stack() + + raise InternalError( + "Unknown OpenSSL error. This error is commonly encountered when " + "another library is not cleaning up the OpenSSL error stack. If " + "you are using cryptography with another library that uses " + "OpenSSL try disabling it before reporting a bug. Otherwise " + "please file an issue at https://github.com/pyca/cryptography/" + "issues with information on how to reproduce " + f"this. ({errors!r})", + errors, + ) + + +def build_conditional_library( + lib: typing.Any, + conditional_names: dict[str, Callable[[], list[str]]], +) -> typing.Any: + conditional_lib = types.ModuleType("lib") + conditional_lib._original_lib = lib # type: ignore[attr-defined] + excluded_names = set() + for condition, names_cb in conditional_names.items(): + if not getattr(lib, condition): + excluded_names.update(names_cb()) + + for attr in dir(lib): + if attr not in excluded_names: + setattr(conditional_lib, attr, getattr(lib, attr)) + + return conditional_lib + + +class Binding: + """ + OpenSSL API wrapper. + """ + + lib: typing.ClassVar[typing.Any] = None + ffi: typing.Any = _openssl.ffi + _lib_loaded = False + _init_lock = threading.Lock() + + def __init__(self) -> None: + self._ensure_ffi_initialized() + + @classmethod + def _ensure_ffi_initialized(cls) -> None: + with cls._init_lock: + if not cls._lib_loaded: + cls.lib = build_conditional_library( + _openssl.lib, CONDITIONAL_NAMES + ) + cls._lib_loaded = True + + @classmethod + def init_static_locks(cls) -> None: + cls._ensure_ffi_initialized() + + +def _verify_package_version(version: str) -> None: + # Occasionally we run into situations where the version of the Python + # package does not match the version of the shared object that is loaded. + # This may occur in environments where multiple versions of cryptography + # are installed and available in the python path. To avoid errors cropping + # up later this code checks that the currently imported package and the + # shared object that were loaded have the same version and raise an + # ImportError if they do not + so_package_version = _openssl.ffi.string( + _openssl.lib.CRYPTOGRAPHY_PACKAGE_VERSION + ) + if version.encode("ascii") != so_package_version: + raise ImportError( + "The version of cryptography does not match the loaded " + "shared object. This can happen if you have multiple copies of " + "cryptography installed in your Python path. Please try creating " + "a new virtual environment to resolve this issue. " + f"Loaded python version: {version}, " + f"shared object version: {so_package_version}" + ) + + _openssl_assert( + _openssl.lib.OpenSSL_version_num() == openssl.openssl_version(), + ) + + +_verify_package_version(cryptography.__version__) + +Binding.init_static_locks() + +if ( + sys.platform == "win32" + and os.environ.get("PROCESSOR_ARCHITEW6432") is not None +): + warnings.warn( + "You are using cryptography on a 32-bit Python on a 64-bit Windows " + "Operating System. Cryptography will be significantly faster if you " + "switch to using a 64-bit Python.", + UserWarning, + stacklevel=2, + ) diff --git a/python/user_packages/Python313/site-packages/cryptography/hazmat/decrepit/__init__.py b/python/user_packages/Python313/site-packages/cryptography/hazmat/decrepit/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..41d731863aa2927b7a4fb02d7e536c35c678a102 --- /dev/null +++ b/python/user_packages/Python313/site-packages/cryptography/hazmat/decrepit/__init__.py @@ -0,0 +1,5 @@ +# This file is dual licensed under the terms of the Apache License, Version +# 2.0, and the BSD License. See the LICENSE file in the root of this repository +# for complete details. + +from __future__ import annotations diff --git a/python/user_packages/Python313/site-packages/cryptography/hazmat/decrepit/__pycache__/__init__.cpython-313.pyc b/python/user_packages/Python313/site-packages/cryptography/hazmat/decrepit/__pycache__/__init__.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..050cd10977dd1573f274cb91d8d618019acf337d Binary files /dev/null and b/python/user_packages/Python313/site-packages/cryptography/hazmat/decrepit/__pycache__/__init__.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/cryptography/hazmat/decrepit/ciphers/__init__.py b/python/user_packages/Python313/site-packages/cryptography/hazmat/decrepit/ciphers/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..41d731863aa2927b7a4fb02d7e536c35c678a102 --- /dev/null +++ b/python/user_packages/Python313/site-packages/cryptography/hazmat/decrepit/ciphers/__init__.py @@ -0,0 +1,5 @@ +# This file is dual licensed under the terms of the Apache License, Version +# 2.0, and the BSD License. See the LICENSE file in the root of this repository +# for complete details. + +from __future__ import annotations diff --git a/python/user_packages/Python313/site-packages/cryptography/hazmat/decrepit/ciphers/__pycache__/__init__.cpython-313.pyc b/python/user_packages/Python313/site-packages/cryptography/hazmat/decrepit/ciphers/__pycache__/__init__.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1c6dfcfee42333027374669d7c907432a962ad69 Binary files /dev/null and b/python/user_packages/Python313/site-packages/cryptography/hazmat/decrepit/ciphers/__pycache__/__init__.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/cryptography/hazmat/decrepit/ciphers/__pycache__/algorithms.cpython-313.pyc b/python/user_packages/Python313/site-packages/cryptography/hazmat/decrepit/ciphers/__pycache__/algorithms.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d6d5df9385ac174b32616597fdd4c64d453e63e4 Binary files /dev/null and b/python/user_packages/Python313/site-packages/cryptography/hazmat/decrepit/ciphers/__pycache__/algorithms.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/cryptography/hazmat/decrepit/ciphers/__pycache__/modes.cpython-313.pyc b/python/user_packages/Python313/site-packages/cryptography/hazmat/decrepit/ciphers/__pycache__/modes.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9cbe5cd0298bf008a0f0c35919d5c287e7bde186 Binary files /dev/null and b/python/user_packages/Python313/site-packages/cryptography/hazmat/decrepit/ciphers/__pycache__/modes.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/cryptography/hazmat/decrepit/ciphers/algorithms.py b/python/user_packages/Python313/site-packages/cryptography/hazmat/decrepit/ciphers/algorithms.py new file mode 100644 index 0000000000000000000000000000000000000000..703c8e4a3e47d94430e486cd40e0a81bb4d0858f --- /dev/null +++ b/python/user_packages/Python313/site-packages/cryptography/hazmat/decrepit/ciphers/algorithms.py @@ -0,0 +1,142 @@ +# This file is dual licensed under the terms of the Apache License, Version +# 2.0, and the BSD License. See the LICENSE file in the root of this repository +# for complete details. + +from __future__ import annotations + +import warnings + +from cryptography import utils +from cryptography.hazmat.primitives._cipheralgorithm import ( + BlockCipherAlgorithm, + CipherAlgorithm, + _verify_key_size, +) + + +class ARC4(CipherAlgorithm): + name = "RC4" + key_sizes = frozenset([40, 56, 64, 80, 128, 160, 192, 256]) + + def __init__(self, key: bytes): + self.key = _verify_key_size(self, key) + + @property + def key_size(self) -> int: + return len(self.key) * 8 + + +class TripleDES(BlockCipherAlgorithm): + name = "3DES" + block_size = 64 + key_sizes = frozenset([64, 128, 192]) + + def __init__(self, key: bytes): + if len(key) == 8: + warnings.warn( + "Single-key TripleDES (8-byte keys) is deprecated and " + "support will be removed in a future release. Use 24-byte " + "keys instead (e.g., key + key + key).", + utils.DeprecatedIn47, + stacklevel=2, + ) + key = key + key + key + elif len(key) == 16: + warnings.warn( + "Two-key TripleDES (16-byte keys) is deprecated and " + "support will be removed in a future release. Use 24-byte " + "keys instead (e.g., key + key[:8]).", + utils.DeprecatedIn47, + stacklevel=2, + ) + key = key + key[:8] + self.key = _verify_key_size(self, key) + + @property + def key_size(self) -> int: + return len(self.key) * 8 + + +# Not actually supported, marker for tests +class _DES: + key_size = 64 + + +class Blowfish(BlockCipherAlgorithm): + name = "Blowfish" + block_size = 64 + key_sizes = frozenset(range(32, 449, 8)) + + def __init__(self, key: bytes): + self.key = _verify_key_size(self, key) + + @property + def key_size(self) -> int: + return len(self.key) * 8 + + +class CAST5(BlockCipherAlgorithm): + name = "CAST5" + block_size = 64 + key_sizes = frozenset(range(40, 129, 8)) + + def __init__(self, key: bytes): + self.key = _verify_key_size(self, key) + + @property + def key_size(self) -> int: + return len(self.key) * 8 + + +class SEED(BlockCipherAlgorithm): + name = "SEED" + block_size = 128 + key_sizes = frozenset([128]) + + def __init__(self, key: bytes): + self.key = _verify_key_size(self, key) + + @property + def key_size(self) -> int: + return len(self.key) * 8 + + +class IDEA(BlockCipherAlgorithm): + name = "IDEA" + block_size = 64 + key_sizes = frozenset([128]) + + def __init__(self, key: bytes): + self.key = _verify_key_size(self, key) + + @property + def key_size(self) -> int: + return len(self.key) * 8 + + +class Camellia(BlockCipherAlgorithm): + name = "camellia" + block_size = 128 + key_sizes = frozenset([128, 192, 256]) + + def __init__(self, key: bytes): + self.key = _verify_key_size(self, key) + + @property + def key_size(self) -> int: + return len(self.key) * 8 + + +# This class only allows RC2 with a 128-bit key. No support for +# effective key bits or other key sizes is provided. +class RC2(BlockCipherAlgorithm): + name = "RC2" + block_size = 64 + key_sizes = frozenset([128]) + + def __init__(self, key: bytes): + self.key = _verify_key_size(self, key) + + @property + def key_size(self) -> int: + return len(self.key) * 8 diff --git a/python/user_packages/Python313/site-packages/cryptography/hazmat/decrepit/ciphers/modes.py b/python/user_packages/Python313/site-packages/cryptography/hazmat/decrepit/ciphers/modes.py new file mode 100644 index 0000000000000000000000000000000000000000..1786bb04c9ee8f2f740e54a782c4e9c97e7e93f0 --- /dev/null +++ b/python/user_packages/Python313/site-packages/cryptography/hazmat/decrepit/ciphers/modes.py @@ -0,0 +1,53 @@ +# This file is dual licensed under the terms of the Apache License, Version +# 2.0, and the BSD License. See the LICENSE file in the root of this repository +# for complete details. + +from __future__ import annotations + +from cryptography import utils +from cryptography.hazmat.primitives._modes import ( + ModeWithInitializationVector, + _check_iv_and_key_length, +) + + +class OFB(ModeWithInitializationVector): + name = "OFB" + + def __init__(self, initialization_vector: utils.Buffer): + utils._check_byteslike("initialization_vector", initialization_vector) + self._initialization_vector = initialization_vector + + @property + def initialization_vector(self) -> utils.Buffer: + return self._initialization_vector + + validate_for_algorithm = _check_iv_and_key_length + + +class CFB(ModeWithInitializationVector): + name = "CFB" + + def __init__(self, initialization_vector: utils.Buffer): + utils._check_byteslike("initialization_vector", initialization_vector) + self._initialization_vector = initialization_vector + + @property + def initialization_vector(self) -> utils.Buffer: + return self._initialization_vector + + validate_for_algorithm = _check_iv_and_key_length + + +class CFB8(ModeWithInitializationVector): + name = "CFB8" + + def __init__(self, initialization_vector: utils.Buffer): + utils._check_byteslike("initialization_vector", initialization_vector) + self._initialization_vector = initialization_vector + + @property + def initialization_vector(self) -> utils.Buffer: + return self._initialization_vector + + validate_for_algorithm = _check_iv_and_key_length diff --git a/python/user_packages/Python313/site-packages/cryptography/hazmat/primitives/__init__.py b/python/user_packages/Python313/site-packages/cryptography/hazmat/primitives/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..b509336233c2fafe4185a49da5909c8bbb38dfd7 --- /dev/null +++ b/python/user_packages/Python313/site-packages/cryptography/hazmat/primitives/__init__.py @@ -0,0 +1,3 @@ +# This file is dual licensed under the terms of the Apache License, Version +# 2.0, and the BSD License. See the LICENSE file in the root of this repository +# for complete details. diff --git a/python/user_packages/Python313/site-packages/cryptography/hazmat/primitives/__pycache__/__init__.cpython-313.pyc b/python/user_packages/Python313/site-packages/cryptography/hazmat/primitives/__pycache__/__init__.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..91e2bca53091b368a34972d3cd49b3433ff00fe0 Binary files /dev/null and b/python/user_packages/Python313/site-packages/cryptography/hazmat/primitives/__pycache__/__init__.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/cryptography/hazmat/primitives/__pycache__/_asymmetric.cpython-313.pyc b/python/user_packages/Python313/site-packages/cryptography/hazmat/primitives/__pycache__/_asymmetric.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..bb8580cfac20096ddc6ca74643f3dd4772cc4e45 Binary files /dev/null and b/python/user_packages/Python313/site-packages/cryptography/hazmat/primitives/__pycache__/_asymmetric.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/cryptography/hazmat/primitives/__pycache__/_cipheralgorithm.cpython-313.pyc b/python/user_packages/Python313/site-packages/cryptography/hazmat/primitives/__pycache__/_cipheralgorithm.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7c1145d24fdb66098449862dcd6f596478ee3565 Binary files /dev/null and b/python/user_packages/Python313/site-packages/cryptography/hazmat/primitives/__pycache__/_cipheralgorithm.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/cryptography/hazmat/primitives/__pycache__/_modes.cpython-313.pyc b/python/user_packages/Python313/site-packages/cryptography/hazmat/primitives/__pycache__/_modes.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d14e03b27e6dc8574ba6c29b584569ba082b6535 Binary files /dev/null and b/python/user_packages/Python313/site-packages/cryptography/hazmat/primitives/__pycache__/_modes.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/cryptography/hazmat/primitives/__pycache__/_serialization.cpython-313.pyc b/python/user_packages/Python313/site-packages/cryptography/hazmat/primitives/__pycache__/_serialization.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4003b2aff078ddac9eb079073f8be0f7a7b88e10 Binary files /dev/null and b/python/user_packages/Python313/site-packages/cryptography/hazmat/primitives/__pycache__/_serialization.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/cryptography/hazmat/primitives/__pycache__/cmac.cpython-313.pyc b/python/user_packages/Python313/site-packages/cryptography/hazmat/primitives/__pycache__/cmac.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..db26ae202e5d5f956feab6fa0122ad6c8535aeac Binary files /dev/null and b/python/user_packages/Python313/site-packages/cryptography/hazmat/primitives/__pycache__/cmac.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/cryptography/hazmat/primitives/__pycache__/constant_time.cpython-313.pyc b/python/user_packages/Python313/site-packages/cryptography/hazmat/primitives/__pycache__/constant_time.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ce5c81797db5661867905dcf2b17817d523313c6 Binary files /dev/null and b/python/user_packages/Python313/site-packages/cryptography/hazmat/primitives/__pycache__/constant_time.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/cryptography/hazmat/primitives/__pycache__/hashes.cpython-313.pyc b/python/user_packages/Python313/site-packages/cryptography/hazmat/primitives/__pycache__/hashes.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e2a5e00864d95cc028d41d21259cae548a1a3f45 Binary files /dev/null and b/python/user_packages/Python313/site-packages/cryptography/hazmat/primitives/__pycache__/hashes.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/cryptography/hazmat/primitives/__pycache__/hmac.cpython-313.pyc b/python/user_packages/Python313/site-packages/cryptography/hazmat/primitives/__pycache__/hmac.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b82ed6a8498cd74c8cb8e29697a5b27e82bcb43e Binary files /dev/null and b/python/user_packages/Python313/site-packages/cryptography/hazmat/primitives/__pycache__/hmac.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/cryptography/hazmat/primitives/__pycache__/hpke.cpython-313.pyc b/python/user_packages/Python313/site-packages/cryptography/hazmat/primitives/__pycache__/hpke.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..30f55735aa112c39b01628e076897fd37f84dccf Binary files /dev/null and b/python/user_packages/Python313/site-packages/cryptography/hazmat/primitives/__pycache__/hpke.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/cryptography/hazmat/primitives/__pycache__/keywrap.cpython-313.pyc b/python/user_packages/Python313/site-packages/cryptography/hazmat/primitives/__pycache__/keywrap.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6ceaf205d3c00d3e8c3876818c49aa790f7991b3 Binary files /dev/null and b/python/user_packages/Python313/site-packages/cryptography/hazmat/primitives/__pycache__/keywrap.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/cryptography/hazmat/primitives/__pycache__/padding.cpython-313.pyc b/python/user_packages/Python313/site-packages/cryptography/hazmat/primitives/__pycache__/padding.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8a5fc75b4773dc949777f5c12fd34ff9dd7d03e5 Binary files /dev/null and b/python/user_packages/Python313/site-packages/cryptography/hazmat/primitives/__pycache__/padding.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/cryptography/hazmat/primitives/__pycache__/poly1305.cpython-313.pyc b/python/user_packages/Python313/site-packages/cryptography/hazmat/primitives/__pycache__/poly1305.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..aa363274bbb7090471dfef96e1e9b3c2a9423067 Binary files /dev/null and b/python/user_packages/Python313/site-packages/cryptography/hazmat/primitives/__pycache__/poly1305.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/cryptography/hazmat/primitives/_asymmetric.py b/python/user_packages/Python313/site-packages/cryptography/hazmat/primitives/_asymmetric.py new file mode 100644 index 0000000000000000000000000000000000000000..ea55ffdf1a721f8fd2de8ae67de913bc47cbf55d --- /dev/null +++ b/python/user_packages/Python313/site-packages/cryptography/hazmat/primitives/_asymmetric.py @@ -0,0 +1,19 @@ +# This file is dual licensed under the terms of the Apache License, Version +# 2.0, and the BSD License. See the LICENSE file in the root of this repository +# for complete details. + +from __future__ import annotations + +import abc + +# This exists to break an import cycle. It is normally accessible from the +# asymmetric padding module. + + +class AsymmetricPadding(metaclass=abc.ABCMeta): + @property + @abc.abstractmethod + def name(self) -> str: + """ + A string naming this padding (e.g. "PSS", "PKCS1"). + """ diff --git a/python/user_packages/Python313/site-packages/cryptography/hazmat/primitives/_cipheralgorithm.py b/python/user_packages/Python313/site-packages/cryptography/hazmat/primitives/_cipheralgorithm.py new file mode 100644 index 0000000000000000000000000000000000000000..305a9fd3179cd439b7a86355e6cd6c8251583532 --- /dev/null +++ b/python/user_packages/Python313/site-packages/cryptography/hazmat/primitives/_cipheralgorithm.py @@ -0,0 +1,60 @@ +# This file is dual licensed under the terms of the Apache License, Version +# 2.0, and the BSD License. See the LICENSE file in the root of this repository +# for complete details. + +from __future__ import annotations + +import abc + +from cryptography import utils + +# This exists to break an import cycle. It is normally accessible from the +# ciphers module. + + +class CipherAlgorithm(metaclass=abc.ABCMeta): + @property + @abc.abstractmethod + def name(self) -> str: + """ + A string naming this mode (e.g. "AES", "Camellia"). + """ + + @property + @abc.abstractmethod + def key_sizes(self) -> frozenset[int]: + """ + Valid key sizes for this algorithm in bits + """ + + @property + @abc.abstractmethod + def key_size(self) -> int: + """ + The size of the key being used as an integer in bits (e.g. 128, 256). + """ + + +class BlockCipherAlgorithm(CipherAlgorithm): + key: utils.Buffer + + @property + @abc.abstractmethod + def block_size(self) -> int: + """ + The size of a block as an integer in bits (e.g. 64, 128). + """ + + +def _verify_key_size( + algorithm: CipherAlgorithm, key: utils.Buffer +) -> utils.Buffer: + # Verify that the key is instance of bytes + utils._check_byteslike("key", key) + + # Verify that the key size matches the expected key size + if len(key) * 8 not in algorithm.key_sizes: + raise ValueError( + f"Invalid key size ({len(key) * 8}) for {algorithm.name}." + ) + return key diff --git a/python/user_packages/Python313/site-packages/cryptography/hazmat/primitives/_modes.py b/python/user_packages/Python313/site-packages/cryptography/hazmat/primitives/_modes.py new file mode 100644 index 0000000000000000000000000000000000000000..deae8bccc97590c8876009b8eed253123d9e3372 --- /dev/null +++ b/python/user_packages/Python313/site-packages/cryptography/hazmat/primitives/_modes.py @@ -0,0 +1,105 @@ +# This file is dual licensed under the terms of the Apache License, Version +# 2.0, and the BSD License. See the LICENSE file in the root of this repository +# for complete details. + +from __future__ import annotations + +import abc + +from cryptography import utils +from cryptography.exceptions import UnsupportedAlgorithm, _Reasons +from cryptography.hazmat.primitives._cipheralgorithm import ( + BlockCipherAlgorithm, + CipherAlgorithm, +) + + +class Mode(metaclass=abc.ABCMeta): + @property + @abc.abstractmethod + def name(self) -> str: + """ + A string naming this mode (e.g. "ECB", "CBC"). + """ + + @abc.abstractmethod + def validate_for_algorithm(self, algorithm: CipherAlgorithm) -> None: + """ + Checks that all the necessary invariants of this (mode, algorithm) + combination are met. + """ + + +class ModeWithInitializationVector(Mode, metaclass=abc.ABCMeta): + @property + @abc.abstractmethod + def initialization_vector(self) -> utils.Buffer: + """ + The value of the initialization vector for this mode as bytes. + """ + + +class ModeWithTweak(Mode, metaclass=abc.ABCMeta): + @property + @abc.abstractmethod + def tweak(self) -> utils.Buffer: + """ + The value of the tweak for this mode as bytes. + """ + + +class ModeWithNonce(Mode, metaclass=abc.ABCMeta): + @property + @abc.abstractmethod + def nonce(self) -> utils.Buffer: + """ + The value of the nonce for this mode as bytes. + """ + + +class ModeWithAuthenticationTag(Mode, metaclass=abc.ABCMeta): + @property + @abc.abstractmethod + def tag(self) -> bytes | None: + """ + The value of the tag supplied to the constructor of this mode. + """ + + +def _check_aes_key_length(self: Mode, algorithm: CipherAlgorithm) -> None: + if algorithm.key_size > 256 and algorithm.name == "AES": + raise ValueError( + "Only 128, 192, and 256 bit keys are allowed for this AES mode" + ) + + +def _check_iv_length( + self: ModeWithInitializationVector, algorithm: BlockCipherAlgorithm +) -> None: + iv_len = len(self.initialization_vector) + if iv_len * 8 != algorithm.block_size: + raise ValueError(f"Invalid IV size ({iv_len}) for {self.name}.") + + +def _check_nonce_length( + nonce: utils.Buffer, name: str, algorithm: CipherAlgorithm +) -> None: + if not isinstance(algorithm, BlockCipherAlgorithm): + raise UnsupportedAlgorithm( + f"{name} requires a block cipher algorithm", + _Reasons.UNSUPPORTED_CIPHER, + ) + if len(nonce) * 8 != algorithm.block_size: + raise ValueError(f"Invalid nonce size ({len(nonce)}) for {name}.") + + +def _check_iv_and_key_length( + self: ModeWithInitializationVector, algorithm: CipherAlgorithm +) -> None: + if not isinstance(algorithm, BlockCipherAlgorithm): + raise UnsupportedAlgorithm( + f"{self} requires a block cipher algorithm", + _Reasons.UNSUPPORTED_CIPHER, + ) + _check_aes_key_length(self, algorithm) + _check_iv_length(self, algorithm) diff --git a/python/user_packages/Python313/site-packages/cryptography/hazmat/primitives/_serialization.py b/python/user_packages/Python313/site-packages/cryptography/hazmat/primitives/_serialization.py new file mode 100644 index 0000000000000000000000000000000000000000..9c3c47447b9c3dc00a4e67d2b25c80969eadced4 --- /dev/null +++ b/python/user_packages/Python313/site-packages/cryptography/hazmat/primitives/_serialization.py @@ -0,0 +1,136 @@ +# This file is dual licensed under the terms of the Apache License, Version +# 2.0, and the BSD License. See the LICENSE file in the root of this repository +# for complete details. + +from __future__ import annotations + +import abc + +from cryptography import utils +from cryptography.hazmat.bindings._rust import Encoding as Encoding +from cryptography.hazmat.bindings._rust import ( + ParameterFormat as ParameterFormat, +) +from cryptography.hazmat.bindings._rust import PrivateFormat as PrivateFormat +from cryptography.hazmat.bindings._rust import PublicFormat as PublicFormat +from cryptography.hazmat.primitives.hashes import HashAlgorithm + +# This exists to break an import cycle. These classes are normally accessible +# from the serialization module. + + +class PBES(utils.Enum): + PBESv1SHA1And3KeyTripleDESCBC = "PBESv1 using SHA1 and 3-Key TripleDES" + PBESv2SHA256AndAES256CBC = "PBESv2 using SHA256 PBKDF2 and AES256 CBC" + + +class KeySerializationEncryption(metaclass=abc.ABCMeta): + pass + + +class BestAvailableEncryption(KeySerializationEncryption): + def __init__(self, password: bytes): + if not isinstance(password, bytes) or len(password) == 0: + raise ValueError("Password must be 1 or more bytes.") + + self.password = password + + +class NoEncryption(KeySerializationEncryption): + pass + + +class KeySerializationEncryptionBuilder: + def __init__( + self, + format: PrivateFormat, + *, + _kdf_rounds: int | None = None, + _hmac_hash: HashAlgorithm | None = None, + _key_cert_algorithm: PBES | None = None, + ) -> None: + self._format = format + + self._kdf_rounds = _kdf_rounds + self._hmac_hash = _hmac_hash + self._key_cert_algorithm = _key_cert_algorithm + + def kdf_rounds(self, rounds: int) -> KeySerializationEncryptionBuilder: + if self._kdf_rounds is not None: + raise ValueError("kdf_rounds already set") + + if not isinstance(rounds, int): + raise TypeError("kdf_rounds must be an integer") + + if rounds < 1: + raise ValueError("kdf_rounds must be a positive integer") + + return KeySerializationEncryptionBuilder( + self._format, + _kdf_rounds=rounds, + _hmac_hash=self._hmac_hash, + _key_cert_algorithm=self._key_cert_algorithm, + ) + + def hmac_hash( + self, algorithm: HashAlgorithm + ) -> KeySerializationEncryptionBuilder: + if self._format is not PrivateFormat.PKCS12: + raise TypeError( + "hmac_hash only supported with PrivateFormat.PKCS12" + ) + + if self._hmac_hash is not None: + raise ValueError("hmac_hash already set") + return KeySerializationEncryptionBuilder( + self._format, + _kdf_rounds=self._kdf_rounds, + _hmac_hash=algorithm, + _key_cert_algorithm=self._key_cert_algorithm, + ) + + def key_cert_algorithm( + self, algorithm: PBES + ) -> KeySerializationEncryptionBuilder: + if self._format is not PrivateFormat.PKCS12: + raise TypeError( + "key_cert_algorithm only supported with PrivateFormat.PKCS12" + ) + if self._key_cert_algorithm is not None: + raise ValueError("key_cert_algorithm already set") + return KeySerializationEncryptionBuilder( + self._format, + _kdf_rounds=self._kdf_rounds, + _hmac_hash=self._hmac_hash, + _key_cert_algorithm=algorithm, + ) + + def build(self, password: bytes) -> KeySerializationEncryption: + if not isinstance(password, bytes) or len(password) == 0: + raise ValueError("Password must be 1 or more bytes.") + + return _KeySerializationEncryption( + self._format, + password, + kdf_rounds=self._kdf_rounds, + hmac_hash=self._hmac_hash, + key_cert_algorithm=self._key_cert_algorithm, + ) + + +class _KeySerializationEncryption(KeySerializationEncryption): + def __init__( + self, + format: PrivateFormat, + password: bytes, + *, + kdf_rounds: int | None, + hmac_hash: HashAlgorithm | None, + key_cert_algorithm: PBES | None, + ): + self._format = format + self.password = password + + self._kdf_rounds = kdf_rounds + self._hmac_hash = hmac_hash + self._key_cert_algorithm = key_cert_algorithm diff --git a/python/user_packages/Python313/site-packages/cryptography/hazmat/primitives/asymmetric/__init__.py b/python/user_packages/Python313/site-packages/cryptography/hazmat/primitives/asymmetric/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..b509336233c2fafe4185a49da5909c8bbb38dfd7 --- /dev/null +++ b/python/user_packages/Python313/site-packages/cryptography/hazmat/primitives/asymmetric/__init__.py @@ -0,0 +1,3 @@ +# This file is dual licensed under the terms of the Apache License, Version +# 2.0, and the BSD License. See the LICENSE file in the root of this repository +# for complete details. diff --git a/python/user_packages/Python313/site-packages/cryptography/hazmat/primitives/asymmetric/__pycache__/__init__.cpython-313.pyc b/python/user_packages/Python313/site-packages/cryptography/hazmat/primitives/asymmetric/__pycache__/__init__.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..018603d2901f74d32fb10ad1317ca53f89ad6c21 Binary files /dev/null and b/python/user_packages/Python313/site-packages/cryptography/hazmat/primitives/asymmetric/__pycache__/__init__.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/cryptography/hazmat/primitives/asymmetric/__pycache__/dh.cpython-313.pyc b/python/user_packages/Python313/site-packages/cryptography/hazmat/primitives/asymmetric/__pycache__/dh.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7d1c51b2470229ec21cf12c19fbec1cabd0c16e1 Binary files /dev/null and b/python/user_packages/Python313/site-packages/cryptography/hazmat/primitives/asymmetric/__pycache__/dh.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/cryptography/hazmat/primitives/asymmetric/__pycache__/dsa.cpython-313.pyc b/python/user_packages/Python313/site-packages/cryptography/hazmat/primitives/asymmetric/__pycache__/dsa.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..095de9fcc796e474d9853876d065b0f3d71d696a Binary files /dev/null and b/python/user_packages/Python313/site-packages/cryptography/hazmat/primitives/asymmetric/__pycache__/dsa.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/cryptography/hazmat/primitives/asymmetric/__pycache__/ec.cpython-313.pyc b/python/user_packages/Python313/site-packages/cryptography/hazmat/primitives/asymmetric/__pycache__/ec.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ffa206f109b4a837eb9b43676f3b988cd8e49b83 Binary files /dev/null and b/python/user_packages/Python313/site-packages/cryptography/hazmat/primitives/asymmetric/__pycache__/ec.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/cryptography/hazmat/primitives/asymmetric/__pycache__/ed25519.cpython-313.pyc b/python/user_packages/Python313/site-packages/cryptography/hazmat/primitives/asymmetric/__pycache__/ed25519.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8a6edffac4613e70b61b4819b5c0ee869c7adffc Binary files /dev/null and b/python/user_packages/Python313/site-packages/cryptography/hazmat/primitives/asymmetric/__pycache__/ed25519.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/cryptography/hazmat/primitives/asymmetric/__pycache__/ed448.cpython-313.pyc b/python/user_packages/Python313/site-packages/cryptography/hazmat/primitives/asymmetric/__pycache__/ed448.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7819e71ca74d412466ab5ecbf822948dcd8a655a Binary files /dev/null and b/python/user_packages/Python313/site-packages/cryptography/hazmat/primitives/asymmetric/__pycache__/ed448.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/cryptography/hazmat/primitives/asymmetric/__pycache__/mldsa.cpython-313.pyc b/python/user_packages/Python313/site-packages/cryptography/hazmat/primitives/asymmetric/__pycache__/mldsa.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..420ab02277416f105748adc2487bcb28e47d7c08 Binary files /dev/null and b/python/user_packages/Python313/site-packages/cryptography/hazmat/primitives/asymmetric/__pycache__/mldsa.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/cryptography/hazmat/primitives/asymmetric/__pycache__/mlkem.cpython-313.pyc b/python/user_packages/Python313/site-packages/cryptography/hazmat/primitives/asymmetric/__pycache__/mlkem.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d70272b4881faaae2dc8045478fc305f07ae132c Binary files /dev/null and b/python/user_packages/Python313/site-packages/cryptography/hazmat/primitives/asymmetric/__pycache__/mlkem.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/cryptography/hazmat/primitives/asymmetric/__pycache__/padding.cpython-313.pyc b/python/user_packages/Python313/site-packages/cryptography/hazmat/primitives/asymmetric/__pycache__/padding.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..107f8939e6cd2cebbf735c37088e60b510fe53db Binary files /dev/null and b/python/user_packages/Python313/site-packages/cryptography/hazmat/primitives/asymmetric/__pycache__/padding.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/cryptography/hazmat/primitives/asymmetric/__pycache__/rsa.cpython-313.pyc b/python/user_packages/Python313/site-packages/cryptography/hazmat/primitives/asymmetric/__pycache__/rsa.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..56bf8f6c9cde4b23c739c1639d37fb66ef047e99 Binary files /dev/null and b/python/user_packages/Python313/site-packages/cryptography/hazmat/primitives/asymmetric/__pycache__/rsa.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/cryptography/hazmat/primitives/asymmetric/__pycache__/types.cpython-313.pyc b/python/user_packages/Python313/site-packages/cryptography/hazmat/primitives/asymmetric/__pycache__/types.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e446dd8097361fdba2a66c07368d4a3ea933bc79 Binary files /dev/null and b/python/user_packages/Python313/site-packages/cryptography/hazmat/primitives/asymmetric/__pycache__/types.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/cryptography/hazmat/primitives/asymmetric/__pycache__/utils.cpython-313.pyc b/python/user_packages/Python313/site-packages/cryptography/hazmat/primitives/asymmetric/__pycache__/utils.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ec7f3d52ee455115dbc450710cfd3627a22c3fdc Binary files /dev/null and b/python/user_packages/Python313/site-packages/cryptography/hazmat/primitives/asymmetric/__pycache__/utils.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/cryptography/hazmat/primitives/asymmetric/__pycache__/x25519.cpython-313.pyc b/python/user_packages/Python313/site-packages/cryptography/hazmat/primitives/asymmetric/__pycache__/x25519.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3324be173ac6059de920faaf55ca399a4ec930a6 Binary files /dev/null and b/python/user_packages/Python313/site-packages/cryptography/hazmat/primitives/asymmetric/__pycache__/x25519.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/cryptography/hazmat/primitives/asymmetric/__pycache__/x448.cpython-313.pyc b/python/user_packages/Python313/site-packages/cryptography/hazmat/primitives/asymmetric/__pycache__/x448.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0d5bd587cd668d6085518e25ed3674a8013fe515 Binary files /dev/null and b/python/user_packages/Python313/site-packages/cryptography/hazmat/primitives/asymmetric/__pycache__/x448.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/cryptography/hazmat/primitives/asymmetric/dh.py b/python/user_packages/Python313/site-packages/cryptography/hazmat/primitives/asymmetric/dh.py new file mode 100644 index 0000000000000000000000000000000000000000..2f6b834ec9fa9c22cbef5286982b76046cbc918a --- /dev/null +++ b/python/user_packages/Python313/site-packages/cryptography/hazmat/primitives/asymmetric/dh.py @@ -0,0 +1,159 @@ +# This file is dual licensed under the terms of the Apache License, Version +# 2.0, and the BSD License. See the LICENSE file in the root of this repository +# for complete details. + +from __future__ import annotations + +import abc + +from cryptography.hazmat.bindings._rust import openssl as rust_openssl +from cryptography.hazmat.primitives import _serialization + +generate_parameters = rust_openssl.dh.generate_parameters + + +DHPrivateNumbers = rust_openssl.dh.DHPrivateNumbers +DHPublicNumbers = rust_openssl.dh.DHPublicNumbers +DHParameterNumbers = rust_openssl.dh.DHParameterNumbers + + +class DHParameters(metaclass=abc.ABCMeta): + @abc.abstractmethod + def generate_private_key(self) -> DHPrivateKey: + """ + Generates and returns a DHPrivateKey. + """ + + @abc.abstractmethod + def parameter_bytes( + self, + encoding: _serialization.Encoding, + format: _serialization.ParameterFormat, + ) -> bytes: + """ + Returns the parameters serialized as bytes. + """ + + @abc.abstractmethod + def parameter_numbers(self) -> DHParameterNumbers: + """ + Returns a DHParameterNumbers. + """ + + +DHParametersWithSerialization = DHParameters +DHParameters.register(rust_openssl.dh.DHParameters) + + +class DHPublicKey(metaclass=abc.ABCMeta): + @property + @abc.abstractmethod + def key_size(self) -> int: + """ + The bit length of the prime modulus. + """ + + @abc.abstractmethod + def parameters(self) -> DHParameters: + """ + The DHParameters object associated with this public key. + """ + + @abc.abstractmethod + def public_numbers(self) -> DHPublicNumbers: + """ + Returns a DHPublicNumbers. + """ + + @abc.abstractmethod + def public_bytes( + self, + encoding: _serialization.Encoding, + format: _serialization.PublicFormat, + ) -> bytes: + """ + Returns the key serialized as bytes. + """ + + @abc.abstractmethod + def __eq__(self, other: object) -> bool: + """ + Checks equality. + """ + + @abc.abstractmethod + def __copy__(self) -> DHPublicKey: + """ + Returns a copy. + """ + + @abc.abstractmethod + def __deepcopy__(self, memo: dict) -> DHPublicKey: + """ + Returns a deep copy. + """ + + +DHPublicKeyWithSerialization = DHPublicKey +DHPublicKey.register(rust_openssl.dh.DHPublicKey) + + +class DHPrivateKey(metaclass=abc.ABCMeta): + @property + @abc.abstractmethod + def key_size(self) -> int: + """ + The bit length of the prime modulus. + """ + + @abc.abstractmethod + def public_key(self) -> DHPublicKey: + """ + The DHPublicKey associated with this private key. + """ + + @abc.abstractmethod + def parameters(self) -> DHParameters: + """ + The DHParameters object associated with this private key. + """ + + @abc.abstractmethod + def exchange(self, peer_public_key: DHPublicKey) -> bytes: + """ + Given peer's DHPublicKey, carry out the key exchange and + return shared key as bytes. + """ + + @abc.abstractmethod + def private_numbers(self) -> DHPrivateNumbers: + """ + Returns a DHPrivateNumbers. + """ + + @abc.abstractmethod + def private_bytes( + self, + encoding: _serialization.Encoding, + format: _serialization.PrivateFormat, + encryption_algorithm: _serialization.KeySerializationEncryption, + ) -> bytes: + """ + Returns the key serialized as bytes. + """ + + @abc.abstractmethod + def __copy__(self) -> DHPrivateKey: + """ + Returns a copy. + """ + + @abc.abstractmethod + def __deepcopy__(self, memo: dict) -> DHPrivateKey: + """ + Returns a deep copy. + """ + + +DHPrivateKeyWithSerialization = DHPrivateKey +DHPrivateKey.register(rust_openssl.dh.DHPrivateKey) diff --git a/python/user_packages/Python313/site-packages/cryptography/hazmat/primitives/asymmetric/dsa.py b/python/user_packages/Python313/site-packages/cryptography/hazmat/primitives/asymmetric/dsa.py new file mode 100644 index 0000000000000000000000000000000000000000..f24555744191461eb39c4a6056f46b93b8b77c57 --- /dev/null +++ b/python/user_packages/Python313/site-packages/cryptography/hazmat/primitives/asymmetric/dsa.py @@ -0,0 +1,179 @@ +# This file is dual licensed under the terms of the Apache License, Version +# 2.0, and the BSD License. See the LICENSE file in the root of this repository +# for complete details. + +from __future__ import annotations + +import abc +import typing + +from cryptography.hazmat.bindings._rust import openssl as rust_openssl +from cryptography.hazmat.primitives import _serialization, hashes +from cryptography.hazmat.primitives.asymmetric import utils as asym_utils +from cryptography.utils import Buffer + + +class DSAParameters(metaclass=abc.ABCMeta): + @abc.abstractmethod + def generate_private_key(self) -> DSAPrivateKey: + """ + Generates and returns a DSAPrivateKey. + """ + + @abc.abstractmethod + def parameter_numbers(self) -> DSAParameterNumbers: + """ + Returns a DSAParameterNumbers. + """ + + +DSAParametersWithNumbers = DSAParameters +DSAParameters.register(rust_openssl.dsa.DSAParameters) + + +class DSAPrivateKey(metaclass=abc.ABCMeta): + @property + @abc.abstractmethod + def key_size(self) -> int: + """ + The bit length of the prime modulus. + """ + + @abc.abstractmethod + def public_key(self) -> DSAPublicKey: + """ + The DSAPublicKey associated with this private key. + """ + + @abc.abstractmethod + def parameters(self) -> DSAParameters: + """ + The DSAParameters object associated with this private key. + """ + + @abc.abstractmethod + def sign( + self, + data: Buffer, + algorithm: asym_utils.Prehashed | hashes.HashAlgorithm, + ) -> bytes: + """ + Signs the data + """ + + @abc.abstractmethod + def private_numbers(self) -> DSAPrivateNumbers: + """ + Returns a DSAPrivateNumbers. + """ + + @abc.abstractmethod + def private_bytes( + self, + encoding: _serialization.Encoding, + format: _serialization.PrivateFormat, + encryption_algorithm: _serialization.KeySerializationEncryption, + ) -> bytes: + """ + Returns the key serialized as bytes. + """ + + @abc.abstractmethod + def __copy__(self) -> DSAPrivateKey: + """ + Returns a copy. + """ + + @abc.abstractmethod + def __deepcopy__(self, memo: dict) -> DSAPrivateKey: + """ + Returns a deep copy. + """ + + +DSAPrivateKeyWithSerialization = DSAPrivateKey +DSAPrivateKey.register(rust_openssl.dsa.DSAPrivateKey) + + +class DSAPublicKey(metaclass=abc.ABCMeta): + @property + @abc.abstractmethod + def key_size(self) -> int: + """ + The bit length of the prime modulus. + """ + + @abc.abstractmethod + def parameters(self) -> DSAParameters: + """ + The DSAParameters object associated with this public key. + """ + + @abc.abstractmethod + def public_numbers(self) -> DSAPublicNumbers: + """ + Returns a DSAPublicNumbers. + """ + + @abc.abstractmethod + def public_bytes( + self, + encoding: _serialization.Encoding, + format: _serialization.PublicFormat, + ) -> bytes: + """ + Returns the key serialized as bytes. + """ + + @abc.abstractmethod + def verify( + self, + signature: Buffer, + data: Buffer, + algorithm: asym_utils.Prehashed | hashes.HashAlgorithm, + ) -> None: + """ + Verifies the signature of the data. + """ + + @abc.abstractmethod + def __eq__(self, other: object) -> bool: + """ + Checks equality. + """ + + @abc.abstractmethod + def __copy__(self) -> DSAPublicKey: + """ + Returns a copy. + """ + + @abc.abstractmethod + def __deepcopy__(self, memo: dict) -> DSAPublicKey: + """ + Returns a deep copy. + """ + + +DSAPublicKeyWithSerialization = DSAPublicKey +DSAPublicKey.register(rust_openssl.dsa.DSAPublicKey) + +DSAPrivateNumbers = rust_openssl.dsa.DSAPrivateNumbers +DSAPublicNumbers = rust_openssl.dsa.DSAPublicNumbers +DSAParameterNumbers = rust_openssl.dsa.DSAParameterNumbers + + +def generate_parameters( + key_size: int, backend: typing.Any = None +) -> DSAParameters: + if key_size not in (1024, 2048, 3072, 4096): + raise ValueError("Key size must be 1024, 2048, 3072, or 4096 bits.") + + return rust_openssl.dsa.generate_parameters(key_size) + + +def generate_private_key( + key_size: int, backend: typing.Any = None +) -> DSAPrivateKey: + parameters = generate_parameters(key_size) + return parameters.generate_private_key() diff --git a/python/user_packages/Python313/site-packages/cryptography/hazmat/primitives/asymmetric/ec.py b/python/user_packages/Python313/site-packages/cryptography/hazmat/primitives/asymmetric/ec.py new file mode 100644 index 0000000000000000000000000000000000000000..39e67519cf92bdbdc3aa93fcde488718f200bb8e --- /dev/null +++ b/python/user_packages/Python313/site-packages/cryptography/hazmat/primitives/asymmetric/ec.py @@ -0,0 +1,369 @@ +# This file is dual licensed under the terms of the Apache License, Version +# 2.0, and the BSD License. See the LICENSE file in the root of this repository +# for complete details. + +from __future__ import annotations + +import abc +import typing + +from cryptography import utils +from cryptography.exceptions import UnsupportedAlgorithm, _Reasons +from cryptography.hazmat._oid import ObjectIdentifier +from cryptography.hazmat.bindings._rust import openssl as rust_openssl +from cryptography.hazmat.primitives import _serialization, hashes +from cryptography.hazmat.primitives.asymmetric import utils as asym_utils + + +class EllipticCurveOID: + SECP192R1 = ObjectIdentifier("1.2.840.10045.3.1.1") + SECP224R1 = ObjectIdentifier("1.3.132.0.33") + SECP256K1 = ObjectIdentifier("1.3.132.0.10") + SECP256R1 = ObjectIdentifier("1.2.840.10045.3.1.7") + SECP384R1 = ObjectIdentifier("1.3.132.0.34") + SECP521R1 = ObjectIdentifier("1.3.132.0.35") + BRAINPOOLP256R1 = ObjectIdentifier("1.3.36.3.3.2.8.1.1.7") + BRAINPOOLP384R1 = ObjectIdentifier("1.3.36.3.3.2.8.1.1.11") + BRAINPOOLP512R1 = ObjectIdentifier("1.3.36.3.3.2.8.1.1.13") + + +class EllipticCurve(metaclass=abc.ABCMeta): + @property + @abc.abstractmethod + def name(self) -> str: + """ + The name of the curve. e.g. secp256r1. + """ + + @property + @abc.abstractmethod + def key_size(self) -> int: + """ + Bit size of a secret scalar for the curve. + """ + + @property + @abc.abstractmethod + def group_order(self) -> int: + """ + The order of the curve's group. + """ + + +class EllipticCurveSignatureAlgorithm(metaclass=abc.ABCMeta): + @property + @abc.abstractmethod + def algorithm( + self, + ) -> asym_utils.Prehashed | hashes.HashAlgorithm: + """ + The digest algorithm used with this signature. + """ + + +class EllipticCurvePrivateKey(metaclass=abc.ABCMeta): + @abc.abstractmethod + def exchange( + self, algorithm: ECDH, peer_public_key: EllipticCurvePublicKey + ) -> bytes: + """ + Performs a key exchange operation using the provided algorithm with the + provided peer's public key. + """ + + @abc.abstractmethod + def public_key(self) -> EllipticCurvePublicKey: + """ + The EllipticCurvePublicKey for this private key. + """ + + @property + @abc.abstractmethod + def curve(self) -> EllipticCurve: + """ + The EllipticCurve that this key is on. + """ + + @property + @abc.abstractmethod + def key_size(self) -> int: + """ + Bit size of a secret scalar for the curve. + """ + + @abc.abstractmethod + def sign( + self, + data: utils.Buffer, + signature_algorithm: EllipticCurveSignatureAlgorithm, + ) -> bytes: + """ + Signs the data + """ + + @abc.abstractmethod + def private_numbers(self) -> EllipticCurvePrivateNumbers: + """ + Returns an EllipticCurvePrivateNumbers. + """ + + @abc.abstractmethod + def private_bytes( + self, + encoding: _serialization.Encoding, + format: _serialization.PrivateFormat, + encryption_algorithm: _serialization.KeySerializationEncryption, + ) -> bytes: + """ + Returns the key serialized as bytes. + """ + + @abc.abstractmethod + def __copy__(self) -> EllipticCurvePrivateKey: + """ + Returns a copy. + """ + + @abc.abstractmethod + def __deepcopy__(self, memo: dict) -> EllipticCurvePrivateKey: + """ + Returns a deep copy. + """ + + +EllipticCurvePrivateKeyWithSerialization = EllipticCurvePrivateKey +EllipticCurvePrivateKey.register(rust_openssl.ec.ECPrivateKey) + + +class EllipticCurvePublicKey(metaclass=abc.ABCMeta): + @property + @abc.abstractmethod + def curve(self) -> EllipticCurve: + """ + The EllipticCurve that this key is on. + """ + + @property + @abc.abstractmethod + def key_size(self) -> int: + """ + Bit size of a secret scalar for the curve. + """ + + @abc.abstractmethod + def public_numbers(self) -> EllipticCurvePublicNumbers: + """ + Returns an EllipticCurvePublicNumbers. + """ + + @abc.abstractmethod + def public_bytes( + self, + encoding: _serialization.Encoding, + format: _serialization.PublicFormat, + ) -> bytes: + """ + Returns the key serialized as bytes. + """ + + @abc.abstractmethod + def verify( + self, + signature: utils.Buffer, + data: utils.Buffer, + signature_algorithm: EllipticCurveSignatureAlgorithm, + ) -> None: + """ + Verifies the signature of the data. + """ + + @classmethod + def from_encoded_point( + cls, curve: EllipticCurve, data: bytes + ) -> EllipticCurvePublicKey: + utils._check_bytes("data", data) + + if len(data) == 0: + raise ValueError("data must not be an empty byte string") + + if data[0] not in [0x02, 0x03, 0x04]: + raise ValueError("Unsupported elliptic curve point type") + + return rust_openssl.ec.from_public_bytes(curve, data) + + @abc.abstractmethod + def __eq__(self, other: object) -> bool: + """ + Checks equality. + """ + + @abc.abstractmethod + def __copy__(self) -> EllipticCurvePublicKey: + """ + Returns a copy. + """ + + @abc.abstractmethod + def __deepcopy__(self, memo: dict) -> EllipticCurvePublicKey: + """ + Returns a deep copy. + """ + + +EllipticCurvePublicKeyWithSerialization = EllipticCurvePublicKey +EllipticCurvePublicKey.register(rust_openssl.ec.ECPublicKey) + +EllipticCurvePrivateNumbers = rust_openssl.ec.EllipticCurvePrivateNumbers +EllipticCurvePublicNumbers = rust_openssl.ec.EllipticCurvePublicNumbers + + +class SECP521R1(EllipticCurve): + name = "secp521r1" + key_size = 521 + group_order = 0x1FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFA51868783BF2F966B7FCC0148F709A5D03BB5C9B8899C47AEBB6FB71E91386409 # noqa: E501 + + +class SECP384R1(EllipticCurve): + name = "secp384r1" + key_size = 384 + group_order = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFC7634D81F4372DDF581A0DB248B0A77AECEC196ACCC52973 # noqa: E501 + + +class SECP256R1(EllipticCurve): + name = "secp256r1" + key_size = 256 + group_order = ( + 0xFFFFFFFF00000000FFFFFFFFFFFFFFFFBCE6FAADA7179E84F3B9CAC2FC632551 + ) + + +class SECP256K1(EllipticCurve): + name = "secp256k1" + key_size = 256 + group_order = ( + 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 + ) + + +class SECP224R1(EllipticCurve): + name = "secp224r1" + key_size = 224 + group_order = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFF16A2E0B8F03E13DD29455C5C2A3D + + +class SECP192R1(EllipticCurve): + name = "secp192r1" + key_size = 192 + group_order = 0xFFFFFFFFFFFFFFFFFFFFFFFF99DEF836146BC9B1B4D22831 + + +class BrainpoolP256R1(EllipticCurve): + name = "brainpoolP256r1" + key_size = 256 + group_order = ( + 0xA9FB57DBA1EEA9BC3E660A909D838D718C397AA3B561A6F7901E0E82974856A7 + ) + + +class BrainpoolP384R1(EllipticCurve): + name = "brainpoolP384r1" + key_size = 384 + group_order = 0x8CB91E82A3386D280F5D6F7E50E641DF152F7109ED5456B31F166E6CAC0425A7CF3AB6AF6B7FC3103B883202E9046565 # noqa: E501 + + +class BrainpoolP512R1(EllipticCurve): + name = "brainpoolP512r1" + key_size = 512 + group_order = 0xAADD9DB8DBE9C48B3FD4E6AE33C9FC07CB308DB3B3C9D20ED6639CCA70330870553E5C414CA92619418661197FAC10471DB1D381085DDADDB58796829CA90069 # noqa: E501 + + +_CURVE_TYPES: dict[str, EllipticCurve] = { + "prime192v1": SECP192R1(), + "prime256v1": SECP256R1(), + "secp192r1": SECP192R1(), + "secp224r1": SECP224R1(), + "secp256r1": SECP256R1(), + "secp384r1": SECP384R1(), + "secp521r1": SECP521R1(), + "secp256k1": SECP256K1(), + "brainpoolP256r1": BrainpoolP256R1(), + "brainpoolP384r1": BrainpoolP384R1(), + "brainpoolP512r1": BrainpoolP512R1(), +} + + +class ECDSA(EllipticCurveSignatureAlgorithm): + def __init__( + self, + algorithm: asym_utils.Prehashed | hashes.HashAlgorithm, + deterministic_signing: bool = False, + ): + from cryptography.hazmat.backends.openssl.backend import backend + + if ( + deterministic_signing + and not backend.ecdsa_deterministic_supported() + ): + raise UnsupportedAlgorithm( + "ECDSA with deterministic signature (RFC 6979) is not " + "supported by this version of OpenSSL.", + _Reasons.UNSUPPORTED_PUBLIC_KEY_ALGORITHM, + ) + self._algorithm = algorithm + self._deterministic_signing = deterministic_signing + + @property + def algorithm( + self, + ) -> asym_utils.Prehashed | hashes.HashAlgorithm: + return self._algorithm + + @property + def deterministic_signing( + self, + ) -> bool: + return self._deterministic_signing + + +generate_private_key = rust_openssl.ec.generate_private_key + + +def derive_private_key( + private_value: int, + curve: EllipticCurve, + backend: typing.Any = None, +) -> EllipticCurvePrivateKey: + if not isinstance(private_value, int): + raise TypeError("private_value must be an integer type.") + + if private_value <= 0: + raise ValueError("private_value must be a positive integer.") + + return rust_openssl.ec.derive_private_key(private_value, curve) + + +class ECDH: + pass + + +_OID_TO_CURVE = { + EllipticCurveOID.SECP192R1: SECP192R1, + EllipticCurveOID.SECP224R1: SECP224R1, + EllipticCurveOID.SECP256K1: SECP256K1, + EllipticCurveOID.SECP256R1: SECP256R1, + EllipticCurveOID.SECP384R1: SECP384R1, + EllipticCurveOID.SECP521R1: SECP521R1, + EllipticCurveOID.BRAINPOOLP256R1: BrainpoolP256R1, + EllipticCurveOID.BRAINPOOLP384R1: BrainpoolP384R1, + EllipticCurveOID.BRAINPOOLP512R1: BrainpoolP512R1, +} + + +def get_curve_for_oid(oid: ObjectIdentifier) -> type[EllipticCurve]: + try: + return _OID_TO_CURVE[oid] + except KeyError: + raise LookupError( + "The provided object identifier has no matching elliptic " + "curve class" + ) diff --git a/python/user_packages/Python313/site-packages/cryptography/hazmat/primitives/asymmetric/ed25519.py b/python/user_packages/Python313/site-packages/cryptography/hazmat/primitives/asymmetric/ed25519.py new file mode 100644 index 0000000000000000000000000000000000000000..70aec5b102172c981a1b3c8b279bcb1ad780ded6 --- /dev/null +++ b/python/user_packages/Python313/site-packages/cryptography/hazmat/primitives/asymmetric/ed25519.py @@ -0,0 +1,116 @@ +# This file is dual licensed under the terms of the Apache License, Version +# 2.0, and the BSD License. See the LICENSE file in the root of this repository +# for complete details. + +from __future__ import annotations + +import abc + +from cryptography.hazmat.bindings._rust import openssl as rust_openssl +from cryptography.hazmat.primitives import _serialization +from cryptography.utils import Buffer + + +class Ed25519PublicKey(metaclass=abc.ABCMeta): + @classmethod + def from_public_bytes(cls, data: bytes) -> Ed25519PublicKey: + return rust_openssl.ed25519.from_public_bytes(data) + + @abc.abstractmethod + def public_bytes( + self, + encoding: _serialization.Encoding, + format: _serialization.PublicFormat, + ) -> bytes: + """ + The serialized bytes of the public key. + """ + + @abc.abstractmethod + def public_bytes_raw(self) -> bytes: + """ + The raw bytes of the public key. + Equivalent to public_bytes(Raw, Raw). + """ + + @abc.abstractmethod + def verify(self, signature: Buffer, data: Buffer) -> None: + """ + Verify the signature. + """ + + @abc.abstractmethod + def __eq__(self, other: object) -> bool: + """ + Checks equality. + """ + + @abc.abstractmethod + def __copy__(self) -> Ed25519PublicKey: + """ + Returns a copy. + """ + + @abc.abstractmethod + def __deepcopy__(self, memo: dict) -> Ed25519PublicKey: + """ + Returns a deep copy. + """ + + +Ed25519PublicKey.register(rust_openssl.ed25519.Ed25519PublicKey) + + +class Ed25519PrivateKey(metaclass=abc.ABCMeta): + @classmethod + def generate(cls) -> Ed25519PrivateKey: + return rust_openssl.ed25519.generate_key() + + @classmethod + def from_private_bytes(cls, data: Buffer) -> Ed25519PrivateKey: + return rust_openssl.ed25519.from_private_bytes(data) + + @abc.abstractmethod + def public_key(self) -> Ed25519PublicKey: + """ + The Ed25519PublicKey derived from the private key. + """ + + @abc.abstractmethod + def private_bytes( + self, + encoding: _serialization.Encoding, + format: _serialization.PrivateFormat, + encryption_algorithm: _serialization.KeySerializationEncryption, + ) -> bytes: + """ + The serialized bytes of the private key. + """ + + @abc.abstractmethod + def private_bytes_raw(self) -> bytes: + """ + The raw bytes of the private key. + Equivalent to private_bytes(Raw, Raw, NoEncryption()). + """ + + @abc.abstractmethod + def sign(self, data: Buffer) -> bytes: + """ + Signs the data. + """ + + @abc.abstractmethod + def __copy__(self) -> Ed25519PrivateKey: + """ + Returns a copy. + """ + + @abc.abstractmethod + def __deepcopy__(self, memo: dict) -> Ed25519PrivateKey: + """ + Returns a deep copy. + """ + + +Ed25519PrivateKey.register(rust_openssl.ed25519.Ed25519PrivateKey) diff --git a/python/user_packages/Python313/site-packages/cryptography/hazmat/primitives/asymmetric/ed448.py b/python/user_packages/Python313/site-packages/cryptography/hazmat/primitives/asymmetric/ed448.py new file mode 100644 index 0000000000000000000000000000000000000000..9ecb478bdf99ec0768dc2c0903f0ddf7f5f2822d --- /dev/null +++ b/python/user_packages/Python313/site-packages/cryptography/hazmat/primitives/asymmetric/ed448.py @@ -0,0 +1,143 @@ +# This file is dual licensed under the terms of the Apache License, Version +# 2.0, and the BSD License. See the LICENSE file in the root of this repository +# for complete details. + +from __future__ import annotations + +import abc + +from cryptography.exceptions import UnsupportedAlgorithm, _Reasons +from cryptography.hazmat.bindings._rust import openssl as rust_openssl +from cryptography.hazmat.primitives import _serialization +from cryptography.utils import Buffer + + +class Ed448PublicKey(metaclass=abc.ABCMeta): + @classmethod + def from_public_bytes(cls, data: bytes) -> Ed448PublicKey: + from cryptography.hazmat.backends.openssl.backend import backend + + if not backend.ed448_supported(): + raise UnsupportedAlgorithm( + "ed448 is not supported by this version of OpenSSL.", + _Reasons.UNSUPPORTED_PUBLIC_KEY_ALGORITHM, + ) + + return rust_openssl.ed448.from_public_bytes(data) + + @abc.abstractmethod + def public_bytes( + self, + encoding: _serialization.Encoding, + format: _serialization.PublicFormat, + ) -> bytes: + """ + The serialized bytes of the public key. + """ + + @abc.abstractmethod + def public_bytes_raw(self) -> bytes: + """ + The raw bytes of the public key. + Equivalent to public_bytes(Raw, Raw). + """ + + @abc.abstractmethod + def verify(self, signature: Buffer, data: Buffer) -> None: + """ + Verify the signature. + """ + + @abc.abstractmethod + def __eq__(self, other: object) -> bool: + """ + Checks equality. + """ + + @abc.abstractmethod + def __copy__(self) -> Ed448PublicKey: + """ + Returns a copy. + """ + + @abc.abstractmethod + def __deepcopy__(self, memo: dict) -> Ed448PublicKey: + """ + Returns a deep copy. + """ + + +if hasattr(rust_openssl, "ed448"): + Ed448PublicKey.register(rust_openssl.ed448.Ed448PublicKey) + + +class Ed448PrivateKey(metaclass=abc.ABCMeta): + @classmethod + def generate(cls) -> Ed448PrivateKey: + from cryptography.hazmat.backends.openssl.backend import backend + + if not backend.ed448_supported(): + raise UnsupportedAlgorithm( + "ed448 is not supported by this version of OpenSSL.", + _Reasons.UNSUPPORTED_PUBLIC_KEY_ALGORITHM, + ) + + return rust_openssl.ed448.generate_key() + + @classmethod + def from_private_bytes(cls, data: Buffer) -> Ed448PrivateKey: + from cryptography.hazmat.backends.openssl.backend import backend + + if not backend.ed448_supported(): + raise UnsupportedAlgorithm( + "ed448 is not supported by this version of OpenSSL.", + _Reasons.UNSUPPORTED_PUBLIC_KEY_ALGORITHM, + ) + + return rust_openssl.ed448.from_private_bytes(data) + + @abc.abstractmethod + def public_key(self) -> Ed448PublicKey: + """ + The Ed448PublicKey derived from the private key. + """ + + @abc.abstractmethod + def sign(self, data: Buffer) -> bytes: + """ + Signs the data. + """ + + @abc.abstractmethod + def private_bytes( + self, + encoding: _serialization.Encoding, + format: _serialization.PrivateFormat, + encryption_algorithm: _serialization.KeySerializationEncryption, + ) -> bytes: + """ + The serialized bytes of the private key. + """ + + @abc.abstractmethod + def private_bytes_raw(self) -> bytes: + """ + The raw bytes of the private key. + Equivalent to private_bytes(Raw, Raw, NoEncryption()). + """ + + @abc.abstractmethod + def __copy__(self) -> Ed448PrivateKey: + """ + Returns a copy. + """ + + @abc.abstractmethod + def __deepcopy__(self, memo: dict) -> Ed448PrivateKey: + """ + Returns a deep copy. + """ + + +if hasattr(rust_openssl, "x448"): + Ed448PrivateKey.register(rust_openssl.ed448.Ed448PrivateKey) diff --git a/python/user_packages/Python313/site-packages/cryptography/hazmat/primitives/asymmetric/mldsa.py b/python/user_packages/Python313/site-packages/cryptography/hazmat/primitives/asymmetric/mldsa.py new file mode 100644 index 0000000000000000000000000000000000000000..0bd968457eb20ca0277a25dd6b6bdd13d81eeef1 --- /dev/null +++ b/python/user_packages/Python313/site-packages/cryptography/hazmat/primitives/asymmetric/mldsa.py @@ -0,0 +1,441 @@ +# This file is dual licensed under the terms of the Apache License, Version +# 2.0, and the BSD License. See the LICENSE file in the root of this repository +# for complete details. + +from __future__ import annotations + +import abc + +from cryptography.exceptions import UnsupportedAlgorithm, _Reasons +from cryptography.hazmat.bindings._rust import openssl as rust_openssl +from cryptography.hazmat.primitives import _serialization +from cryptography.utils import Buffer + + +class MLDSA44PublicKey(metaclass=abc.ABCMeta): + @classmethod + def from_public_bytes(cls, data: bytes) -> MLDSA44PublicKey: + from cryptography.hazmat.backends.openssl.backend import backend + + if not backend.mldsa_supported(): + raise UnsupportedAlgorithm( + "ML-DSA-44 is not supported by this backend.", + _Reasons.UNSUPPORTED_PUBLIC_KEY_ALGORITHM, + ) + + return rust_openssl.mldsa.from_mldsa44_public_bytes(data) + + @abc.abstractmethod + def public_bytes( + self, + encoding: _serialization.Encoding, + format: _serialization.PublicFormat, + ) -> bytes: + """ + The serialized bytes of the public key. + """ + + @abc.abstractmethod + def public_bytes_raw(self) -> bytes: + """ + The raw bytes of the public key. + Equivalent to public_bytes(Raw, Raw). + + The public key is 1,312 bytes for MLDSA-44. + """ + + @abc.abstractmethod + def verify( + self, + signature: Buffer, + data: Buffer, + context: Buffer | None = None, + ) -> None: + """ + Verify the signature. + """ + + @abc.abstractmethod + def __eq__(self, other: object) -> bool: + """ + Checks equality. + """ + + @abc.abstractmethod + def __copy__(self) -> MLDSA44PublicKey: + """ + Returns a copy. + """ + + @abc.abstractmethod + def __deepcopy__(self, memo: dict) -> MLDSA44PublicKey: + """ + Returns a deep copy. + """ + + +if hasattr(rust_openssl, "mldsa"): + MLDSA44PublicKey.register(rust_openssl.mldsa.MLDSA44PublicKey) + + +class MLDSA44PrivateKey(metaclass=abc.ABCMeta): + @classmethod + def generate(cls) -> MLDSA44PrivateKey: + from cryptography.hazmat.backends.openssl.backend import backend + + if not backend.mldsa_supported(): + raise UnsupportedAlgorithm( + "ML-DSA-44 is not supported by this backend.", + _Reasons.UNSUPPORTED_PUBLIC_KEY_ALGORITHM, + ) + + return rust_openssl.mldsa.generate_mldsa44_key() + + @classmethod + def from_seed_bytes(cls, data: Buffer) -> MLDSA44PrivateKey: + from cryptography.hazmat.backends.openssl.backend import backend + + if not backend.mldsa_supported(): + raise UnsupportedAlgorithm( + "ML-DSA-44 is not supported by this backend.", + _Reasons.UNSUPPORTED_PUBLIC_KEY_ALGORITHM, + ) + + return rust_openssl.mldsa.from_mldsa44_seed_bytes(data) + + @abc.abstractmethod + def public_key(self) -> MLDSA44PublicKey: + """ + The MLDSA44PublicKey derived from the private key. + """ + + @abc.abstractmethod + def private_bytes( + self, + encoding: _serialization.Encoding, + format: _serialization.PrivateFormat, + encryption_algorithm: _serialization.KeySerializationEncryption, + ) -> bytes: + """ + The serialized bytes of the private key. + + This method only returns the serialization of the seed form of the + private key, never the expanded one. + """ + + @abc.abstractmethod + def private_bytes_raw(self) -> bytes: + """ + The raw bytes of the private key. + Equivalent to private_bytes(Raw, Raw, NoEncryption()). + + This method only returns the seed form of the private key (32 bytes). + """ + + @abc.abstractmethod + def sign(self, data: Buffer, context: Buffer | None = None) -> bytes: + """ + Signs the data. + """ + + @abc.abstractmethod + def __copy__(self) -> MLDSA44PrivateKey: + """ + Returns a copy. + """ + + @abc.abstractmethod + def __deepcopy__(self, memo: dict) -> MLDSA44PrivateKey: + """ + Returns a deep copy. + """ + + +if hasattr(rust_openssl, "mldsa"): + MLDSA44PrivateKey.register(rust_openssl.mldsa.MLDSA44PrivateKey) + + +class MLDSA65PublicKey(metaclass=abc.ABCMeta): + @classmethod + def from_public_bytes(cls, data: bytes) -> MLDSA65PublicKey: + from cryptography.hazmat.backends.openssl.backend import backend + + if not backend.mldsa_supported(): + raise UnsupportedAlgorithm( + "ML-DSA-65 is not supported by this backend.", + _Reasons.UNSUPPORTED_PUBLIC_KEY_ALGORITHM, + ) + + return rust_openssl.mldsa.from_mldsa65_public_bytes(data) + + @abc.abstractmethod + def public_bytes( + self, + encoding: _serialization.Encoding, + format: _serialization.PublicFormat, + ) -> bytes: + """ + The serialized bytes of the public key. + """ + + @abc.abstractmethod + def public_bytes_raw(self) -> bytes: + """ + The raw bytes of the public key. + Equivalent to public_bytes(Raw, Raw). + + The public key is 1,952 bytes for MLDSA-65. + """ + + @abc.abstractmethod + def verify( + self, + signature: Buffer, + data: Buffer, + context: Buffer | None = None, + ) -> None: + """ + Verify the signature. + """ + + @abc.abstractmethod + def __eq__(self, other: object) -> bool: + """ + Checks equality. + """ + + @abc.abstractmethod + def __copy__(self) -> MLDSA65PublicKey: + """ + Returns a copy. + """ + + @abc.abstractmethod + def __deepcopy__(self, memo: dict) -> MLDSA65PublicKey: + """ + Returns a deep copy. + """ + + +if hasattr(rust_openssl, "mldsa"): + MLDSA65PublicKey.register(rust_openssl.mldsa.MLDSA65PublicKey) + + +class MLDSA65PrivateKey(metaclass=abc.ABCMeta): + @classmethod + def generate(cls) -> MLDSA65PrivateKey: + from cryptography.hazmat.backends.openssl.backend import backend + + if not backend.mldsa_supported(): + raise UnsupportedAlgorithm( + "ML-DSA-65 is not supported by this backend.", + _Reasons.UNSUPPORTED_PUBLIC_KEY_ALGORITHM, + ) + + return rust_openssl.mldsa.generate_mldsa65_key() + + @classmethod + def from_seed_bytes(cls, data: Buffer) -> MLDSA65PrivateKey: + from cryptography.hazmat.backends.openssl.backend import backend + + if not backend.mldsa_supported(): + raise UnsupportedAlgorithm( + "ML-DSA-65 is not supported by this backend.", + _Reasons.UNSUPPORTED_PUBLIC_KEY_ALGORITHM, + ) + + return rust_openssl.mldsa.from_mldsa65_seed_bytes(data) + + @abc.abstractmethod + def public_key(self) -> MLDSA65PublicKey: + """ + The MLDSA65PublicKey derived from the private key. + """ + + @abc.abstractmethod + def private_bytes( + self, + encoding: _serialization.Encoding, + format: _serialization.PrivateFormat, + encryption_algorithm: _serialization.KeySerializationEncryption, + ) -> bytes: + """ + The serialized bytes of the private key. + + This method only returns the serialization of the seed form of the + private key, never the expanded one. + """ + + @abc.abstractmethod + def private_bytes_raw(self) -> bytes: + """ + The raw bytes of the private key. + Equivalent to private_bytes(Raw, Raw, NoEncryption()). + + This method only returns the seed form of the private key (32 bytes). + """ + + @abc.abstractmethod + def sign(self, data: Buffer, context: Buffer | None = None) -> bytes: + """ + Signs the data. + """ + + @abc.abstractmethod + def __copy__(self) -> MLDSA65PrivateKey: + """ + Returns a copy. + """ + + @abc.abstractmethod + def __deepcopy__(self, memo: dict) -> MLDSA65PrivateKey: + """ + Returns a deep copy. + """ + + +if hasattr(rust_openssl, "mldsa"): + MLDSA65PrivateKey.register(rust_openssl.mldsa.MLDSA65PrivateKey) + + +class MLDSA87PublicKey(metaclass=abc.ABCMeta): + @classmethod + def from_public_bytes(cls, data: bytes) -> MLDSA87PublicKey: + from cryptography.hazmat.backends.openssl.backend import backend + + if not backend.mldsa_supported(): + raise UnsupportedAlgorithm( + "ML-DSA-87 is not supported by this backend.", + _Reasons.UNSUPPORTED_PUBLIC_KEY_ALGORITHM, + ) + + return rust_openssl.mldsa.from_mldsa87_public_bytes(data) + + @abc.abstractmethod + def public_bytes( + self, + encoding: _serialization.Encoding, + format: _serialization.PublicFormat, + ) -> bytes: + """ + The serialized bytes of the public key. + """ + + @abc.abstractmethod + def public_bytes_raw(self) -> bytes: + """ + The raw bytes of the public key. + Equivalent to public_bytes(Raw, Raw). + + The public key is 2,592 bytes for MLDSA-87. + """ + + @abc.abstractmethod + def verify( + self, + signature: Buffer, + data: Buffer, + context: Buffer | None = None, + ) -> None: + """ + Verify the signature. + """ + + @abc.abstractmethod + def __eq__(self, other: object) -> bool: + """ + Checks equality. + """ + + @abc.abstractmethod + def __copy__(self) -> MLDSA87PublicKey: + """ + Returns a copy. + """ + + @abc.abstractmethod + def __deepcopy__(self, memo: dict) -> MLDSA87PublicKey: + """ + Returns a deep copy. + """ + + +if hasattr(rust_openssl, "mldsa"): + MLDSA87PublicKey.register(rust_openssl.mldsa.MLDSA87PublicKey) + + +class MLDSA87PrivateKey(metaclass=abc.ABCMeta): + @classmethod + def generate(cls) -> MLDSA87PrivateKey: + from cryptography.hazmat.backends.openssl.backend import backend + + if not backend.mldsa_supported(): + raise UnsupportedAlgorithm( + "ML-DSA-87 is not supported by this backend.", + _Reasons.UNSUPPORTED_PUBLIC_KEY_ALGORITHM, + ) + + return rust_openssl.mldsa.generate_mldsa87_key() + + @classmethod + def from_seed_bytes(cls, data: Buffer) -> MLDSA87PrivateKey: + from cryptography.hazmat.backends.openssl.backend import backend + + if not backend.mldsa_supported(): + raise UnsupportedAlgorithm( + "ML-DSA-87 is not supported by this backend.", + _Reasons.UNSUPPORTED_PUBLIC_KEY_ALGORITHM, + ) + + return rust_openssl.mldsa.from_mldsa87_seed_bytes(data) + + @abc.abstractmethod + def public_key(self) -> MLDSA87PublicKey: + """ + The MLDSA87PublicKey derived from the private key. + """ + + @abc.abstractmethod + def private_bytes( + self, + encoding: _serialization.Encoding, + format: _serialization.PrivateFormat, + encryption_algorithm: _serialization.KeySerializationEncryption, + ) -> bytes: + """ + The serialized bytes of the private key. + + This method only returns the serialization of the seed form of the + private key, never the expanded one. + """ + + @abc.abstractmethod + def private_bytes_raw(self) -> bytes: + """ + The raw bytes of the private key. + Equivalent to private_bytes(Raw, Raw, NoEncryption()). + + This method only returns the seed form of the private key (32 bytes). + """ + + @abc.abstractmethod + def sign(self, data: Buffer, context: Buffer | None = None) -> bytes: + """ + Signs the data. + """ + + @abc.abstractmethod + def __copy__(self) -> MLDSA87PrivateKey: + """ + Returns a copy. + """ + + @abc.abstractmethod + def __deepcopy__(self, memo: dict) -> MLDSA87PrivateKey: + """ + Returns a deep copy. + """ + + +if hasattr(rust_openssl, "mldsa"): + MLDSA87PrivateKey.register(rust_openssl.mldsa.MLDSA87PrivateKey) diff --git a/python/user_packages/Python313/site-packages/cryptography/hazmat/primitives/asymmetric/mlkem.py b/python/user_packages/Python313/site-packages/cryptography/hazmat/primitives/asymmetric/mlkem.py new file mode 100644 index 0000000000000000000000000000000000000000..64bca1151bd2be5e73fb0bf365bb1ea73ddaee49 --- /dev/null +++ b/python/user_packages/Python313/site-packages/cryptography/hazmat/primitives/asymmetric/mlkem.py @@ -0,0 +1,278 @@ +# This file is dual licensed under the terms of the Apache License, Version +# 2.0, and the BSD License. See the LICENSE file in the root of this repository +# for complete details. + +from __future__ import annotations + +import abc + +from cryptography.exceptions import UnsupportedAlgorithm, _Reasons +from cryptography.hazmat.bindings._rust import openssl as rust_openssl +from cryptography.hazmat.primitives import _serialization +from cryptography.utils import Buffer + + +class MLKEM768PublicKey(metaclass=abc.ABCMeta): + @classmethod + def from_public_bytes(cls, data: Buffer) -> MLKEM768PublicKey: + from cryptography.hazmat.backends.openssl.backend import backend + + if not backend.mlkem_supported(): + raise UnsupportedAlgorithm( + "ML-KEM-768 is not supported by this backend.", + _Reasons.UNSUPPORTED_PUBLIC_KEY_ALGORITHM, + ) + + return rust_openssl.mlkem.from_mlkem768_public_bytes(data) + + @abc.abstractmethod + def encapsulate(self) -> tuple[bytes, bytes]: + """ + Encapsulate: returns (shared_secret, ciphertext). + """ + + @abc.abstractmethod + def public_bytes( + self, + encoding: _serialization.Encoding, + format: _serialization.PublicFormat, + ) -> bytes: + """ + The serialized bytes of the public key. + """ + + @abc.abstractmethod + def public_bytes_raw(self) -> bytes: + """ + The raw bytes of the public key. + Equivalent to public_bytes(Raw, Raw). + + The public key is 1,184 bytes for ML-KEM-768. + """ + + @abc.abstractmethod + def __eq__(self, other: object) -> bool: + """ + Checks equality. + """ + + @abc.abstractmethod + def __copy__(self) -> MLKEM768PublicKey: + """ + Returns a copy. + """ + + @abc.abstractmethod + def __deepcopy__(self, memo: dict) -> MLKEM768PublicKey: + """ + Returns a deep copy. + """ + + +if hasattr(rust_openssl, "mlkem"): + MLKEM768PublicKey.register(rust_openssl.mlkem.MLKEM768PublicKey) + + +class MLKEM768PrivateKey(metaclass=abc.ABCMeta): + @classmethod + def generate(cls) -> MLKEM768PrivateKey: + from cryptography.hazmat.backends.openssl.backend import backend + + if not backend.mlkem_supported(): + raise UnsupportedAlgorithm( + "ML-KEM-768 is not supported by this backend.", + _Reasons.UNSUPPORTED_PUBLIC_KEY_ALGORITHM, + ) + + return rust_openssl.mlkem.generate_mlkem768_key() + + @classmethod + def from_seed_bytes(cls, data: Buffer) -> MLKEM768PrivateKey: + from cryptography.hazmat.backends.openssl.backend import backend + + if not backend.mlkem_supported(): + raise UnsupportedAlgorithm( + "ML-KEM-768 is not supported by this backend.", + _Reasons.UNSUPPORTED_PUBLIC_KEY_ALGORITHM, + ) + + return rust_openssl.mlkem.from_mlkem768_seed_bytes(data) + + @abc.abstractmethod + def decapsulate(self, ciphertext: Buffer) -> bytes: + """ + Decapsulate: returns shared_secret. + """ + + @abc.abstractmethod + def public_key(self) -> MLKEM768PublicKey: + """ + The MLKEM768PublicKey derived from this private key. + """ + + @abc.abstractmethod + def private_bytes( + self, + encoding: _serialization.Encoding, + format: _serialization.PrivateFormat, + encryption_algorithm: _serialization.KeySerializationEncryption, + ) -> bytes: + """ + The serialized bytes of the private key. + """ + + @abc.abstractmethod + def private_bytes_raw(self) -> bytes: + """ + The raw bytes of the private key (64-byte seed). + Equivalent to private_bytes(Raw, Raw, NoEncryption()). + """ + + @abc.abstractmethod + def __copy__(self) -> MLKEM768PrivateKey: + """ + Returns a copy. + """ + + @abc.abstractmethod + def __deepcopy__(self, memo: dict) -> MLKEM768PrivateKey: + """ + Returns a deep copy. + """ + + +if hasattr(rust_openssl, "mlkem"): + MLKEM768PrivateKey.register(rust_openssl.mlkem.MLKEM768PrivateKey) + + +class MLKEM1024PublicKey(metaclass=abc.ABCMeta): + @classmethod + def from_public_bytes(cls, data: Buffer) -> MLKEM1024PublicKey: + from cryptography.hazmat.backends.openssl.backend import backend + + if not backend.mlkem_supported(): + raise UnsupportedAlgorithm( + "ML-KEM-1024 is not supported by this backend.", + _Reasons.UNSUPPORTED_PUBLIC_KEY_ALGORITHM, + ) + + return rust_openssl.mlkem.from_mlkem1024_public_bytes(data) + + @abc.abstractmethod + def encapsulate(self) -> tuple[bytes, bytes]: + """ + Encapsulate: returns (shared_secret, ciphertext). + """ + + @abc.abstractmethod + def public_bytes( + self, + encoding: _serialization.Encoding, + format: _serialization.PublicFormat, + ) -> bytes: + """ + The serialized bytes of the public key. + """ + + @abc.abstractmethod + def public_bytes_raw(self) -> bytes: + """ + The raw bytes of the public key. + Equivalent to public_bytes(Raw, Raw). + + The public key is 1,568 bytes for ML-KEM-1024. + """ + + @abc.abstractmethod + def __eq__(self, other: object) -> bool: + """ + Checks equality. + """ + + @abc.abstractmethod + def __copy__(self) -> MLKEM1024PublicKey: + """ + Returns a copy. + """ + + @abc.abstractmethod + def __deepcopy__(self, memo: dict) -> MLKEM1024PublicKey: + """ + Returns a deep copy. + """ + + +if hasattr(rust_openssl, "mlkem"): + MLKEM1024PublicKey.register(rust_openssl.mlkem.MLKEM1024PublicKey) + + +class MLKEM1024PrivateKey(metaclass=abc.ABCMeta): + @classmethod + def generate(cls) -> MLKEM1024PrivateKey: + from cryptography.hazmat.backends.openssl.backend import backend + + if not backend.mlkem_supported(): + raise UnsupportedAlgorithm( + "ML-KEM-1024 is not supported by this backend.", + _Reasons.UNSUPPORTED_PUBLIC_KEY_ALGORITHM, + ) + + return rust_openssl.mlkem.generate_mlkem1024_key() + + @classmethod + def from_seed_bytes(cls, data: Buffer) -> MLKEM1024PrivateKey: + from cryptography.hazmat.backends.openssl.backend import backend + + if not backend.mlkem_supported(): + raise UnsupportedAlgorithm( + "ML-KEM-1024 is not supported by this backend.", + _Reasons.UNSUPPORTED_PUBLIC_KEY_ALGORITHM, + ) + + return rust_openssl.mlkem.from_mlkem1024_seed_bytes(data) + + @abc.abstractmethod + def decapsulate(self, ciphertext: Buffer) -> bytes: + """ + Decapsulate: returns shared_secret. + """ + + @abc.abstractmethod + def public_key(self) -> MLKEM1024PublicKey: + """ + The MLKEM1024PublicKey derived from this private key. + """ + + @abc.abstractmethod + def private_bytes( + self, + encoding: _serialization.Encoding, + format: _serialization.PrivateFormat, + encryption_algorithm: _serialization.KeySerializationEncryption, + ) -> bytes: + """ + The serialized bytes of the private key. + """ + + @abc.abstractmethod + def private_bytes_raw(self) -> bytes: + """ + The raw bytes of the private key (64-byte seed). + Equivalent to private_bytes(Raw, Raw, NoEncryption()). + """ + + @abc.abstractmethod + def __copy__(self) -> MLKEM1024PrivateKey: + """ + Returns a copy. + """ + + @abc.abstractmethod + def __deepcopy__(self, memo: dict) -> MLKEM1024PrivateKey: + """ + Returns a deep copy. + """ + + +if hasattr(rust_openssl, "mlkem"): + MLKEM1024PrivateKey.register(rust_openssl.mlkem.MLKEM1024PrivateKey) diff --git a/python/user_packages/Python313/site-packages/cryptography/hazmat/primitives/asymmetric/padding.py b/python/user_packages/Python313/site-packages/cryptography/hazmat/primitives/asymmetric/padding.py new file mode 100644 index 0000000000000000000000000000000000000000..5121a288fcc7ebc333285deb941630954739623d --- /dev/null +++ b/python/user_packages/Python313/site-packages/cryptography/hazmat/primitives/asymmetric/padding.py @@ -0,0 +1,111 @@ +# This file is dual licensed under the terms of the Apache License, Version +# 2.0, and the BSD License. See the LICENSE file in the root of this repository +# for complete details. + +from __future__ import annotations + +import abc + +from cryptography.hazmat.primitives import hashes +from cryptography.hazmat.primitives._asymmetric import ( + AsymmetricPadding as AsymmetricPadding, +) +from cryptography.hazmat.primitives.asymmetric import rsa + + +class PKCS1v15(AsymmetricPadding): + name = "EMSA-PKCS1-v1_5" + + +class _MaxLength: + "Sentinel value for `MAX_LENGTH`." + + +class _Auto: + "Sentinel value for `AUTO`." + + +class _DigestLength: + "Sentinel value for `DIGEST_LENGTH`." + + +class PSS(AsymmetricPadding): + MAX_LENGTH = _MaxLength() + AUTO = _Auto() + DIGEST_LENGTH = _DigestLength() + name = "EMSA-PSS" + _salt_length: int | _MaxLength | _Auto | _DigestLength + + def __init__( + self, + mgf: MGF, + salt_length: int | _MaxLength | _Auto | _DigestLength, + ) -> None: + self._mgf = mgf + + if not isinstance( + salt_length, (int, _MaxLength, _Auto, _DigestLength) + ): + raise TypeError( + "salt_length must be an integer, MAX_LENGTH, " + "DIGEST_LENGTH, or AUTO" + ) + + if isinstance(salt_length, int) and salt_length < 0: + raise ValueError("salt_length must be zero or greater.") + + self._salt_length = salt_length + + @property + def mgf(self) -> MGF: + return self._mgf + + +class OAEP(AsymmetricPadding): + name = "EME-OAEP" + + def __init__( + self, + mgf: MGF, + algorithm: hashes.HashAlgorithm, + label: bytes | None, + ): + if not isinstance(algorithm, hashes.HashAlgorithm): + raise TypeError("Expected instance of hashes.HashAlgorithm.") + + self._mgf = mgf + self._algorithm = algorithm + self._label = label + + @property + def algorithm(self) -> hashes.HashAlgorithm: + return self._algorithm + + @property + def mgf(self) -> MGF: + return self._mgf + + +class MGF(metaclass=abc.ABCMeta): + _algorithm: hashes.HashAlgorithm + + +class MGF1(MGF): + def __init__(self, algorithm: hashes.HashAlgorithm): + if not isinstance(algorithm, hashes.HashAlgorithm): + raise TypeError("Expected instance of hashes.HashAlgorithm.") + + self._algorithm = algorithm + + +def calculate_max_pss_salt_length( + key: rsa.RSAPrivateKey | rsa.RSAPublicKey, + hash_algorithm: hashes.HashAlgorithm, +) -> int: + if not isinstance(key, (rsa.RSAPrivateKey, rsa.RSAPublicKey)): + raise TypeError("key must be an RSA public or private key") + # bit length - 1 per RFC 3447 + emlen = (key.key_size + 6) // 8 + salt_length = emlen - hash_algorithm.digest_size - 2 + assert salt_length >= 0 + return salt_length diff --git a/python/user_packages/Python313/site-packages/cryptography/hazmat/primitives/asymmetric/rsa.py b/python/user_packages/Python313/site-packages/cryptography/hazmat/primitives/asymmetric/rsa.py new file mode 100644 index 0000000000000000000000000000000000000000..d730cebdd35c809eff23dd627d3ce075c3360a7d --- /dev/null +++ b/python/user_packages/Python313/site-packages/cryptography/hazmat/primitives/asymmetric/rsa.py @@ -0,0 +1,295 @@ +# This file is dual licensed under the terms of the Apache License, Version +# 2.0, and the BSD License. See the LICENSE file in the root of this repository +# for complete details. + +from __future__ import annotations + +import abc +import random +import typing +from math import gcd, lcm + +from cryptography.hazmat.bindings._rust import openssl as rust_openssl +from cryptography.hazmat.primitives import _serialization, hashes +from cryptography.hazmat.primitives._asymmetric import AsymmetricPadding +from cryptography.hazmat.primitives.asymmetric import utils as asym_utils + + +class RSAPrivateKey(metaclass=abc.ABCMeta): + @abc.abstractmethod + def decrypt(self, ciphertext: bytes, padding: AsymmetricPadding) -> bytes: + """ + Decrypts the provided ciphertext. + """ + + @property + @abc.abstractmethod + def key_size(self) -> int: + """ + The bit length of the public modulus. + """ + + @abc.abstractmethod + def public_key(self) -> RSAPublicKey: + """ + The RSAPublicKey associated with this private key. + """ + + @abc.abstractmethod + def sign( + self, + data: bytes, + padding: AsymmetricPadding, + algorithm: asym_utils.Prehashed + | hashes.HashAlgorithm + | asym_utils.NoDigestInfo, + ) -> bytes: + """ + Signs the data. + """ + + @abc.abstractmethod + def private_numbers(self) -> RSAPrivateNumbers: + """ + Returns an RSAPrivateNumbers. + """ + + @abc.abstractmethod + def private_bytes( + self, + encoding: _serialization.Encoding, + format: _serialization.PrivateFormat, + encryption_algorithm: _serialization.KeySerializationEncryption, + ) -> bytes: + """ + Returns the key serialized as bytes. + """ + + @abc.abstractmethod + def __copy__(self) -> RSAPrivateKey: + """ + Returns a copy. + """ + + @abc.abstractmethod + def __deepcopy__(self, memo: dict) -> RSAPrivateKey: + """ + Returns a deep copy. + """ + + +RSAPrivateKeyWithSerialization = RSAPrivateKey +RSAPrivateKey.register(rust_openssl.rsa.RSAPrivateKey) + + +class RSAPublicKey(metaclass=abc.ABCMeta): + @abc.abstractmethod + def encrypt(self, plaintext: bytes, padding: AsymmetricPadding) -> bytes: + """ + Encrypts the given plaintext. + """ + + @property + @abc.abstractmethod + def key_size(self) -> int: + """ + The bit length of the public modulus. + """ + + @abc.abstractmethod + def public_numbers(self) -> RSAPublicNumbers: + """ + Returns an RSAPublicNumbers + """ + + @abc.abstractmethod + def public_bytes( + self, + encoding: _serialization.Encoding, + format: _serialization.PublicFormat, + ) -> bytes: + """ + Returns the key serialized as bytes. + """ + + @abc.abstractmethod + def verify( + self, + signature: bytes, + data: bytes, + padding: AsymmetricPadding, + algorithm: asym_utils.Prehashed | hashes.HashAlgorithm, + ) -> None: + """ + Verifies the signature of the data. + """ + + @abc.abstractmethod + def recover_data_from_signature( + self, + signature: bytes, + padding: AsymmetricPadding, + algorithm: hashes.HashAlgorithm | asym_utils.NoDigestInfo | None, + ) -> bytes: + """ + Recovers the original data from the signature. + """ + + @abc.abstractmethod + def __eq__(self, other: object) -> bool: + """ + Checks equality. + """ + + @abc.abstractmethod + def __copy__(self) -> RSAPublicKey: + """ + Returns a copy. + """ + + @abc.abstractmethod + def __deepcopy__(self, memo: dict) -> RSAPublicKey: + """ + Returns a deep copy. + """ + + +RSAPublicKeyWithSerialization = RSAPublicKey +RSAPublicKey.register(rust_openssl.rsa.RSAPublicKey) + +RSAPrivateNumbers = rust_openssl.rsa.RSAPrivateNumbers +RSAPublicNumbers = rust_openssl.rsa.RSAPublicNumbers + + +def generate_private_key( + public_exponent: int, + key_size: int, + backend: typing.Any = None, +) -> RSAPrivateKey: + _verify_rsa_parameters(public_exponent, key_size) + return rust_openssl.rsa.generate_private_key(public_exponent, key_size) + + +def _verify_rsa_parameters(public_exponent: int, key_size: int) -> None: + if public_exponent not in (3, 65537): + raise ValueError( + "public_exponent must be either 3 (for legacy compatibility) or " + "65537. Almost everyone should choose 65537 here!" + ) + + if key_size < 1024: + raise ValueError("key_size must be at least 1024-bits.") + + +def _modinv(e: int, m: int) -> int: + """ + Modular Multiplicative Inverse. Returns x such that: (x*e) mod m == 1 + """ + x1, x2 = 1, 0 + a, b = e, m + while b > 0: + q, r = divmod(a, b) + xn = x1 - q * x2 + a, b, x1, x2 = b, r, x2, xn + return x1 % m + + +def rsa_crt_iqmp(p: int, q: int) -> int: + """ + Compute the CRT (q ** -1) % p value from RSA primes p and q. + """ + if p <= 1 or q <= 1: + raise ValueError("Values can't be <= 1") + return _modinv(q, p) + + +def rsa_crt_dmp1(private_exponent: int, p: int) -> int: + """ + Compute the CRT private_exponent % (p - 1) value from the RSA + private_exponent (d) and p. + """ + if private_exponent <= 1 or p <= 1: + raise ValueError("Values can't be <= 1") + return private_exponent % (p - 1) + + +def rsa_crt_dmq1(private_exponent: int, q: int) -> int: + """ + Compute the CRT private_exponent % (q - 1) value from the RSA + private_exponent (d) and q. + """ + if private_exponent <= 1 or q <= 1: + raise ValueError("Values can't be <= 1") + return private_exponent % (q - 1) + + +def rsa_recover_private_exponent(e: int, p: int, q: int) -> int: + """ + Compute the RSA private_exponent (d) given the public exponent (e) + and the RSA primes p and q. + + This uses the Carmichael totient function to generate the + smallest possible working value of the private exponent. + """ + # This lambda_n is the Carmichael totient function. + # The original RSA paper uses the Euler totient function + # here: phi_n = (p - 1) * (q - 1) + # Either version of the private exponent will work, but the + # one generated by the older formulation may be larger + # than necessary. (lambda_n always divides phi_n) + if e <= 1 or p <= 1 or q <= 1: + raise ValueError("Values can't be <= 1") + return _modinv(e, lcm(p - 1, q - 1)) + + +# Controls the number of iterations rsa_recover_prime_factors will perform +# to obtain the prime factors. +_MAX_RECOVERY_ATTEMPTS = 500 + + +def rsa_recover_prime_factors(n: int, e: int, d: int) -> tuple[int, int]: + """ + Compute factors p and q from the private exponent d. We assume that n has + no more than two factors. This function is adapted from code in PyCrypto. + """ + # reject invalid values early + if d <= 1 or e <= 1: + raise ValueError("d, e can't be <= 1") + if 17 != pow(17, e * d, n): + raise ValueError("n, d, e don't match") + # See 8.2.2(i) in Handbook of Applied Cryptography. + ktot = d * e - 1 + # The quantity d*e-1 is a multiple of phi(n), even, + # and can be represented as t*2^s. + t = ktot + while t % 2 == 0: + t = t // 2 + # Cycle through all multiplicative inverses in Zn. + # The algorithm is non-deterministic, but there is a 50% chance + # any candidate a leads to successful factoring. + # See "Digitalized Signatures and Public Key Functions as Intractable + # as Factorization", M. Rabin, 1979 + spotted = False + tries = 0 + while not spotted and tries < _MAX_RECOVERY_ATTEMPTS: + a = random.randint(2, n - 1) + tries += 1 + k = t + # Cycle through all values a^{t*2^i}=a^k + while k < ktot: + cand = pow(a, k, n) + # Check if a^k is a non-trivial root of unity (mod n) + if cand != 1 and cand != (n - 1) and pow(cand, 2, n) == 1: + # We have found a number such that (cand-1)(cand+1)=0 (mod n). + # Either of the terms divides n. + p = gcd(cand + 1, n) + spotted = True + break + k *= 2 + if not spotted: + raise ValueError("Unable to compute factors p and q from exponent d.") + # Found ! + q, r = divmod(n, p) + assert r == 0 + p, q = sorted((p, q), reverse=True) + return (p, q) diff --git a/python/user_packages/Python313/site-packages/cryptography/hazmat/primitives/asymmetric/types.py b/python/user_packages/Python313/site-packages/cryptography/hazmat/primitives/asymmetric/types.py new file mode 100644 index 0000000000000000000000000000000000000000..dfd12ce007a4010fe92416d8ea2f698883c6770f --- /dev/null +++ b/python/user_packages/Python313/site-packages/cryptography/hazmat/primitives/asymmetric/types.py @@ -0,0 +1,123 @@ +# This file is dual licensed under the terms of the Apache License, Version +# 2.0, and the BSD License. See the LICENSE file in the root of this repository +# for complete details. + +from __future__ import annotations + +import typing + +from cryptography import utils +from cryptography.hazmat.primitives.asymmetric import ( + dh, + dsa, + ec, + ed448, + ed25519, + mldsa, + mlkem, + rsa, + x448, + x25519, +) + +# Every asymmetric key type +PublicKeyTypes = typing.Union[ + dh.DHPublicKey, + dsa.DSAPublicKey, + rsa.RSAPublicKey, + ec.EllipticCurvePublicKey, + ed25519.Ed25519PublicKey, + ed448.Ed448PublicKey, + mldsa.MLDSA44PublicKey, + mldsa.MLDSA65PublicKey, + mldsa.MLDSA87PublicKey, + mlkem.MLKEM768PublicKey, + mlkem.MLKEM1024PublicKey, + x25519.X25519PublicKey, + x448.X448PublicKey, +] +PUBLIC_KEY_TYPES = PublicKeyTypes +utils.deprecated( + PUBLIC_KEY_TYPES, + __name__, + "Use PublicKeyTypes instead", + utils.DeprecatedIn40, + name="PUBLIC_KEY_TYPES", +) +# Every asymmetric key type +PrivateKeyTypes = typing.Union[ + dh.DHPrivateKey, + ed25519.Ed25519PrivateKey, + ed448.Ed448PrivateKey, + mldsa.MLDSA44PrivateKey, + mldsa.MLDSA65PrivateKey, + mldsa.MLDSA87PrivateKey, + mlkem.MLKEM768PrivateKey, + mlkem.MLKEM1024PrivateKey, + rsa.RSAPrivateKey, + dsa.DSAPrivateKey, + ec.EllipticCurvePrivateKey, + x25519.X25519PrivateKey, + x448.X448PrivateKey, +] +PRIVATE_KEY_TYPES = PrivateKeyTypes +utils.deprecated( + PRIVATE_KEY_TYPES, + __name__, + "Use PrivateKeyTypes instead", + utils.DeprecatedIn40, + name="PRIVATE_KEY_TYPES", +) +# Just the key types we allow to be used for x509 signing. This mirrors +# the certificate public key types +CertificateIssuerPrivateKeyTypes = typing.Union[ + ed25519.Ed25519PrivateKey, + ed448.Ed448PrivateKey, + rsa.RSAPrivateKey, + dsa.DSAPrivateKey, + ec.EllipticCurvePrivateKey, +] +CERTIFICATE_PRIVATE_KEY_TYPES = CertificateIssuerPrivateKeyTypes +utils.deprecated( + CERTIFICATE_PRIVATE_KEY_TYPES, + __name__, + "Use CertificateIssuerPrivateKeyTypes instead", + utils.DeprecatedIn40, + name="CERTIFICATE_PRIVATE_KEY_TYPES", +) +# Just the key types we allow to be used for x509 signing. This mirrors +# the certificate private key types +CertificateIssuerPublicKeyTypes = typing.Union[ + dsa.DSAPublicKey, + rsa.RSAPublicKey, + ec.EllipticCurvePublicKey, + ed25519.Ed25519PublicKey, + ed448.Ed448PublicKey, +] +CERTIFICATE_ISSUER_PUBLIC_KEY_TYPES = CertificateIssuerPublicKeyTypes +utils.deprecated( + CERTIFICATE_ISSUER_PUBLIC_KEY_TYPES, + __name__, + "Use CertificateIssuerPublicKeyTypes instead", + utils.DeprecatedIn40, + name="CERTIFICATE_ISSUER_PUBLIC_KEY_TYPES", +) +# This type removes DHPublicKey. x448/x25519 can be a public key +# but cannot be used in signing so they are allowed here. +CertificatePublicKeyTypes = typing.Union[ + dsa.DSAPublicKey, + rsa.RSAPublicKey, + ec.EllipticCurvePublicKey, + ed25519.Ed25519PublicKey, + ed448.Ed448PublicKey, + x25519.X25519PublicKey, + x448.X448PublicKey, +] +CERTIFICATE_PUBLIC_KEY_TYPES = CertificatePublicKeyTypes +utils.deprecated( + CERTIFICATE_PUBLIC_KEY_TYPES, + __name__, + "Use CertificatePublicKeyTypes instead", + utils.DeprecatedIn40, + name="CERTIFICATE_PUBLIC_KEY_TYPES", +) diff --git a/python/user_packages/Python313/site-packages/cryptography/hazmat/primitives/asymmetric/utils.py b/python/user_packages/Python313/site-packages/cryptography/hazmat/primitives/asymmetric/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..c01c34274be5356360c9c0e065bc32843f6a6e9d --- /dev/null +++ b/python/user_packages/Python313/site-packages/cryptography/hazmat/primitives/asymmetric/utils.py @@ -0,0 +1,28 @@ +# This file is dual licensed under the terms of the Apache License, Version +# 2.0, and the BSD License. See the LICENSE file in the root of this repository +# for complete details. + +from __future__ import annotations + +from cryptography.hazmat.bindings._rust import asn1 +from cryptography.hazmat.primitives import hashes + +decode_dss_signature = asn1.decode_dss_signature +encode_dss_signature = asn1.encode_dss_signature + + +class NoDigestInfo: + pass + + +class Prehashed: + def __init__(self, algorithm: hashes.HashAlgorithm): + if not isinstance(algorithm, hashes.HashAlgorithm): + raise TypeError("Expected instance of HashAlgorithm.") + + self._algorithm = algorithm + self._digest_size = algorithm.digest_size + + @property + def digest_size(self) -> int: + return self._digest_size diff --git a/python/user_packages/Python313/site-packages/cryptography/hazmat/primitives/asymmetric/x25519.py b/python/user_packages/Python313/site-packages/cryptography/hazmat/primitives/asymmetric/x25519.py new file mode 100644 index 0000000000000000000000000000000000000000..749899888f2bf6e7e875450fd76b0682a9a0e80e --- /dev/null +++ b/python/user_packages/Python313/site-packages/cryptography/hazmat/primitives/asymmetric/x25519.py @@ -0,0 +1,134 @@ +# This file is dual licensed under the terms of the Apache License, Version +# 2.0, and the BSD License. See the LICENSE file in the root of this repository +# for complete details. + +from __future__ import annotations + +import abc + +from cryptography.exceptions import UnsupportedAlgorithm, _Reasons +from cryptography.hazmat.bindings._rust import openssl as rust_openssl +from cryptography.hazmat.primitives import _serialization +from cryptography.utils import Buffer + + +class X25519PublicKey(metaclass=abc.ABCMeta): + @classmethod + def from_public_bytes(cls, data: bytes) -> X25519PublicKey: + from cryptography.hazmat.backends.openssl.backend import backend + + if not backend.x25519_supported(): + raise UnsupportedAlgorithm( + "X25519 is not supported by this version of OpenSSL.", + _Reasons.UNSUPPORTED_EXCHANGE_ALGORITHM, + ) + + return rust_openssl.x25519.from_public_bytes(data) + + @abc.abstractmethod + def public_bytes( + self, + encoding: _serialization.Encoding, + format: _serialization.PublicFormat, + ) -> bytes: + """ + The serialized bytes of the public key. + """ + + @abc.abstractmethod + def public_bytes_raw(self) -> bytes: + """ + The raw bytes of the public key. + Equivalent to public_bytes(Raw, Raw). + """ + + @abc.abstractmethod + def __eq__(self, other: object) -> bool: + """ + Checks equality. + """ + + @abc.abstractmethod + def __copy__(self) -> X25519PublicKey: + """ + Returns a copy. + """ + + @abc.abstractmethod + def __deepcopy__(self, memo: dict) -> X25519PublicKey: + """ + Returns a deep copy. + """ + + +X25519PublicKey.register(rust_openssl.x25519.X25519PublicKey) + + +class X25519PrivateKey(metaclass=abc.ABCMeta): + @classmethod + def generate(cls) -> X25519PrivateKey: + from cryptography.hazmat.backends.openssl.backend import backend + + if not backend.x25519_supported(): + raise UnsupportedAlgorithm( + "X25519 is not supported by this version of OpenSSL.", + _Reasons.UNSUPPORTED_EXCHANGE_ALGORITHM, + ) + return rust_openssl.x25519.generate_key() + + @classmethod + def from_private_bytes(cls, data: Buffer) -> X25519PrivateKey: + from cryptography.hazmat.backends.openssl.backend import backend + + if not backend.x25519_supported(): + raise UnsupportedAlgorithm( + "X25519 is not supported by this version of OpenSSL.", + _Reasons.UNSUPPORTED_EXCHANGE_ALGORITHM, + ) + + return rust_openssl.x25519.from_private_bytes(data) + + @abc.abstractmethod + def public_key(self) -> X25519PublicKey: + """ + Returns the public key associated with this private key + """ + + @abc.abstractmethod + def private_bytes( + self, + encoding: _serialization.Encoding, + format: _serialization.PrivateFormat, + encryption_algorithm: _serialization.KeySerializationEncryption, + ) -> bytes: + """ + The serialized bytes of the private key. + """ + + @abc.abstractmethod + def private_bytes_raw(self) -> bytes: + """ + The raw bytes of the private key. + Equivalent to private_bytes(Raw, Raw, NoEncryption()). + """ + + @abc.abstractmethod + def exchange(self, peer_public_key: X25519PublicKey) -> bytes: + """ + Performs a key exchange operation using the provided peer's public key. + """ + + @abc.abstractmethod + def __copy__(self) -> X25519PrivateKey: + """ + Returns a copy. + """ + + @abc.abstractmethod + def __deepcopy__(self, memo: dict) -> X25519PrivateKey: + """ + Returns a deep copy. + """ + + +X25519PrivateKey.register(rust_openssl.x25519.X25519PrivateKey) diff --git a/python/user_packages/Python313/site-packages/cryptography/hazmat/primitives/asymmetric/x448.py b/python/user_packages/Python313/site-packages/cryptography/hazmat/primitives/asymmetric/x448.py new file mode 100644 index 0000000000000000000000000000000000000000..b9dc8261a2f2fce4ed3482098817c40608665a84 --- /dev/null +++ b/python/user_packages/Python313/site-packages/cryptography/hazmat/primitives/asymmetric/x448.py @@ -0,0 +1,137 @@ +# This file is dual licensed under the terms of the Apache License, Version +# 2.0, and the BSD License. See the LICENSE file in the root of this repository +# for complete details. + +from __future__ import annotations + +import abc + +from cryptography.exceptions import UnsupportedAlgorithm, _Reasons +from cryptography.hazmat.bindings._rust import openssl as rust_openssl +from cryptography.hazmat.primitives import _serialization +from cryptography.utils import Buffer + + +class X448PublicKey(metaclass=abc.ABCMeta): + @classmethod + def from_public_bytes(cls, data: bytes) -> X448PublicKey: + from cryptography.hazmat.backends.openssl.backend import backend + + if not backend.x448_supported(): + raise UnsupportedAlgorithm( + "X448 is not supported by this version of OpenSSL.", + _Reasons.UNSUPPORTED_EXCHANGE_ALGORITHM, + ) + + return rust_openssl.x448.from_public_bytes(data) + + @abc.abstractmethod + def public_bytes( + self, + encoding: _serialization.Encoding, + format: _serialization.PublicFormat, + ) -> bytes: + """ + The serialized bytes of the public key. + """ + + @abc.abstractmethod + def public_bytes_raw(self) -> bytes: + """ + The raw bytes of the public key. + Equivalent to public_bytes(Raw, Raw). + """ + + @abc.abstractmethod + def __eq__(self, other: object) -> bool: + """ + Checks equality. + """ + + @abc.abstractmethod + def __copy__(self) -> X448PublicKey: + """ + Returns a copy. + """ + + @abc.abstractmethod + def __deepcopy__(self, memo: dict) -> X448PublicKey: + """ + Returns a deep copy. + """ + + +if hasattr(rust_openssl, "x448"): + X448PublicKey.register(rust_openssl.x448.X448PublicKey) + + +class X448PrivateKey(metaclass=abc.ABCMeta): + @classmethod + def generate(cls) -> X448PrivateKey: + from cryptography.hazmat.backends.openssl.backend import backend + + if not backend.x448_supported(): + raise UnsupportedAlgorithm( + "X448 is not supported by this version of OpenSSL.", + _Reasons.UNSUPPORTED_EXCHANGE_ALGORITHM, + ) + + return rust_openssl.x448.generate_key() + + @classmethod + def from_private_bytes(cls, data: Buffer) -> X448PrivateKey: + from cryptography.hazmat.backends.openssl.backend import backend + + if not backend.x448_supported(): + raise UnsupportedAlgorithm( + "X448 is not supported by this version of OpenSSL.", + _Reasons.UNSUPPORTED_EXCHANGE_ALGORITHM, + ) + + return rust_openssl.x448.from_private_bytes(data) + + @abc.abstractmethod + def public_key(self) -> X448PublicKey: + """ + Returns the public key associated with this private key + """ + + @abc.abstractmethod + def private_bytes( + self, + encoding: _serialization.Encoding, + format: _serialization.PrivateFormat, + encryption_algorithm: _serialization.KeySerializationEncryption, + ) -> bytes: + """ + The serialized bytes of the private key. + """ + + @abc.abstractmethod + def private_bytes_raw(self) -> bytes: + """ + The raw bytes of the private key. + Equivalent to private_bytes(Raw, Raw, NoEncryption()). + """ + + @abc.abstractmethod + def exchange(self, peer_public_key: X448PublicKey) -> bytes: + """ + Performs a key exchange operation using the provided peer's public key. + """ + + @abc.abstractmethod + def __copy__(self) -> X448PrivateKey: + """ + Returns a copy. + """ + + @abc.abstractmethod + def __deepcopy__(self, memo: dict) -> X448PrivateKey: + """ + Returns a deep copy. + """ + + +if hasattr(rust_openssl, "x448"): + X448PrivateKey.register(rust_openssl.x448.X448PrivateKey) diff --git a/python/user_packages/Python313/site-packages/cryptography/hazmat/primitives/ciphers/__init__.py b/python/user_packages/Python313/site-packages/cryptography/hazmat/primitives/ciphers/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..10c15d0f5cb36f19ce23b3a4255e92ef27998c9b --- /dev/null +++ b/python/user_packages/Python313/site-packages/cryptography/hazmat/primitives/ciphers/__init__.py @@ -0,0 +1,27 @@ +# This file is dual licensed under the terms of the Apache License, Version +# 2.0, and the BSD License. See the LICENSE file in the root of this repository +# for complete details. + +from __future__ import annotations + +from cryptography.hazmat.primitives._cipheralgorithm import ( + BlockCipherAlgorithm, + CipherAlgorithm, +) +from cryptography.hazmat.primitives.ciphers.base import ( + AEADCipherContext, + AEADDecryptionContext, + AEADEncryptionContext, + Cipher, + CipherContext, +) + +__all__ = [ + "AEADCipherContext", + "AEADDecryptionContext", + "AEADEncryptionContext", + "BlockCipherAlgorithm", + "Cipher", + "CipherAlgorithm", + "CipherContext", +] diff --git a/python/user_packages/Python313/site-packages/cryptography/hazmat/primitives/ciphers/__pycache__/__init__.cpython-313.pyc b/python/user_packages/Python313/site-packages/cryptography/hazmat/primitives/ciphers/__pycache__/__init__.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..dab73b7c2c8e01beaa0d0f5053d4f5c4c0db6e78 Binary files /dev/null and b/python/user_packages/Python313/site-packages/cryptography/hazmat/primitives/ciphers/__pycache__/__init__.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/cryptography/hazmat/primitives/ciphers/__pycache__/aead.cpython-313.pyc b/python/user_packages/Python313/site-packages/cryptography/hazmat/primitives/ciphers/__pycache__/aead.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ad30aa2d23c8fe1c0db60efc968bca4abd22634b Binary files /dev/null and b/python/user_packages/Python313/site-packages/cryptography/hazmat/primitives/ciphers/__pycache__/aead.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/cryptography/hazmat/primitives/ciphers/__pycache__/algorithms.cpython-313.pyc b/python/user_packages/Python313/site-packages/cryptography/hazmat/primitives/ciphers/__pycache__/algorithms.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9607b470b9ec582297e75538a00af12c40ed2824 Binary files /dev/null and b/python/user_packages/Python313/site-packages/cryptography/hazmat/primitives/ciphers/__pycache__/algorithms.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/cryptography/hazmat/primitives/ciphers/__pycache__/base.cpython-313.pyc b/python/user_packages/Python313/site-packages/cryptography/hazmat/primitives/ciphers/__pycache__/base.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..697987bb2832ab5631c0b8c2f4c759b3424aec5a Binary files /dev/null and b/python/user_packages/Python313/site-packages/cryptography/hazmat/primitives/ciphers/__pycache__/base.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/cryptography/hazmat/primitives/ciphers/__pycache__/modes.cpython-313.pyc b/python/user_packages/Python313/site-packages/cryptography/hazmat/primitives/ciphers/__pycache__/modes.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9e3629235418e43bbd367ebd3998a5d648dac462 Binary files /dev/null and b/python/user_packages/Python313/site-packages/cryptography/hazmat/primitives/ciphers/__pycache__/modes.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/cryptography/hazmat/primitives/ciphers/aead.py b/python/user_packages/Python313/site-packages/cryptography/hazmat/primitives/ciphers/aead.py new file mode 100644 index 0000000000000000000000000000000000000000..c8a582d7844ddf57670ba657b69b5ac1f20af1d1 --- /dev/null +++ b/python/user_packages/Python313/site-packages/cryptography/hazmat/primitives/ciphers/aead.py @@ -0,0 +1,23 @@ +# This file is dual licensed under the terms of the Apache License, Version +# 2.0, and the BSD License. See the LICENSE file in the root of this repository +# for complete details. + +from __future__ import annotations + +from cryptography.hazmat.bindings._rust import openssl as rust_openssl + +__all__ = [ + "AESCCM", + "AESGCM", + "AESGCMSIV", + "AESOCB3", + "AESSIV", + "ChaCha20Poly1305", +] + +AESGCM = rust_openssl.aead.AESGCM +ChaCha20Poly1305 = rust_openssl.aead.ChaCha20Poly1305 +AESCCM = rust_openssl.aead.AESCCM +AESSIV = rust_openssl.aead.AESSIV +AESOCB3 = rust_openssl.aead.AESOCB3 +AESGCMSIV = rust_openssl.aead.AESGCMSIV diff --git a/python/user_packages/Python313/site-packages/cryptography/hazmat/primitives/ciphers/algorithms.py b/python/user_packages/Python313/site-packages/cryptography/hazmat/primitives/ciphers/algorithms.py new file mode 100644 index 0000000000000000000000000000000000000000..6b20dd57eb428eef216d1d510c8052c48a25fe41 --- /dev/null +++ b/python/user_packages/Python313/site-packages/cryptography/hazmat/primitives/ciphers/algorithms.py @@ -0,0 +1,138 @@ +# This file is dual licensed under the terms of the Apache License, Version +# 2.0, and the BSD License. See the LICENSE file in the root of this repository +# for complete details. + +from __future__ import annotations + +from cryptography import utils +from cryptography.hazmat.decrepit.ciphers.algorithms import ( + ARC4 as ARC4, +) +from cryptography.hazmat.decrepit.ciphers.algorithms import ( + CAST5 as CAST5, +) +from cryptography.hazmat.decrepit.ciphers.algorithms import ( + IDEA as IDEA, +) +from cryptography.hazmat.decrepit.ciphers.algorithms import ( + SEED as SEED, +) +from cryptography.hazmat.decrepit.ciphers.algorithms import ( + Blowfish as Blowfish, +) +from cryptography.hazmat.decrepit.ciphers.algorithms import ( + Camellia as Camellia, +) +from cryptography.hazmat.decrepit.ciphers.algorithms import ( + TripleDES as TripleDES, +) +from cryptography.hazmat.primitives._cipheralgorithm import _verify_key_size +from cryptography.hazmat.primitives.ciphers import ( + BlockCipherAlgorithm, + CipherAlgorithm, +) + + +class AES(BlockCipherAlgorithm): + name = "AES" + block_size = 128 + # 512 added to support AES-256-XTS, which uses 512-bit keys + key_sizes = frozenset([128, 192, 256, 512]) + + def __init__(self, key: utils.Buffer): + self.key = _verify_key_size(self, key) + + @property + def key_size(self) -> int: + return len(self.key) * 8 + + +class AES128(BlockCipherAlgorithm): + name = "AES" + block_size = 128 + key_sizes = frozenset([128]) + key_size = 128 + + def __init__(self, key: utils.Buffer): + self.key = _verify_key_size(self, key) + + +class AES256(BlockCipherAlgorithm): + name = "AES" + block_size = 128 + key_sizes = frozenset([256]) + key_size = 256 + + def __init__(self, key: utils.Buffer): + self.key = _verify_key_size(self, key) + + +utils.deprecated( + Camellia, + __name__, + "Camellia has been moved to " + "cryptography.hazmat.decrepit.ciphers.algorithms.Camellia and " + "will be removed from " + "cryptography.hazmat.primitives.ciphers.algorithms in 49.0.0.", + utils.DeprecatedIn43, + name="Camellia", +) + + +utils.deprecated( + ARC4, + __name__, + "ARC4 has been moved to " + "cryptography.hazmat.decrepit.ciphers.algorithms.ARC4 and " + "will be removed from " + "cryptography.hazmat.primitives.ciphers.algorithms in 48.0.0.", + utils.DeprecatedIn43, + name="ARC4", +) + + +utils.deprecated( + TripleDES, + __name__, + "TripleDES has been moved to " + "cryptography.hazmat.decrepit.ciphers.algorithms.TripleDES and " + "will be removed from " + "cryptography.hazmat.primitives.ciphers.algorithms in 48.0.0.", + utils.DeprecatedIn43, + name="TripleDES", +) + + +class ChaCha20(CipherAlgorithm): + name = "ChaCha20" + key_sizes = frozenset([256]) + + def __init__(self, key: utils.Buffer, nonce: utils.Buffer): + self.key = _verify_key_size(self, key) + utils._check_byteslike("nonce", nonce) + + if len(nonce) != 16: + raise ValueError("nonce must be 128-bits (16 bytes)") + + self._nonce = nonce + + @property + def nonce(self) -> utils.Buffer: + return self._nonce + + @property + def key_size(self) -> int: + return len(self.key) * 8 + + +class SM4(BlockCipherAlgorithm): + name = "SM4" + block_size = 128 + key_sizes = frozenset([128]) + + def __init__(self, key: bytes): + self.key = _verify_key_size(self, key) + + @property + def key_size(self) -> int: + return len(self.key) * 8 diff --git a/python/user_packages/Python313/site-packages/cryptography/hazmat/primitives/ciphers/base.py b/python/user_packages/Python313/site-packages/cryptography/hazmat/primitives/ciphers/base.py new file mode 100644 index 0000000000000000000000000000000000000000..24fceea236cb0f385f4b8c8c8e2e5772d018681b --- /dev/null +++ b/python/user_packages/Python313/site-packages/cryptography/hazmat/primitives/ciphers/base.py @@ -0,0 +1,146 @@ +# This file is dual licensed under the terms of the Apache License, Version +# 2.0, and the BSD License. See the LICENSE file in the root of this repository +# for complete details. + +from __future__ import annotations + +import abc +import typing + +from cryptography.hazmat.bindings._rust import openssl as rust_openssl +from cryptography.hazmat.primitives._cipheralgorithm import CipherAlgorithm +from cryptography.hazmat.primitives.ciphers import modes +from cryptography.utils import Buffer + + +class CipherContext(metaclass=abc.ABCMeta): + @abc.abstractmethod + def update(self, data: Buffer) -> bytes: + """ + Processes the provided bytes through the cipher and returns the results + as bytes. + """ + + @abc.abstractmethod + def update_into(self, data: Buffer, buf: Buffer) -> int: + """ + Processes the provided bytes and writes the resulting data into the + provided buffer. Returns the number of bytes written. + """ + + @abc.abstractmethod + def finalize(self) -> bytes: + """ + Returns the results of processing the final block as bytes. + """ + + @abc.abstractmethod + def reset_nonce(self, nonce: bytes) -> None: + """ + Resets the nonce for the cipher context to the provided value. + Raises an exception if it does not support reset or if the + provided nonce does not have a valid length. + """ + + +class AEADCipherContext(CipherContext, metaclass=abc.ABCMeta): + @abc.abstractmethod + def authenticate_additional_data(self, data: Buffer) -> None: + """ + Authenticates the provided bytes. + """ + + +class AEADDecryptionContext(AEADCipherContext, metaclass=abc.ABCMeta): + @abc.abstractmethod + def finalize_with_tag(self, tag: bytes) -> bytes: + """ + Returns the results of processing the final block as bytes and allows + delayed passing of the authentication tag. + """ + + +class AEADEncryptionContext(AEADCipherContext, metaclass=abc.ABCMeta): + @property + @abc.abstractmethod + def tag(self) -> bytes: + """ + Returns tag bytes. This is only available after encryption is + finalized. + """ + + +Mode = typing.TypeVar( + "Mode", bound=typing.Optional[modes.Mode], covariant=True +) + + +class Cipher(typing.Generic[Mode]): + def __init__( + self, + algorithm: CipherAlgorithm, + mode: Mode, + backend: typing.Any = None, + ) -> None: + if not isinstance(algorithm, CipherAlgorithm): + raise TypeError("Expected interface of CipherAlgorithm.") + + if mode is not None: + # mypy needs this assert to narrow the type from our generic + # type. Maybe it won't some time in the future. + assert isinstance(mode, modes.Mode) + mode.validate_for_algorithm(algorithm) + + self.algorithm = algorithm + self.mode = mode + + @typing.overload + def encryptor( + self: Cipher[modes.ModeWithAuthenticationTag], + ) -> AEADEncryptionContext: ... + + @typing.overload + def encryptor( + self: _CIPHER_TYPE, + ) -> CipherContext: ... + + def encryptor(self): + if isinstance(self.mode, modes.ModeWithAuthenticationTag): + if self.mode.tag is not None: + raise ValueError( + "Authentication tag must be None when encrypting." + ) + + return rust_openssl.ciphers.create_encryption_ctx( + self.algorithm, self.mode + ) + + @typing.overload + def decryptor( + self: Cipher[modes.ModeWithAuthenticationTag], + ) -> AEADDecryptionContext: ... + + @typing.overload + def decryptor( + self: _CIPHER_TYPE, + ) -> CipherContext: ... + + def decryptor(self): + return rust_openssl.ciphers.create_decryption_ctx( + self.algorithm, self.mode + ) + + +_CIPHER_TYPE = Cipher[ + typing.Union[ + modes.ModeWithNonce, + modes.ModeWithTweak, + modes.ECB, + modes.ModeWithInitializationVector, + None, + ] +] + +CipherContext.register(rust_openssl.ciphers.CipherContext) +AEADEncryptionContext.register(rust_openssl.ciphers.AEADEncryptionContext) +AEADDecryptionContext.register(rust_openssl.ciphers.AEADDecryptionContext) diff --git a/python/user_packages/Python313/site-packages/cryptography/hazmat/primitives/ciphers/modes.py b/python/user_packages/Python313/site-packages/cryptography/hazmat/primitives/ciphers/modes.py new file mode 100644 index 0000000000000000000000000000000000000000..0f1c21799abda0ba3c445f1e0201dbca51731ef5 --- /dev/null +++ b/python/user_packages/Python313/site-packages/cryptography/hazmat/primitives/ciphers/modes.py @@ -0,0 +1,192 @@ +# This file is dual licensed under the terms of the Apache License, Version +# 2.0, and the BSD License. See the LICENSE file in the root of this repository +# for complete details. + +from __future__ import annotations + +from cryptography import utils +from cryptography.exceptions import UnsupportedAlgorithm, _Reasons +from cryptography.hazmat.decrepit.ciphers.modes import CFB as CFB +from cryptography.hazmat.decrepit.ciphers.modes import CFB8 as CFB8 +from cryptography.hazmat.decrepit.ciphers.modes import OFB as OFB +from cryptography.hazmat.primitives._cipheralgorithm import ( + BlockCipherAlgorithm, + CipherAlgorithm, +) +from cryptography.hazmat.primitives._modes import ( + Mode as Mode, +) +from cryptography.hazmat.primitives._modes import ( + ModeWithAuthenticationTag as ModeWithAuthenticationTag, +) +from cryptography.hazmat.primitives._modes import ( + ModeWithInitializationVector as ModeWithInitializationVector, +) +from cryptography.hazmat.primitives._modes import ( + ModeWithNonce as ModeWithNonce, +) +from cryptography.hazmat.primitives._modes import ( + ModeWithTweak as ModeWithTweak, +) +from cryptography.hazmat.primitives._modes import ( + _check_aes_key_length, + _check_iv_and_key_length, + _check_nonce_length, +) +from cryptography.hazmat.primitives.ciphers import algorithms + + +class CBC(ModeWithInitializationVector): + name = "CBC" + + def __init__(self, initialization_vector: utils.Buffer): + utils._check_byteslike("initialization_vector", initialization_vector) + self._initialization_vector = initialization_vector + + @property + def initialization_vector(self) -> utils.Buffer: + return self._initialization_vector + + validate_for_algorithm = _check_iv_and_key_length + + +class XTS(ModeWithTweak): + name = "XTS" + + def __init__(self, tweak: utils.Buffer): + utils._check_byteslike("tweak", tweak) + + if len(tweak) != 16: + raise ValueError("tweak must be 128-bits (16 bytes)") + + self._tweak = tweak + + @property + def tweak(self) -> utils.Buffer: + return self._tweak + + def validate_for_algorithm(self, algorithm: CipherAlgorithm) -> None: + if isinstance(algorithm, (algorithms.AES128, algorithms.AES256)): + raise TypeError( + "The AES128 and AES256 classes do not support XTS, please use " + "the standard AES class instead." + ) + + if algorithm.key_size not in (256, 512): + raise ValueError( + "The XTS specification requires a 256-bit key for AES-128-XTS" + " and 512-bit key for AES-256-XTS" + ) + + +class ECB(Mode): + name = "ECB" + + validate_for_algorithm = _check_aes_key_length + + +class CTR(ModeWithNonce): + name = "CTR" + + def __init__(self, nonce: utils.Buffer): + utils._check_byteslike("nonce", nonce) + self._nonce = nonce + + @property + def nonce(self) -> utils.Buffer: + return self._nonce + + def validate_for_algorithm(self, algorithm: CipherAlgorithm) -> None: + _check_aes_key_length(self, algorithm) + _check_nonce_length(self.nonce, self.name, algorithm) + + +class GCM(ModeWithInitializationVector, ModeWithAuthenticationTag): + name = "GCM" + _MAX_ENCRYPTED_BYTES = (2**39 - 256) // 8 + _MAX_AAD_BYTES = (2**64) // 8 + + def __init__( + self, + initialization_vector: utils.Buffer, + tag: bytes | None = None, + min_tag_length: int = 16, + ): + # OpenSSL 3.0.0 constrains GCM IVs to [64, 1024] bits inclusive + # This is a sane limit anyway so we'll enforce it here. + utils._check_byteslike("initialization_vector", initialization_vector) + if len(initialization_vector) < 8 or len(initialization_vector) > 128: + raise ValueError( + "initialization_vector must be between 8 and 128 bytes (64 " + "and 1024 bits)." + ) + self._initialization_vector = initialization_vector + if tag is not None: + utils._check_bytes("tag", tag) + if min_tag_length < 4: + raise ValueError("min_tag_length must be >= 4") + if len(tag) < min_tag_length: + raise ValueError( + f"Authentication tag must be {min_tag_length} bytes or " + "longer." + ) + self._tag = tag + self._min_tag_length = min_tag_length + + @property + def tag(self) -> bytes | None: + return self._tag + + @property + def initialization_vector(self) -> utils.Buffer: + return self._initialization_vector + + def validate_for_algorithm(self, algorithm: CipherAlgorithm) -> None: + _check_aes_key_length(self, algorithm) + if not isinstance(algorithm, BlockCipherAlgorithm): + raise UnsupportedAlgorithm( + "GCM requires a block cipher algorithm", + _Reasons.UNSUPPORTED_CIPHER, + ) + block_size_bytes = algorithm.block_size // 8 + if self._tag is not None and len(self._tag) > block_size_bytes: + raise ValueError( + f"Authentication tag cannot be more than {block_size_bytes} " + "bytes." + ) + + +utils.deprecated( + OFB, + __name__, + "OFB has been moved to " + "cryptography.hazmat.decrepit.ciphers.modes.OFB and " + "will be removed from " + "cryptography.hazmat.primitives.ciphers.modes in 49.0.0.", + utils.DeprecatedIn47, + name="OFB", +) + + +utils.deprecated( + CFB, + __name__, + "CFB has been moved to " + "cryptography.hazmat.decrepit.ciphers.modes.CFB and " + "will be removed from " + "cryptography.hazmat.primitives.ciphers.modes in 49.0.0.", + utils.DeprecatedIn47, + name="CFB", +) + + +utils.deprecated( + CFB8, + __name__, + "CFB8 has been moved to " + "cryptography.hazmat.decrepit.ciphers.modes.CFB8 and " + "will be removed from " + "cryptography.hazmat.primitives.ciphers.modes in 49.0.0.", + utils.DeprecatedIn47, + name="CFB8", +) diff --git a/python/user_packages/Python313/site-packages/cryptography/hazmat/primitives/cmac.py b/python/user_packages/Python313/site-packages/cryptography/hazmat/primitives/cmac.py new file mode 100644 index 0000000000000000000000000000000000000000..2c67ce2206e4c36c7ab8c4a49ba9d87f07529598 --- /dev/null +++ b/python/user_packages/Python313/site-packages/cryptography/hazmat/primitives/cmac.py @@ -0,0 +1,10 @@ +# This file is dual licensed under the terms of the Apache License, Version +# 2.0, and the BSD License. See the LICENSE file in the root of this repository +# for complete details. + +from __future__ import annotations + +from cryptography.hazmat.bindings._rust import openssl as rust_openssl + +__all__ = ["CMAC"] +CMAC = rust_openssl.cmac.CMAC diff --git a/python/user_packages/Python313/site-packages/cryptography/hazmat/primitives/constant_time.py b/python/user_packages/Python313/site-packages/cryptography/hazmat/primitives/constant_time.py new file mode 100644 index 0000000000000000000000000000000000000000..3975c7147eb92b56685423aa1c5810adcf253a23 --- /dev/null +++ b/python/user_packages/Python313/site-packages/cryptography/hazmat/primitives/constant_time.py @@ -0,0 +1,14 @@ +# This file is dual licensed under the terms of the Apache License, Version +# 2.0, and the BSD License. See the LICENSE file in the root of this repository +# for complete details. + +from __future__ import annotations + +import hmac + + +def bytes_eq(a: bytes, b: bytes) -> bool: + if not isinstance(a, bytes) or not isinstance(b, bytes): + raise TypeError("a and b must be bytes.") + + return hmac.compare_digest(a, b) diff --git a/python/user_packages/Python313/site-packages/cryptography/hazmat/primitives/hashes.py b/python/user_packages/Python313/site-packages/cryptography/hazmat/primitives/hashes.py new file mode 100644 index 0000000000000000000000000000000000000000..4b55ec33dbff64bb848c8633619bbbd36362936a --- /dev/null +++ b/python/user_packages/Python313/site-packages/cryptography/hazmat/primitives/hashes.py @@ -0,0 +1,246 @@ +# This file is dual licensed under the terms of the Apache License, Version +# 2.0, and the BSD License. See the LICENSE file in the root of this repository +# for complete details. + +from __future__ import annotations + +import abc + +from cryptography.hazmat.bindings._rust import openssl as rust_openssl +from cryptography.utils import Buffer + +__all__ = [ + "MD5", + "SHA1", + "SHA3_224", + "SHA3_256", + "SHA3_384", + "SHA3_512", + "SHA224", + "SHA256", + "SHA384", + "SHA512", + "SHA512_224", + "SHA512_256", + "SHAKE128", + "SHAKE256", + "SM3", + "BLAKE2b", + "BLAKE2s", + "ExtendableOutputFunction", + "Hash", + "HashAlgorithm", + "HashContext", + "XOFHash", +] + + +class HashAlgorithm(metaclass=abc.ABCMeta): + @property + @abc.abstractmethod + def name(self) -> str: + """ + A string naming this algorithm (e.g. "sha256", "md5"). + """ + + @property + @abc.abstractmethod + def digest_size(self) -> int: + """ + The size of the resulting digest in bytes. + """ + + @property + @abc.abstractmethod + def block_size(self) -> int | None: + """ + The internal block size of the hash function, or None if the hash + function does not use blocks internally (e.g. SHA3). + """ + + +class HashContext(metaclass=abc.ABCMeta): + @property + @abc.abstractmethod + def algorithm(self) -> HashAlgorithm: + """ + A HashAlgorithm that will be used by this context. + """ + + @abc.abstractmethod + def update(self, data: Buffer) -> None: + """ + Processes the provided bytes through the hash. + """ + + @abc.abstractmethod + def finalize(self) -> bytes: + """ + Finalizes the hash context and returns the hash digest as bytes. + """ + + @abc.abstractmethod + def copy(self) -> HashContext: + """ + Return a HashContext that is a copy of the current context. + """ + + +Hash = rust_openssl.hashes.Hash +HashContext.register(Hash) + +XOFHash = rust_openssl.hashes.XOFHash + + +class ExtendableOutputFunction(metaclass=abc.ABCMeta): + """ + An interface for extendable output functions. + """ + + +class SHA1(HashAlgorithm): + name = "sha1" + digest_size = 20 + block_size = 64 + + +class SHA512_224(HashAlgorithm): # noqa: N801 + name = "sha512-224" + digest_size = 28 + block_size = 128 + + +class SHA512_256(HashAlgorithm): # noqa: N801 + name = "sha512-256" + digest_size = 32 + block_size = 128 + + +class SHA224(HashAlgorithm): + name = "sha224" + digest_size = 28 + block_size = 64 + + +class SHA256(HashAlgorithm): + name = "sha256" + digest_size = 32 + block_size = 64 + + +class SHA384(HashAlgorithm): + name = "sha384" + digest_size = 48 + block_size = 128 + + +class SHA512(HashAlgorithm): + name = "sha512" + digest_size = 64 + block_size = 128 + + +class SHA3_224(HashAlgorithm): # noqa: N801 + name = "sha3-224" + digest_size = 28 + block_size = None + + +class SHA3_256(HashAlgorithm): # noqa: N801 + name = "sha3-256" + digest_size = 32 + block_size = None + + +class SHA3_384(HashAlgorithm): # noqa: N801 + name = "sha3-384" + digest_size = 48 + block_size = None + + +class SHA3_512(HashAlgorithm): # noqa: N801 + name = "sha3-512" + digest_size = 64 + block_size = None + + +class SHAKE128(HashAlgorithm, ExtendableOutputFunction): + name = "shake128" + block_size = None + + def __init__(self, digest_size: int): + if not isinstance(digest_size, int): + raise TypeError("digest_size must be an integer") + + if digest_size < 1: + raise ValueError("digest_size must be a positive integer") + + self._digest_size = digest_size + + @property + def digest_size(self) -> int: + return self._digest_size + + +class SHAKE256(HashAlgorithm, ExtendableOutputFunction): + name = "shake256" + block_size = None + + def __init__(self, digest_size: int): + if not isinstance(digest_size, int): + raise TypeError("digest_size must be an integer") + + if digest_size < 1: + raise ValueError("digest_size must be a positive integer") + + self._digest_size = digest_size + + @property + def digest_size(self) -> int: + return self._digest_size + + +class MD5(HashAlgorithm): + name = "md5" + digest_size = 16 + block_size = 64 + + +class BLAKE2b(HashAlgorithm): + name = "blake2b" + _max_digest_size = 64 + _min_digest_size = 1 + block_size = 128 + + def __init__(self, digest_size: int): + if digest_size != 64: + raise ValueError("Digest size must be 64") + + self._digest_size = digest_size + + @property + def digest_size(self) -> int: + return self._digest_size + + +class BLAKE2s(HashAlgorithm): + name = "blake2s" + block_size = 64 + _max_digest_size = 32 + _min_digest_size = 1 + + def __init__(self, digest_size: int): + if digest_size != 32: + raise ValueError("Digest size must be 32") + + self._digest_size = digest_size + + @property + def digest_size(self) -> int: + return self._digest_size + + +class SM3(HashAlgorithm): + name = "sm3" + digest_size = 32 + block_size = 64 diff --git a/python/user_packages/Python313/site-packages/cryptography/hazmat/primitives/hmac.py b/python/user_packages/Python313/site-packages/cryptography/hazmat/primitives/hmac.py new file mode 100644 index 0000000000000000000000000000000000000000..a9442d59ab474ac680ff7253f2ca0e67d0e93c1a --- /dev/null +++ b/python/user_packages/Python313/site-packages/cryptography/hazmat/primitives/hmac.py @@ -0,0 +1,13 @@ +# This file is dual licensed under the terms of the Apache License, Version +# 2.0, and the BSD License. See the LICENSE file in the root of this repository +# for complete details. + +from __future__ import annotations + +from cryptography.hazmat.bindings._rust import openssl as rust_openssl +from cryptography.hazmat.primitives import hashes + +__all__ = ["HMAC"] + +HMAC = rust_openssl.hmac.HMAC +hashes.HashContext.register(HMAC) diff --git a/python/user_packages/Python313/site-packages/cryptography/hazmat/primitives/hpke.py b/python/user_packages/Python313/site-packages/cryptography/hazmat/primitives/hpke.py new file mode 100644 index 0000000000000000000000000000000000000000..c80280881f551ba79b5e3b922352431a2da809be --- /dev/null +++ b/python/user_packages/Python313/site-packages/cryptography/hazmat/primitives/hpke.py @@ -0,0 +1,27 @@ +# This file is dual licensed under the terms of the Apache License, Version +# 2.0, and the BSD License. See the LICENSE file in the root of this repository +# for complete details. + +from __future__ import annotations + +from cryptography.hazmat.bindings._rust import openssl as rust_openssl + +AEAD = rust_openssl.hpke.AEAD +KDF = rust_openssl.hpke.KDF +KEM = rust_openssl.hpke.KEM +MLKEM768X25519PrivateKey = rust_openssl.hpke.MLKEM768X25519PrivateKey +MLKEM768X25519PublicKey = rust_openssl.hpke.MLKEM768X25519PublicKey +MLKEM1024P384PrivateKey = rust_openssl.hpke.MLKEM1024P384PrivateKey +MLKEM1024P384PublicKey = rust_openssl.hpke.MLKEM1024P384PublicKey +Suite = rust_openssl.hpke.Suite + +__all__ = [ + "AEAD", + "KDF", + "KEM", + "MLKEM768X25519PrivateKey", + "MLKEM768X25519PublicKey", + "MLKEM1024P384PrivateKey", + "MLKEM1024P384PublicKey", + "Suite", +] diff --git a/python/user_packages/Python313/site-packages/cryptography/hazmat/primitives/kdf/__init__.py b/python/user_packages/Python313/site-packages/cryptography/hazmat/primitives/kdf/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..26c45bd78f18f0b47085737f6b4fde460d5165e0 --- /dev/null +++ b/python/user_packages/Python313/site-packages/cryptography/hazmat/primitives/kdf/__init__.py @@ -0,0 +1,32 @@ +# This file is dual licensed under the terms of the Apache License, Version +# 2.0, and the BSD License. See the LICENSE file in the root of this repository +# for complete details. + +from __future__ import annotations + +import abc + +from cryptography.utils import Buffer + + +class KeyDerivationFunction(metaclass=abc.ABCMeta): + @abc.abstractmethod + def derive(self, key_material: bytes) -> bytes: + """ + Deterministically generates and returns a new key based on the existing + key material. + """ + + @abc.abstractmethod + def derive_into(self, key_material: bytes, buffer: Buffer) -> None: + """ + Deterministically generates a new key based on the existing key + material and stores it in the provided buffer. + """ + + @abc.abstractmethod + def verify(self, key_material: bytes, expected_key: bytes) -> None: + """ + Checks whether the key generated by the key material matches the + expected derived key. Raises an exception if they do not match. + """ diff --git a/python/user_packages/Python313/site-packages/cryptography/hazmat/primitives/kdf/__pycache__/__init__.cpython-313.pyc b/python/user_packages/Python313/site-packages/cryptography/hazmat/primitives/kdf/__pycache__/__init__.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..057838ef366c8424dda200a32fc189435ffbcb8f Binary files /dev/null and b/python/user_packages/Python313/site-packages/cryptography/hazmat/primitives/kdf/__pycache__/__init__.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/cryptography/hazmat/primitives/kdf/__pycache__/argon2.cpython-313.pyc b/python/user_packages/Python313/site-packages/cryptography/hazmat/primitives/kdf/__pycache__/argon2.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..42e779d85ef86f203c24a487f1cf95cb0effb880 Binary files /dev/null and b/python/user_packages/Python313/site-packages/cryptography/hazmat/primitives/kdf/__pycache__/argon2.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/cryptography/hazmat/primitives/kdf/__pycache__/concatkdf.cpython-313.pyc b/python/user_packages/Python313/site-packages/cryptography/hazmat/primitives/kdf/__pycache__/concatkdf.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e0e34d939c96871cb2d3569416413a08bdb842e7 Binary files /dev/null and b/python/user_packages/Python313/site-packages/cryptography/hazmat/primitives/kdf/__pycache__/concatkdf.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/cryptography/hazmat/primitives/kdf/__pycache__/hkdf.cpython-313.pyc b/python/user_packages/Python313/site-packages/cryptography/hazmat/primitives/kdf/__pycache__/hkdf.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2d730c8cc1002d0e7e77524f591087d7ec656355 Binary files /dev/null and b/python/user_packages/Python313/site-packages/cryptography/hazmat/primitives/kdf/__pycache__/hkdf.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/cryptography/hazmat/primitives/kdf/__pycache__/kbkdf.cpython-313.pyc b/python/user_packages/Python313/site-packages/cryptography/hazmat/primitives/kdf/__pycache__/kbkdf.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3bd954536df7d4c8f4bd4501fffcfaf66ced2008 Binary files /dev/null and b/python/user_packages/Python313/site-packages/cryptography/hazmat/primitives/kdf/__pycache__/kbkdf.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/cryptography/hazmat/primitives/kdf/__pycache__/pbkdf2.cpython-313.pyc b/python/user_packages/Python313/site-packages/cryptography/hazmat/primitives/kdf/__pycache__/pbkdf2.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..fdc21d5b32facb2c80f8cec0ba6f03f92eea8893 Binary files /dev/null and b/python/user_packages/Python313/site-packages/cryptography/hazmat/primitives/kdf/__pycache__/pbkdf2.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/cryptography/hazmat/primitives/kdf/__pycache__/scrypt.cpython-313.pyc b/python/user_packages/Python313/site-packages/cryptography/hazmat/primitives/kdf/__pycache__/scrypt.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..dfd2e20dcb6a5cf023225fe8cb01b23d3031bd0a Binary files /dev/null and b/python/user_packages/Python313/site-packages/cryptography/hazmat/primitives/kdf/__pycache__/scrypt.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/cryptography/hazmat/primitives/kdf/__pycache__/x963kdf.cpython-313.pyc b/python/user_packages/Python313/site-packages/cryptography/hazmat/primitives/kdf/__pycache__/x963kdf.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..700a2d706da60e0a282ee213cb23983e87088b2e Binary files /dev/null and b/python/user_packages/Python313/site-packages/cryptography/hazmat/primitives/kdf/__pycache__/x963kdf.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/cryptography/hazmat/primitives/kdf/argon2.py b/python/user_packages/Python313/site-packages/cryptography/hazmat/primitives/kdf/argon2.py new file mode 100644 index 0000000000000000000000000000000000000000..03e84d48ad41beb77c7be38a6d867535c79d35fd --- /dev/null +++ b/python/user_packages/Python313/site-packages/cryptography/hazmat/primitives/kdf/argon2.py @@ -0,0 +1,17 @@ +# This file is dual licensed under the terms of the Apache License, Version +# 2.0, and the BSD License. See the LICENSE file in the root of this repository +# for complete details. + +from __future__ import annotations + +from cryptography.hazmat.bindings._rust import openssl as rust_openssl +from cryptography.hazmat.primitives.kdf import KeyDerivationFunction + +Argon2d = rust_openssl.kdf.Argon2d +Argon2i = rust_openssl.kdf.Argon2i +Argon2id = rust_openssl.kdf.Argon2id +KeyDerivationFunction.register(Argon2d) +KeyDerivationFunction.register(Argon2i) +KeyDerivationFunction.register(Argon2id) + +__all__ = ["Argon2d", "Argon2i", "Argon2id"] diff --git a/python/user_packages/Python313/site-packages/cryptography/hazmat/primitives/kdf/concatkdf.py b/python/user_packages/Python313/site-packages/cryptography/hazmat/primitives/kdf/concatkdf.py new file mode 100644 index 0000000000000000000000000000000000000000..398dc5dc55c39a3c428d37c96ca1ad74a52a89c1 --- /dev/null +++ b/python/user_packages/Python313/site-packages/cryptography/hazmat/primitives/kdf/concatkdf.py @@ -0,0 +1,16 @@ +# This file is dual licensed under the terms of the Apache License, Version +# 2.0, and the BSD License. See the LICENSE file in the root of this repository +# for complete details. + +from __future__ import annotations + +from cryptography.hazmat.bindings._rust import openssl as rust_openssl +from cryptography.hazmat.primitives.kdf import KeyDerivationFunction + +ConcatKDFHash = rust_openssl.kdf.ConcatKDFHash +ConcatKDFHMAC = rust_openssl.kdf.ConcatKDFHMAC + +KeyDerivationFunction.register(ConcatKDFHash) +KeyDerivationFunction.register(ConcatKDFHMAC) + +__all__ = ["ConcatKDFHMAC", "ConcatKDFHash"] diff --git a/python/user_packages/Python313/site-packages/cryptography/hazmat/primitives/kdf/hkdf.py b/python/user_packages/Python313/site-packages/cryptography/hazmat/primitives/kdf/hkdf.py new file mode 100644 index 0000000000000000000000000000000000000000..1e162d9dee0ddb5f2d61a4421e5984933ae63a70 --- /dev/null +++ b/python/user_packages/Python313/site-packages/cryptography/hazmat/primitives/kdf/hkdf.py @@ -0,0 +1,16 @@ +# This file is dual licensed under the terms of the Apache License, Version +# 2.0, and the BSD License. See the LICENSE file in the root of this repository +# for complete details. + +from __future__ import annotations + +from cryptography.hazmat.bindings._rust import openssl as rust_openssl +from cryptography.hazmat.primitives.kdf import KeyDerivationFunction + +HKDF = rust_openssl.kdf.HKDF +HKDFExpand = rust_openssl.kdf.HKDFExpand + +KeyDerivationFunction.register(HKDF) +KeyDerivationFunction.register(HKDFExpand) + +__all__ = ["HKDF", "HKDFExpand"] diff --git a/python/user_packages/Python313/site-packages/cryptography/hazmat/primitives/kdf/kbkdf.py b/python/user_packages/Python313/site-packages/cryptography/hazmat/primitives/kdf/kbkdf.py new file mode 100644 index 0000000000000000000000000000000000000000..e559df8fbd17640478cbf6f632824cb74d66db77 --- /dev/null +++ b/python/user_packages/Python313/site-packages/cryptography/hazmat/primitives/kdf/kbkdf.py @@ -0,0 +1,26 @@ +# This file is dual licensed under the terms of the Apache License, Version +# 2.0, and the BSD License. See the LICENSE file in the root of this repository +# for complete details. + +from __future__ import annotations + +from cryptography import utils +from cryptography.hazmat.bindings._rust import openssl as rust_openssl +from cryptography.hazmat.primitives.kdf import KeyDerivationFunction + + +class Mode(utils.Enum): + CounterMode = "ctr" + + +class CounterLocation(utils.Enum): + BeforeFixed = "before_fixed" + AfterFixed = "after_fixed" + MiddleFixed = "middle_fixed" + + +KBKDFHMAC = rust_openssl.kdf.KBKDFHMAC +KeyDerivationFunction.register(KBKDFHMAC) + +KBKDFCMAC = rust_openssl.kdf.KBKDFCMAC +KeyDerivationFunction.register(KBKDFCMAC) diff --git a/python/user_packages/Python313/site-packages/cryptography/hazmat/primitives/kdf/pbkdf2.py b/python/user_packages/Python313/site-packages/cryptography/hazmat/primitives/kdf/pbkdf2.py new file mode 100644 index 0000000000000000000000000000000000000000..771d80d4a25edd23563b5a51703f6e97dab02752 --- /dev/null +++ b/python/user_packages/Python313/site-packages/cryptography/hazmat/primitives/kdf/pbkdf2.py @@ -0,0 +1,13 @@ +# This file is dual licensed under the terms of the Apache License, Version +# 2.0, and the BSD License. See the LICENSE file in the root of this repository +# for complete details. + +from __future__ import annotations + +from cryptography.hazmat.bindings._rust import openssl as rust_openssl +from cryptography.hazmat.primitives.kdf import KeyDerivationFunction + +PBKDF2HMAC = rust_openssl.kdf.PBKDF2HMAC +KeyDerivationFunction.register(PBKDF2HMAC) + +__all__ = ["PBKDF2HMAC"] diff --git a/python/user_packages/Python313/site-packages/cryptography/hazmat/primitives/kdf/scrypt.py b/python/user_packages/Python313/site-packages/cryptography/hazmat/primitives/kdf/scrypt.py new file mode 100644 index 0000000000000000000000000000000000000000..f791ceea371b11c0d873ff031cf3bd653cb1b2b8 --- /dev/null +++ b/python/user_packages/Python313/site-packages/cryptography/hazmat/primitives/kdf/scrypt.py @@ -0,0 +1,19 @@ +# This file is dual licensed under the terms of the Apache License, Version +# 2.0, and the BSD License. See the LICENSE file in the root of this repository +# for complete details. + +from __future__ import annotations + +import sys + +from cryptography.hazmat.bindings._rust import openssl as rust_openssl +from cryptography.hazmat.primitives.kdf import KeyDerivationFunction + +# This is used by the scrypt tests to skip tests that require more memory +# than the MEM_LIMIT +_MEM_LIMIT = sys.maxsize // 2 + +Scrypt = rust_openssl.kdf.Scrypt +KeyDerivationFunction.register(Scrypt) + +__all__ = ["Scrypt"] diff --git a/python/user_packages/Python313/site-packages/cryptography/hazmat/primitives/kdf/x963kdf.py b/python/user_packages/Python313/site-packages/cryptography/hazmat/primitives/kdf/x963kdf.py new file mode 100644 index 0000000000000000000000000000000000000000..8c4e2d31ddf68ec90801f871afb9b0fe9b74888b --- /dev/null +++ b/python/user_packages/Python313/site-packages/cryptography/hazmat/primitives/kdf/x963kdf.py @@ -0,0 +1,13 @@ +# This file is dual licensed under the terms of the Apache License, Version +# 2.0, and the BSD License. See the LICENSE file in the root of this repository +# for complete details. + +from __future__ import annotations + +from cryptography.hazmat.bindings._rust import openssl as rust_openssl +from cryptography.hazmat.primitives.kdf import KeyDerivationFunction + +X963KDF = rust_openssl.kdf.X963KDF +KeyDerivationFunction.register(X963KDF) + +__all__ = ["X963KDF"] diff --git a/python/user_packages/Python313/site-packages/cryptography/hazmat/primitives/keywrap.py b/python/user_packages/Python313/site-packages/cryptography/hazmat/primitives/keywrap.py new file mode 100644 index 0000000000000000000000000000000000000000..a3e56b958512ca34ad9440d92bec92ee24d3113e --- /dev/null +++ b/python/user_packages/Python313/site-packages/cryptography/hazmat/primitives/keywrap.py @@ -0,0 +1,180 @@ +# This file is dual licensed under the terms of the Apache License, Version +# 2.0, and the BSD License. See the LICENSE file in the root of this repository +# for complete details. + +from __future__ import annotations + +import typing + +from cryptography.hazmat.primitives.ciphers import Cipher +from cryptography.hazmat.primitives.ciphers.algorithms import AES +from cryptography.hazmat.primitives.ciphers.modes import ECB +from cryptography.hazmat.primitives.constant_time import bytes_eq + + +def _wrap_core( + wrapping_key: bytes, + a: bytes, + r: list[bytes], +) -> bytes: + # RFC 3394 Key Wrap - 2.2.1 (index method) + encryptor = Cipher(AES(wrapping_key), ECB()).encryptor() + n = len(r) + for j in range(6): + for i in range(n): + # every encryption operation is a discrete 16 byte chunk (because + # AES has a 128-bit block size) and since we're using ECB it is + # safe to reuse the encryptor for the entire operation + b = encryptor.update(a + r[i]) + a = ( + int.from_bytes(b[:8], byteorder="big") ^ ((n * j) + i + 1) + ).to_bytes(length=8, byteorder="big") + r[i] = b[-8:] + + assert encryptor.finalize() == b"" + + return a + b"".join(r) + + +def aes_key_wrap( + wrapping_key: bytes, + key_to_wrap: bytes, + backend: typing.Any = None, +) -> bytes: + if len(wrapping_key) not in [16, 24, 32]: + raise ValueError("The wrapping key must be a valid AES key length") + + if len(key_to_wrap) < 16: + raise ValueError("The key to wrap must be at least 16 bytes") + + if len(key_to_wrap) % 8 != 0: + raise ValueError("The key to wrap must be a multiple of 8 bytes") + + a = b"\xa6\xa6\xa6\xa6\xa6\xa6\xa6\xa6" + r = [key_to_wrap[i : i + 8] for i in range(0, len(key_to_wrap), 8)] + return _wrap_core(wrapping_key, a, r) + + +def _unwrap_core( + wrapping_key: bytes, + a: bytes, + r: list[bytes], +) -> tuple[bytes, list[bytes]]: + # Implement RFC 3394 Key Unwrap - 2.2.2 (index method) + decryptor = Cipher(AES(wrapping_key), ECB()).decryptor() + n = len(r) + for j in reversed(range(6)): + for i in reversed(range(n)): + atr = ( + int.from_bytes(a, byteorder="big") ^ ((n * j) + i + 1) + ).to_bytes(length=8, byteorder="big") + r[i] + # every decryption operation is a discrete 16 byte chunk so + # it is safe to reuse the decryptor for the entire operation + b = decryptor.update(atr) + a = b[:8] + r[i] = b[-8:] + + assert decryptor.finalize() == b"" + return a, r + + +def aes_key_wrap_with_padding( + wrapping_key: bytes, + key_to_wrap: bytes, + backend: typing.Any = None, +) -> bytes: + if len(wrapping_key) not in [16, 24, 32]: + raise ValueError("The wrapping key must be a valid AES key length") + + if not key_to_wrap or len(key_to_wrap) > 2**32: + raise ValueError("key_to_wrap must be between 1 and 2^32 bytes") + + aiv = b"\xa6\x59\x59\xa6" + len(key_to_wrap).to_bytes( + length=4, byteorder="big" + ) + # pad the key to wrap if necessary + pad = (8 - (len(key_to_wrap) % 8)) % 8 + key_to_wrap = key_to_wrap + b"\x00" * pad + if len(key_to_wrap) == 8: + # RFC 5649 - 4.1 - exactly 8 octets after padding + encryptor = Cipher(AES(wrapping_key), ECB()).encryptor() + b = encryptor.update(aiv + key_to_wrap) + assert encryptor.finalize() == b"" + return b + else: + r = [key_to_wrap[i : i + 8] for i in range(0, len(key_to_wrap), 8)] + return _wrap_core(wrapping_key, aiv, r) + + +def aes_key_unwrap_with_padding( + wrapping_key: bytes, + wrapped_key: bytes, + backend: typing.Any = None, +) -> bytes: + if len(wrapped_key) < 16: + raise InvalidUnwrap("Must be at least 16 bytes") + + if len(wrapping_key) not in [16, 24, 32]: + raise ValueError("The wrapping key must be a valid AES key length") + + if len(wrapped_key) == 16: + # RFC 5649 - 4.2 - exactly two 64-bit blocks + decryptor = Cipher(AES(wrapping_key), ECB()).decryptor() + out = decryptor.update(wrapped_key) + assert decryptor.finalize() == b"" + a = out[:8] + data = out[8:] + n = 1 + else: + r = [wrapped_key[i : i + 8] for i in range(0, len(wrapped_key), 8)] + encrypted_aiv = r.pop(0) + n = len(r) + a, r = _unwrap_core(wrapping_key, encrypted_aiv, r) + data = b"".join(r) + + # 1) Check that MSB(32,A) = A65959A6. + # 2) Check that 8*(n-1) < LSB(32,A) <= 8*n. If so, let + # MLI = LSB(32,A). + # 3) Let b = (8*n)-MLI, and then check that the rightmost b octets of + # the output data are zero. + mli = int.from_bytes(a[4:], byteorder="big") + b = (8 * n) - mli + if ( + not bytes_eq(a[:4], b"\xa6\x59\x59\xa6") + or not 8 * (n - 1) < mli <= 8 * n + or (b != 0 and not bytes_eq(data[-b:], b"\x00" * b)) + ): + raise InvalidUnwrap() + + if b == 0: + return data + else: + return data[:-b] + + +def aes_key_unwrap( + wrapping_key: bytes, + wrapped_key: bytes, + backend: typing.Any = None, +) -> bytes: + if len(wrapped_key) < 24: + raise InvalidUnwrap("Must be at least 24 bytes") + + if len(wrapped_key) % 8 != 0: + raise InvalidUnwrap("The wrapped key must be a multiple of 8 bytes") + + if len(wrapping_key) not in [16, 24, 32]: + raise ValueError("The wrapping key must be a valid AES key length") + + aiv = b"\xa6\xa6\xa6\xa6\xa6\xa6\xa6\xa6" + r = [wrapped_key[i : i + 8] for i in range(0, len(wrapped_key), 8)] + a = r.pop(0) + a, r = _unwrap_core(wrapping_key, a, r) + if not bytes_eq(a, aiv): + raise InvalidUnwrap() + + return b"".join(r) + + +class InvalidUnwrap(Exception): + pass diff --git a/python/user_packages/Python313/site-packages/cryptography/hazmat/primitives/padding.py b/python/user_packages/Python313/site-packages/cryptography/hazmat/primitives/padding.py new file mode 100644 index 0000000000000000000000000000000000000000..f9cd1f13c469beec5512d58b3de6ee1ced4362d5 --- /dev/null +++ b/python/user_packages/Python313/site-packages/cryptography/hazmat/primitives/padding.py @@ -0,0 +1,69 @@ +# This file is dual licensed under the terms of the Apache License, Version +# 2.0, and the BSD License. See the LICENSE file in the root of this repository +# for complete details. + +from __future__ import annotations + +import abc + +from cryptography import utils +from cryptography.hazmat.bindings._rust import ( + ANSIX923PaddingContext, + ANSIX923UnpaddingContext, + PKCS7PaddingContext, + PKCS7UnpaddingContext, +) + + +class PaddingContext(metaclass=abc.ABCMeta): + @abc.abstractmethod + def update(self, data: utils.Buffer) -> bytes: + """ + Pads the provided bytes and returns any available data as bytes. + """ + + @abc.abstractmethod + def finalize(self) -> bytes: + """ + Finalize the padding, returns bytes. + """ + + +def _byte_padding_check(block_size: int) -> None: + if not (0 <= block_size <= 2040): + raise ValueError("block_size must be in range(0, 2041).") + + if block_size % 8 != 0: + raise ValueError("block_size must be a multiple of 8.") + + +class PKCS7: + def __init__(self, block_size: int): + _byte_padding_check(block_size) + self.block_size = block_size + + def padder(self) -> PaddingContext: + return PKCS7PaddingContext(self.block_size) + + def unpadder(self) -> PaddingContext: + return PKCS7UnpaddingContext(self.block_size) + + +PaddingContext.register(PKCS7PaddingContext) +PaddingContext.register(PKCS7UnpaddingContext) + + +class ANSIX923: + def __init__(self, block_size: int): + _byte_padding_check(block_size) + self.block_size = block_size + + def padder(self) -> PaddingContext: + return ANSIX923PaddingContext(self.block_size) + + def unpadder(self) -> PaddingContext: + return ANSIX923UnpaddingContext(self.block_size) + + +PaddingContext.register(ANSIX923PaddingContext) +PaddingContext.register(ANSIX923UnpaddingContext) diff --git a/python/user_packages/Python313/site-packages/cryptography/hazmat/primitives/poly1305.py b/python/user_packages/Python313/site-packages/cryptography/hazmat/primitives/poly1305.py new file mode 100644 index 0000000000000000000000000000000000000000..7f5a77a576fd258a9a634ae3c3365fc3f7d4702a --- /dev/null +++ b/python/user_packages/Python313/site-packages/cryptography/hazmat/primitives/poly1305.py @@ -0,0 +1,11 @@ +# This file is dual licensed under the terms of the Apache License, Version +# 2.0, and the BSD License. See the LICENSE file in the root of this repository +# for complete details. + +from __future__ import annotations + +from cryptography.hazmat.bindings._rust import openssl as rust_openssl + +__all__ = ["Poly1305"] + +Poly1305 = rust_openssl.poly1305.Poly1305 diff --git a/python/user_packages/Python313/site-packages/cryptography/hazmat/primitives/serialization/__init__.py b/python/user_packages/Python313/site-packages/cryptography/hazmat/primitives/serialization/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..62283cc70fd6bb7d29da3dd67773761a56e86f10 --- /dev/null +++ b/python/user_packages/Python313/site-packages/cryptography/hazmat/primitives/serialization/__init__.py @@ -0,0 +1,65 @@ +# This file is dual licensed under the terms of the Apache License, Version +# 2.0, and the BSD License. See the LICENSE file in the root of this repository +# for complete details. + +from __future__ import annotations + +from cryptography.hazmat.primitives._serialization import ( + BestAvailableEncryption, + Encoding, + KeySerializationEncryption, + NoEncryption, + ParameterFormat, + PrivateFormat, + PublicFormat, + _KeySerializationEncryption, +) +from cryptography.hazmat.primitives.serialization.base import ( + load_der_parameters, + load_der_private_key, + load_der_public_key, + load_pem_parameters, + load_pem_private_key, + load_pem_public_key, +) +from cryptography.hazmat.primitives.serialization.ssh import ( + SSHCertificate, + SSHCertificateBuilder, + SSHCertificateType, + SSHCertPrivateKeyTypes, + SSHCertPublicKeyTypes, + SSHPrivateKeyTypes, + SSHPublicKeyTypes, + load_ssh_private_key, + load_ssh_public_identity, + load_ssh_public_key, + ssh_key_fingerprint, +) + +__all__ = [ + "BestAvailableEncryption", + "Encoding", + "KeySerializationEncryption", + "NoEncryption", + "ParameterFormat", + "PrivateFormat", + "PublicFormat", + "SSHCertPrivateKeyTypes", + "SSHCertPublicKeyTypes", + "SSHCertificate", + "SSHCertificateBuilder", + "SSHCertificateType", + "SSHPrivateKeyTypes", + "SSHPublicKeyTypes", + "_KeySerializationEncryption", + "load_der_parameters", + "load_der_private_key", + "load_der_public_key", + "load_pem_parameters", + "load_pem_private_key", + "load_pem_public_key", + "load_ssh_private_key", + "load_ssh_public_identity", + "load_ssh_public_key", + "ssh_key_fingerprint", +] diff --git a/python/user_packages/Python313/site-packages/cryptography/hazmat/primitives/serialization/__pycache__/__init__.cpython-313.pyc b/python/user_packages/Python313/site-packages/cryptography/hazmat/primitives/serialization/__pycache__/__init__.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..00f4cff5b8f57631136a23da6e3d97cf9dfa6ca6 Binary files /dev/null and b/python/user_packages/Python313/site-packages/cryptography/hazmat/primitives/serialization/__pycache__/__init__.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/cryptography/hazmat/primitives/serialization/__pycache__/base.cpython-313.pyc b/python/user_packages/Python313/site-packages/cryptography/hazmat/primitives/serialization/__pycache__/base.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8bf9a6e8a869d117030dfa4a3d7d84b735fa0515 Binary files /dev/null and b/python/user_packages/Python313/site-packages/cryptography/hazmat/primitives/serialization/__pycache__/base.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/cryptography/hazmat/primitives/serialization/__pycache__/pkcs12.cpython-313.pyc b/python/user_packages/Python313/site-packages/cryptography/hazmat/primitives/serialization/__pycache__/pkcs12.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a77d5394a10d1b72be922711cf676a9ac6e5474a Binary files /dev/null and b/python/user_packages/Python313/site-packages/cryptography/hazmat/primitives/serialization/__pycache__/pkcs12.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/cryptography/hazmat/primitives/serialization/__pycache__/pkcs7.cpython-313.pyc b/python/user_packages/Python313/site-packages/cryptography/hazmat/primitives/serialization/__pycache__/pkcs7.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..dbde81dcc5d3a443a7f5171d10579a3ef3f2a83e Binary files /dev/null and b/python/user_packages/Python313/site-packages/cryptography/hazmat/primitives/serialization/__pycache__/pkcs7.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/cryptography/hazmat/primitives/serialization/__pycache__/ssh.cpython-313.pyc b/python/user_packages/Python313/site-packages/cryptography/hazmat/primitives/serialization/__pycache__/ssh.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..74532dc8cf005a14d2ef168c936b751873d34708 Binary files /dev/null and b/python/user_packages/Python313/site-packages/cryptography/hazmat/primitives/serialization/__pycache__/ssh.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/cryptography/hazmat/primitives/serialization/base.py b/python/user_packages/Python313/site-packages/cryptography/hazmat/primitives/serialization/base.py new file mode 100644 index 0000000000000000000000000000000000000000..e7c998b7f35b3e364909348f0516f51cf902ebfe --- /dev/null +++ b/python/user_packages/Python313/site-packages/cryptography/hazmat/primitives/serialization/base.py @@ -0,0 +1,14 @@ +# This file is dual licensed under the terms of the Apache License, Version +# 2.0, and the BSD License. See the LICENSE file in the root of this repository +# for complete details. + +from cryptography.hazmat.bindings._rust import openssl as rust_openssl + +load_pem_private_key = rust_openssl.keys.load_pem_private_key +load_der_private_key = rust_openssl.keys.load_der_private_key + +load_pem_public_key = rust_openssl.keys.load_pem_public_key +load_der_public_key = rust_openssl.keys.load_der_public_key + +load_pem_parameters = rust_openssl.dh.from_pem_parameters +load_der_parameters = rust_openssl.dh.from_der_parameters diff --git a/python/user_packages/Python313/site-packages/cryptography/hazmat/primitives/serialization/pkcs12.py b/python/user_packages/Python313/site-packages/cryptography/hazmat/primitives/serialization/pkcs12.py new file mode 100644 index 0000000000000000000000000000000000000000..58884ff61a79e50afe2df7ed134c33d447d02998 --- /dev/null +++ b/python/user_packages/Python313/site-packages/cryptography/hazmat/primitives/serialization/pkcs12.py @@ -0,0 +1,176 @@ +# This file is dual licensed under the terms of the Apache License, Version +# 2.0, and the BSD License. See the LICENSE file in the root of this repository +# for complete details. + +from __future__ import annotations + +import typing +from collections.abc import Iterable + +from cryptography import x509 +from cryptography.hazmat.bindings._rust import pkcs12 as rust_pkcs12 +from cryptography.hazmat.primitives import serialization +from cryptography.hazmat.primitives._serialization import PBES as PBES +from cryptography.hazmat.primitives.asymmetric import ( + dsa, + ec, + ed448, + ed25519, + rsa, +) +from cryptography.hazmat.primitives.asymmetric.types import PrivateKeyTypes + +__all__ = [ + "PBES", + "PKCS12Certificate", + "PKCS12KeyAndCertificates", + "PKCS12PrivateKeyTypes", + "load_key_and_certificates", + "load_pkcs12", + "serialize_java_truststore", + "serialize_key_and_certificates", +] + +PKCS12PrivateKeyTypes = typing.Union[ + rsa.RSAPrivateKey, + dsa.DSAPrivateKey, + ec.EllipticCurvePrivateKey, + ed25519.Ed25519PrivateKey, + ed448.Ed448PrivateKey, +] + + +PKCS12Certificate = rust_pkcs12.PKCS12Certificate + + +class PKCS12KeyAndCertificates: + def __init__( + self, + key: PrivateKeyTypes | None, + cert: PKCS12Certificate | None, + additional_certs: list[PKCS12Certificate], + ): + if key is not None and not isinstance( + key, + ( + rsa.RSAPrivateKey, + dsa.DSAPrivateKey, + ec.EllipticCurvePrivateKey, + ed25519.Ed25519PrivateKey, + ed448.Ed448PrivateKey, + ), + ): + raise TypeError( + "Key must be RSA, DSA, EllipticCurve, ED25519, or ED448" + " private key, or None." + ) + if cert is not None and not isinstance(cert, PKCS12Certificate): + raise TypeError("cert must be a PKCS12Certificate object or None") + if not all( + isinstance(add_cert, PKCS12Certificate) + for add_cert in additional_certs + ): + raise TypeError( + "all values in additional_certs must be PKCS12Certificate" + " objects" + ) + self._key = key + self._cert = cert + self._additional_certs = additional_certs + + @property + def key(self) -> PrivateKeyTypes | None: + return self._key + + @property + def cert(self) -> PKCS12Certificate | None: + return self._cert + + @property + def additional_certs(self) -> list[PKCS12Certificate]: + return self._additional_certs + + def __eq__(self, other: object) -> bool: + if not isinstance(other, PKCS12KeyAndCertificates): + return NotImplemented + + return ( + self.key == other.key + and self.cert == other.cert + and self.additional_certs == other.additional_certs + ) + + def __hash__(self) -> int: + return hash((self.key, self.cert, tuple(self.additional_certs))) + + def __repr__(self) -> str: + fmt = ( + "" + ) + return fmt.format(self.key, self.cert, self.additional_certs) + + +load_key_and_certificates = rust_pkcs12.load_key_and_certificates +load_pkcs12 = rust_pkcs12.load_pkcs12 + + +_PKCS12CATypes = typing.Union[ + x509.Certificate, + PKCS12Certificate, +] + + +def serialize_java_truststore( + certs: Iterable[PKCS12Certificate], + encryption_algorithm: serialization.KeySerializationEncryption, +) -> bytes: + if not certs: + raise ValueError("You must supply at least one cert") + + if not isinstance( + encryption_algorithm, serialization.KeySerializationEncryption + ): + raise TypeError( + "Key encryption algorithm must be a " + "KeySerializationEncryption instance" + ) + + return rust_pkcs12.serialize_java_truststore(certs, encryption_algorithm) + + +def serialize_key_and_certificates( + name: bytes | None, + key: PKCS12PrivateKeyTypes | None, + cert: x509.Certificate | None, + cas: Iterable[_PKCS12CATypes] | None, + encryption_algorithm: serialization.KeySerializationEncryption, +) -> bytes: + if key is not None and not isinstance( + key, + ( + rsa.RSAPrivateKey, + dsa.DSAPrivateKey, + ec.EllipticCurvePrivateKey, + ed25519.Ed25519PrivateKey, + ed448.Ed448PrivateKey, + ), + ): + raise TypeError( + "Key must be RSA, DSA, EllipticCurve, ED25519, or ED448" + " private key, or None." + ) + + if not isinstance( + encryption_algorithm, serialization.KeySerializationEncryption + ): + raise TypeError( + "Key encryption algorithm must be a " + "KeySerializationEncryption instance" + ) + + if key is None and cert is None and not cas: + raise ValueError("You must supply at least one of key, cert, or cas") + + return rust_pkcs12.serialize_key_and_certificates( + name, key, cert, cas, encryption_algorithm + ) diff --git a/python/user_packages/Python313/site-packages/cryptography/hazmat/primitives/serialization/pkcs7.py b/python/user_packages/Python313/site-packages/cryptography/hazmat/primitives/serialization/pkcs7.py new file mode 100644 index 0000000000000000000000000000000000000000..76b667a22a47fc0e2dc932519e9fa1d23a3bc7bf --- /dev/null +++ b/python/user_packages/Python313/site-packages/cryptography/hazmat/primitives/serialization/pkcs7.py @@ -0,0 +1,412 @@ +# This file is dual licensed under the terms of the Apache License, Version +# 2.0, and the BSD License. See the LICENSE file in the root of this repository +# for complete details. + +from __future__ import annotations + +import email.base64mime +import email.generator +import email.message +import email.policy +import io +import typing +from collections.abc import Iterable + +from cryptography import utils, x509 +from cryptography.exceptions import UnsupportedAlgorithm, _Reasons +from cryptography.hazmat.bindings._rust import pkcs7 as rust_pkcs7 +from cryptography.hazmat.primitives import hashes, serialization +from cryptography.hazmat.primitives.asymmetric import ec, padding, rsa +from cryptography.hazmat.primitives.ciphers import ( + algorithms, +) +from cryptography.utils import _check_byteslike + +load_pem_pkcs7_certificates = rust_pkcs7.load_pem_pkcs7_certificates + +load_der_pkcs7_certificates = rust_pkcs7.load_der_pkcs7_certificates + +serialize_certificates = rust_pkcs7.serialize_certificates + +PKCS7HashTypes = typing.Union[ + hashes.SHA224, + hashes.SHA256, + hashes.SHA384, + hashes.SHA512, +] + +PKCS7PrivateKeyTypes = typing.Union[ + rsa.RSAPrivateKey, ec.EllipticCurvePrivateKey +] + +ContentEncryptionAlgorithm = typing.Union[ + type[algorithms.AES128], type[algorithms.AES256] +] + + +class PKCS7Options(utils.Enum): + Text = "Add text/plain MIME type" + Binary = "Don't translate input data into canonical MIME format" + DetachedSignature = "Don't embed data in the PKCS7 structure" + NoCapabilities = "Don't embed SMIME capabilities" + NoAttributes = "Don't embed authenticatedAttributes" + NoCerts = "Don't embed signer certificate" + + +class PKCS7SignatureBuilder: + def __init__( + self, + data: utils.Buffer | None = None, + signers: list[ + tuple[ + x509.Certificate, + PKCS7PrivateKeyTypes, + PKCS7HashTypes, + padding.PSS | padding.PKCS1v15 | None, + ] + ] = [], + additional_certs: list[x509.Certificate] = [], + ): + self._data = data + self._signers = signers + self._additional_certs = additional_certs + + def set_data(self, data: utils.Buffer) -> PKCS7SignatureBuilder: + _check_byteslike("data", data) + if self._data is not None: + raise ValueError("data may only be set once") + + return PKCS7SignatureBuilder(data, self._signers) + + def add_signer( + self, + certificate: x509.Certificate, + private_key: PKCS7PrivateKeyTypes, + hash_algorithm: PKCS7HashTypes, + *, + rsa_padding: padding.PSS | padding.PKCS1v15 | None = None, + ) -> PKCS7SignatureBuilder: + if not isinstance( + hash_algorithm, + ( + hashes.SHA224, + hashes.SHA256, + hashes.SHA384, + hashes.SHA512, + ), + ): + raise TypeError( + "hash_algorithm must be one of hashes.SHA224, " + "SHA256, SHA384, or SHA512" + ) + if not isinstance(certificate, x509.Certificate): + raise TypeError("certificate must be a x509.Certificate") + + if not isinstance( + private_key, (rsa.RSAPrivateKey, ec.EllipticCurvePrivateKey) + ): + raise TypeError("Only RSA & EC keys are supported at this time.") + + if rsa_padding is not None: + if not isinstance(rsa_padding, (padding.PSS, padding.PKCS1v15)): + raise TypeError("Padding must be PSS or PKCS1v15") + if not isinstance(private_key, rsa.RSAPrivateKey): + raise TypeError("Padding is only supported for RSA keys") + + return PKCS7SignatureBuilder( + self._data, + [ + *self._signers, + (certificate, private_key, hash_algorithm, rsa_padding), + ], + ) + + def add_certificate( + self, certificate: x509.Certificate + ) -> PKCS7SignatureBuilder: + if not isinstance(certificate, x509.Certificate): + raise TypeError("certificate must be a x509.Certificate") + + return PKCS7SignatureBuilder( + self._data, self._signers, [*self._additional_certs, certificate] + ) + + def sign( + self, + encoding: serialization.Encoding, + options: Iterable[PKCS7Options], + backend: typing.Any = None, + ) -> bytes: + if len(self._signers) == 0: + raise ValueError("Must have at least one signer") + if self._data is None: + raise ValueError("You must add data to sign") + options = list(options) + if not all(isinstance(x, PKCS7Options) for x in options): + raise ValueError("options must be from the PKCS7Options enum") + if encoding not in ( + serialization.Encoding.PEM, + serialization.Encoding.DER, + serialization.Encoding.SMIME, + ): + raise ValueError( + "Must be PEM, DER, or SMIME from the Encoding enum" + ) + + # Text is a meaningless option unless it is accompanied by + # DetachedSignature + if ( + PKCS7Options.Text in options + and PKCS7Options.DetachedSignature not in options + ): + raise ValueError( + "When passing the Text option you must also pass " + "DetachedSignature" + ) + + if PKCS7Options.Text in options and encoding in ( + serialization.Encoding.DER, + serialization.Encoding.PEM, + ): + raise ValueError( + "The Text option is only available for SMIME serialization" + ) + + # No attributes implies no capabilities so we'll error if you try to + # pass both. + if ( + PKCS7Options.NoAttributes in options + and PKCS7Options.NoCapabilities in options + ): + raise ValueError( + "NoAttributes is a superset of NoCapabilities. Do not pass " + "both values." + ) + + return rust_pkcs7.sign_and_serialize(self, encoding, options) + + +class PKCS7EnvelopeBuilder: + def __init__( + self, + *, + _data: bytes | None = None, + _recipients: list[x509.Certificate] | None = None, + _content_encryption_algorithm: ContentEncryptionAlgorithm + | None = None, + ): + from cryptography.hazmat.backends.openssl.backend import ( + backend as ossl, + ) + + if not ossl.rsa_encryption_supported(padding=padding.PKCS1v15()): + raise UnsupportedAlgorithm( + "RSA with PKCS1 v1.5 padding is not supported by this version" + " of OpenSSL.", + _Reasons.UNSUPPORTED_PADDING, + ) + self._data = _data + self._recipients = _recipients if _recipients is not None else [] + self._content_encryption_algorithm = _content_encryption_algorithm + + def set_data(self, data: bytes) -> PKCS7EnvelopeBuilder: + _check_byteslike("data", data) + if self._data is not None: + raise ValueError("data may only be set once") + + return PKCS7EnvelopeBuilder( + _data=data, + _recipients=self._recipients, + _content_encryption_algorithm=self._content_encryption_algorithm, + ) + + def add_recipient( + self, + certificate: x509.Certificate, + ) -> PKCS7EnvelopeBuilder: + if not isinstance(certificate, x509.Certificate): + raise TypeError("certificate must be a x509.Certificate") + + if not isinstance(certificate.public_key(), rsa.RSAPublicKey): + raise TypeError("Only RSA keys are supported at this time.") + + return PKCS7EnvelopeBuilder( + _data=self._data, + _recipients=[ + *self._recipients, + certificate, + ], + _content_encryption_algorithm=self._content_encryption_algorithm, + ) + + def set_content_encryption_algorithm( + self, content_encryption_algorithm: ContentEncryptionAlgorithm + ) -> PKCS7EnvelopeBuilder: + if self._content_encryption_algorithm is not None: + raise ValueError("Content encryption algo may only be set once") + if content_encryption_algorithm not in { + algorithms.AES128, + algorithms.AES256, + }: + raise TypeError("Only AES128 and AES256 are supported") + + return PKCS7EnvelopeBuilder( + _data=self._data, + _recipients=self._recipients, + _content_encryption_algorithm=content_encryption_algorithm, + ) + + def encrypt( + self, + encoding: serialization.Encoding, + options: Iterable[PKCS7Options], + ) -> bytes: + if len(self._recipients) == 0: + raise ValueError("Must have at least one recipient") + if self._data is None: + raise ValueError("You must add data to encrypt") + + # The default content encryption algorithm is AES-128-CBC, which the + # S/MIME v3.2 RFC specifies as MUST support (https://datatracker.ietf.org/doc/html/rfc5751#section-2.7) + # however rest of S/MIME v3.2 is not currently supported + content_encryption_algorithm = ( + self._content_encryption_algorithm or algorithms.AES128 + ) + + options = list(options) + if not all(isinstance(x, PKCS7Options) for x in options): + raise ValueError("options must be from the PKCS7Options enum") + if encoding not in ( + serialization.Encoding.PEM, + serialization.Encoding.DER, + serialization.Encoding.SMIME, + ): + raise ValueError( + "Must be PEM, DER, or SMIME from the Encoding enum" + ) + + # Only allow options that make sense for encryption + if any( + opt not in [PKCS7Options.Text, PKCS7Options.Binary] + for opt in options + ): + raise ValueError( + "Only the following options are supported for encryption: " + "Text, Binary" + ) + elif PKCS7Options.Text in options and PKCS7Options.Binary in options: + # OpenSSL accepts both options at the same time, but ignores Text. + # We fail defensively to avoid unexpected outputs. + raise ValueError( + "Cannot use Binary and Text options at the same time" + ) + + return rust_pkcs7.encrypt_and_serialize( + self, content_encryption_algorithm, encoding, options + ) + + +pkcs7_decrypt_der = rust_pkcs7.decrypt_der +pkcs7_decrypt_pem = rust_pkcs7.decrypt_pem +pkcs7_decrypt_smime = rust_pkcs7.decrypt_smime + + +def _smime_signed_encode( + data: bytes, signature: bytes, micalg: str, text_mode: bool +) -> bytes: + # This function works pretty hard to replicate what OpenSSL does + # precisely. For good and for ill. + + m = email.message.Message() + m.add_header("MIME-Version", "1.0") + m.add_header( + "Content-Type", + "multipart/signed", + protocol="application/x-pkcs7-signature", + micalg=micalg, + ) + + m.preamble = "This is an S/MIME signed message\n" + + msg_part = OpenSSLMimePart() + msg_part.set_payload(data) + if text_mode: + msg_part.add_header("Content-Type", "text/plain") + m.attach(msg_part) + + sig_part = email.message.MIMEPart() + sig_part.add_header( + "Content-Type", "application/x-pkcs7-signature", name="smime.p7s" + ) + sig_part.add_header("Content-Transfer-Encoding", "base64") + sig_part.add_header( + "Content-Disposition", "attachment", filename="smime.p7s" + ) + sig_part.set_payload( + email.base64mime.body_encode(signature, maxlinelen=65) + ) + del sig_part["MIME-Version"] + m.attach(sig_part) + + fp = io.BytesIO() + g = email.generator.BytesGenerator( + fp, + maxheaderlen=0, + mangle_from_=False, + policy=m.policy.clone(linesep="\r\n"), + ) + g.flatten(m) + return fp.getvalue() + + +def _smime_enveloped_encode(data: bytes) -> bytes: + m = email.message.Message() + m.add_header("MIME-Version", "1.0") + m.add_header("Content-Disposition", "attachment", filename="smime.p7m") + m.add_header( + "Content-Type", + "application/pkcs7-mime", + smime_type="enveloped-data", + name="smime.p7m", + ) + m.add_header("Content-Transfer-Encoding", "base64") + + m.set_payload(email.base64mime.body_encode(data, maxlinelen=65)) + + return m.as_bytes(policy=m.policy.clone(linesep="\n", max_line_length=0)) + + +def _smime_enveloped_decode(data: bytes) -> bytes: + m = email.message_from_bytes(data) + if m.get_content_type() not in { + "application/x-pkcs7-mime", + "application/pkcs7-mime", + }: + raise ValueError("Not an S/MIME enveloped message") + return bytes(m.get_payload(decode=True)) + + +def _smime_remove_text_headers(data: bytes) -> bytes: + m = email.message_from_bytes(data) + # Using get() instead of get_content_type() since it has None as default, + # where the latter has "text/plain". Both methods are case-insensitive. + content_type = m.get("content-type") + if content_type is None: + raise ValueError( + "Decrypted MIME data has no 'Content-Type' header. " + "Please remove the 'Text' option to parse it manually." + ) + if "text/plain" not in content_type: + raise ValueError( + f"Decrypted MIME data content type is '{content_type}', not " + "'text/plain'. Remove the 'Text' option to parse it manually." + ) + return bytes(m.get_payload(decode=True)) + + +class OpenSSLMimePart(email.message.MIMEPart): + # A MIMEPart subclass that replicates OpenSSL's behavior of not including + # a newline if there are no headers. + def _write_headers(self, generator) -> None: + if list(self.raw_items()): + generator._write_headers(self) diff --git a/python/user_packages/Python313/site-packages/cryptography/hazmat/primitives/serialization/ssh.py b/python/user_packages/Python313/site-packages/cryptography/hazmat/primitives/serialization/ssh.py new file mode 100644 index 0000000000000000000000000000000000000000..411113bc42bfc51f2f4ecfb19146e781734708ca --- /dev/null +++ b/python/user_packages/Python313/site-packages/cryptography/hazmat/primitives/serialization/ssh.py @@ -0,0 +1,1621 @@ +# This file is dual licensed under the terms of the Apache License, Version +# 2.0, and the BSD License. See the LICENSE file in the root of this repository +# for complete details. + +from __future__ import annotations + +import binascii +import enum +import os +import re +import typing +import warnings +from base64 import encodebytes as _base64_encode +from dataclasses import dataclass + +from cryptography import utils +from cryptography.exceptions import UnsupportedAlgorithm +from cryptography.hazmat.primitives import hashes +from cryptography.hazmat.primitives.asymmetric import ( + dsa, + ec, + ed25519, + padding, + rsa, +) +from cryptography.hazmat.primitives.asymmetric import utils as asym_utils +from cryptography.hazmat.primitives.ciphers import ( + AEADDecryptionContext, + Cipher, + algorithms, + modes, +) +from cryptography.hazmat.primitives.serialization import ( + Encoding, + KeySerializationEncryption, + NoEncryption, + PrivateFormat, + PublicFormat, + _KeySerializationEncryption, +) + +try: + from bcrypt import kdf as _bcrypt_kdf + + _bcrypt_supported = True +except ImportError: + _bcrypt_supported = False + + def _bcrypt_kdf( + password: bytes, + salt: bytes, + desired_key_bytes: int, + rounds: int, + ignore_few_rounds: bool = False, + ) -> bytes: + raise UnsupportedAlgorithm("Need bcrypt module") + + +_SSH_ED25519 = b"ssh-ed25519" +_SSH_RSA = b"ssh-rsa" +_SSH_DSA = b"ssh-dss" +_ECDSA_NISTP256 = b"ecdsa-sha2-nistp256" +_ECDSA_NISTP384 = b"ecdsa-sha2-nistp384" +_ECDSA_NISTP521 = b"ecdsa-sha2-nistp521" +_CERT_SUFFIX = b"-cert-v01@openssh.com" + +# U2F application string suffixed pubkey +_SK_SSH_ED25519 = b"sk-ssh-ed25519@openssh.com" +_SK_SSH_ECDSA_NISTP256 = b"sk-ecdsa-sha2-nistp256@openssh.com" + +# These are not key types, only algorithms, so they cannot appear +# as a public key type +_SSH_RSA_SHA256 = b"rsa-sha2-256" +_SSH_RSA_SHA512 = b"rsa-sha2-512" + +_SSH_PUBKEY_RC = re.compile(rb"\A(\S+)[ \t]+(\S+)") +_SK_MAGIC = b"openssh-key-v1\0" +_SK_START = b"-----BEGIN OPENSSH PRIVATE KEY-----" +_SK_END = b"-----END OPENSSH PRIVATE KEY-----" +_BCRYPT = b"bcrypt" +_NONE = b"none" +_DEFAULT_CIPHER = b"aes256-ctr" +_DEFAULT_ROUNDS = 16 + +# re is only way to work on bytes-like data +_PEM_RC = re.compile(_SK_START + b"(.*?)" + _SK_END, re.DOTALL) + +# padding for max blocksize +_PADDING = memoryview(bytearray(range(1, 1 + 16))) + + +@dataclass +class _SSHCipher: + alg: type[algorithms.AES] + key_len: int + mode: type[modes.CTR] | type[modes.CBC] | type[modes.GCM] + block_len: int + iv_len: int + tag_len: int | None + is_aead: bool + + +# ciphers that are actually used in key wrapping +_SSH_CIPHERS: dict[bytes, _SSHCipher] = { + b"aes256-ctr": _SSHCipher( + alg=algorithms.AES, + key_len=32, + mode=modes.CTR, + block_len=16, + iv_len=16, + tag_len=None, + is_aead=False, + ), + b"aes256-cbc": _SSHCipher( + alg=algorithms.AES, + key_len=32, + mode=modes.CBC, + block_len=16, + iv_len=16, + tag_len=None, + is_aead=False, + ), + b"aes256-gcm@openssh.com": _SSHCipher( + alg=algorithms.AES, + key_len=32, + mode=modes.GCM, + block_len=16, + iv_len=12, + tag_len=16, + is_aead=True, + ), +} + +# map local curve name to key type +_ECDSA_KEY_TYPE = { + "secp256r1": _ECDSA_NISTP256, + "secp384r1": _ECDSA_NISTP384, + "secp521r1": _ECDSA_NISTP521, +} + + +def _get_ssh_key_type(key: SSHPrivateKeyTypes | SSHPublicKeyTypes) -> bytes: + if isinstance(key, ec.EllipticCurvePrivateKey): + key_type = _ecdsa_key_type(key.public_key()) + elif isinstance(key, ec.EllipticCurvePublicKey): + key_type = _ecdsa_key_type(key) + elif isinstance(key, (rsa.RSAPrivateKey, rsa.RSAPublicKey)): + key_type = _SSH_RSA + elif isinstance(key, (dsa.DSAPrivateKey, dsa.DSAPublicKey)): + key_type = _SSH_DSA + elif isinstance( + key, (ed25519.Ed25519PrivateKey, ed25519.Ed25519PublicKey) + ): + key_type = _SSH_ED25519 + else: + raise ValueError("Unsupported key type") + + return key_type + + +def _ecdsa_key_type(public_key: ec.EllipticCurvePublicKey) -> bytes: + """Return SSH key_type and curve_name for private key.""" + curve = public_key.curve + if curve.name not in _ECDSA_KEY_TYPE: + raise ValueError( + f"Unsupported curve for ssh private key: {curve.name!r}" + ) + return _ECDSA_KEY_TYPE[curve.name] + + +def _ssh_pem_encode( + data: utils.Buffer, + prefix: bytes = _SK_START + b"\n", + suffix: bytes = _SK_END + b"\n", +) -> bytes: + return b"".join([prefix, _base64_encode(data), suffix]) + + +def _check_block_size(data: utils.Buffer, block_len: int) -> None: + """Require data to be full blocks""" + if not data or len(data) % block_len != 0: + raise ValueError("Corrupt data: missing padding") + + +def _check_empty(data: utils.Buffer) -> None: + """All data should have been parsed.""" + if data: + raise ValueError("Corrupt data: unparsed data") + + +def _init_cipher( + ciphername: bytes, + password: bytes | None, + salt: bytes, + rounds: int, +) -> Cipher[modes.CBC | modes.CTR | modes.GCM]: + """Generate key + iv and return cipher.""" + if not password: + raise TypeError( + "Key is password-protected, but password was not provided." + ) + + ciph = _SSH_CIPHERS[ciphername] + seed = _bcrypt_kdf( + password, salt, ciph.key_len + ciph.iv_len, rounds, True + ) + return Cipher( + ciph.alg(seed[: ciph.key_len]), + ciph.mode(seed[ciph.key_len :]), + ) + + +def _get_u32(data: memoryview) -> tuple[int, memoryview]: + """Uint32""" + if len(data) < 4: + raise ValueError("Invalid data") + return int.from_bytes(data[:4], byteorder="big"), data[4:] + + +def _get_u64(data: memoryview) -> tuple[int, memoryview]: + """Uint64""" + if len(data) < 8: + raise ValueError("Invalid data") + return int.from_bytes(data[:8], byteorder="big"), data[8:] + + +def _get_sshstr(data: memoryview) -> tuple[memoryview, memoryview]: + """Bytes with u32 length prefix""" + n, data = _get_u32(data) + if n > len(data): + raise ValueError("Invalid data") + return data[:n], data[n:] + + +def _get_mpint(data: memoryview) -> tuple[int, memoryview]: + """Big integer.""" + val, data = _get_sshstr(data) + if val and val[0] > 0x7F: + raise ValueError("Invalid data") + return int.from_bytes(val, "big"), data + + +def _to_mpint(val: int) -> bytes: + """Storage format for signed bigint.""" + if val < 0: + raise ValueError("negative mpint not allowed") + if not val: + return b"" + nbytes = (val.bit_length() + 8) // 8 + return utils.int_to_bytes(val, nbytes) + + +class _FragList: + """Build recursive structure without data copy.""" + + flist: list[utils.Buffer] + + def __init__(self, init: list[utils.Buffer] | None = None) -> None: + self.flist = [] + if init: + self.flist.extend(init) + + def put_raw(self, val: utils.Buffer) -> None: + """Add plain bytes""" + self.flist.append(val) + + def put_u32(self, val: int) -> None: + """Big-endian uint32""" + self.flist.append(val.to_bytes(length=4, byteorder="big")) + + def put_u64(self, val: int) -> None: + """Big-endian uint64""" + self.flist.append(val.to_bytes(length=8, byteorder="big")) + + def put_sshstr(self, val: bytes | _FragList) -> None: + """Bytes prefixed with u32 length""" + if isinstance(val, (bytes, memoryview, bytearray)): + self.put_u32(len(val)) + self.flist.append(val) + else: + self.put_u32(val.size()) + self.flist.extend(val.flist) + + def put_mpint(self, val: int) -> None: + """Big-endian bigint prefixed with u32 length""" + self.put_sshstr(_to_mpint(val)) + + def size(self) -> int: + """Current number of bytes""" + return sum(map(len, self.flist)) + + def render(self, dstbuf: memoryview, pos: int = 0) -> int: + """Write into bytearray""" + for frag in self.flist: + flen = len(frag) + start, pos = pos, pos + flen + dstbuf[start:pos] = frag + return pos + + def tobytes(self) -> bytes: + """Return as bytes""" + buf = memoryview(bytearray(self.size())) + self.render(buf) + return buf.tobytes() + + +class _SSHFormatRSA: + """Format for RSA keys. + + Public: + mpint e, n + Private: + mpint n, e, d, iqmp, p, q + """ + + def get_public( + self, data: memoryview + ) -> tuple[tuple[int, int], memoryview]: + """RSA public fields""" + e, data = _get_mpint(data) + n, data = _get_mpint(data) + return (e, n), data + + def load_public( + self, data: memoryview + ) -> tuple[rsa.RSAPublicKey, memoryview]: + """Make RSA public key from data.""" + (e, n), data = self.get_public(data) + public_numbers = rsa.RSAPublicNumbers(e, n) + public_key = public_numbers.public_key() + return public_key, data + + def load_private( + self, data: memoryview, pubfields, unsafe_skip_rsa_key_validation: bool + ) -> tuple[rsa.RSAPrivateKey, memoryview]: + """Make RSA private key from data.""" + n, data = _get_mpint(data) + e, data = _get_mpint(data) + d, data = _get_mpint(data) + iqmp, data = _get_mpint(data) + p, data = _get_mpint(data) + q, data = _get_mpint(data) + + if (e, n) != pubfields: + raise ValueError("Corrupt data: rsa field mismatch") + dmp1 = rsa.rsa_crt_dmp1(d, p) + dmq1 = rsa.rsa_crt_dmq1(d, q) + public_numbers = rsa.RSAPublicNumbers(e, n) + private_numbers = rsa.RSAPrivateNumbers( + p, q, d, dmp1, dmq1, iqmp, public_numbers + ) + private_key = private_numbers.private_key( + unsafe_skip_rsa_key_validation=unsafe_skip_rsa_key_validation + ) + return private_key, data + + def encode_public( + self, public_key: rsa.RSAPublicKey, f_pub: _FragList + ) -> None: + """Write RSA public key""" + pubn = public_key.public_numbers() + f_pub.put_mpint(pubn.e) + f_pub.put_mpint(pubn.n) + + def encode_private( + self, private_key: rsa.RSAPrivateKey, f_priv: _FragList + ) -> None: + """Write RSA private key""" + private_numbers = private_key.private_numbers() + public_numbers = private_numbers.public_numbers + + f_priv.put_mpint(public_numbers.n) + f_priv.put_mpint(public_numbers.e) + + f_priv.put_mpint(private_numbers.d) + f_priv.put_mpint(private_numbers.iqmp) + f_priv.put_mpint(private_numbers.p) + f_priv.put_mpint(private_numbers.q) + + +class _SSHFormatDSA: + """Format for DSA keys. + + Public: + mpint p, q, g, y + Private: + mpint p, q, g, y, x + """ + + def get_public(self, data: memoryview) -> tuple[tuple, memoryview]: + """DSA public fields""" + p, data = _get_mpint(data) + q, data = _get_mpint(data) + g, data = _get_mpint(data) + y, data = _get_mpint(data) + return (p, q, g, y), data + + def load_public( + self, data: memoryview + ) -> tuple[dsa.DSAPublicKey, memoryview]: + """Make DSA public key from data.""" + (p, q, g, y), data = self.get_public(data) + parameter_numbers = dsa.DSAParameterNumbers(p, q, g) + public_numbers = dsa.DSAPublicNumbers(y, parameter_numbers) + self._validate(public_numbers) + public_key = public_numbers.public_key() + return public_key, data + + def load_private( + self, data: memoryview, pubfields, unsafe_skip_rsa_key_validation: bool + ) -> tuple[dsa.DSAPrivateKey, memoryview]: + """Make DSA private key from data.""" + (p, q, g, y), data = self.get_public(data) + x, data = _get_mpint(data) + + if (p, q, g, y) != pubfields: + raise ValueError("Corrupt data: dsa field mismatch") + parameter_numbers = dsa.DSAParameterNumbers(p, q, g) + public_numbers = dsa.DSAPublicNumbers(y, parameter_numbers) + self._validate(public_numbers) + private_numbers = dsa.DSAPrivateNumbers(x, public_numbers) + private_key = private_numbers.private_key() + return private_key, data + + def encode_public( + self, public_key: dsa.DSAPublicKey, f_pub: _FragList + ) -> None: + """Write DSA public key""" + public_numbers = public_key.public_numbers() + parameter_numbers = public_numbers.parameter_numbers + self._validate(public_numbers) + + f_pub.put_mpint(parameter_numbers.p) + f_pub.put_mpint(parameter_numbers.q) + f_pub.put_mpint(parameter_numbers.g) + f_pub.put_mpint(public_numbers.y) + + def encode_private( + self, private_key: dsa.DSAPrivateKey, f_priv: _FragList + ) -> None: + """Write DSA private key""" + self.encode_public(private_key.public_key(), f_priv) + f_priv.put_mpint(private_key.private_numbers().x) + + def _validate(self, public_numbers: dsa.DSAPublicNumbers) -> None: + parameter_numbers = public_numbers.parameter_numbers + if parameter_numbers.p.bit_length() != 1024: + raise ValueError("SSH supports only 1024 bit DSA keys") + + +class _SSHFormatECDSA: + """Format for ECDSA keys. + + Public: + str curve + bytes point + Private: + str curve + bytes point + mpint secret + """ + + def __init__(self, ssh_curve_name: bytes, curve: ec.EllipticCurve): + self.ssh_curve_name = ssh_curve_name + self.curve = curve + + def get_public( + self, data: memoryview + ) -> tuple[tuple[memoryview, memoryview], memoryview]: + """ECDSA public fields""" + curve, data = _get_sshstr(data) + point, data = _get_sshstr(data) + if curve != self.ssh_curve_name: + raise ValueError("Curve name mismatch") + if len(point) == 0: + raise ValueError("Invalid EC point: empty data") + if point[0] != 4: + raise NotImplementedError("Need uncompressed point") + return (curve, point), data + + def load_public( + self, data: memoryview + ) -> tuple[ec.EllipticCurvePublicKey, memoryview]: + """Make ECDSA public key from data.""" + (_, point), data = self.get_public(data) + public_key = ec.EllipticCurvePublicKey.from_encoded_point( + self.curve, point.tobytes() + ) + return public_key, data + + def load_private( + self, data: memoryview, pubfields, unsafe_skip_rsa_key_validation: bool + ) -> tuple[ec.EllipticCurvePrivateKey, memoryview]: + """Make ECDSA private key from data.""" + (curve_name, point), data = self.get_public(data) + secret, data = _get_mpint(data) + + if (curve_name, point) != pubfields: + raise ValueError("Corrupt data: ecdsa field mismatch") + private_key = ec.derive_private_key(secret, self.curve) + return private_key, data + + def encode_public( + self, public_key: ec.EllipticCurvePublicKey, f_pub: _FragList + ) -> None: + """Write ECDSA public key""" + point = public_key.public_bytes( + Encoding.X962, PublicFormat.UncompressedPoint + ) + f_pub.put_sshstr(self.ssh_curve_name) + f_pub.put_sshstr(point) + + def encode_private( + self, private_key: ec.EllipticCurvePrivateKey, f_priv: _FragList + ) -> None: + """Write ECDSA private key""" + public_key = private_key.public_key() + private_numbers = private_key.private_numbers() + + self.encode_public(public_key, f_priv) + f_priv.put_mpint(private_numbers.private_value) + + +class _SSHFormatEd25519: + """Format for Ed25519 keys. + + Public: + bytes point + Private: + bytes point + bytes secret_and_point + """ + + def get_public( + self, data: memoryview + ) -> tuple[tuple[memoryview], memoryview]: + """Ed25519 public fields""" + point, data = _get_sshstr(data) + return (point,), data + + def load_public( + self, data: memoryview + ) -> tuple[ed25519.Ed25519PublicKey, memoryview]: + """Make Ed25519 public key from data.""" + (point,), data = self.get_public(data) + public_key = ed25519.Ed25519PublicKey.from_public_bytes( + point.tobytes() + ) + return public_key, data + + def load_private( + self, data: memoryview, pubfields, unsafe_skip_rsa_key_validation: bool + ) -> tuple[ed25519.Ed25519PrivateKey, memoryview]: + """Make Ed25519 private key from data.""" + (point,), data = self.get_public(data) + keypair, data = _get_sshstr(data) + + secret = keypair[:32] + point2 = keypair[32:] + if point != point2 or (point,) != pubfields: + raise ValueError("Corrupt data: ed25519 field mismatch") + private_key = ed25519.Ed25519PrivateKey.from_private_bytes(secret) + return private_key, data + + def encode_public( + self, public_key: ed25519.Ed25519PublicKey, f_pub: _FragList + ) -> None: + """Write Ed25519 public key""" + raw_public_key = public_key.public_bytes( + Encoding.Raw, PublicFormat.Raw + ) + f_pub.put_sshstr(raw_public_key) + + def encode_private( + self, private_key: ed25519.Ed25519PrivateKey, f_priv: _FragList + ) -> None: + """Write Ed25519 private key""" + public_key = private_key.public_key() + raw_private_key = private_key.private_bytes( + Encoding.Raw, PrivateFormat.Raw, NoEncryption() + ) + raw_public_key = public_key.public_bytes( + Encoding.Raw, PublicFormat.Raw + ) + f_keypair = _FragList([raw_private_key, raw_public_key]) + + self.encode_public(public_key, f_priv) + f_priv.put_sshstr(f_keypair) + + +def load_application(data) -> tuple[memoryview, memoryview]: + """ + U2F application strings + """ + application, data = _get_sshstr(data) + if not application.tobytes().startswith(b"ssh:"): + raise ValueError( + "U2F application string does not start with b'ssh:' " + f"({application})" + ) + return application, data + + +class _SSHFormatSKEd25519: + """ + The format of a sk-ssh-ed25519@openssh.com public key is: + + string "sk-ssh-ed25519@openssh.com" + string public key + string application (user-specified, but typically "ssh:") + """ + + def load_public( + self, data: memoryview + ) -> tuple[ed25519.Ed25519PublicKey, memoryview]: + """Make Ed25519 public key from data.""" + public_key, data = _lookup_kformat(_SSH_ED25519).load_public(data) + _, data = load_application(data) + return public_key, data + + def get_public(self, data: memoryview) -> typing.NoReturn: + # Confusingly `get_public` is an entry point used by private key + # loading. + raise UnsupportedAlgorithm( + "sk-ssh-ed25519 private keys cannot be loaded" + ) + + +class _SSHFormatSKECDSA: + """ + The format of a sk-ecdsa-sha2-nistp256@openssh.com public key is: + + string "sk-ecdsa-sha2-nistp256@openssh.com" + string curve name + ec_point Q + string application (user-specified, but typically "ssh:") + """ + + def load_public( + self, data: memoryview + ) -> tuple[ec.EllipticCurvePublicKey, memoryview]: + """Make ECDSA public key from data.""" + public_key, data = _lookup_kformat(_ECDSA_NISTP256).load_public(data) + _, data = load_application(data) + return public_key, data + + def get_public(self, data: memoryview) -> typing.NoReturn: + # Confusingly `get_public` is an entry point used by private key + # loading. + raise UnsupportedAlgorithm( + "sk-ecdsa-sha2-nistp256 private keys cannot be loaded" + ) + + +_KEY_FORMATS = { + _SSH_RSA: _SSHFormatRSA(), + _SSH_DSA: _SSHFormatDSA(), + _SSH_ED25519: _SSHFormatEd25519(), + _ECDSA_NISTP256: _SSHFormatECDSA(b"nistp256", ec.SECP256R1()), + _ECDSA_NISTP384: _SSHFormatECDSA(b"nistp384", ec.SECP384R1()), + _ECDSA_NISTP521: _SSHFormatECDSA(b"nistp521", ec.SECP521R1()), + _SK_SSH_ED25519: _SSHFormatSKEd25519(), + _SK_SSH_ECDSA_NISTP256: _SSHFormatSKECDSA(), +} + + +def _lookup_kformat(key_type: utils.Buffer): + """Return valid format or throw error""" + if not isinstance(key_type, bytes): + key_type = memoryview(key_type).tobytes() + if key_type in _KEY_FORMATS: + return _KEY_FORMATS[key_type] + raise UnsupportedAlgorithm(f"Unsupported key type: {key_type!r}") + + +SSHPrivateKeyTypes = typing.Union[ + ec.EllipticCurvePrivateKey, + rsa.RSAPrivateKey, + dsa.DSAPrivateKey, + ed25519.Ed25519PrivateKey, +] + + +def load_ssh_private_key( + data: utils.Buffer, + password: bytes | None, + backend: typing.Any = None, + *, + unsafe_skip_rsa_key_validation: bool = False, +) -> SSHPrivateKeyTypes: + """Load private key from OpenSSH custom encoding.""" + utils._check_byteslike("data", data) + if password is not None: + utils._check_bytes("password", password) + + m = _PEM_RC.search(data) + if not m: + raise ValueError("Not OpenSSH private key format") + p1 = m.start(1) + p2 = m.end(1) + data = binascii.a2b_base64(memoryview(data)[p1:p2]) + if not data.startswith(_SK_MAGIC): + raise ValueError("Not OpenSSH private key format") + data = memoryview(data)[len(_SK_MAGIC) :] + + # parse header + ciphername, data = _get_sshstr(data) + kdfname, data = _get_sshstr(data) + kdfoptions, data = _get_sshstr(data) + nkeys, data = _get_u32(data) + if nkeys != 1: + raise ValueError("Only one key supported") + + # load public key data + pubdata, data = _get_sshstr(data) + pub_key_type, pubdata = _get_sshstr(pubdata) + kformat = _lookup_kformat(pub_key_type) + pubfields, pubdata = kformat.get_public(pubdata) + _check_empty(pubdata) + + if ciphername != _NONE or kdfname != _NONE: + ciphername_bytes = ciphername.tobytes() + if ciphername_bytes not in _SSH_CIPHERS: + raise UnsupportedAlgorithm( + f"Unsupported cipher: {ciphername_bytes!r}" + ) + if kdfname != _BCRYPT: + raise UnsupportedAlgorithm(f"Unsupported KDF: {kdfname!r}") + blklen = _SSH_CIPHERS[ciphername_bytes].block_len + tag_len = _SSH_CIPHERS[ciphername_bytes].tag_len + # load secret data + edata, data = _get_sshstr(data) + # see https://bugzilla.mindrot.org/show_bug.cgi?id=3553 for + # information about how OpenSSH handles AEAD tags + if _SSH_CIPHERS[ciphername_bytes].is_aead: + tag = bytes(data) + if len(tag) != tag_len: + raise ValueError("Corrupt data: invalid tag length for cipher") + else: + _check_empty(data) + _check_block_size(edata, blklen) + salt, kbuf = _get_sshstr(kdfoptions) + rounds, kbuf = _get_u32(kbuf) + _check_empty(kbuf) + ciph = _init_cipher(ciphername_bytes, password, salt.tobytes(), rounds) + dec = ciph.decryptor() + edata = memoryview(dec.update(edata)) + if _SSH_CIPHERS[ciphername_bytes].is_aead: + assert isinstance(dec, AEADDecryptionContext) + _check_empty(dec.finalize_with_tag(tag)) + else: + # _check_block_size requires data to be a full block so there + # should be no output from finalize + _check_empty(dec.finalize()) + else: + if password: + raise TypeError( + "Password was given but private key is not encrypted." + ) + # load secret data + edata, data = _get_sshstr(data) + _check_empty(data) + blklen = 8 + _check_block_size(edata, blklen) + ck1, edata = _get_u32(edata) + ck2, edata = _get_u32(edata) + if ck1 != ck2: + raise ValueError("Corrupt data: broken checksum") + + # load per-key struct + key_type, edata = _get_sshstr(edata) + if key_type != pub_key_type: + raise ValueError("Corrupt data: key type mismatch") + private_key, edata = kformat.load_private( + edata, + pubfields, + unsafe_skip_rsa_key_validation=unsafe_skip_rsa_key_validation, + ) + # We don't use the comment + _, edata = _get_sshstr(edata) + + # yes, SSH does padding check *after* all other parsing is done. + # need to follow as it writes zero-byte padding too. + if edata != _PADDING[: len(edata)]: + raise ValueError("Corrupt data: invalid padding") + + if isinstance(private_key, dsa.DSAPrivateKey): + warnings.warn( + "SSH DSA keys are deprecated and will be removed in a future " + "release.", + utils.DeprecatedIn40, + stacklevel=2, + ) + + return private_key + + +def _serialize_ssh_private_key( + private_key: SSHPrivateKeyTypes, + password: bytes, + encryption_algorithm: KeySerializationEncryption, +) -> bytes: + """Serialize private key with OpenSSH custom encoding.""" + utils._check_bytes("password", password) + if isinstance(private_key, dsa.DSAPrivateKey): + warnings.warn( + "SSH DSA key support is deprecated and will be " + "removed in a future release", + utils.DeprecatedIn40, + stacklevel=4, + ) + + key_type = _get_ssh_key_type(private_key) + kformat = _lookup_kformat(key_type) + + # setup parameters + f_kdfoptions = _FragList() + if password: + ciphername = _DEFAULT_CIPHER + blklen = _SSH_CIPHERS[ciphername].block_len + kdfname = _BCRYPT + rounds = _DEFAULT_ROUNDS + if ( + isinstance(encryption_algorithm, _KeySerializationEncryption) + and encryption_algorithm._kdf_rounds is not None + ): + rounds = encryption_algorithm._kdf_rounds + salt = os.urandom(16) + f_kdfoptions.put_sshstr(salt) + f_kdfoptions.put_u32(rounds) + ciph = _init_cipher(ciphername, password, salt, rounds) + else: + ciphername = kdfname = _NONE + blklen = 8 + ciph = None + nkeys = 1 + checkval = os.urandom(4) + comment = b"" + + # encode public and private parts together + f_public_key = _FragList() + f_public_key.put_sshstr(key_type) + kformat.encode_public(private_key.public_key(), f_public_key) + + f_secrets = _FragList([checkval, checkval]) + f_secrets.put_sshstr(key_type) + kformat.encode_private(private_key, f_secrets) + f_secrets.put_sshstr(comment) + f_secrets.put_raw(_PADDING[: blklen - (f_secrets.size() % blklen)]) + + # top-level structure + f_main = _FragList() + f_main.put_raw(_SK_MAGIC) + f_main.put_sshstr(ciphername) + f_main.put_sshstr(kdfname) + f_main.put_sshstr(f_kdfoptions) + f_main.put_u32(nkeys) + f_main.put_sshstr(f_public_key) + f_main.put_sshstr(f_secrets) + + # copy result info bytearray + slen = f_secrets.size() + mlen = f_main.size() + buf = memoryview(bytearray(mlen + blklen)) + f_main.render(buf) + ofs = mlen - slen + + # encrypt in-place + if ciph is not None: + ciph.encryptor().update_into(buf[ofs:mlen], buf[ofs:]) + + return _ssh_pem_encode(buf[:mlen]) + + +SSHPublicKeyTypes = typing.Union[ + ec.EllipticCurvePublicKey, + rsa.RSAPublicKey, + dsa.DSAPublicKey, + ed25519.Ed25519PublicKey, +] + +SSHCertPublicKeyTypes = typing.Union[ + ec.EllipticCurvePublicKey, + rsa.RSAPublicKey, + ed25519.Ed25519PublicKey, +] + + +class SSHCertificateType(enum.Enum): + USER = 1 + HOST = 2 + + +class SSHCertificate: + def __init__( + self, + _nonce: memoryview, + _public_key: SSHPublicKeyTypes, + _serial: int, + _cctype: int, + _key_id: memoryview, + _valid_principals: list[bytes], + _valid_after: int, + _valid_before: int, + _critical_options: dict[bytes, bytes], + _extensions: dict[bytes, bytes], + _sig_type: memoryview, + _sig_key: memoryview, + _inner_sig_type: memoryview, + _signature: memoryview, + _tbs_cert_body: memoryview, + _cert_key_type: bytes, + _cert_body: memoryview, + ): + self._nonce = _nonce + self._public_key = _public_key + self._serial = _serial + try: + self._type = SSHCertificateType(_cctype) + except ValueError: + raise ValueError("Invalid certificate type") + self._key_id = _key_id + self._valid_principals = _valid_principals + self._valid_after = _valid_after + self._valid_before = _valid_before + self._critical_options = _critical_options + self._extensions = _extensions + self._sig_type = _sig_type + self._sig_key = _sig_key + self._inner_sig_type = _inner_sig_type + self._signature = _signature + self._cert_key_type = _cert_key_type + self._cert_body = _cert_body + self._tbs_cert_body = _tbs_cert_body + + @property + def nonce(self) -> bytes: + return bytes(self._nonce) + + def public_key(self) -> SSHCertPublicKeyTypes: + # make mypy happy until we remove DSA support entirely and + # the underlying union won't have a disallowed type + return typing.cast(SSHCertPublicKeyTypes, self._public_key) + + @property + def serial(self) -> int: + return self._serial + + @property + def type(self) -> SSHCertificateType: + return self._type + + @property + def key_id(self) -> bytes: + return bytes(self._key_id) + + @property + def valid_principals(self) -> list[bytes]: + return self._valid_principals + + @property + def valid_before(self) -> int: + return self._valid_before + + @property + def valid_after(self) -> int: + return self._valid_after + + @property + def critical_options(self) -> dict[bytes, bytes]: + return self._critical_options + + @property + def extensions(self) -> dict[bytes, bytes]: + return self._extensions + + def signature_key(self) -> SSHCertPublicKeyTypes: + sigformat = _lookup_kformat(self._sig_type) + signature_key, sigkey_rest = sigformat.load_public(self._sig_key) + _check_empty(sigkey_rest) + return signature_key + + def public_bytes(self) -> bytes: + return ( + bytes(self._cert_key_type) + + b" " + + binascii.b2a_base64(bytes(self._cert_body), newline=False) + ) + + def verify_cert_signature(self) -> None: + signature_key = self.signature_key() + if isinstance(signature_key, ed25519.Ed25519PublicKey): + signature_key.verify( + bytes(self._signature), bytes(self._tbs_cert_body) + ) + elif isinstance(signature_key, ec.EllipticCurvePublicKey): + # The signature is encoded as a pair of big-endian integers + r, data = _get_mpint(self._signature) + s, data = _get_mpint(data) + _check_empty(data) + computed_sig = asym_utils.encode_dss_signature(r, s) + hash_alg = _get_ec_hash_alg(signature_key.curve) + signature_key.verify( + computed_sig, bytes(self._tbs_cert_body), ec.ECDSA(hash_alg) + ) + else: + assert isinstance(signature_key, rsa.RSAPublicKey) + if self._inner_sig_type == _SSH_RSA: + hash_alg = hashes.SHA1() + elif self._inner_sig_type == _SSH_RSA_SHA256: + hash_alg = hashes.SHA256() + else: + assert self._inner_sig_type == _SSH_RSA_SHA512 + hash_alg = hashes.SHA512() + signature_key.verify( + bytes(self._signature), + bytes(self._tbs_cert_body), + padding.PKCS1v15(), + hash_alg, + ) + + +def _get_ec_hash_alg(curve: ec.EllipticCurve) -> hashes.HashAlgorithm: + if isinstance(curve, ec.SECP256R1): + return hashes.SHA256() + elif isinstance(curve, ec.SECP384R1): + return hashes.SHA384() + else: + assert isinstance(curve, ec.SECP521R1) + return hashes.SHA512() + + +def _load_ssh_public_identity( + data: utils.Buffer, + _legacy_dsa_allowed=False, +) -> SSHCertificate | SSHPublicKeyTypes: + utils._check_byteslike("data", data) + + m = _SSH_PUBKEY_RC.match(data) + if not m: + raise ValueError("Invalid line format") + key_type = orig_key_type = m.group(1) + key_body = m.group(2) + with_cert = False + if key_type.endswith(_CERT_SUFFIX): + with_cert = True + key_type = key_type[: -len(_CERT_SUFFIX)] + if key_type == _SSH_DSA and not _legacy_dsa_allowed: + raise UnsupportedAlgorithm( + "DSA keys aren't supported in SSH certificates" + ) + kformat = _lookup_kformat(key_type) + + try: + rest = memoryview(binascii.a2b_base64(key_body)) + except (TypeError, binascii.Error): + raise ValueError("Invalid format") + + if with_cert: + cert_body = rest + inner_key_type, rest = _get_sshstr(rest) + if inner_key_type != orig_key_type: + raise ValueError("Invalid key format") + if with_cert: + nonce, rest = _get_sshstr(rest) + public_key, rest = kformat.load_public(rest) + if with_cert: + serial, rest = _get_u64(rest) + cctype, rest = _get_u32(rest) + key_id, rest = _get_sshstr(rest) + principals, rest = _get_sshstr(rest) + valid_principals = [] + while principals: + principal, principals = _get_sshstr(principals) + valid_principals.append(bytes(principal)) + valid_after, rest = _get_u64(rest) + valid_before, rest = _get_u64(rest) + crit_options, rest = _get_sshstr(rest) + critical_options = _parse_exts_opts(crit_options) + exts, rest = _get_sshstr(rest) + extensions = _parse_exts_opts(exts) + # Get the reserved field, which is unused. + _, rest = _get_sshstr(rest) + sig_key_raw, rest = _get_sshstr(rest) + sig_type, sig_key = _get_sshstr(sig_key_raw) + if sig_type == _SSH_DSA and not _legacy_dsa_allowed: + raise UnsupportedAlgorithm( + "DSA signatures aren't supported in SSH certificates" + ) + # Get the entire cert body and subtract the signature + tbs_cert_body = cert_body[: -len(rest)] + signature_raw, rest = _get_sshstr(rest) + _check_empty(rest) + inner_sig_type, sig_rest = _get_sshstr(signature_raw) + # RSA certs can have multiple algorithm types + if ( + sig_type == _SSH_RSA + and inner_sig_type + not in [_SSH_RSA_SHA256, _SSH_RSA_SHA512, _SSH_RSA] + ) or (sig_type != _SSH_RSA and inner_sig_type != sig_type): + raise ValueError("Signature key type does not match") + signature, sig_rest = _get_sshstr(sig_rest) + _check_empty(sig_rest) + return SSHCertificate( + nonce, + public_key, + serial, + cctype, + key_id, + valid_principals, + valid_after, + valid_before, + critical_options, + extensions, + sig_type, + sig_key, + inner_sig_type, + signature, + tbs_cert_body, + orig_key_type, + cert_body, + ) + else: + _check_empty(rest) + return public_key + + +def load_ssh_public_identity( + data: utils.Buffer, +) -> SSHCertificate | SSHPublicKeyTypes: + return _load_ssh_public_identity(data) + + +def _parse_exts_opts(exts_opts: memoryview) -> dict[bytes, bytes]: + result: dict[bytes, bytes] = {} + last_name = None + while exts_opts: + name, exts_opts = _get_sshstr(exts_opts) + bname: bytes = bytes(name) + if bname in result: + raise ValueError("Duplicate name") + if last_name is not None and bname < last_name: + raise ValueError("Fields not lexically sorted") + value, exts_opts = _get_sshstr(exts_opts) + if len(value) > 0: + value, extra = _get_sshstr(value) + if len(extra) > 0: + raise ValueError("Unexpected extra data after value") + result[bname] = bytes(value) + last_name = bname + return result + + +def ssh_key_fingerprint( + key: SSHPublicKeyTypes, + hash_algorithm: hashes.MD5 | hashes.SHA256, +) -> bytes: + if not isinstance(hash_algorithm, (hashes.MD5, hashes.SHA256)): + raise TypeError("hash_algorithm must be either MD5 or SHA256") + + key_type = _get_ssh_key_type(key) + kformat = _lookup_kformat(key_type) + + f_pub = _FragList() + f_pub.put_sshstr(key_type) + kformat.encode_public(key, f_pub) + + ssh_binary_data = f_pub.tobytes() + + # Hash the binary data + hash_obj = hashes.Hash(hash_algorithm) + hash_obj.update(ssh_binary_data) + return hash_obj.finalize() + + +def load_ssh_public_key( + data: utils.Buffer, backend: typing.Any = None +) -> SSHPublicKeyTypes: + cert_or_key = _load_ssh_public_identity(data, _legacy_dsa_allowed=True) + public_key: SSHPublicKeyTypes + if isinstance(cert_or_key, SSHCertificate): + public_key = cert_or_key.public_key() + else: + public_key = cert_or_key + + if isinstance(public_key, dsa.DSAPublicKey): + warnings.warn( + "SSH DSA keys are deprecated and will be removed in a future " + "release.", + utils.DeprecatedIn40, + stacklevel=2, + ) + return public_key + + +def serialize_ssh_public_key(public_key: SSHPublicKeyTypes) -> bytes: + """One-line public key format for OpenSSH""" + if isinstance(public_key, dsa.DSAPublicKey): + warnings.warn( + "SSH DSA key support is deprecated and will be " + "removed in a future release", + utils.DeprecatedIn40, + stacklevel=4, + ) + key_type = _get_ssh_key_type(public_key) + kformat = _lookup_kformat(key_type) + + f_pub = _FragList() + f_pub.put_sshstr(key_type) + kformat.encode_public(public_key, f_pub) + + pub = binascii.b2a_base64(f_pub.tobytes()).strip() + return b"".join([key_type, b" ", pub]) + + +SSHCertPrivateKeyTypes = typing.Union[ + ec.EllipticCurvePrivateKey, + rsa.RSAPrivateKey, + ed25519.Ed25519PrivateKey, +] + + +# This is an undocumented limit enforced in the openssh codebase for sshd and +# ssh-keygen, but it is undefined in the ssh certificates spec. +_SSHKEY_CERT_MAX_PRINCIPALS = 256 + + +class SSHCertificateBuilder: + def __init__( + self, + _public_key: SSHCertPublicKeyTypes | None = None, + _serial: int | None = None, + _type: SSHCertificateType | None = None, + _key_id: bytes | None = None, + _valid_principals: list[bytes] = [], + _valid_for_all_principals: bool = False, + _valid_before: int | None = None, + _valid_after: int | None = None, + _critical_options: list[tuple[bytes, bytes]] = [], + _extensions: list[tuple[bytes, bytes]] = [], + ): + self._public_key = _public_key + self._serial = _serial + self._type = _type + self._key_id = _key_id + self._valid_principals = _valid_principals + self._valid_for_all_principals = _valid_for_all_principals + self._valid_before = _valid_before + self._valid_after = _valid_after + self._critical_options = _critical_options + self._extensions = _extensions + + def public_key( + self, public_key: SSHCertPublicKeyTypes + ) -> SSHCertificateBuilder: + if not isinstance( + public_key, + ( + ec.EllipticCurvePublicKey, + rsa.RSAPublicKey, + ed25519.Ed25519PublicKey, + ), + ): + raise TypeError("Unsupported key type") + if self._public_key is not None: + raise ValueError("public_key already set") + + return SSHCertificateBuilder( + _public_key=public_key, + _serial=self._serial, + _type=self._type, + _key_id=self._key_id, + _valid_principals=self._valid_principals, + _valid_for_all_principals=self._valid_for_all_principals, + _valid_before=self._valid_before, + _valid_after=self._valid_after, + _critical_options=self._critical_options, + _extensions=self._extensions, + ) + + def serial(self, serial: int) -> SSHCertificateBuilder: + if not isinstance(serial, int): + raise TypeError("serial must be an integer") + if not 0 <= serial < 2**64: + raise ValueError("serial must be between 0 and 2**64") + if self._serial is not None: + raise ValueError("serial already set") + + return SSHCertificateBuilder( + _public_key=self._public_key, + _serial=serial, + _type=self._type, + _key_id=self._key_id, + _valid_principals=self._valid_principals, + _valid_for_all_principals=self._valid_for_all_principals, + _valid_before=self._valid_before, + _valid_after=self._valid_after, + _critical_options=self._critical_options, + _extensions=self._extensions, + ) + + def type(self, type: SSHCertificateType) -> SSHCertificateBuilder: + if not isinstance(type, SSHCertificateType): + raise TypeError("type must be an SSHCertificateType") + if self._type is not None: + raise ValueError("type already set") + + return SSHCertificateBuilder( + _public_key=self._public_key, + _serial=self._serial, + _type=type, + _key_id=self._key_id, + _valid_principals=self._valid_principals, + _valid_for_all_principals=self._valid_for_all_principals, + _valid_before=self._valid_before, + _valid_after=self._valid_after, + _critical_options=self._critical_options, + _extensions=self._extensions, + ) + + def key_id(self, key_id: bytes) -> SSHCertificateBuilder: + if not isinstance(key_id, bytes): + raise TypeError("key_id must be bytes") + if self._key_id is not None: + raise ValueError("key_id already set") + + return SSHCertificateBuilder( + _public_key=self._public_key, + _serial=self._serial, + _type=self._type, + _key_id=key_id, + _valid_principals=self._valid_principals, + _valid_for_all_principals=self._valid_for_all_principals, + _valid_before=self._valid_before, + _valid_after=self._valid_after, + _critical_options=self._critical_options, + _extensions=self._extensions, + ) + + def valid_principals( + self, valid_principals: list[bytes] + ) -> SSHCertificateBuilder: + if self._valid_for_all_principals: + raise ValueError( + "Principals can't be set because the cert is valid " + "for all principals" + ) + if ( + not all(isinstance(x, bytes) for x in valid_principals) + or not valid_principals + ): + raise TypeError( + "principals must be a list of bytes and can't be empty" + ) + if self._valid_principals: + raise ValueError("valid_principals already set") + + if len(valid_principals) > _SSHKEY_CERT_MAX_PRINCIPALS: + raise ValueError( + "Reached or exceeded the maximum number of valid_principals" + ) + + return SSHCertificateBuilder( + _public_key=self._public_key, + _serial=self._serial, + _type=self._type, + _key_id=self._key_id, + _valid_principals=valid_principals, + _valid_for_all_principals=self._valid_for_all_principals, + _valid_before=self._valid_before, + _valid_after=self._valid_after, + _critical_options=self._critical_options, + _extensions=self._extensions, + ) + + def valid_for_all_principals(self): + if self._valid_principals: + raise ValueError( + "valid_principals already set, can't set " + "valid_for_all_principals" + ) + if self._valid_for_all_principals: + raise ValueError("valid_for_all_principals already set") + + return SSHCertificateBuilder( + _public_key=self._public_key, + _serial=self._serial, + _type=self._type, + _key_id=self._key_id, + _valid_principals=self._valid_principals, + _valid_for_all_principals=True, + _valid_before=self._valid_before, + _valid_after=self._valid_after, + _critical_options=self._critical_options, + _extensions=self._extensions, + ) + + def valid_before(self, valid_before: int | float) -> SSHCertificateBuilder: + if not isinstance(valid_before, (int, float)): + raise TypeError("valid_before must be an int or float") + valid_before = int(valid_before) + if valid_before < 0 or valid_before >= 2**64: + raise ValueError("valid_before must [0, 2**64)") + if self._valid_before is not None: + raise ValueError("valid_before already set") + + return SSHCertificateBuilder( + _public_key=self._public_key, + _serial=self._serial, + _type=self._type, + _key_id=self._key_id, + _valid_principals=self._valid_principals, + _valid_for_all_principals=self._valid_for_all_principals, + _valid_before=valid_before, + _valid_after=self._valid_after, + _critical_options=self._critical_options, + _extensions=self._extensions, + ) + + def valid_after(self, valid_after: int | float) -> SSHCertificateBuilder: + if not isinstance(valid_after, (int, float)): + raise TypeError("valid_after must be an int or float") + valid_after = int(valid_after) + if valid_after < 0 or valid_after >= 2**64: + raise ValueError("valid_after must [0, 2**64)") + if self._valid_after is not None: + raise ValueError("valid_after already set") + + return SSHCertificateBuilder( + _public_key=self._public_key, + _serial=self._serial, + _type=self._type, + _key_id=self._key_id, + _valid_principals=self._valid_principals, + _valid_for_all_principals=self._valid_for_all_principals, + _valid_before=self._valid_before, + _valid_after=valid_after, + _critical_options=self._critical_options, + _extensions=self._extensions, + ) + + def add_critical_option( + self, name: bytes, value: bytes + ) -> SSHCertificateBuilder: + if not isinstance(name, bytes) or not isinstance(value, bytes): + raise TypeError("name and value must be bytes") + # This is O(n**2) + if name in [name for name, _ in self._critical_options]: + raise ValueError("Duplicate critical option name") + + return SSHCertificateBuilder( + _public_key=self._public_key, + _serial=self._serial, + _type=self._type, + _key_id=self._key_id, + _valid_principals=self._valid_principals, + _valid_for_all_principals=self._valid_for_all_principals, + _valid_before=self._valid_before, + _valid_after=self._valid_after, + _critical_options=[*self._critical_options, (name, value)], + _extensions=self._extensions, + ) + + def add_extension( + self, name: bytes, value: bytes + ) -> SSHCertificateBuilder: + if not isinstance(name, bytes) or not isinstance(value, bytes): + raise TypeError("name and value must be bytes") + # This is O(n**2) + if name in [name for name, _ in self._extensions]: + raise ValueError("Duplicate extension name") + + return SSHCertificateBuilder( + _public_key=self._public_key, + _serial=self._serial, + _type=self._type, + _key_id=self._key_id, + _valid_principals=self._valid_principals, + _valid_for_all_principals=self._valid_for_all_principals, + _valid_before=self._valid_before, + _valid_after=self._valid_after, + _critical_options=self._critical_options, + _extensions=[*self._extensions, (name, value)], + ) + + def sign(self, private_key: SSHCertPrivateKeyTypes) -> SSHCertificate: + if not isinstance( + private_key, + ( + ec.EllipticCurvePrivateKey, + rsa.RSAPrivateKey, + ed25519.Ed25519PrivateKey, + ), + ): + raise TypeError("Unsupported private key type") + + if self._public_key is None: + raise ValueError("public_key must be set") + + # Not required + serial = 0 if self._serial is None else self._serial + + if self._type is None: + raise ValueError("type must be set") + + # Not required + key_id = b"" if self._key_id is None else self._key_id + + # A zero length list is valid, but means the certificate + # is valid for any principal of the specified type. We require + # the user to explicitly set valid_for_all_principals to get + # that behavior. + if not self._valid_principals and not self._valid_for_all_principals: + raise ValueError( + "valid_principals must be set if valid_for_all_principals " + "is False" + ) + + if self._valid_before is None: + raise ValueError("valid_before must be set") + + if self._valid_after is None: + raise ValueError("valid_after must be set") + + if self._valid_after > self._valid_before: + raise ValueError("valid_after must be earlier than valid_before") + + # lexically sort our byte strings + self._critical_options.sort(key=lambda x: x[0]) + self._extensions.sort(key=lambda x: x[0]) + + key_type = _get_ssh_key_type(self._public_key) + cert_prefix = key_type + _CERT_SUFFIX + + # Marshal the bytes to be signed + nonce = os.urandom(32) + kformat = _lookup_kformat(key_type) + f = _FragList() + f.put_sshstr(cert_prefix) + f.put_sshstr(nonce) + kformat.encode_public(self._public_key, f) + f.put_u64(serial) + f.put_u32(self._type.value) + f.put_sshstr(key_id) + fprincipals = _FragList() + for p in self._valid_principals: + fprincipals.put_sshstr(p) + f.put_sshstr(fprincipals.tobytes()) + f.put_u64(self._valid_after) + f.put_u64(self._valid_before) + fcrit = _FragList() + for name, value in self._critical_options: + fcrit.put_sshstr(name) + if len(value) > 0: + foptval = _FragList() + foptval.put_sshstr(value) + fcrit.put_sshstr(foptval.tobytes()) + else: + fcrit.put_sshstr(value) + f.put_sshstr(fcrit.tobytes()) + fext = _FragList() + for name, value in self._extensions: + fext.put_sshstr(name) + if len(value) > 0: + fextval = _FragList() + fextval.put_sshstr(value) + fext.put_sshstr(fextval.tobytes()) + else: + fext.put_sshstr(value) + f.put_sshstr(fext.tobytes()) + f.put_sshstr(b"") # RESERVED FIELD + # encode CA public key + ca_type = _get_ssh_key_type(private_key) + caformat = _lookup_kformat(ca_type) + caf = _FragList() + caf.put_sshstr(ca_type) + caformat.encode_public(private_key.public_key(), caf) + f.put_sshstr(caf.tobytes()) + # Sigs according to the rules defined for the CA's public key + # (RFC4253 section 6.6 for ssh-rsa, RFC5656 for ECDSA, + # and RFC8032 for Ed25519). + if isinstance(private_key, ed25519.Ed25519PrivateKey): + signature = private_key.sign(f.tobytes()) + fsig = _FragList() + fsig.put_sshstr(ca_type) + fsig.put_sshstr(signature) + f.put_sshstr(fsig.tobytes()) + elif isinstance(private_key, ec.EllipticCurvePrivateKey): + hash_alg = _get_ec_hash_alg(private_key.curve) + signature = private_key.sign(f.tobytes(), ec.ECDSA(hash_alg)) + r, s = asym_utils.decode_dss_signature(signature) + fsig = _FragList() + fsig.put_sshstr(ca_type) + fsigblob = _FragList() + fsigblob.put_mpint(r) + fsigblob.put_mpint(s) + fsig.put_sshstr(fsigblob.tobytes()) + f.put_sshstr(fsig.tobytes()) + + else: + assert isinstance(private_key, rsa.RSAPrivateKey) + # Just like Golang, we're going to use SHA512 for RSA + # https://cs.opensource.google/go/x/crypto/+/refs/tags/ + # v0.4.0:ssh/certs.go;l=445 + # RFC 8332 defines SHA256 and 512 as options + fsig = _FragList() + fsig.put_sshstr(_SSH_RSA_SHA512) + signature = private_key.sign( + f.tobytes(), padding.PKCS1v15(), hashes.SHA512() + ) + fsig.put_sshstr(signature) + f.put_sshstr(fsig.tobytes()) + + cert_data = binascii.b2a_base64(f.tobytes()).strip() + # load_ssh_public_identity returns a union, but this is + # guaranteed to be an SSHCertificate, so we cast to make + # mypy happy. + return typing.cast( + SSHCertificate, + load_ssh_public_identity(b"".join([cert_prefix, b" ", cert_data])), + ) diff --git a/python/user_packages/Python313/site-packages/cryptography/hazmat/primitives/twofactor/__init__.py b/python/user_packages/Python313/site-packages/cryptography/hazmat/primitives/twofactor/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..c1af423004863e7db3e163f61a6baa4ddc157351 --- /dev/null +++ b/python/user_packages/Python313/site-packages/cryptography/hazmat/primitives/twofactor/__init__.py @@ -0,0 +1,9 @@ +# This file is dual licensed under the terms of the Apache License, Version +# 2.0, and the BSD License. See the LICENSE file in the root of this repository +# for complete details. + +from __future__ import annotations + + +class InvalidToken(Exception): + pass diff --git a/python/user_packages/Python313/site-packages/cryptography/hazmat/primitives/twofactor/__pycache__/__init__.cpython-313.pyc b/python/user_packages/Python313/site-packages/cryptography/hazmat/primitives/twofactor/__pycache__/__init__.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2439b14b28eac12aa7c8bae2f6e8a70177b34def Binary files /dev/null and b/python/user_packages/Python313/site-packages/cryptography/hazmat/primitives/twofactor/__pycache__/__init__.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/cryptography/hazmat/primitives/twofactor/__pycache__/hotp.cpython-313.pyc b/python/user_packages/Python313/site-packages/cryptography/hazmat/primitives/twofactor/__pycache__/hotp.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..fec3452a707c2f11a19f59c4264e692d738d257b Binary files /dev/null and b/python/user_packages/Python313/site-packages/cryptography/hazmat/primitives/twofactor/__pycache__/hotp.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/cryptography/hazmat/primitives/twofactor/__pycache__/totp.cpython-313.pyc b/python/user_packages/Python313/site-packages/cryptography/hazmat/primitives/twofactor/__pycache__/totp.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..88c2094d7443e60bbbfeee065cbf96b127a1e860 Binary files /dev/null and b/python/user_packages/Python313/site-packages/cryptography/hazmat/primitives/twofactor/__pycache__/totp.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/cryptography/hazmat/primitives/twofactor/hotp.py b/python/user_packages/Python313/site-packages/cryptography/hazmat/primitives/twofactor/hotp.py new file mode 100644 index 0000000000000000000000000000000000000000..21fb000499c43cb8492ce60d9a2c5ed6fab704e2 --- /dev/null +++ b/python/user_packages/Python313/site-packages/cryptography/hazmat/primitives/twofactor/hotp.py @@ -0,0 +1,101 @@ +# This file is dual licensed under the terms of the Apache License, Version +# 2.0, and the BSD License. See the LICENSE file in the root of this repository +# for complete details. + +from __future__ import annotations + +import base64 +import typing +from urllib.parse import quote, urlencode + +from cryptography.hazmat.primitives import constant_time, hmac +from cryptography.hazmat.primitives.hashes import SHA1, SHA256, SHA512 +from cryptography.hazmat.primitives.twofactor import InvalidToken +from cryptography.utils import Buffer + +HOTPHashTypes = typing.Union[SHA1, SHA256, SHA512] + + +def _generate_uri( + hotp: HOTP, + type_name: str, + account_name: str, + issuer: str | None, + extra_parameters: list[tuple[str, int]], +) -> str: + parameters = [ + ("digits", hotp._length), + ("secret", base64.b32encode(hotp._key)), + ("algorithm", hotp._algorithm.name.upper()), + ] + + if issuer is not None: + parameters.append(("issuer", issuer)) + + parameters.extend(extra_parameters) + + label = ( + f"{quote(issuer)}:{quote(account_name)}" + if issuer + else quote(account_name) + ) + return f"otpauth://{type_name}/{label}?{urlencode(parameters)}" + + +class HOTP: + def __init__( + self, + key: Buffer, + length: int, + algorithm: HOTPHashTypes, + backend: typing.Any = None, + enforce_key_length: bool = True, + ) -> None: + if len(key) < 16 and enforce_key_length is True: + raise ValueError("Key length has to be at least 128 bits.") + + if not isinstance(length, int): + raise TypeError("Length parameter must be an integer type.") + + if length < 6 or length > 8: + raise ValueError("Length of HOTP has to be between 6 and 8.") + + if not isinstance(algorithm, (SHA1, SHA256, SHA512)): + raise TypeError("Algorithm must be SHA1, SHA256 or SHA512.") + + self._key = key + self._length = length + self._algorithm = algorithm + + def generate(self, counter: int) -> bytes: + if not isinstance(counter, int): + raise TypeError("Counter parameter must be an integer type.") + + truncated_value = self._dynamic_truncate(counter) + hotp = truncated_value % (10**self._length) + return "{0:0{1}}".format(hotp, self._length).encode() + + def verify(self, hotp: bytes, counter: int) -> None: + if not constant_time.bytes_eq(self.generate(counter), hotp): + raise InvalidToken("Supplied HOTP value does not match.") + + def _dynamic_truncate(self, counter: int) -> int: + ctx = hmac.HMAC(self._key, self._algorithm) + + try: + ctx.update(counter.to_bytes(length=8, byteorder="big")) + except OverflowError: + raise ValueError(f"Counter must be between 0 and {2**64 - 1}.") + + hmac_value = ctx.finalize() + + offset = hmac_value[len(hmac_value) - 1] & 0b1111 + p = hmac_value[offset : offset + 4] + return int.from_bytes(p, byteorder="big") & 0x7FFFFFFF + + def get_provisioning_uri( + self, account_name: str, counter: int, issuer: str | None + ) -> str: + return _generate_uri( + self, "hotp", account_name, issuer, [("counter", int(counter))] + ) diff --git a/python/user_packages/Python313/site-packages/cryptography/hazmat/primitives/twofactor/totp.py b/python/user_packages/Python313/site-packages/cryptography/hazmat/primitives/twofactor/totp.py new file mode 100644 index 0000000000000000000000000000000000000000..10c725cc0ab0c9fff5a978a3d5278ccce52d4e67 --- /dev/null +++ b/python/user_packages/Python313/site-packages/cryptography/hazmat/primitives/twofactor/totp.py @@ -0,0 +1,56 @@ +# This file is dual licensed under the terms of the Apache License, Version +# 2.0, and the BSD License. See the LICENSE file in the root of this repository +# for complete details. + +from __future__ import annotations + +import typing + +from cryptography.hazmat.primitives import constant_time +from cryptography.hazmat.primitives.twofactor import InvalidToken +from cryptography.hazmat.primitives.twofactor.hotp import ( + HOTP, + HOTPHashTypes, + _generate_uri, +) +from cryptography.utils import Buffer + + +class TOTP: + def __init__( + self, + key: Buffer, + length: int, + algorithm: HOTPHashTypes, + time_step: int, + backend: typing.Any = None, + enforce_key_length: bool = True, + ): + self._time_step = time_step + self._hotp = HOTP( + key, length, algorithm, enforce_key_length=enforce_key_length + ) + + def generate(self, time: int | float) -> bytes: + if not isinstance(time, (int, float)): + raise TypeError( + "Time parameter must be an integer type or float type." + ) + + counter = int(time / self._time_step) + return self._hotp.generate(counter) + + def verify(self, totp: bytes, time: int) -> None: + if not constant_time.bytes_eq(self.generate(time), totp): + raise InvalidToken("Supplied TOTP value does not match.") + + def get_provisioning_uri( + self, account_name: str, issuer: str | None + ) -> str: + return _generate_uri( + self._hotp, + "totp", + account_name, + issuer, + [("period", int(self._time_step))], + ) diff --git a/python/user_packages/Python313/site-packages/cryptography/x509/__init__.py b/python/user_packages/Python313/site-packages/cryptography/x509/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..cb348335127deb95dae23dcd222e89cfee21fb4e --- /dev/null +++ b/python/user_packages/Python313/site-packages/cryptography/x509/__init__.py @@ -0,0 +1,271 @@ +# This file is dual licensed under the terms of the Apache License, Version +# 2.0, and the BSD License. See the LICENSE file in the root of this repository +# for complete details. + +from __future__ import annotations + +from cryptography.x509 import certificate_transparency, oid, verification +from cryptography.x509.base import ( + Attribute, + AttributeNotFound, + Attributes, + Certificate, + CertificateBuilder, + CertificateRevocationList, + CertificateRevocationListBuilder, + CertificateSigningRequest, + CertificateSigningRequestBuilder, + InvalidVersion, + RevokedCertificate, + RevokedCertificateBuilder, + Version, + load_der_x509_certificate, + load_der_x509_crl, + load_der_x509_csr, + load_pem_x509_certificate, + load_pem_x509_certificates, + load_pem_x509_crl, + load_pem_x509_csr, + random_serial_number, +) +from cryptography.x509.extensions import ( + AccessDescription, + Admission, + Admissions, + AuthorityInformationAccess, + AuthorityKeyIdentifier, + BasicConstraints, + CertificateIssuer, + CertificatePolicies, + CRLDistributionPoints, + CRLNumber, + CRLReason, + DeltaCRLIndicator, + DistributionPoint, + DuplicateExtension, + ExtendedKeyUsage, + Extension, + ExtensionNotFound, + Extensions, + ExtensionType, + FreshestCRL, + GeneralNames, + InhibitAnyPolicy, + InvalidityDate, + IssuerAlternativeName, + IssuingDistributionPoint, + KeyUsage, + MSCertificateTemplate, + NameConstraints, + NamingAuthority, + NoticeReference, + OCSPAcceptableResponses, + OCSPNoCheck, + OCSPNonce, + PolicyConstraints, + PolicyInformation, + PrecertificateSignedCertificateTimestamps, + PrecertPoison, + PrivateKeyUsagePeriod, + ProfessionInfo, + ReasonFlags, + SignedCertificateTimestamps, + SubjectAlternativeName, + SubjectInformationAccess, + SubjectKeyIdentifier, + TLSFeature, + TLSFeatureType, + UnrecognizedExtension, + UserNotice, +) +from cryptography.x509.general_name import ( + DirectoryName, + DNSName, + GeneralName, + IPAddress, + OtherName, + RegisteredID, + RFC822Name, + UniformResourceIdentifier, + UnsupportedGeneralNameType, +) +from cryptography.x509.name import ( + Name, + NameAttribute, + RelativeDistinguishedName, +) +from cryptography.x509.oid import ( + AuthorityInformationAccessOID, + CertificatePoliciesOID, + CRLEntryExtensionOID, + ExtendedKeyUsageOID, + ExtensionOID, + NameOID, + ObjectIdentifier, + PublicKeyAlgorithmOID, + SignatureAlgorithmOID, +) + +OID_AUTHORITY_INFORMATION_ACCESS = ExtensionOID.AUTHORITY_INFORMATION_ACCESS +OID_AUTHORITY_KEY_IDENTIFIER = ExtensionOID.AUTHORITY_KEY_IDENTIFIER +OID_BASIC_CONSTRAINTS = ExtensionOID.BASIC_CONSTRAINTS +OID_CERTIFICATE_POLICIES = ExtensionOID.CERTIFICATE_POLICIES +OID_CRL_DISTRIBUTION_POINTS = ExtensionOID.CRL_DISTRIBUTION_POINTS +OID_EXTENDED_KEY_USAGE = ExtensionOID.EXTENDED_KEY_USAGE +OID_FRESHEST_CRL = ExtensionOID.FRESHEST_CRL +OID_INHIBIT_ANY_POLICY = ExtensionOID.INHIBIT_ANY_POLICY +OID_ISSUER_ALTERNATIVE_NAME = ExtensionOID.ISSUER_ALTERNATIVE_NAME +OID_KEY_USAGE = ExtensionOID.KEY_USAGE +OID_PRIVATE_KEY_USAGE_PERIOD = ExtensionOID.PRIVATE_KEY_USAGE_PERIOD +OID_NAME_CONSTRAINTS = ExtensionOID.NAME_CONSTRAINTS +OID_OCSP_NO_CHECK = ExtensionOID.OCSP_NO_CHECK +OID_POLICY_CONSTRAINTS = ExtensionOID.POLICY_CONSTRAINTS +OID_POLICY_MAPPINGS = ExtensionOID.POLICY_MAPPINGS +OID_SUBJECT_ALTERNATIVE_NAME = ExtensionOID.SUBJECT_ALTERNATIVE_NAME +OID_SUBJECT_DIRECTORY_ATTRIBUTES = ExtensionOID.SUBJECT_DIRECTORY_ATTRIBUTES +OID_SUBJECT_INFORMATION_ACCESS = ExtensionOID.SUBJECT_INFORMATION_ACCESS +OID_SUBJECT_KEY_IDENTIFIER = ExtensionOID.SUBJECT_KEY_IDENTIFIER + +OID_DSA_WITH_SHA1 = SignatureAlgorithmOID.DSA_WITH_SHA1 +OID_DSA_WITH_SHA224 = SignatureAlgorithmOID.DSA_WITH_SHA224 +OID_DSA_WITH_SHA256 = SignatureAlgorithmOID.DSA_WITH_SHA256 +OID_ECDSA_WITH_SHA1 = SignatureAlgorithmOID.ECDSA_WITH_SHA1 +OID_ECDSA_WITH_SHA224 = SignatureAlgorithmOID.ECDSA_WITH_SHA224 +OID_ECDSA_WITH_SHA256 = SignatureAlgorithmOID.ECDSA_WITH_SHA256 +OID_ECDSA_WITH_SHA384 = SignatureAlgorithmOID.ECDSA_WITH_SHA384 +OID_ECDSA_WITH_SHA512 = SignatureAlgorithmOID.ECDSA_WITH_SHA512 +OID_RSA_WITH_MD5 = SignatureAlgorithmOID.RSA_WITH_MD5 +OID_RSA_WITH_SHA1 = SignatureAlgorithmOID.RSA_WITH_SHA1 +OID_RSA_WITH_SHA224 = SignatureAlgorithmOID.RSA_WITH_SHA224 +OID_RSA_WITH_SHA256 = SignatureAlgorithmOID.RSA_WITH_SHA256 +OID_RSA_WITH_SHA384 = SignatureAlgorithmOID.RSA_WITH_SHA384 +OID_RSA_WITH_SHA512 = SignatureAlgorithmOID.RSA_WITH_SHA512 +OID_RSASSA_PSS = SignatureAlgorithmOID.RSASSA_PSS + +OID_COMMON_NAME = NameOID.COMMON_NAME +OID_COUNTRY_NAME = NameOID.COUNTRY_NAME +OID_DOMAIN_COMPONENT = NameOID.DOMAIN_COMPONENT +OID_DN_QUALIFIER = NameOID.DN_QUALIFIER +OID_EMAIL_ADDRESS = NameOID.EMAIL_ADDRESS +OID_GENERATION_QUALIFIER = NameOID.GENERATION_QUALIFIER +OID_GIVEN_NAME = NameOID.GIVEN_NAME +OID_LOCALITY_NAME = NameOID.LOCALITY_NAME +OID_ORGANIZATIONAL_UNIT_NAME = NameOID.ORGANIZATIONAL_UNIT_NAME +OID_ORGANIZATION_NAME = NameOID.ORGANIZATION_NAME +OID_PSEUDONYM = NameOID.PSEUDONYM +OID_SERIAL_NUMBER = NameOID.SERIAL_NUMBER +OID_STATE_OR_PROVINCE_NAME = NameOID.STATE_OR_PROVINCE_NAME +OID_SURNAME = NameOID.SURNAME +OID_TITLE = NameOID.TITLE + +OID_CLIENT_AUTH = ExtendedKeyUsageOID.CLIENT_AUTH +OID_CODE_SIGNING = ExtendedKeyUsageOID.CODE_SIGNING +OID_EMAIL_PROTECTION = ExtendedKeyUsageOID.EMAIL_PROTECTION +OID_OCSP_SIGNING = ExtendedKeyUsageOID.OCSP_SIGNING +OID_SERVER_AUTH = ExtendedKeyUsageOID.SERVER_AUTH +OID_TIME_STAMPING = ExtendedKeyUsageOID.TIME_STAMPING + +OID_ANY_POLICY = CertificatePoliciesOID.ANY_POLICY +OID_CPS_QUALIFIER = CertificatePoliciesOID.CPS_QUALIFIER +OID_CPS_USER_NOTICE = CertificatePoliciesOID.CPS_USER_NOTICE + +OID_CERTIFICATE_ISSUER = CRLEntryExtensionOID.CERTIFICATE_ISSUER +OID_CRL_REASON = CRLEntryExtensionOID.CRL_REASON +OID_INVALIDITY_DATE = CRLEntryExtensionOID.INVALIDITY_DATE + +OID_CA_ISSUERS = AuthorityInformationAccessOID.CA_ISSUERS +OID_OCSP = AuthorityInformationAccessOID.OCSP + +__all__ = [ + "OID_CA_ISSUERS", + "OID_OCSP", + "AccessDescription", + "Admission", + "Admissions", + "Attribute", + "AttributeNotFound", + "Attributes", + "AuthorityInformationAccess", + "AuthorityKeyIdentifier", + "BasicConstraints", + "CRLDistributionPoints", + "CRLNumber", + "CRLReason", + "Certificate", + "CertificateBuilder", + "CertificateIssuer", + "CertificatePolicies", + "CertificateRevocationList", + "CertificateRevocationListBuilder", + "CertificateSigningRequest", + "CertificateSigningRequestBuilder", + "DNSName", + "DeltaCRLIndicator", + "DirectoryName", + "DistributionPoint", + "DuplicateExtension", + "ExtendedKeyUsage", + "Extension", + "ExtensionNotFound", + "ExtensionType", + "Extensions", + "FreshestCRL", + "GeneralName", + "GeneralNames", + "IPAddress", + "InhibitAnyPolicy", + "InvalidVersion", + "InvalidityDate", + "IssuerAlternativeName", + "IssuingDistributionPoint", + "KeyUsage", + "MSCertificateTemplate", + "Name", + "NameAttribute", + "NameConstraints", + "NameOID", + "NamingAuthority", + "NoticeReference", + "OCSPAcceptableResponses", + "OCSPNoCheck", + "OCSPNonce", + "ObjectIdentifier", + "OtherName", + "PolicyConstraints", + "PolicyInformation", + "PrecertPoison", + "PrecertificateSignedCertificateTimestamps", + "PrivateKeyUsagePeriod", + "ProfessionInfo", + "PublicKeyAlgorithmOID", + "RFC822Name", + "ReasonFlags", + "RegisteredID", + "RelativeDistinguishedName", + "RevokedCertificate", + "RevokedCertificateBuilder", + "SignatureAlgorithmOID", + "SignedCertificateTimestamps", + "SubjectAlternativeName", + "SubjectInformationAccess", + "SubjectKeyIdentifier", + "TLSFeature", + "TLSFeatureType", + "UniformResourceIdentifier", + "UnrecognizedExtension", + "UnsupportedGeneralNameType", + "UserNotice", + "Version", + "certificate_transparency", + "load_der_x509_certificate", + "load_der_x509_crl", + "load_der_x509_csr", + "load_pem_x509_certificate", + "load_pem_x509_certificates", + "load_pem_x509_crl", + "load_pem_x509_csr", + "oid", + "random_serial_number", + "verification", + "verification", +] diff --git a/python/user_packages/Python313/site-packages/cryptography/x509/__pycache__/__init__.cpython-313.pyc b/python/user_packages/Python313/site-packages/cryptography/x509/__pycache__/__init__.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4f0aa48d520925a5cf891ed7fbe0bf6029ffb84f Binary files /dev/null and b/python/user_packages/Python313/site-packages/cryptography/x509/__pycache__/__init__.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/cryptography/x509/__pycache__/base.cpython-313.pyc b/python/user_packages/Python313/site-packages/cryptography/x509/__pycache__/base.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7dbe2530b189f559760f27bdf6d369351c06125b Binary files /dev/null and b/python/user_packages/Python313/site-packages/cryptography/x509/__pycache__/base.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/cryptography/x509/__pycache__/certificate_transparency.cpython-313.pyc b/python/user_packages/Python313/site-packages/cryptography/x509/__pycache__/certificate_transparency.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3539f64a57d727ec2f04da9ff2af3958d425c909 Binary files /dev/null and b/python/user_packages/Python313/site-packages/cryptography/x509/__pycache__/certificate_transparency.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/cryptography/x509/__pycache__/general_name.cpython-313.pyc b/python/user_packages/Python313/site-packages/cryptography/x509/__pycache__/general_name.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a5e73905f7793ca951d56a386a6842f0fd8ceb1d Binary files /dev/null and b/python/user_packages/Python313/site-packages/cryptography/x509/__pycache__/general_name.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/cryptography/x509/__pycache__/name.cpython-313.pyc b/python/user_packages/Python313/site-packages/cryptography/x509/__pycache__/name.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f6191439b902eacdd8362117fb169c6098a004c0 Binary files /dev/null and b/python/user_packages/Python313/site-packages/cryptography/x509/__pycache__/name.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/cryptography/x509/__pycache__/ocsp.cpython-313.pyc b/python/user_packages/Python313/site-packages/cryptography/x509/__pycache__/ocsp.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..bbbcfeac111054bd442590db6efd074959c3bb35 Binary files /dev/null and b/python/user_packages/Python313/site-packages/cryptography/x509/__pycache__/ocsp.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/cryptography/x509/__pycache__/oid.cpython-313.pyc b/python/user_packages/Python313/site-packages/cryptography/x509/__pycache__/oid.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b63e59213afbe871089eddd02dd750e8373d8e6c Binary files /dev/null and b/python/user_packages/Python313/site-packages/cryptography/x509/__pycache__/oid.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/cryptography/x509/__pycache__/verification.cpython-313.pyc b/python/user_packages/Python313/site-packages/cryptography/x509/__pycache__/verification.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..faec212a075c7ab6d9b585d754ce0ee6cf2239c9 Binary files /dev/null and b/python/user_packages/Python313/site-packages/cryptography/x509/__pycache__/verification.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/cryptography/x509/base.py b/python/user_packages/Python313/site-packages/cryptography/x509/base.py new file mode 100644 index 0000000000000000000000000000000000000000..a11b8fe02b730aa4f1f668dd86e0cd7cc0568395 --- /dev/null +++ b/python/user_packages/Python313/site-packages/cryptography/x509/base.py @@ -0,0 +1,773 @@ +# This file is dual licensed under the terms of the Apache License, Version +# 2.0, and the BSD License. See the LICENSE file in the root of this repository +# for complete details. + +from __future__ import annotations + +import datetime +import os +import typing +from collections.abc import Iterable + +from cryptography import utils +from cryptography.hazmat.bindings._rust import x509 as rust_x509 +from cryptography.hazmat.primitives import hashes +from cryptography.hazmat.primitives.asymmetric import ( + dsa, + ec, + ed448, + ed25519, + padding, + rsa, + x448, + x25519, +) +from cryptography.hazmat.primitives.asymmetric.types import ( + CertificateIssuerPrivateKeyTypes, + CertificatePublicKeyTypes, +) +from cryptography.x509.extensions import ( + Extension, + ExtensionType, + _make_sequence_methods, +) +from cryptography.x509.name import Name, _ASN1Type +from cryptography.x509.oid import ObjectIdentifier + +_EARLIEST_UTC_TIME = datetime.datetime(1950, 1, 1) + +# This must be kept in sync with sign.rs's list of allowable types in +# identify_hash_type +_AllowedHashTypes = typing.Union[ + hashes.SHA224, + hashes.SHA256, + hashes.SHA384, + hashes.SHA512, + hashes.SHA3_224, + hashes.SHA3_256, + hashes.SHA3_384, + hashes.SHA3_512, +] + + +class AttributeNotFound(Exception): + def __init__(self, msg: str, oid: ObjectIdentifier) -> None: + super().__init__(msg) + self.oid = oid + + +def _reject_duplicate_extension( + extension: Extension[ExtensionType], + extensions: list[Extension[ExtensionType]], +) -> None: + # This is quadratic in the number of extensions + for e in extensions: + if e.oid == extension.oid: + raise ValueError("This extension has already been set.") + + +def _reject_duplicate_attribute( + oid: ObjectIdentifier, + attributes: list[tuple[ObjectIdentifier, bytes, int | None]], +) -> None: + # This is quadratic in the number of attributes + for attr_oid, _, _ in attributes: + if attr_oid == oid: + raise ValueError("This attribute has already been set.") + + +def _convert_to_naive_utc_time(time: datetime.datetime) -> datetime.datetime: + """Normalizes a datetime to a naive datetime in UTC. + + time -- datetime to normalize. Assumed to be in UTC if not timezone + aware. + """ + if time.tzinfo is not None: + offset = time.utcoffset() + offset = offset if offset else datetime.timedelta() + return time.replace(tzinfo=None) - offset + else: + return time + + +class Attribute: + def __init__( + self, + oid: ObjectIdentifier, + value: bytes, + _type: int = _ASN1Type.UTF8String.value, + ) -> None: + self._oid = oid + self._value = value + self._type = _type + + @property + def oid(self) -> ObjectIdentifier: + return self._oid + + @property + def value(self) -> bytes: + return self._value + + def __repr__(self) -> str: + return f"" + + def __eq__(self, other: object) -> bool: + if not isinstance(other, Attribute): + return NotImplemented + + return ( + self.oid == other.oid + and self.value == other.value + and self._type == other._type + ) + + def __hash__(self) -> int: + return hash((self.oid, self.value, self._type)) + + +class Attributes: + def __init__( + self, + attributes: Iterable[Attribute], + ) -> None: + self._attributes = list(attributes) + + __len__, __iter__, __getitem__ = _make_sequence_methods("_attributes") + + def __repr__(self) -> str: + return f"" + + def get_attribute_for_oid(self, oid: ObjectIdentifier) -> Attribute: + for attr in self: + if attr.oid == oid: + return attr + + raise AttributeNotFound(f"No {oid} attribute was found", oid) + + +class Version(utils.Enum): + v1 = 0 + v3 = 2 + + +class InvalidVersion(Exception): + def __init__(self, msg: str, parsed_version: int) -> None: + super().__init__(msg) + self.parsed_version = parsed_version + + +Certificate = rust_x509.Certificate +RevokedCertificate = rust_x509.RevokedCertificate + + +CertificateRevocationList = rust_x509.CertificateRevocationList +CertificateSigningRequest = rust_x509.CertificateSigningRequest + + +load_pem_x509_certificate = rust_x509.load_pem_x509_certificate +load_der_x509_certificate = rust_x509.load_der_x509_certificate + +load_pem_x509_certificates = rust_x509.load_pem_x509_certificates + +load_pem_x509_csr = rust_x509.load_pem_x509_csr +load_der_x509_csr = rust_x509.load_der_x509_csr + +load_pem_x509_crl = rust_x509.load_pem_x509_crl +load_der_x509_crl = rust_x509.load_der_x509_crl + + +class CertificateSigningRequestBuilder: + def __init__( + self, + subject_name: Name | None = None, + extensions: list[Extension[ExtensionType]] = [], + attributes: list[tuple[ObjectIdentifier, bytes, int | None]] = [], + ): + """ + Creates an empty X.509 certificate request (v1). + """ + self._subject_name = subject_name + self._extensions = extensions + self._attributes = attributes + + def subject_name(self, name: Name) -> CertificateSigningRequestBuilder: + """ + Sets the certificate requestor's distinguished name. + """ + if not isinstance(name, Name): + raise TypeError("Expecting x509.Name object.") + if self._subject_name is not None: + raise ValueError("The subject name may only be set once.") + return CertificateSigningRequestBuilder( + name, self._extensions, self._attributes + ) + + def add_extension( + self, extval: ExtensionType, critical: bool + ) -> CertificateSigningRequestBuilder: + """ + Adds an X.509 extension to the certificate request. + """ + if not isinstance(extval, ExtensionType): + raise TypeError("extension must be an ExtensionType") + + extension = Extension(extval.oid, critical, extval) + _reject_duplicate_extension(extension, self._extensions) + + return CertificateSigningRequestBuilder( + self._subject_name, + [*self._extensions, extension], + self._attributes, + ) + + def add_attribute( + self, + oid: ObjectIdentifier, + value: bytes, + *, + _tag: _ASN1Type | None = None, + ) -> CertificateSigningRequestBuilder: + """ + Adds an X.509 attribute with an OID and associated value. + """ + if not isinstance(oid, ObjectIdentifier): + raise TypeError("oid must be an ObjectIdentifier") + + if not isinstance(value, bytes): + raise TypeError("value must be bytes") + + if _tag is not None and not isinstance(_tag, _ASN1Type): + raise TypeError("tag must be _ASN1Type") + + _reject_duplicate_attribute(oid, self._attributes) + + if _tag is not None: + tag = _tag.value + else: + tag = None + + return CertificateSigningRequestBuilder( + self._subject_name, + self._extensions, + [*self._attributes, (oid, value, tag)], + ) + + def sign( + self, + private_key: CertificateIssuerPrivateKeyTypes, + algorithm: _AllowedHashTypes | None, + backend: typing.Any = None, + *, + rsa_padding: padding.PSS | padding.PKCS1v15 | None = None, + ecdsa_deterministic: bool | None = None, + ) -> CertificateSigningRequest: + """ + Signs the request using the requestor's private key. + """ + if self._subject_name is None: + raise ValueError("A CertificateSigningRequest must have a subject") + + if rsa_padding is not None: + if not isinstance(rsa_padding, (padding.PSS, padding.PKCS1v15)): + raise TypeError("Padding must be PSS or PKCS1v15") + if not isinstance(private_key, rsa.RSAPrivateKey): + raise TypeError("Padding is only supported for RSA keys") + + if ecdsa_deterministic is not None: + if not isinstance(private_key, ec.EllipticCurvePrivateKey): + raise TypeError( + "Deterministic ECDSA is only supported for EC keys" + ) + + return rust_x509.create_x509_csr( + self, + private_key, + algorithm, + rsa_padding, + ecdsa_deterministic, + ) + + +class CertificateBuilder: + _extensions: list[Extension[ExtensionType]] + + def __init__( + self, + issuer_name: Name | None = None, + subject_name: Name | None = None, + public_key: CertificatePublicKeyTypes | None = None, + serial_number: int | None = None, + not_valid_before: datetime.datetime | None = None, + not_valid_after: datetime.datetime | None = None, + extensions: list[Extension[ExtensionType]] = [], + ) -> None: + self._version = Version.v3 + self._issuer_name = issuer_name + self._subject_name = subject_name + self._public_key = public_key + self._serial_number = serial_number + self._not_valid_before = not_valid_before + self._not_valid_after = not_valid_after + self._extensions = extensions + + def issuer_name(self, name: Name) -> CertificateBuilder: + """ + Sets the CA's distinguished name. + """ + if not isinstance(name, Name): + raise TypeError("Expecting x509.Name object.") + if self._issuer_name is not None: + raise ValueError("The issuer name may only be set once.") + return CertificateBuilder( + name, + self._subject_name, + self._public_key, + self._serial_number, + self._not_valid_before, + self._not_valid_after, + self._extensions, + ) + + def subject_name(self, name: Name) -> CertificateBuilder: + """ + Sets the requestor's distinguished name. + """ + if not isinstance(name, Name): + raise TypeError("Expecting x509.Name object.") + if self._subject_name is not None: + raise ValueError("The subject name may only be set once.") + return CertificateBuilder( + self._issuer_name, + name, + self._public_key, + self._serial_number, + self._not_valid_before, + self._not_valid_after, + self._extensions, + ) + + def public_key( + self, + key: CertificatePublicKeyTypes, + ) -> CertificateBuilder: + """ + Sets the requestor's public key (as found in the signing request). + """ + if not isinstance( + key, + ( + dsa.DSAPublicKey, + rsa.RSAPublicKey, + ec.EllipticCurvePublicKey, + ed25519.Ed25519PublicKey, + ed448.Ed448PublicKey, + x25519.X25519PublicKey, + x448.X448PublicKey, + ), + ): + raise TypeError( + "Expecting one of DSAPublicKey, RSAPublicKey," + " EllipticCurvePublicKey, Ed25519PublicKey," + " Ed448PublicKey, X25519PublicKey, or " + "X448PublicKey." + ) + if self._public_key is not None: + raise ValueError("The public key may only be set once.") + return CertificateBuilder( + self._issuer_name, + self._subject_name, + key, + self._serial_number, + self._not_valid_before, + self._not_valid_after, + self._extensions, + ) + + def serial_number(self, number: int) -> CertificateBuilder: + """ + Sets the certificate serial number. + """ + if not isinstance(number, int): + raise TypeError("Serial number must be of integral type.") + if self._serial_number is not None: + raise ValueError("The serial number may only be set once.") + if number <= 0: + raise ValueError("The serial number should be positive.") + + # ASN.1 integers are always signed, so most significant bit must be + # zero. + if number.bit_length() >= 160: # As defined in RFC 5280 + raise ValueError( + "The serial number should not be more than 159 bits." + ) + return CertificateBuilder( + self._issuer_name, + self._subject_name, + self._public_key, + number, + self._not_valid_before, + self._not_valid_after, + self._extensions, + ) + + def not_valid_before(self, time: datetime.datetime) -> CertificateBuilder: + """ + Sets the certificate activation time. + """ + if not isinstance(time, datetime.datetime): + raise TypeError("Expecting datetime object.") + if self._not_valid_before is not None: + raise ValueError("The not valid before may only be set once.") + time = _convert_to_naive_utc_time(time) + if time < _EARLIEST_UTC_TIME: + raise ValueError( + "The not valid before date must be on or after" + " 1950 January 1)." + ) + if self._not_valid_after is not None and time > self._not_valid_after: + raise ValueError( + "The not valid before date must be before the not valid after " + "date." + ) + return CertificateBuilder( + self._issuer_name, + self._subject_name, + self._public_key, + self._serial_number, + time, + self._not_valid_after, + self._extensions, + ) + + def not_valid_after(self, time: datetime.datetime) -> CertificateBuilder: + """ + Sets the certificate expiration time. + """ + if not isinstance(time, datetime.datetime): + raise TypeError("Expecting datetime object.") + if self._not_valid_after is not None: + raise ValueError("The not valid after may only be set once.") + time = _convert_to_naive_utc_time(time) + if time < _EARLIEST_UTC_TIME: + raise ValueError( + "The not valid after date must be on or after 1950 January 1." + ) + if ( + self._not_valid_before is not None + and time < self._not_valid_before + ): + raise ValueError( + "The not valid after date must be after the not valid before " + "date." + ) + return CertificateBuilder( + self._issuer_name, + self._subject_name, + self._public_key, + self._serial_number, + self._not_valid_before, + time, + self._extensions, + ) + + def add_extension( + self, extval: ExtensionType, critical: bool + ) -> CertificateBuilder: + """ + Adds an X.509 extension to the certificate. + """ + if not isinstance(extval, ExtensionType): + raise TypeError("extension must be an ExtensionType") + + extension = Extension(extval.oid, critical, extval) + _reject_duplicate_extension(extension, self._extensions) + + return CertificateBuilder( + self._issuer_name, + self._subject_name, + self._public_key, + self._serial_number, + self._not_valid_before, + self._not_valid_after, + [*self._extensions, extension], + ) + + def sign( + self, + private_key: CertificateIssuerPrivateKeyTypes, + algorithm: _AllowedHashTypes | None, + backend: typing.Any = None, + *, + rsa_padding: padding.PSS | padding.PKCS1v15 | None = None, + ecdsa_deterministic: bool | None = None, + ) -> Certificate: + """ + Signs the certificate using the CA's private key. + """ + if self._subject_name is None: + raise ValueError("A certificate must have a subject name") + + if self._issuer_name is None: + raise ValueError("A certificate must have an issuer name") + + if self._serial_number is None: + raise ValueError("A certificate must have a serial number") + + if self._not_valid_before is None: + raise ValueError("A certificate must have a not valid before time") + + if self._not_valid_after is None: + raise ValueError("A certificate must have a not valid after time") + + if self._public_key is None: + raise ValueError("A certificate must have a public key") + + if rsa_padding is not None: + if not isinstance(rsa_padding, (padding.PSS, padding.PKCS1v15)): + raise TypeError("Padding must be PSS or PKCS1v15") + if not isinstance(private_key, rsa.RSAPrivateKey): + raise TypeError("Padding is only supported for RSA keys") + + if ecdsa_deterministic is not None: + if not isinstance(private_key, ec.EllipticCurvePrivateKey): + raise TypeError( + "Deterministic ECDSA is only supported for EC keys" + ) + + return rust_x509.create_x509_certificate( + self, + private_key, + algorithm, + rsa_padding, + ecdsa_deterministic, + ) + + +class CertificateRevocationListBuilder: + _extensions: list[Extension[ExtensionType]] + _revoked_certificates: list[RevokedCertificate] + + def __init__( + self, + issuer_name: Name | None = None, + last_update: datetime.datetime | None = None, + next_update: datetime.datetime | None = None, + extensions: list[Extension[ExtensionType]] = [], + revoked_certificates: list[RevokedCertificate] = [], + ): + self._issuer_name = issuer_name + self._last_update = last_update + self._next_update = next_update + self._extensions = extensions + self._revoked_certificates = revoked_certificates + + def issuer_name( + self, issuer_name: Name + ) -> CertificateRevocationListBuilder: + if not isinstance(issuer_name, Name): + raise TypeError("Expecting x509.Name object.") + if self._issuer_name is not None: + raise ValueError("The issuer name may only be set once.") + return CertificateRevocationListBuilder( + issuer_name, + self._last_update, + self._next_update, + self._extensions, + self._revoked_certificates, + ) + + def last_update( + self, last_update: datetime.datetime + ) -> CertificateRevocationListBuilder: + if not isinstance(last_update, datetime.datetime): + raise TypeError("Expecting datetime object.") + if self._last_update is not None: + raise ValueError("Last update may only be set once.") + last_update = _convert_to_naive_utc_time(last_update) + if last_update < _EARLIEST_UTC_TIME: + raise ValueError( + "The last update date must be on or after 1950 January 1." + ) + if self._next_update is not None and last_update > self._next_update: + raise ValueError( + "The last update date must be before the next update date." + ) + return CertificateRevocationListBuilder( + self._issuer_name, + last_update, + self._next_update, + self._extensions, + self._revoked_certificates, + ) + + def next_update( + self, next_update: datetime.datetime + ) -> CertificateRevocationListBuilder: + if not isinstance(next_update, datetime.datetime): + raise TypeError("Expecting datetime object.") + if self._next_update is not None: + raise ValueError("Last update may only be set once.") + next_update = _convert_to_naive_utc_time(next_update) + if next_update < _EARLIEST_UTC_TIME: + raise ValueError( + "The last update date must be on or after 1950 January 1." + ) + if self._last_update is not None and next_update < self._last_update: + raise ValueError( + "The next update date must be after the last update date." + ) + return CertificateRevocationListBuilder( + self._issuer_name, + self._last_update, + next_update, + self._extensions, + self._revoked_certificates, + ) + + def add_extension( + self, extval: ExtensionType, critical: bool + ) -> CertificateRevocationListBuilder: + """ + Adds an X.509 extension to the certificate revocation list. + """ + if not isinstance(extval, ExtensionType): + raise TypeError("extension must be an ExtensionType") + + extension = Extension(extval.oid, critical, extval) + _reject_duplicate_extension(extension, self._extensions) + return CertificateRevocationListBuilder( + self._issuer_name, + self._last_update, + self._next_update, + [*self._extensions, extension], + self._revoked_certificates, + ) + + def add_revoked_certificate( + self, revoked_certificate: RevokedCertificate + ) -> CertificateRevocationListBuilder: + """ + Adds a revoked certificate to the CRL. + """ + if not isinstance(revoked_certificate, RevokedCertificate): + raise TypeError("Must be an instance of RevokedCertificate") + + return CertificateRevocationListBuilder( + self._issuer_name, + self._last_update, + self._next_update, + self._extensions, + [*self._revoked_certificates, revoked_certificate], + ) + + def sign( + self, + private_key: CertificateIssuerPrivateKeyTypes, + algorithm: _AllowedHashTypes | None, + backend: typing.Any = None, + *, + rsa_padding: padding.PSS | padding.PKCS1v15 | None = None, + ecdsa_deterministic: bool | None = None, + ) -> CertificateRevocationList: + if self._issuer_name is None: + raise ValueError("A CRL must have an issuer name") + + if self._last_update is None: + raise ValueError("A CRL must have a last update time") + + if self._next_update is None: + raise ValueError("A CRL must have a next update time") + + if rsa_padding is not None: + if not isinstance(rsa_padding, (padding.PSS, padding.PKCS1v15)): + raise TypeError("Padding must be PSS or PKCS1v15") + if not isinstance(private_key, rsa.RSAPrivateKey): + raise TypeError("Padding is only supported for RSA keys") + + if ecdsa_deterministic is not None: + if not isinstance(private_key, ec.EllipticCurvePrivateKey): + raise TypeError( + "Deterministic ECDSA is only supported for EC keys" + ) + + return rust_x509.create_x509_crl( + self, + private_key, + algorithm, + rsa_padding, + ecdsa_deterministic, + ) + + +class RevokedCertificateBuilder: + def __init__( + self, + serial_number: int | None = None, + revocation_date: datetime.datetime | None = None, + extensions: list[Extension[ExtensionType]] = [], + ): + self._serial_number = serial_number + self._revocation_date = revocation_date + self._extensions = extensions + + def serial_number(self, number: int) -> RevokedCertificateBuilder: + if not isinstance(number, int): + raise TypeError("Serial number must be of integral type.") + if self._serial_number is not None: + raise ValueError("The serial number may only be set once.") + if number <= 0: + raise ValueError("The serial number should be positive") + + # ASN.1 integers are always signed, so most significant bit must be + # zero. + if number.bit_length() >= 160: # As defined in RFC 5280 + raise ValueError( + "The serial number should not be more than 159 bits." + ) + return RevokedCertificateBuilder( + number, self._revocation_date, self._extensions + ) + + def revocation_date( + self, time: datetime.datetime + ) -> RevokedCertificateBuilder: + if not isinstance(time, datetime.datetime): + raise TypeError("Expecting datetime object.") + if self._revocation_date is not None: + raise ValueError("The revocation date may only be set once.") + time = _convert_to_naive_utc_time(time) + if time < _EARLIEST_UTC_TIME: + raise ValueError( + "The revocation date must be on or after 1950 January 1." + ) + return RevokedCertificateBuilder( + self._serial_number, time, self._extensions + ) + + def add_extension( + self, extval: ExtensionType, critical: bool + ) -> RevokedCertificateBuilder: + if not isinstance(extval, ExtensionType): + raise TypeError("extension must be an ExtensionType") + + extension = Extension(extval.oid, critical, extval) + _reject_duplicate_extension(extension, self._extensions) + return RevokedCertificateBuilder( + self._serial_number, + self._revocation_date, + [*self._extensions, extension], + ) + + def build(self, backend: typing.Any = None) -> RevokedCertificate: + if self._serial_number is None: + raise ValueError("A revoked certificate must have a serial number") + if self._revocation_date is None: + raise ValueError( + "A revoked certificate must have a revocation date" + ) + return rust_x509.create_revoked_certificate(self) + + +def random_serial_number() -> int: + return int.from_bytes(os.urandom(20), "big") >> 1 diff --git a/python/user_packages/Python313/site-packages/cryptography/x509/certificate_transparency.py b/python/user_packages/Python313/site-packages/cryptography/x509/certificate_transparency.py new file mode 100644 index 0000000000000000000000000000000000000000..fb66cc6049528dd012f07bfcef765e284d0062d2 --- /dev/null +++ b/python/user_packages/Python313/site-packages/cryptography/x509/certificate_transparency.py @@ -0,0 +1,35 @@ +# This file is dual licensed under the terms of the Apache License, Version +# 2.0, and the BSD License. See the LICENSE file in the root of this repository +# for complete details. + +from __future__ import annotations + +from cryptography import utils +from cryptography.hazmat.bindings._rust import x509 as rust_x509 + + +class LogEntryType(utils.Enum): + X509_CERTIFICATE = 0 + PRE_CERTIFICATE = 1 + + +class Version(utils.Enum): + v1 = 0 + + +class SignatureAlgorithm(utils.Enum): + """ + Signature algorithms that are valid for SCTs. + + These are exactly the same as SignatureAlgorithm in RFC 5246 (TLS 1.2). + + See: + """ + + ANONYMOUS = 0 + RSA = 1 + DSA = 2 + ECDSA = 3 + + +SignedCertificateTimestamp = rust_x509.Sct diff --git a/python/user_packages/Python313/site-packages/cryptography/x509/extensions.py b/python/user_packages/Python313/site-packages/cryptography/x509/extensions.py new file mode 100644 index 0000000000000000000000000000000000000000..7b78e9e28b144cc188a08de0d23277584b6a7fbb --- /dev/null +++ b/python/user_packages/Python313/site-packages/cryptography/x509/extensions.py @@ -0,0 +1,2533 @@ +# This file is dual licensed under the terms of the Apache License, Version +# 2.0, and the BSD License. See the LICENSE file in the root of this repository +# for complete details. + +from __future__ import annotations + +import abc +import datetime +import hashlib +import ipaddress +import typing +from collections.abc import Iterable, Iterator + +from cryptography import utils +from cryptography.hazmat.bindings._rust import asn1 +from cryptography.hazmat.bindings._rust import x509 as rust_x509 +from cryptography.hazmat.primitives import constant_time, serialization +from cryptography.hazmat.primitives.asymmetric.ec import EllipticCurvePublicKey +from cryptography.hazmat.primitives.asymmetric.rsa import RSAPublicKey +from cryptography.hazmat.primitives.asymmetric.types import ( + CertificateIssuerPublicKeyTypes, + CertificatePublicKeyTypes, +) +from cryptography.x509.certificate_transparency import ( + SignedCertificateTimestamp, +) +from cryptography.x509.general_name import ( + DirectoryName, + DNSName, + GeneralName, + IPAddress, + OtherName, + RegisteredID, + RFC822Name, + UniformResourceIdentifier, + _IPAddressTypes, +) +from cryptography.x509.name import Name, RelativeDistinguishedName +from cryptography.x509.oid import ( + CRLEntryExtensionOID, + ExtensionOID, + ObjectIdentifier, + OCSPExtensionOID, +) + +ExtensionTypeVar = typing.TypeVar( + "ExtensionTypeVar", bound="ExtensionType", covariant=True +) + + +def _key_identifier_from_public_key( + public_key: CertificatePublicKeyTypes, +) -> bytes: + if isinstance(public_key, RSAPublicKey): + data = public_key.public_bytes( + serialization.Encoding.DER, + serialization.PublicFormat.PKCS1, + ) + elif isinstance(public_key, EllipticCurvePublicKey): + data = public_key.public_bytes( + serialization.Encoding.X962, + serialization.PublicFormat.UncompressedPoint, + ) + else: + # This is a very slow way to do this. + serialized = public_key.public_bytes( + serialization.Encoding.DER, + serialization.PublicFormat.SubjectPublicKeyInfo, + ) + data = asn1.parse_spki_for_data(serialized) + + return hashlib.sha1(data).digest() + + +def _make_sequence_methods(field_name: str): + def len_method(self) -> int: + return len(getattr(self, field_name)) + + def iter_method(self): + return iter(getattr(self, field_name)) + + def getitem_method(self, idx): + return getattr(self, field_name)[idx] + + return len_method, iter_method, getitem_method + + +class DuplicateExtension(Exception): + def __init__(self, msg: str, oid: ObjectIdentifier) -> None: + super().__init__(msg) + self.oid = oid + + +class ExtensionNotFound(Exception): + def __init__(self, msg: str, oid: ObjectIdentifier) -> None: + super().__init__(msg) + self.oid = oid + + +class ExtensionType(metaclass=abc.ABCMeta): + oid: typing.ClassVar[ObjectIdentifier] + + def public_bytes(self) -> bytes: + """ + Serializes the extension type to DER. + """ + raise NotImplementedError( + f"public_bytes is not implemented for extension type {self!r}" + ) + + +class Extensions: + def __init__(self, extensions: Iterable[Extension[ExtensionType]]) -> None: + self._extensions = list(extensions) + + def get_extension_for_oid( + self, oid: ObjectIdentifier + ) -> Extension[ExtensionType]: + for ext in self: + if ext.oid == oid: + return ext + + raise ExtensionNotFound(f"No {oid} extension was found", oid) + + def get_extension_for_class( + self, extclass: type[ExtensionTypeVar] + ) -> Extension[ExtensionTypeVar]: + if extclass is UnrecognizedExtension: + raise TypeError( + "UnrecognizedExtension can't be used with " + "get_extension_for_class because more than one instance of the" + " class may be present." + ) + + for ext in self: + if isinstance(ext.value, extclass): + return ext + + raise ExtensionNotFound( + f"No {extclass} extension was found", extclass.oid + ) + + __len__, __iter__, __getitem__ = _make_sequence_methods("_extensions") + + def __repr__(self) -> str: + return f"" + + +class CRLNumber(ExtensionType): + oid = ExtensionOID.CRL_NUMBER + + def __init__(self, crl_number: int) -> None: + if not isinstance(crl_number, int): + raise TypeError("crl_number must be an integer") + + self._crl_number = crl_number + + def __eq__(self, other: object) -> bool: + if not isinstance(other, CRLNumber): + return NotImplemented + + return self.crl_number == other.crl_number + + def __hash__(self) -> int: + return hash(self.crl_number) + + def __repr__(self) -> str: + return f"" + + @property + def crl_number(self) -> int: + return self._crl_number + + def public_bytes(self) -> bytes: + return rust_x509.encode_extension_value(self) + + +class AuthorityKeyIdentifier(ExtensionType): + oid = ExtensionOID.AUTHORITY_KEY_IDENTIFIER + + def __init__( + self, + key_identifier: bytes | None, + authority_cert_issuer: Iterable[GeneralName] | None, + authority_cert_serial_number: int | None, + ) -> None: + if (authority_cert_issuer is None) != ( + authority_cert_serial_number is None + ): + raise ValueError( + "authority_cert_issuer and authority_cert_serial_number " + "must both be present or both None" + ) + + if authority_cert_issuer is not None: + authority_cert_issuer = list(authority_cert_issuer) + if not all( + isinstance(x, GeneralName) for x in authority_cert_issuer + ): + raise TypeError( + "authority_cert_issuer must be a list of GeneralName " + "objects" + ) + + if authority_cert_serial_number is not None and not isinstance( + authority_cert_serial_number, int + ): + raise TypeError("authority_cert_serial_number must be an integer") + + self._key_identifier = key_identifier + self._authority_cert_issuer = authority_cert_issuer + self._authority_cert_serial_number = authority_cert_serial_number + + # This takes a subset of CertificatePublicKeyTypes because an issuer + # cannot have an X25519/X448 key. This introduces some unfortunate + # asymmetry that requires typing users to explicitly + # narrow their type, but we should make this accurate and not just + # convenient. + @classmethod + def from_issuer_public_key( + cls, public_key: CertificateIssuerPublicKeyTypes + ) -> AuthorityKeyIdentifier: + digest = _key_identifier_from_public_key(public_key) + return cls( + key_identifier=digest, + authority_cert_issuer=None, + authority_cert_serial_number=None, + ) + + @classmethod + def from_issuer_subject_key_identifier( + cls, ski: SubjectKeyIdentifier + ) -> AuthorityKeyIdentifier: + return cls( + key_identifier=ski.digest, + authority_cert_issuer=None, + authority_cert_serial_number=None, + ) + + def __repr__(self) -> str: + return ( + f"" + ) + + def __eq__(self, other: object) -> bool: + if not isinstance(other, AuthorityKeyIdentifier): + return NotImplemented + + return ( + self.key_identifier == other.key_identifier + and self.authority_cert_issuer == other.authority_cert_issuer + and self.authority_cert_serial_number + == other.authority_cert_serial_number + ) + + def __hash__(self) -> int: + if self.authority_cert_issuer is None: + aci = None + else: + aci = tuple(self.authority_cert_issuer) + return hash( + (self.key_identifier, aci, self.authority_cert_serial_number) + ) + + @property + def key_identifier(self) -> bytes | None: + return self._key_identifier + + @property + def authority_cert_issuer( + self, + ) -> list[GeneralName] | None: + return self._authority_cert_issuer + + @property + def authority_cert_serial_number(self) -> int | None: + return self._authority_cert_serial_number + + def public_bytes(self) -> bytes: + return rust_x509.encode_extension_value(self) + + +class SubjectKeyIdentifier(ExtensionType): + oid = ExtensionOID.SUBJECT_KEY_IDENTIFIER + + def __init__(self, digest: bytes) -> None: + self._digest = digest + + @classmethod + def from_public_key( + cls, public_key: CertificatePublicKeyTypes + ) -> SubjectKeyIdentifier: + return cls(_key_identifier_from_public_key(public_key)) + + @property + def digest(self) -> bytes: + return self._digest + + @property + def key_identifier(self) -> bytes: + return self._digest + + def __repr__(self) -> str: + return f"" + + def __eq__(self, other: object) -> bool: + if not isinstance(other, SubjectKeyIdentifier): + return NotImplemented + + return constant_time.bytes_eq(self.digest, other.digest) + + def __hash__(self) -> int: + return hash(self.digest) + + def public_bytes(self) -> bytes: + return rust_x509.encode_extension_value(self) + + +class AuthorityInformationAccess(ExtensionType): + oid = ExtensionOID.AUTHORITY_INFORMATION_ACCESS + + def __init__(self, descriptions: Iterable[AccessDescription]) -> None: + descriptions = list(descriptions) + if not all(isinstance(x, AccessDescription) for x in descriptions): + raise TypeError( + "Every item in the descriptions list must be an " + "AccessDescription" + ) + + self._descriptions = descriptions + + __len__, __iter__, __getitem__ = _make_sequence_methods("_descriptions") + + def __repr__(self) -> str: + return f"" + + def __eq__(self, other: object) -> bool: + if not isinstance(other, AuthorityInformationAccess): + return NotImplemented + + return self._descriptions == other._descriptions + + def __hash__(self) -> int: + return hash(tuple(self._descriptions)) + + def public_bytes(self) -> bytes: + return rust_x509.encode_extension_value(self) + + +class SubjectInformationAccess(ExtensionType): + oid = ExtensionOID.SUBJECT_INFORMATION_ACCESS + + def __init__(self, descriptions: Iterable[AccessDescription]) -> None: + descriptions = list(descriptions) + if not all(isinstance(x, AccessDescription) for x in descriptions): + raise TypeError( + "Every item in the descriptions list must be an " + "AccessDescription" + ) + + self._descriptions = descriptions + + __len__, __iter__, __getitem__ = _make_sequence_methods("_descriptions") + + def __repr__(self) -> str: + return f"" + + def __eq__(self, other: object) -> bool: + if not isinstance(other, SubjectInformationAccess): + return NotImplemented + + return self._descriptions == other._descriptions + + def __hash__(self) -> int: + return hash(tuple(self._descriptions)) + + def public_bytes(self) -> bytes: + return rust_x509.encode_extension_value(self) + + +class AccessDescription: + def __init__( + self, access_method: ObjectIdentifier, access_location: GeneralName + ) -> None: + if not isinstance(access_method, ObjectIdentifier): + raise TypeError("access_method must be an ObjectIdentifier") + + if not isinstance(access_location, GeneralName): + raise TypeError("access_location must be a GeneralName") + + self._access_method = access_method + self._access_location = access_location + + def __repr__(self) -> str: + return ( + f"" + ) + + def __eq__(self, other: object) -> bool: + if not isinstance(other, AccessDescription): + return NotImplemented + + return ( + self.access_method == other.access_method + and self.access_location == other.access_location + ) + + def __hash__(self) -> int: + return hash((self.access_method, self.access_location)) + + @property + def access_method(self) -> ObjectIdentifier: + return self._access_method + + @property + def access_location(self) -> GeneralName: + return self._access_location + + +class BasicConstraints(ExtensionType): + oid = ExtensionOID.BASIC_CONSTRAINTS + + def __init__(self, ca: bool, path_length: int | None) -> None: + if not isinstance(ca, bool): + raise TypeError("ca must be a boolean value") + + if path_length is not None and not ca: + raise ValueError("path_length must be None when ca is False") + + if path_length is not None and ( + not isinstance(path_length, int) or path_length < 0 + ): + raise TypeError( + "path_length must be a non-negative integer or None" + ) + + self._ca = ca + self._path_length = path_length + + @property + def ca(self) -> bool: + return self._ca + + @property + def path_length(self) -> int | None: + return self._path_length + + def __repr__(self) -> str: + return ( + f"" + ) + + def __eq__(self, other: object) -> bool: + if not isinstance(other, BasicConstraints): + return NotImplemented + + return self.ca == other.ca and self.path_length == other.path_length + + def __hash__(self) -> int: + return hash((self.ca, self.path_length)) + + def public_bytes(self) -> bytes: + return rust_x509.encode_extension_value(self) + + +class DeltaCRLIndicator(ExtensionType): + oid = ExtensionOID.DELTA_CRL_INDICATOR + + def __init__(self, crl_number: int) -> None: + if not isinstance(crl_number, int): + raise TypeError("crl_number must be an integer") + + self._crl_number = crl_number + + @property + def crl_number(self) -> int: + return self._crl_number + + def __eq__(self, other: object) -> bool: + if not isinstance(other, DeltaCRLIndicator): + return NotImplemented + + return self.crl_number == other.crl_number + + def __hash__(self) -> int: + return hash(self.crl_number) + + def __repr__(self) -> str: + return f"" + + def public_bytes(self) -> bytes: + return rust_x509.encode_extension_value(self) + + +class CRLDistributionPoints(ExtensionType): + oid = ExtensionOID.CRL_DISTRIBUTION_POINTS + + def __init__( + self, distribution_points: Iterable[DistributionPoint] + ) -> None: + distribution_points = list(distribution_points) + if not all( + isinstance(x, DistributionPoint) for x in distribution_points + ): + raise TypeError( + "distribution_points must be a list of DistributionPoint " + "objects" + ) + + self._distribution_points = distribution_points + + __len__, __iter__, __getitem__ = _make_sequence_methods( + "_distribution_points" + ) + + def __repr__(self) -> str: + return f"" + + def __eq__(self, other: object) -> bool: + if not isinstance(other, CRLDistributionPoints): + return NotImplemented + + return self._distribution_points == other._distribution_points + + def __hash__(self) -> int: + return hash(tuple(self._distribution_points)) + + def public_bytes(self) -> bytes: + return rust_x509.encode_extension_value(self) + + +class FreshestCRL(ExtensionType): + oid = ExtensionOID.FRESHEST_CRL + + def __init__( + self, distribution_points: Iterable[DistributionPoint] + ) -> None: + distribution_points = list(distribution_points) + if not all( + isinstance(x, DistributionPoint) for x in distribution_points + ): + raise TypeError( + "distribution_points must be a list of DistributionPoint " + "objects" + ) + + self._distribution_points = distribution_points + + __len__, __iter__, __getitem__ = _make_sequence_methods( + "_distribution_points" + ) + + def __repr__(self) -> str: + return f"" + + def __eq__(self, other: object) -> bool: + if not isinstance(other, FreshestCRL): + return NotImplemented + + return self._distribution_points == other._distribution_points + + def __hash__(self) -> int: + return hash(tuple(self._distribution_points)) + + def public_bytes(self) -> bytes: + return rust_x509.encode_extension_value(self) + + +class DistributionPoint: + def __init__( + self, + full_name: Iterable[GeneralName] | None, + relative_name: RelativeDistinguishedName | None, + reasons: frozenset[ReasonFlags] | None, + crl_issuer: Iterable[GeneralName] | None, + ) -> None: + if full_name and relative_name: + raise ValueError( + "You cannot provide both full_name and relative_name, at " + "least one must be None." + ) + if not full_name and not relative_name and not crl_issuer: + raise ValueError( + "Either full_name, relative_name or crl_issuer must be " + "provided." + ) + + if full_name is not None: + full_name = list(full_name) + if not all(isinstance(x, GeneralName) for x in full_name): + raise TypeError( + "full_name must be a list of GeneralName objects" + ) + + if relative_name: + if not isinstance(relative_name, RelativeDistinguishedName): + raise TypeError( + "relative_name must be a RelativeDistinguishedName" + ) + + if crl_issuer is not None: + crl_issuer = list(crl_issuer) + if not all(isinstance(x, GeneralName) for x in crl_issuer): + raise TypeError( + "crl_issuer must be None or a list of general names" + ) + + if reasons and ( + not isinstance(reasons, frozenset) + or not all(isinstance(x, ReasonFlags) for x in reasons) + ): + raise TypeError("reasons must be None or frozenset of ReasonFlags") + + if reasons and ( + ReasonFlags.unspecified in reasons + or ReasonFlags.remove_from_crl in reasons + ): + raise ValueError( + "unspecified and remove_from_crl are not valid reasons in a " + "DistributionPoint" + ) + + self._full_name = full_name + self._relative_name = relative_name + self._reasons = reasons + self._crl_issuer = crl_issuer + + def __repr__(self) -> str: + return ( + "".format(self) + ) + + def __eq__(self, other: object) -> bool: + if not isinstance(other, DistributionPoint): + return NotImplemented + + return ( + self.full_name == other.full_name + and self.relative_name == other.relative_name + and self.reasons == other.reasons + and self.crl_issuer == other.crl_issuer + ) + + def __hash__(self) -> int: + if self.full_name is not None: + fn: tuple[GeneralName, ...] | None = tuple(self.full_name) + else: + fn = None + + if self.crl_issuer is not None: + crl_issuer: tuple[GeneralName, ...] | None = tuple(self.crl_issuer) + else: + crl_issuer = None + + return hash((fn, self.relative_name, self.reasons, crl_issuer)) + + @property + def full_name(self) -> list[GeneralName] | None: + return self._full_name + + @property + def relative_name(self) -> RelativeDistinguishedName | None: + return self._relative_name + + @property + def reasons(self) -> frozenset[ReasonFlags] | None: + return self._reasons + + @property + def crl_issuer(self) -> list[GeneralName] | None: + return self._crl_issuer + + +class ReasonFlags(utils.Enum): + unspecified = "unspecified" + key_compromise = "keyCompromise" + ca_compromise = "cACompromise" + affiliation_changed = "affiliationChanged" + superseded = "superseded" + cessation_of_operation = "cessationOfOperation" + certificate_hold = "certificateHold" + privilege_withdrawn = "privilegeWithdrawn" + aa_compromise = "aACompromise" + remove_from_crl = "removeFromCRL" + + +# These are distribution point bit string mappings. Not to be confused with +# CRLReason reason flags bit string mappings. +# ReasonFlags ::= BIT STRING { +# unused (0), +# keyCompromise (1), +# cACompromise (2), +# affiliationChanged (3), +# superseded (4), +# cessationOfOperation (5), +# certificateHold (6), +# privilegeWithdrawn (7), +# aACompromise (8) } +_REASON_BIT_MAPPING = { + 1: ReasonFlags.key_compromise, + 2: ReasonFlags.ca_compromise, + 3: ReasonFlags.affiliation_changed, + 4: ReasonFlags.superseded, + 5: ReasonFlags.cessation_of_operation, + 6: ReasonFlags.certificate_hold, + 7: ReasonFlags.privilege_withdrawn, + 8: ReasonFlags.aa_compromise, +} + +_CRLREASONFLAGS = { + ReasonFlags.key_compromise: 1, + ReasonFlags.ca_compromise: 2, + ReasonFlags.affiliation_changed: 3, + ReasonFlags.superseded: 4, + ReasonFlags.cessation_of_operation: 5, + ReasonFlags.certificate_hold: 6, + ReasonFlags.privilege_withdrawn: 7, + ReasonFlags.aa_compromise: 8, +} + +# CRLReason ::= ENUMERATED { +# unspecified (0), +# keyCompromise (1), +# cACompromise (2), +# affiliationChanged (3), +# superseded (4), +# cessationOfOperation (5), +# certificateHold (6), +# -- value 7 is not used +# removeFromCRL (8), +# privilegeWithdrawn (9), +# aACompromise (10) } +_CRL_ENTRY_REASON_ENUM_TO_CODE = { + ReasonFlags.unspecified: 0, + ReasonFlags.key_compromise: 1, + ReasonFlags.ca_compromise: 2, + ReasonFlags.affiliation_changed: 3, + ReasonFlags.superseded: 4, + ReasonFlags.cessation_of_operation: 5, + ReasonFlags.certificate_hold: 6, + ReasonFlags.remove_from_crl: 8, + ReasonFlags.privilege_withdrawn: 9, + ReasonFlags.aa_compromise: 10, +} + + +class PolicyConstraints(ExtensionType): + oid = ExtensionOID.POLICY_CONSTRAINTS + + def __init__( + self, + require_explicit_policy: int | None, + inhibit_policy_mapping: int | None, + ) -> None: + if require_explicit_policy is not None and not isinstance( + require_explicit_policy, int + ): + raise TypeError( + "require_explicit_policy must be a non-negative integer or " + "None" + ) + + if inhibit_policy_mapping is not None and not isinstance( + inhibit_policy_mapping, int + ): + raise TypeError( + "inhibit_policy_mapping must be a non-negative integer or None" + ) + + if inhibit_policy_mapping is None and require_explicit_policy is None: + raise ValueError( + "At least one of require_explicit_policy and " + "inhibit_policy_mapping must not be None" + ) + + self._require_explicit_policy = require_explicit_policy + self._inhibit_policy_mapping = inhibit_policy_mapping + + def __repr__(self) -> str: + return ( + "".format(self) + ) + + def __eq__(self, other: object) -> bool: + if not isinstance(other, PolicyConstraints): + return NotImplemented + + return ( + self.require_explicit_policy == other.require_explicit_policy + and self.inhibit_policy_mapping == other.inhibit_policy_mapping + ) + + def __hash__(self) -> int: + return hash( + (self.require_explicit_policy, self.inhibit_policy_mapping) + ) + + @property + def require_explicit_policy(self) -> int | None: + return self._require_explicit_policy + + @property + def inhibit_policy_mapping(self) -> int | None: + return self._inhibit_policy_mapping + + def public_bytes(self) -> bytes: + return rust_x509.encode_extension_value(self) + + +class CertificatePolicies(ExtensionType): + oid = ExtensionOID.CERTIFICATE_POLICIES + + def __init__(self, policies: Iterable[PolicyInformation]) -> None: + policies = list(policies) + if not all(isinstance(x, PolicyInformation) for x in policies): + raise TypeError( + "Every item in the policies list must be a PolicyInformation" + ) + + self._policies = policies + + __len__, __iter__, __getitem__ = _make_sequence_methods("_policies") + + def __repr__(self) -> str: + return f"" + + def __eq__(self, other: object) -> bool: + if not isinstance(other, CertificatePolicies): + return NotImplemented + + return self._policies == other._policies + + def __hash__(self) -> int: + return hash(tuple(self._policies)) + + def public_bytes(self) -> bytes: + return rust_x509.encode_extension_value(self) + + +class PolicyInformation: + def __init__( + self, + policy_identifier: ObjectIdentifier, + policy_qualifiers: Iterable[str | UserNotice] | None, + ) -> None: + if not isinstance(policy_identifier, ObjectIdentifier): + raise TypeError("policy_identifier must be an ObjectIdentifier") + + self._policy_identifier = policy_identifier + + if policy_qualifiers is not None: + policy_qualifiers = list(policy_qualifiers) + if not all( + isinstance(x, (str, UserNotice)) for x in policy_qualifiers + ): + raise TypeError( + "policy_qualifiers must be a list of strings and/or " + "UserNotice objects or None" + ) + + self._policy_qualifiers = policy_qualifiers + + def __repr__(self) -> str: + return ( + f"" + ) + + def __eq__(self, other: object) -> bool: + if not isinstance(other, PolicyInformation): + return NotImplemented + + return ( + self.policy_identifier == other.policy_identifier + and self.policy_qualifiers == other.policy_qualifiers + ) + + def __hash__(self) -> int: + if self.policy_qualifiers is not None: + pq = tuple(self.policy_qualifiers) + else: + pq = None + + return hash((self.policy_identifier, pq)) + + @property + def policy_identifier(self) -> ObjectIdentifier: + return self._policy_identifier + + @property + def policy_qualifiers( + self, + ) -> list[str | UserNotice] | None: + return self._policy_qualifiers + + +class UserNotice: + def __init__( + self, + notice_reference: NoticeReference | None, + explicit_text: str | None, + ) -> None: + if notice_reference and not isinstance( + notice_reference, NoticeReference + ): + raise TypeError( + "notice_reference must be None or a NoticeReference" + ) + + self._notice_reference = notice_reference + self._explicit_text = explicit_text + + def __repr__(self) -> str: + return ( + f"" + ) + + def __eq__(self, other: object) -> bool: + if not isinstance(other, UserNotice): + return NotImplemented + + return ( + self.notice_reference == other.notice_reference + and self.explicit_text == other.explicit_text + ) + + def __hash__(self) -> int: + return hash((self.notice_reference, self.explicit_text)) + + @property + def notice_reference(self) -> NoticeReference | None: + return self._notice_reference + + @property + def explicit_text(self) -> str | None: + return self._explicit_text + + +class NoticeReference: + def __init__( + self, + organization: str | None, + notice_numbers: Iterable[int], + ) -> None: + self._organization = organization + notice_numbers = list(notice_numbers) + if not all(isinstance(x, int) for x in notice_numbers): + raise TypeError("notice_numbers must be a list of integers") + + self._notice_numbers = notice_numbers + + def __repr__(self) -> str: + return ( + f"" + ) + + def __eq__(self, other: object) -> bool: + if not isinstance(other, NoticeReference): + return NotImplemented + + return ( + self.organization == other.organization + and self.notice_numbers == other.notice_numbers + ) + + def __hash__(self) -> int: + return hash((self.organization, tuple(self.notice_numbers))) + + @property + def organization(self) -> str | None: + return self._organization + + @property + def notice_numbers(self) -> list[int]: + return self._notice_numbers + + +class ExtendedKeyUsage(ExtensionType): + oid = ExtensionOID.EXTENDED_KEY_USAGE + + def __init__(self, usages: Iterable[ObjectIdentifier]) -> None: + usages = list(usages) + if not all(isinstance(x, ObjectIdentifier) for x in usages): + raise TypeError( + "Every item in the usages list must be an ObjectIdentifier" + ) + + self._usages = usages + + __len__, __iter__, __getitem__ = _make_sequence_methods("_usages") + + def __repr__(self) -> str: + return f"" + + def __eq__(self, other: object) -> bool: + if not isinstance(other, ExtendedKeyUsage): + return NotImplemented + + return self._usages == other._usages + + def __hash__(self) -> int: + return hash(tuple(self._usages)) + + def public_bytes(self) -> bytes: + return rust_x509.encode_extension_value(self) + + +class OCSPNoCheck(ExtensionType): + oid = ExtensionOID.OCSP_NO_CHECK + + def __eq__(self, other: object) -> bool: + if not isinstance(other, OCSPNoCheck): + return NotImplemented + + return True + + def __hash__(self) -> int: + return hash(OCSPNoCheck) + + def __repr__(self) -> str: + return "" + + def public_bytes(self) -> bytes: + return rust_x509.encode_extension_value(self) + + +class PrecertPoison(ExtensionType): + oid = ExtensionOID.PRECERT_POISON + + def __eq__(self, other: object) -> bool: + if not isinstance(other, PrecertPoison): + return NotImplemented + + return True + + def __hash__(self) -> int: + return hash(PrecertPoison) + + def __repr__(self) -> str: + return "" + + def public_bytes(self) -> bytes: + return rust_x509.encode_extension_value(self) + + +class TLSFeature(ExtensionType): + oid = ExtensionOID.TLS_FEATURE + + def __init__(self, features: Iterable[TLSFeatureType]) -> None: + features = list(features) + if ( + not all(isinstance(x, TLSFeatureType) for x in features) + or len(features) == 0 + ): + raise TypeError( + "features must be a list of elements from the TLSFeatureType " + "enum" + ) + + self._features = features + + __len__, __iter__, __getitem__ = _make_sequence_methods("_features") + + def __repr__(self) -> str: + return f"" + + def __eq__(self, other: object) -> bool: + if not isinstance(other, TLSFeature): + return NotImplemented + + return self._features == other._features + + def __hash__(self) -> int: + return hash(tuple(self._features)) + + def public_bytes(self) -> bytes: + return rust_x509.encode_extension_value(self) + + +class TLSFeatureType(utils.Enum): + # status_request is defined in RFC 6066 and is used for what is commonly + # called OCSP Must-Staple when present in the TLS Feature extension in an + # X.509 certificate. + status_request = 5 + # status_request_v2 is defined in RFC 6961 and allows multiple OCSP + # responses to be provided. It is not currently in use by clients or + # servers. + status_request_v2 = 17 + + +_TLS_FEATURE_TYPE_TO_ENUM = {x.value: x for x in TLSFeatureType} + + +class InhibitAnyPolicy(ExtensionType): + oid = ExtensionOID.INHIBIT_ANY_POLICY + + def __init__(self, skip_certs: int) -> None: + if not isinstance(skip_certs, int): + raise TypeError("skip_certs must be an integer") + + if skip_certs < 0: + raise ValueError("skip_certs must be a non-negative integer") + + self._skip_certs = skip_certs + + def __repr__(self) -> str: + return f"" + + def __eq__(self, other: object) -> bool: + if not isinstance(other, InhibitAnyPolicy): + return NotImplemented + + return self.skip_certs == other.skip_certs + + def __hash__(self) -> int: + return hash(self.skip_certs) + + @property + def skip_certs(self) -> int: + return self._skip_certs + + def public_bytes(self) -> bytes: + return rust_x509.encode_extension_value(self) + + +class KeyUsage(ExtensionType): + oid = ExtensionOID.KEY_USAGE + + def __init__( + self, + digital_signature: bool, + content_commitment: bool, + key_encipherment: bool, + data_encipherment: bool, + key_agreement: bool, + key_cert_sign: bool, + crl_sign: bool, + encipher_only: bool, + decipher_only: bool, + ) -> None: + if not key_agreement and (encipher_only or decipher_only): + raise ValueError( + "encipher_only and decipher_only can only be true when " + "key_agreement is true" + ) + + self._digital_signature = digital_signature + self._content_commitment = content_commitment + self._key_encipherment = key_encipherment + self._data_encipherment = data_encipherment + self._key_agreement = key_agreement + self._key_cert_sign = key_cert_sign + self._crl_sign = crl_sign + self._encipher_only = encipher_only + self._decipher_only = decipher_only + + @property + def digital_signature(self) -> bool: + return self._digital_signature + + @property + def content_commitment(self) -> bool: + return self._content_commitment + + @property + def key_encipherment(self) -> bool: + return self._key_encipherment + + @property + def data_encipherment(self) -> bool: + return self._data_encipherment + + @property + def key_agreement(self) -> bool: + return self._key_agreement + + @property + def key_cert_sign(self) -> bool: + return self._key_cert_sign + + @property + def crl_sign(self) -> bool: + return self._crl_sign + + @property + def encipher_only(self) -> bool: + if not self.key_agreement: + raise ValueError( + "encipher_only is undefined unless key_agreement is true" + ) + else: + return self._encipher_only + + @property + def decipher_only(self) -> bool: + if not self.key_agreement: + raise ValueError( + "decipher_only is undefined unless key_agreement is true" + ) + else: + return self._decipher_only + + def __repr__(self) -> str: + try: + encipher_only = self.encipher_only + decipher_only = self.decipher_only + except ValueError: + # Users found None confusing because even though encipher/decipher + # have no meaning unless key_agreement is true, to construct an + # instance of the class you still need to pass False. + encipher_only = False + decipher_only = False + + return ( + f"" + ) + + def __eq__(self, other: object) -> bool: + if not isinstance(other, KeyUsage): + return NotImplemented + + return ( + self.digital_signature == other.digital_signature + and self.content_commitment == other.content_commitment + and self.key_encipherment == other.key_encipherment + and self.data_encipherment == other.data_encipherment + and self.key_agreement == other.key_agreement + and self.key_cert_sign == other.key_cert_sign + and self.crl_sign == other.crl_sign + and self._encipher_only == other._encipher_only + and self._decipher_only == other._decipher_only + ) + + def __hash__(self) -> int: + return hash( + ( + self.digital_signature, + self.content_commitment, + self.key_encipherment, + self.data_encipherment, + self.key_agreement, + self.key_cert_sign, + self.crl_sign, + self._encipher_only, + self._decipher_only, + ) + ) + + def public_bytes(self) -> bytes: + return rust_x509.encode_extension_value(self) + + +class PrivateKeyUsagePeriod(ExtensionType): + oid = ExtensionOID.PRIVATE_KEY_USAGE_PERIOD + + def __init__( + self, + not_before: datetime.datetime | None, + not_after: datetime.datetime | None, + ) -> None: + if ( + not isinstance(not_before, datetime.datetime) + and not_before is not None + ): + raise TypeError("not_before must be a datetime.datetime or None") + + if ( + not isinstance(not_after, datetime.datetime) + and not_after is not None + ): + raise TypeError("not_after must be a datetime.datetime or None") + + if not_before is None and not_after is None: + raise ValueError( + "At least one of not_before and not_after must not be None" + ) + + if ( + not_before is not None + and not_after is not None + and not_before > not_after + ): + raise ValueError("not_before must be before not_after") + + self._not_before = not_before + self._not_after = not_after + + @property + def not_before(self) -> datetime.datetime | None: + return self._not_before + + @property + def not_after(self) -> datetime.datetime | None: + return self._not_after + + def __repr__(self) -> str: + return ( + f"" + ) + + def __eq__(self, other: object) -> bool: + if not isinstance(other, PrivateKeyUsagePeriod): + return NotImplemented + + return ( + self.not_before == other.not_before + and self.not_after == other.not_after + ) + + def __hash__(self) -> int: + return hash((self.not_before, self.not_after)) + + def public_bytes(self) -> bytes: + return rust_x509.encode_extension_value(self) + + +class NameConstraints(ExtensionType): + oid = ExtensionOID.NAME_CONSTRAINTS + + def __init__( + self, + permitted_subtrees: Iterable[GeneralName] | None, + excluded_subtrees: Iterable[GeneralName] | None, + ) -> None: + if permitted_subtrees is not None: + permitted_subtrees = list(permitted_subtrees) + if not permitted_subtrees: + raise ValueError( + "permitted_subtrees must be a non-empty list or None" + ) + if not all(isinstance(x, GeneralName) for x in permitted_subtrees): + raise TypeError( + "permitted_subtrees must be a list of GeneralName objects " + "or None" + ) + + self._validate_tree(permitted_subtrees) + + if excluded_subtrees is not None: + excluded_subtrees = list(excluded_subtrees) + if not excluded_subtrees: + raise ValueError( + "excluded_subtrees must be a non-empty list or None" + ) + if not all(isinstance(x, GeneralName) for x in excluded_subtrees): + raise TypeError( + "excluded_subtrees must be a list of GeneralName objects " + "or None" + ) + + self._validate_tree(excluded_subtrees) + + if permitted_subtrees is None and excluded_subtrees is None: + raise ValueError( + "At least one of permitted_subtrees and excluded_subtrees " + "must not be None" + ) + + self._permitted_subtrees = permitted_subtrees + self._excluded_subtrees = excluded_subtrees + + def __eq__(self, other: object) -> bool: + if not isinstance(other, NameConstraints): + return NotImplemented + + return ( + self.excluded_subtrees == other.excluded_subtrees + and self.permitted_subtrees == other.permitted_subtrees + ) + + def _validate_tree(self, tree: Iterable[GeneralName]) -> None: + self._validate_ip_name(tree) + self._validate_dns_name(tree) + + def _validate_ip_name(self, tree: Iterable[GeneralName]) -> None: + if any( + isinstance(name, IPAddress) + and not isinstance( + name.value, (ipaddress.IPv4Network, ipaddress.IPv6Network) + ) + for name in tree + ): + raise TypeError( + "IPAddress name constraints must be an IPv4Network or" + " IPv6Network object" + ) + + def _validate_dns_name(self, tree: Iterable[GeneralName]) -> None: + if any( + isinstance(name, DNSName) and "*" in name.value for name in tree + ): + raise ValueError( + "DNSName name constraints must not contain the '*' wildcard" + " character" + ) + + def __repr__(self) -> str: + return ( + f"" + ) + + def __hash__(self) -> int: + if self.permitted_subtrees is not None: + ps: tuple[GeneralName, ...] | None = tuple(self.permitted_subtrees) + else: + ps = None + + if self.excluded_subtrees is not None: + es: tuple[GeneralName, ...] | None = tuple(self.excluded_subtrees) + else: + es = None + + return hash((ps, es)) + + @property + def permitted_subtrees( + self, + ) -> list[GeneralName] | None: + return self._permitted_subtrees + + @property + def excluded_subtrees( + self, + ) -> list[GeneralName] | None: + return self._excluded_subtrees + + def public_bytes(self) -> bytes: + return rust_x509.encode_extension_value(self) + + +class Extension(typing.Generic[ExtensionTypeVar]): + def __init__( + self, oid: ObjectIdentifier, critical: bool, value: ExtensionTypeVar + ) -> None: + if not isinstance(oid, ObjectIdentifier): + raise TypeError( + "oid argument must be an ObjectIdentifier instance." + ) + + if not isinstance(critical, bool): + raise TypeError("critical must be a boolean value") + + self._oid = oid + self._critical = critical + self._value = value + + @property + def oid(self) -> ObjectIdentifier: + return self._oid + + @property + def critical(self) -> bool: + return self._critical + + @property + def value(self) -> ExtensionTypeVar: + return self._value + + def __repr__(self) -> str: + return ( + f"" + ) + + def __eq__(self, other: object) -> bool: + if not isinstance(other, Extension): + return NotImplemented + + return ( + self.oid == other.oid + and self.critical == other.critical + and self.value == other.value + ) + + def __hash__(self) -> int: + return hash((self.oid, self.critical, self.value)) + + +class GeneralNames: + def __init__(self, general_names: Iterable[GeneralName]) -> None: + general_names = list(general_names) + if not all(isinstance(x, GeneralName) for x in general_names): + raise TypeError( + "Every item in the general_names list must be an " + "object conforming to the GeneralName interface" + ) + + self._general_names = general_names + + __len__, __iter__, __getitem__ = _make_sequence_methods("_general_names") + + @typing.overload + def get_values_for_type( + self, + type: type[DNSName] + | type[UniformResourceIdentifier] + | type[RFC822Name], + ) -> list[str]: ... + + @typing.overload + def get_values_for_type( + self, + type: type[DirectoryName], + ) -> list[Name]: ... + + @typing.overload + def get_values_for_type( + self, + type: type[RegisteredID], + ) -> list[ObjectIdentifier]: ... + + @typing.overload + def get_values_for_type( + self, type: type[IPAddress] + ) -> list[_IPAddressTypes]: ... + + @typing.overload + def get_values_for_type( + self, type: type[OtherName] + ) -> list[OtherName]: ... + + def get_values_for_type( + self, + type: type[DNSName] + | type[DirectoryName] + | type[IPAddress] + | type[OtherName] + | type[RFC822Name] + | type[RegisteredID] + | type[UniformResourceIdentifier], + ) -> ( + list[_IPAddressTypes] + | list[str] + | list[OtherName] + | list[Name] + | list[ObjectIdentifier] + ): + # Return the value of each GeneralName, except for OtherName instances + # which we return directly because it has two important properties not + # just one value. + objs = (i for i in self if isinstance(i, type)) + if type != OtherName: + return [i.value for i in objs] # type: ignore[return-value,unused-ignore] + return list(objs) # type: ignore[return-value,unused-ignore] + + def __repr__(self) -> str: + return f"" + + def __eq__(self, other: object) -> bool: + if not isinstance(other, GeneralNames): + return NotImplemented + + return self._general_names == other._general_names + + def __hash__(self) -> int: + return hash(tuple(self._general_names)) + + +class SubjectAlternativeName(ExtensionType): + oid = ExtensionOID.SUBJECT_ALTERNATIVE_NAME + + def __init__(self, general_names: Iterable[GeneralName]) -> None: + self._general_names = GeneralNames(general_names) + + __len__, __iter__, __getitem__ = _make_sequence_methods("_general_names") + + @typing.overload + def get_values_for_type( + self, + type: type[DNSName] + | type[UniformResourceIdentifier] + | type[RFC822Name], + ) -> list[str]: ... + + @typing.overload + def get_values_for_type( + self, + type: type[DirectoryName], + ) -> list[Name]: ... + + @typing.overload + def get_values_for_type( + self, + type: type[RegisteredID], + ) -> list[ObjectIdentifier]: ... + + @typing.overload + def get_values_for_type( + self, type: type[IPAddress] + ) -> list[_IPAddressTypes]: ... + + @typing.overload + def get_values_for_type( + self, type: type[OtherName] + ) -> list[OtherName]: ... + + def get_values_for_type( + self, + type: type[DNSName] + | type[DirectoryName] + | type[IPAddress] + | type[OtherName] + | type[RFC822Name] + | type[RegisteredID] + | type[UniformResourceIdentifier], + ) -> ( + list[_IPAddressTypes] + | list[str] + | list[OtherName] + | list[Name] + | list[ObjectIdentifier] + ): + return self._general_names.get_values_for_type(type) + + def __repr__(self) -> str: + return f"" + + def __eq__(self, other: object) -> bool: + if not isinstance(other, SubjectAlternativeName): + return NotImplemented + + return self._general_names == other._general_names + + def __hash__(self) -> int: + return hash(self._general_names) + + def public_bytes(self) -> bytes: + return rust_x509.encode_extension_value(self) + + +class IssuerAlternativeName(ExtensionType): + oid = ExtensionOID.ISSUER_ALTERNATIVE_NAME + + def __init__(self, general_names: Iterable[GeneralName]) -> None: + self._general_names = GeneralNames(general_names) + + __len__, __iter__, __getitem__ = _make_sequence_methods("_general_names") + + @typing.overload + def get_values_for_type( + self, + type: type[DNSName] + | type[UniformResourceIdentifier] + | type[RFC822Name], + ) -> list[str]: ... + + @typing.overload + def get_values_for_type( + self, + type: type[DirectoryName], + ) -> list[Name]: ... + + @typing.overload + def get_values_for_type( + self, + type: type[RegisteredID], + ) -> list[ObjectIdentifier]: ... + + @typing.overload + def get_values_for_type( + self, type: type[IPAddress] + ) -> list[_IPAddressTypes]: ... + + @typing.overload + def get_values_for_type( + self, type: type[OtherName] + ) -> list[OtherName]: ... + + def get_values_for_type( + self, + type: type[DNSName] + | type[DirectoryName] + | type[IPAddress] + | type[OtherName] + | type[RFC822Name] + | type[RegisteredID] + | type[UniformResourceIdentifier], + ) -> ( + list[_IPAddressTypes] + | list[str] + | list[OtherName] + | list[Name] + | list[ObjectIdentifier] + ): + return self._general_names.get_values_for_type(type) + + def __repr__(self) -> str: + return f"" + + def __eq__(self, other: object) -> bool: + if not isinstance(other, IssuerAlternativeName): + return NotImplemented + + return self._general_names == other._general_names + + def __hash__(self) -> int: + return hash(self._general_names) + + def public_bytes(self) -> bytes: + return rust_x509.encode_extension_value(self) + + +class CertificateIssuer(ExtensionType): + oid = CRLEntryExtensionOID.CERTIFICATE_ISSUER + + def __init__(self, general_names: Iterable[GeneralName]) -> None: + self._general_names = GeneralNames(general_names) + + __len__, __iter__, __getitem__ = _make_sequence_methods("_general_names") + + @typing.overload + def get_values_for_type( + self, + type: type[DNSName] + | type[UniformResourceIdentifier] + | type[RFC822Name], + ) -> list[str]: ... + + @typing.overload + def get_values_for_type( + self, + type: type[DirectoryName], + ) -> list[Name]: ... + + @typing.overload + def get_values_for_type( + self, + type: type[RegisteredID], + ) -> list[ObjectIdentifier]: ... + + @typing.overload + def get_values_for_type( + self, type: type[IPAddress] + ) -> list[_IPAddressTypes]: ... + + @typing.overload + def get_values_for_type( + self, type: type[OtherName] + ) -> list[OtherName]: ... + + def get_values_for_type( + self, + type: type[DNSName] + | type[DirectoryName] + | type[IPAddress] + | type[OtherName] + | type[RFC822Name] + | type[RegisteredID] + | type[UniformResourceIdentifier], + ) -> ( + list[_IPAddressTypes] + | list[str] + | list[OtherName] + | list[Name] + | list[ObjectIdentifier] + ): + return self._general_names.get_values_for_type(type) + + def __repr__(self) -> str: + return f"" + + def __eq__(self, other: object) -> bool: + if not isinstance(other, CertificateIssuer): + return NotImplemented + + return self._general_names == other._general_names + + def __hash__(self) -> int: + return hash(self._general_names) + + def public_bytes(self) -> bytes: + return rust_x509.encode_extension_value(self) + + +class CRLReason(ExtensionType): + oid = CRLEntryExtensionOID.CRL_REASON + + def __init__(self, reason: ReasonFlags) -> None: + if not isinstance(reason, ReasonFlags): + raise TypeError("reason must be an element from ReasonFlags") + + self._reason = reason + + def __repr__(self) -> str: + return f"" + + def __eq__(self, other: object) -> bool: + if not isinstance(other, CRLReason): + return NotImplemented + + return self.reason == other.reason + + def __hash__(self) -> int: + return hash(self.reason) + + @property + def reason(self) -> ReasonFlags: + return self._reason + + def public_bytes(self) -> bytes: + return rust_x509.encode_extension_value(self) + + +class InvalidityDate(ExtensionType): + oid = CRLEntryExtensionOID.INVALIDITY_DATE + + def __init__(self, invalidity_date: datetime.datetime) -> None: + if not isinstance(invalidity_date, datetime.datetime): + raise TypeError("invalidity_date must be a datetime.datetime") + + self._invalidity_date = invalidity_date + + def __repr__(self) -> str: + return f"" + + def __eq__(self, other: object) -> bool: + if not isinstance(other, InvalidityDate): + return NotImplemented + + return self.invalidity_date == other.invalidity_date + + def __hash__(self) -> int: + return hash(self.invalidity_date) + + @property + def invalidity_date(self) -> datetime.datetime: + return self._invalidity_date + + @property + def invalidity_date_utc(self) -> datetime.datetime: + if self._invalidity_date.tzinfo is None: + return self._invalidity_date.replace(tzinfo=datetime.timezone.utc) + else: + return self._invalidity_date.astimezone(tz=datetime.timezone.utc) + + def public_bytes(self) -> bytes: + return rust_x509.encode_extension_value(self) + + +class PrecertificateSignedCertificateTimestamps(ExtensionType): + oid = ExtensionOID.PRECERT_SIGNED_CERTIFICATE_TIMESTAMPS + + def __init__( + self, + signed_certificate_timestamps: Iterable[SignedCertificateTimestamp], + ) -> None: + signed_certificate_timestamps = list(signed_certificate_timestamps) + if not all( + isinstance(sct, SignedCertificateTimestamp) + for sct in signed_certificate_timestamps + ): + raise TypeError( + "Every item in the signed_certificate_timestamps list must be " + "a SignedCertificateTimestamp" + ) + self._signed_certificate_timestamps = signed_certificate_timestamps + + __len__, __iter__, __getitem__ = _make_sequence_methods( + "_signed_certificate_timestamps" + ) + + def __repr__(self) -> str: + return f"" + + def __hash__(self) -> int: + return hash(tuple(self._signed_certificate_timestamps)) + + def __eq__(self, other: object) -> bool: + if not isinstance(other, PrecertificateSignedCertificateTimestamps): + return NotImplemented + + return ( + self._signed_certificate_timestamps + == other._signed_certificate_timestamps + ) + + def public_bytes(self) -> bytes: + return rust_x509.encode_extension_value(self) + + +class SignedCertificateTimestamps(ExtensionType): + oid = ExtensionOID.SIGNED_CERTIFICATE_TIMESTAMPS + + def __init__( + self, + signed_certificate_timestamps: Iterable[SignedCertificateTimestamp], + ) -> None: + signed_certificate_timestamps = list(signed_certificate_timestamps) + if not all( + isinstance(sct, SignedCertificateTimestamp) + for sct in signed_certificate_timestamps + ): + raise TypeError( + "Every item in the signed_certificate_timestamps list must be " + "a SignedCertificateTimestamp" + ) + self._signed_certificate_timestamps = signed_certificate_timestamps + + __len__, __iter__, __getitem__ = _make_sequence_methods( + "_signed_certificate_timestamps" + ) + + def __repr__(self) -> str: + return f"" + + def __hash__(self) -> int: + return hash(tuple(self._signed_certificate_timestamps)) + + def __eq__(self, other: object) -> bool: + if not isinstance(other, SignedCertificateTimestamps): + return NotImplemented + + return ( + self._signed_certificate_timestamps + == other._signed_certificate_timestamps + ) + + def public_bytes(self) -> bytes: + return rust_x509.encode_extension_value(self) + + +class OCSPNonce(ExtensionType): + oid = OCSPExtensionOID.NONCE + + def __init__(self, nonce: bytes) -> None: + if not isinstance(nonce, bytes): + raise TypeError("nonce must be bytes") + + self._nonce = nonce + + def __eq__(self, other: object) -> bool: + if not isinstance(other, OCSPNonce): + return NotImplemented + + return self.nonce == other.nonce + + def __hash__(self) -> int: + return hash(self.nonce) + + def __repr__(self) -> str: + return f"" + + @property + def nonce(self) -> bytes: + return self._nonce + + def public_bytes(self) -> bytes: + return rust_x509.encode_extension_value(self) + + +class OCSPAcceptableResponses(ExtensionType): + oid = OCSPExtensionOID.ACCEPTABLE_RESPONSES + + def __init__(self, responses: Iterable[ObjectIdentifier]) -> None: + responses = list(responses) + if any(not isinstance(r, ObjectIdentifier) for r in responses): + raise TypeError("All responses must be ObjectIdentifiers") + + self._responses = responses + + def __eq__(self, other: object) -> bool: + if not isinstance(other, OCSPAcceptableResponses): + return NotImplemented + + return self._responses == other._responses + + def __hash__(self) -> int: + return hash(tuple(self._responses)) + + def __repr__(self) -> str: + return f"" + + def __iter__(self) -> Iterator[ObjectIdentifier]: + return iter(self._responses) + + def public_bytes(self) -> bytes: + return rust_x509.encode_extension_value(self) + + +class IssuingDistributionPoint(ExtensionType): + oid = ExtensionOID.ISSUING_DISTRIBUTION_POINT + + def __init__( + self, + full_name: Iterable[GeneralName] | None, + relative_name: RelativeDistinguishedName | None, + only_contains_user_certs: bool, + only_contains_ca_certs: bool, + only_some_reasons: frozenset[ReasonFlags] | None, + indirect_crl: bool, + only_contains_attribute_certs: bool, + ) -> None: + if full_name is not None: + full_name = list(full_name) + + if only_some_reasons and ( + not isinstance(only_some_reasons, frozenset) + or not all(isinstance(x, ReasonFlags) for x in only_some_reasons) + ): + raise TypeError( + "only_some_reasons must be None or frozenset of ReasonFlags" + ) + + if only_some_reasons and ( + ReasonFlags.unspecified in only_some_reasons + or ReasonFlags.remove_from_crl in only_some_reasons + ): + raise ValueError( + "unspecified and remove_from_crl are not valid reasons in an " + "IssuingDistributionPoint" + ) + + if not ( + isinstance(only_contains_user_certs, bool) + and isinstance(only_contains_ca_certs, bool) + and isinstance(indirect_crl, bool) + and isinstance(only_contains_attribute_certs, bool) + ): + raise TypeError( + "only_contains_user_certs, only_contains_ca_certs, " + "indirect_crl and only_contains_attribute_certs " + "must all be boolean." + ) + + # Per RFC5280 Section 5.2.5, the Issuing Distribution Point extension + # in a CRL can have only one of onlyContainsUserCerts, + # onlyContainsCACerts, onlyContainsAttributeCerts set to TRUE. + crl_constraints = [ + only_contains_user_certs, + only_contains_ca_certs, + only_contains_attribute_certs, + ] + + if len([x for x in crl_constraints if x]) > 1: + raise ValueError( + "Only one of the following can be set to True: " + "only_contains_user_certs, only_contains_ca_certs, " + "only_contains_attribute_certs" + ) + + if not any( + [ + only_contains_user_certs, + only_contains_ca_certs, + indirect_crl, + only_contains_attribute_certs, + full_name, + relative_name, + only_some_reasons, + ] + ): + raise ValueError( + "Cannot create empty extension: " + "if only_contains_user_certs, only_contains_ca_certs, " + "indirect_crl, and only_contains_attribute_certs are all False" + ", then either full_name, relative_name, or only_some_reasons " + "must have a value." + ) + + self._only_contains_user_certs = only_contains_user_certs + self._only_contains_ca_certs = only_contains_ca_certs + self._indirect_crl = indirect_crl + self._only_contains_attribute_certs = only_contains_attribute_certs + self._only_some_reasons = only_some_reasons + self._full_name = full_name + self._relative_name = relative_name + + def __repr__(self) -> str: + return ( + f"" + ) + + def __eq__(self, other: object) -> bool: + if not isinstance(other, IssuingDistributionPoint): + return NotImplemented + + return ( + self.full_name == other.full_name + and self.relative_name == other.relative_name + and self.only_contains_user_certs == other.only_contains_user_certs + and self.only_contains_ca_certs == other.only_contains_ca_certs + and self.only_some_reasons == other.only_some_reasons + and self.indirect_crl == other.indirect_crl + and self.only_contains_attribute_certs + == other.only_contains_attribute_certs + ) + + def __hash__(self) -> int: + if self.full_name is not None: + full_name: tuple[GeneralName, ...] | None = tuple(self.full_name) + else: + full_name = None + + return hash( + ( + full_name, + self.relative_name, + self.only_contains_user_certs, + self.only_contains_ca_certs, + self.only_some_reasons, + self.indirect_crl, + self.only_contains_attribute_certs, + ) + ) + + @property + def full_name(self) -> list[GeneralName] | None: + return self._full_name + + @property + def relative_name(self) -> RelativeDistinguishedName | None: + return self._relative_name + + @property + def only_contains_user_certs(self) -> bool: + return self._only_contains_user_certs + + @property + def only_contains_ca_certs(self) -> bool: + return self._only_contains_ca_certs + + @property + def only_some_reasons( + self, + ) -> frozenset[ReasonFlags] | None: + return self._only_some_reasons + + @property + def indirect_crl(self) -> bool: + return self._indirect_crl + + @property + def only_contains_attribute_certs(self) -> bool: + return self._only_contains_attribute_certs + + def public_bytes(self) -> bytes: + return rust_x509.encode_extension_value(self) + + +class MSCertificateTemplate(ExtensionType): + oid = ExtensionOID.MS_CERTIFICATE_TEMPLATE + + def __init__( + self, + template_id: ObjectIdentifier, + major_version: int | None, + minor_version: int | None, + ) -> None: + if not isinstance(template_id, ObjectIdentifier): + raise TypeError("oid must be an ObjectIdentifier") + self._template_id = template_id + if ( + major_version is not None and not isinstance(major_version, int) + ) or ( + minor_version is not None and not isinstance(minor_version, int) + ): + raise TypeError( + "major_version and minor_version must be integers or None" + ) + self._major_version = major_version + self._minor_version = minor_version + + @property + def template_id(self) -> ObjectIdentifier: + return self._template_id + + @property + def major_version(self) -> int | None: + return self._major_version + + @property + def minor_version(self) -> int | None: + return self._minor_version + + def __repr__(self) -> str: + return ( + f"" + ) + + def __eq__(self, other: object) -> bool: + if not isinstance(other, MSCertificateTemplate): + return NotImplemented + + return ( + self.template_id == other.template_id + and self.major_version == other.major_version + and self.minor_version == other.minor_version + ) + + def __hash__(self) -> int: + return hash((self.template_id, self.major_version, self.minor_version)) + + def public_bytes(self) -> bytes: + return rust_x509.encode_extension_value(self) + + +class NamingAuthority: + def __init__( + self, + id: ObjectIdentifier | None, + url: str | None, + text: str | None, + ) -> None: + if id is not None and not isinstance(id, ObjectIdentifier): + raise TypeError("id must be an ObjectIdentifier") + + if url is not None and not isinstance(url, str): + raise TypeError("url must be a str") + + if text is not None and not isinstance(text, str): + raise TypeError("text must be a str") + + self._id = id + self._url = url + self._text = text + + @property + def id(self) -> ObjectIdentifier | None: + return self._id + + @property + def url(self) -> str | None: + return self._url + + @property + def text(self) -> str | None: + return self._text + + def __repr__(self) -> str: + return ( + f"" + ) + + def __eq__(self, other: object) -> bool: + if not isinstance(other, NamingAuthority): + return NotImplemented + + return ( + self.id == other.id + and self.url == other.url + and self.text == other.text + ) + + def __hash__(self) -> int: + return hash( + ( + self.id, + self.url, + self.text, + ) + ) + + +class ProfessionInfo: + def __init__( + self, + naming_authority: NamingAuthority | None, + profession_items: Iterable[str], + profession_oids: Iterable[ObjectIdentifier] | None, + registration_number: str | None, + add_profession_info: bytes | None, + ) -> None: + if naming_authority is not None and not isinstance( + naming_authority, NamingAuthority + ): + raise TypeError("naming_authority must be a NamingAuthority") + + profession_items = list(profession_items) + if not all(isinstance(item, str) for item in profession_items): + raise TypeError( + "Every item in the profession_items list must be a str" + ) + + if profession_oids is not None: + profession_oids = list(profession_oids) + if not all( + isinstance(oid, ObjectIdentifier) for oid in profession_oids + ): + raise TypeError( + "Every item in the profession_oids list must be an " + "ObjectIdentifier" + ) + + if registration_number is not None and not isinstance( + registration_number, str + ): + raise TypeError("registration_number must be a str") + + if add_profession_info is not None and not isinstance( + add_profession_info, bytes + ): + raise TypeError("add_profession_info must be bytes") + + self._naming_authority = naming_authority + self._profession_items = profession_items + self._profession_oids = profession_oids + self._registration_number = registration_number + self._add_profession_info = add_profession_info + + @property + def naming_authority(self) -> NamingAuthority | None: + return self._naming_authority + + @property + def profession_items(self) -> list[str]: + return self._profession_items + + @property + def profession_oids(self) -> list[ObjectIdentifier] | None: + return self._profession_oids + + @property + def registration_number(self) -> str | None: + return self._registration_number + + @property + def add_profession_info(self) -> bytes | None: + return self._add_profession_info + + def __repr__(self) -> str: + return ( + f"" + ) + + def __eq__(self, other: object) -> bool: + if not isinstance(other, ProfessionInfo): + return NotImplemented + + return ( + self.naming_authority == other.naming_authority + and self.profession_items == other.profession_items + and self.profession_oids == other.profession_oids + and self.registration_number == other.registration_number + and self.add_profession_info == other.add_profession_info + ) + + def __hash__(self) -> int: + if self.profession_oids is not None: + profession_oids = tuple(self.profession_oids) + else: + profession_oids = None + return hash( + ( + self.naming_authority, + tuple(self.profession_items), + profession_oids, + self.registration_number, + self.add_profession_info, + ) + ) + + +class Admission: + def __init__( + self, + admission_authority: GeneralName | None, + naming_authority: NamingAuthority | None, + profession_infos: Iterable[ProfessionInfo], + ) -> None: + if admission_authority is not None and not isinstance( + admission_authority, GeneralName + ): + raise TypeError("admission_authority must be a GeneralName") + + if naming_authority is not None and not isinstance( + naming_authority, NamingAuthority + ): + raise TypeError("naming_authority must be a NamingAuthority") + + profession_infos = list(profession_infos) + if not all( + isinstance(info, ProfessionInfo) for info in profession_infos + ): + raise TypeError( + "Every item in the profession_infos list must be a " + "ProfessionInfo" + ) + + self._admission_authority = admission_authority + self._naming_authority = naming_authority + self._profession_infos = profession_infos + + @property + def admission_authority(self) -> GeneralName | None: + return self._admission_authority + + @property + def naming_authority(self) -> NamingAuthority | None: + return self._naming_authority + + @property + def profession_infos(self) -> list[ProfessionInfo]: + return self._profession_infos + + def __repr__(self) -> str: + return ( + f"" + ) + + def __eq__(self, other: object) -> bool: + if not isinstance(other, Admission): + return NotImplemented + + return ( + self.admission_authority == other.admission_authority + and self.naming_authority == other.naming_authority + and self.profession_infos == other.profession_infos + ) + + def __hash__(self) -> int: + return hash( + ( + self.admission_authority, + self.naming_authority, + tuple(self.profession_infos), + ) + ) + + +class Admissions(ExtensionType): + oid = ExtensionOID.ADMISSIONS + + def __init__( + self, + authority: GeneralName | None, + admissions: Iterable[Admission], + ) -> None: + if authority is not None and not isinstance(authority, GeneralName): + raise TypeError("authority must be a GeneralName") + + admissions = list(admissions) + if not all( + isinstance(admission, Admission) for admission in admissions + ): + raise TypeError( + "Every item in the contents_of_admissions list must be an " + "Admission" + ) + + self._authority = authority + self._admissions = admissions + + __len__, __iter__, __getitem__ = _make_sequence_methods("_admissions") + + @property + def authority(self) -> GeneralName | None: + return self._authority + + def __repr__(self) -> str: + return ( + f"" + ) + + def __eq__(self, other: object) -> bool: + if not isinstance(other, Admissions): + return NotImplemented + + return ( + self.authority == other.authority + and self._admissions == other._admissions + ) + + def __hash__(self) -> int: + return hash((self.authority, tuple(self._admissions))) + + def public_bytes(self) -> bytes: + return rust_x509.encode_extension_value(self) + + +class UnrecognizedExtension(ExtensionType): + def __init__(self, oid: ObjectIdentifier, value: bytes) -> None: + if not isinstance(oid, ObjectIdentifier): + raise TypeError("oid must be an ObjectIdentifier") + self._oid = oid + self._value = value + + @property + def oid(self) -> ObjectIdentifier: # type: ignore[override] + return self._oid + + @property + def value(self) -> bytes: + return self._value + + def __repr__(self) -> str: + return f"" + + def __eq__(self, other: object) -> bool: + if not isinstance(other, UnrecognizedExtension): + return NotImplemented + + return self.oid == other.oid and self.value == other.value + + def __hash__(self) -> int: + return hash((self.oid, self.value)) + + def public_bytes(self) -> bytes: + return self.value diff --git a/python/user_packages/Python313/site-packages/cryptography/x509/general_name.py b/python/user_packages/Python313/site-packages/cryptography/x509/general_name.py new file mode 100644 index 0000000000000000000000000000000000000000..672f28759cb0ab6d60cb4e38a574095ae3e0159d --- /dev/null +++ b/python/user_packages/Python313/site-packages/cryptography/x509/general_name.py @@ -0,0 +1,281 @@ +# This file is dual licensed under the terms of the Apache License, Version +# 2.0, and the BSD License. See the LICENSE file in the root of this repository +# for complete details. + +from __future__ import annotations + +import abc +import ipaddress +import typing +from email.utils import parseaddr + +from cryptography.x509.name import Name +from cryptography.x509.oid import ObjectIdentifier + +_IPAddressTypes = typing.Union[ + ipaddress.IPv4Address, + ipaddress.IPv6Address, + ipaddress.IPv4Network, + ipaddress.IPv6Network, +] + + +class UnsupportedGeneralNameType(Exception): + pass + + +class GeneralName(metaclass=abc.ABCMeta): + @property + @abc.abstractmethod + def value(self) -> typing.Any: + """ + Return the value of the object + """ + + +class RFC822Name(GeneralName): + def __init__(self, value: str) -> None: + if isinstance(value, str): + try: + value.encode("ascii") + except UnicodeEncodeError: + raise ValueError( + "RFC822Name values should be passed as an A-label string. " + "This means unicode characters should be encoded via " + "a library like idna." + ) + else: + raise TypeError("value must be string") + + name, address = parseaddr(value) + if name or not address: + # parseaddr has found a name (e.g. Name ) or the entire + # value is an empty string. + raise ValueError("Invalid rfc822name value") + + self._value = value + + @property + def value(self) -> str: + return self._value + + @classmethod + def _init_without_validation(cls, value: str) -> RFC822Name: + instance = cls.__new__(cls) + instance._value = value + return instance + + def __repr__(self) -> str: + return f"" + + def __eq__(self, other: object) -> bool: + if not isinstance(other, RFC822Name): + return NotImplemented + + return self.value == other.value + + def __hash__(self) -> int: + return hash(self.value) + + +class DNSName(GeneralName): + def __init__(self, value: str) -> None: + if isinstance(value, str): + try: + value.encode("ascii") + except UnicodeEncodeError: + raise ValueError( + "DNSName values should be passed as an A-label string. " + "This means unicode characters should be encoded via " + "a library like idna." + ) + else: + raise TypeError("value must be string") + + self._value = value + + @property + def value(self) -> str: + return self._value + + @classmethod + def _init_without_validation(cls, value: str) -> DNSName: + instance = cls.__new__(cls) + instance._value = value + return instance + + def __repr__(self) -> str: + return f"" + + def __eq__(self, other: object) -> bool: + if not isinstance(other, DNSName): + return NotImplemented + + return self.value == other.value + + def __hash__(self) -> int: + return hash(self.value) + + +class UniformResourceIdentifier(GeneralName): + def __init__(self, value: str) -> None: + if isinstance(value, str): + try: + value.encode("ascii") + except UnicodeEncodeError: + raise ValueError( + "URI values should be passed as an A-label string. " + "This means unicode characters should be encoded via " + "a library like idna." + ) + else: + raise TypeError("value must be string") + + self._value = value + + @property + def value(self) -> str: + return self._value + + @classmethod + def _init_without_validation(cls, value: str) -> UniformResourceIdentifier: + instance = cls.__new__(cls) + instance._value = value + return instance + + def __repr__(self) -> str: + return f"" + + def __eq__(self, other: object) -> bool: + if not isinstance(other, UniformResourceIdentifier): + return NotImplemented + + return self.value == other.value + + def __hash__(self) -> int: + return hash(self.value) + + +class DirectoryName(GeneralName): + def __init__(self, value: Name) -> None: + if not isinstance(value, Name): + raise TypeError("value must be a Name") + + self._value = value + + @property + def value(self) -> Name: + return self._value + + def __repr__(self) -> str: + return f"" + + def __eq__(self, other: object) -> bool: + if not isinstance(other, DirectoryName): + return NotImplemented + + return self.value == other.value + + def __hash__(self) -> int: + return hash(self.value) + + +class RegisteredID(GeneralName): + def __init__(self, value: ObjectIdentifier) -> None: + if not isinstance(value, ObjectIdentifier): + raise TypeError("value must be an ObjectIdentifier") + + self._value = value + + @property + def value(self) -> ObjectIdentifier: + return self._value + + def __repr__(self) -> str: + return f"" + + def __eq__(self, other: object) -> bool: + if not isinstance(other, RegisteredID): + return NotImplemented + + return self.value == other.value + + def __hash__(self) -> int: + return hash(self.value) + + +class IPAddress(GeneralName): + def __init__(self, value: _IPAddressTypes) -> None: + if not isinstance( + value, + ( + ipaddress.IPv4Address, + ipaddress.IPv6Address, + ipaddress.IPv4Network, + ipaddress.IPv6Network, + ), + ): + raise TypeError( + "value must be an instance of ipaddress.IPv4Address, " + "ipaddress.IPv6Address, ipaddress.IPv4Network, or " + "ipaddress.IPv6Network" + ) + + self._value = value + + @property + def value(self) -> _IPAddressTypes: + return self._value + + def _packed(self) -> bytes: + if isinstance( + self.value, (ipaddress.IPv4Address, ipaddress.IPv6Address) + ): + return self.value.packed + else: + return ( + self.value.network_address.packed + self.value.netmask.packed + ) + + def __repr__(self) -> str: + return f"" + + def __eq__(self, other: object) -> bool: + if not isinstance(other, IPAddress): + return NotImplemented + + return self.value == other.value + + def __hash__(self) -> int: + return hash(self.value) + + +class OtherName(GeneralName): + def __init__(self, type_id: ObjectIdentifier, value: bytes) -> None: + if not isinstance(type_id, ObjectIdentifier): + raise TypeError("type_id must be an ObjectIdentifier") + if not isinstance(value, bytes): + raise TypeError("value must be a binary string") + + self._type_id = type_id + self._value = value + + @property + def type_id(self) -> ObjectIdentifier: + return self._type_id + + @property + def value(self) -> bytes: + return self._value + + def __repr__(self) -> str: + return f"" + + def __eq__(self, other: object) -> bool: + if not isinstance(other, OtherName): + return NotImplemented + + return self.type_id == other.type_id and self.value == other.value + + def __hash__(self) -> int: + return hash((self.type_id, self.value)) diff --git a/python/user_packages/Python313/site-packages/cryptography/x509/name.py b/python/user_packages/Python313/site-packages/cryptography/x509/name.py new file mode 100644 index 0000000000000000000000000000000000000000..57f3d568584751d94b62572eac1966f5d2110108 --- /dev/null +++ b/python/user_packages/Python313/site-packages/cryptography/x509/name.py @@ -0,0 +1,482 @@ +# This file is dual licensed under the terms of the Apache License, Version +# 2.0, and the BSD License. See the LICENSE file in the root of this repository +# for complete details. + +from __future__ import annotations + +import binascii +import re +import sys +import typing +import warnings +from collections.abc import Iterable, Iterator + +from cryptography import utils +from cryptography.hazmat.bindings._rust import x509 as rust_x509 +from cryptography.x509.oid import NameOID, ObjectIdentifier + + +class _ASN1Type(utils.Enum): + BitString = 3 + OctetString = 4 + UTF8String = 12 + NumericString = 18 + PrintableString = 19 + T61String = 20 + IA5String = 22 + UTCTime = 23 + GeneralizedTime = 24 + VisibleString = 26 + UniversalString = 28 + BMPString = 30 + + +_ASN1_TYPE_TO_ENUM = {i.value: i for i in _ASN1Type} +_NAMEOID_DEFAULT_TYPE: dict[ObjectIdentifier, _ASN1Type] = { + NameOID.COUNTRY_NAME: _ASN1Type.PrintableString, + NameOID.JURISDICTION_COUNTRY_NAME: _ASN1Type.PrintableString, + NameOID.SERIAL_NUMBER: _ASN1Type.PrintableString, + NameOID.DN_QUALIFIER: _ASN1Type.PrintableString, + NameOID.EMAIL_ADDRESS: _ASN1Type.IA5String, + NameOID.DOMAIN_COMPONENT: _ASN1Type.IA5String, +} + +# Type alias +_OidNameMap = typing.Mapping[ObjectIdentifier, str] +_NameOidMap = typing.Mapping[str, ObjectIdentifier] + +#: Short attribute names from RFC 4514: +#: https://tools.ietf.org/html/rfc4514#page-7 +_NAMEOID_TO_NAME: _OidNameMap = { + NameOID.COMMON_NAME: "CN", + NameOID.LOCALITY_NAME: "L", + NameOID.STATE_OR_PROVINCE_NAME: "ST", + NameOID.ORGANIZATION_NAME: "O", + NameOID.ORGANIZATIONAL_UNIT_NAME: "OU", + NameOID.COUNTRY_NAME: "C", + NameOID.STREET_ADDRESS: "STREET", + NameOID.DOMAIN_COMPONENT: "DC", + NameOID.USER_ID: "UID", +} +_NAME_TO_NAMEOID = {v: k for k, v in _NAMEOID_TO_NAME.items()} + +_NAMEOID_LENGTH_LIMIT = { + NameOID.COUNTRY_NAME: (2, 2), + NameOID.JURISDICTION_COUNTRY_NAME: (2, 2), + NameOID.COMMON_NAME: (1, 64), +} + + +def _escape_dn_value(val: str | bytes) -> str: + """Escape special characters in RFC4514 Distinguished Name value.""" + + if not val: + return "" + + # RFC 4514 Section 2.4 defines the value as being the # (U+0023) character + # followed by the hexadecimal encoding of the octets. + if isinstance(val, bytes): + return "#" + binascii.hexlify(val).decode("utf8") + + # See https://tools.ietf.org/html/rfc4514#section-2.4 + val = val.replace("\\", "\\\\") + val = val.replace('"', '\\"') + val = val.replace("+", "\\+") + val = val.replace(",", "\\,") + val = val.replace(";", "\\;") + val = val.replace("<", "\\<") + val = val.replace(">", "\\>") + val = val.replace("\0", "\\00") + + if val[0] == "#" or (val[0] == " " and len(val) > 1): + val = "\\" + val + if val[-1] == " ": + val = val[:-1] + "\\ " + + return val + + +def _unescape_dn_value(val: str) -> str: + if not val: + return "" + + # See https://tools.ietf.org/html/rfc4514#section-3 + + # special = escaped / SPACE / SHARP / EQUALS + # escaped = DQUOTE / PLUS / COMMA / SEMI / LANGLE / RANGLE + def sub(m): + val = m.group(0) + # Special character escape + if len(val) == 2: + return val[1:] + + # Unicode string of hex + return binascii.unhexlify(val.replace("\\", "")).decode() + + return _RFC4514NameParser._PAIR_MULTI_RE.sub(sub, val) + + +NameAttributeValueType = typing.TypeVar( + "NameAttributeValueType", + typing.Union[str, bytes], + str, + bytes, + covariant=True, +) + + +class NameAttribute(typing.Generic[NameAttributeValueType]): + def __init__( + self, + oid: ObjectIdentifier, + value: NameAttributeValueType, + _type: _ASN1Type | None = None, + *, + _validate: bool = True, + ) -> None: + if not isinstance(oid, ObjectIdentifier): + raise TypeError( + "oid argument must be an ObjectIdentifier instance." + ) + if _type == _ASN1Type.BitString: + if oid != NameOID.X500_UNIQUE_IDENTIFIER: + raise TypeError( + "oid must be X500_UNIQUE_IDENTIFIER for BitString type." + ) + if not isinstance(value, bytes): + raise TypeError("value must be bytes for BitString") + elif not isinstance(value, str): + raise TypeError("value argument must be a str") + + length_limits = _NAMEOID_LENGTH_LIMIT.get(oid) + if length_limits is not None: + min_length, max_length = length_limits + assert isinstance(value, str) + c_len = len(value.encode("utf8")) + if c_len < min_length or c_len > max_length: + msg = ( + f"Attribute's length must be >= {min_length} and " + f"<= {max_length}, but it was {c_len}" + ) + if _validate is True: + raise ValueError(msg) + else: + warnings.warn(msg, stacklevel=2) + + # The appropriate ASN1 string type varies by OID and is defined across + # multiple RFCs including 2459, 3280, and 5280. In general UTF8String + # is preferred (2459), but 3280 and 5280 specify several OIDs with + # alternate types. This means when we see the sentinel value we need + # to look up whether the OID has a non-UTF8 type. If it does, set it + # to that. Otherwise, UTF8! + if _type is None: + _type = _NAMEOID_DEFAULT_TYPE.get(oid, _ASN1Type.UTF8String) + + if not isinstance(_type, _ASN1Type): + raise TypeError("_type must be from the _ASN1Type enum") + + self._oid = oid + self._value: NameAttributeValueType = value + self._type: _ASN1Type = _type + + @property + def oid(self) -> ObjectIdentifier: + return self._oid + + @property + def value(self) -> NameAttributeValueType: + return self._value + + @property + def rfc4514_attribute_name(self) -> str: + """ + The short attribute name (for example "CN") if available, + otherwise the OID dotted string. + """ + return _NAMEOID_TO_NAME.get(self.oid, self.oid.dotted_string) + + def rfc4514_string( + self, attr_name_overrides: _OidNameMap | None = None + ) -> str: + """ + Format as RFC4514 Distinguished Name string. + + Use short attribute name if available, otherwise fall back to OID + dotted string. + """ + attr_name = ( + attr_name_overrides.get(self.oid) if attr_name_overrides else None + ) + if attr_name is None: + attr_name = self.rfc4514_attribute_name + + return f"{attr_name}={_escape_dn_value(self.value)}" + + def __eq__(self, other: object) -> bool: + if not isinstance(other, NameAttribute): + return NotImplemented + + return self.oid == other.oid and self.value == other.value + + def __hash__(self) -> int: + return hash((self.oid, self.value)) + + def __repr__(self) -> str: + return f"" + + +class RelativeDistinguishedName: + def __init__(self, attributes: Iterable[NameAttribute[str | bytes]]): + attributes = list(attributes) + if not attributes: + raise ValueError("a relative distinguished name cannot be empty") + if not all(isinstance(x, NameAttribute) for x in attributes): + raise TypeError("attributes must be an iterable of NameAttribute") + + # Keep list and frozenset to preserve attribute order where it matters + self._attributes = attributes + self._attribute_set = frozenset(attributes) + + if len(self._attribute_set) != len(attributes): + raise ValueError("duplicate attributes are not allowed") + + def get_attributes_for_oid( + self, + oid: ObjectIdentifier, + ) -> list[NameAttribute[str | bytes]]: + return [i for i in self if i.oid == oid] + + def rfc4514_string( + self, attr_name_overrides: _OidNameMap | None = None + ) -> str: + """ + Format as RFC4514 Distinguished Name string. + + Within each RDN, attributes are joined by '+', although that is rarely + used in certificates. + """ + return "+".join( + attr.rfc4514_string(attr_name_overrides) + for attr in self._attributes + ) + + def __eq__(self, other: object) -> bool: + if not isinstance(other, RelativeDistinguishedName): + return NotImplemented + + return self._attribute_set == other._attribute_set + + def __hash__(self) -> int: + return hash(self._attribute_set) + + def __iter__(self) -> Iterator[NameAttribute[str | bytes]]: + return iter(self._attributes) + + def __len__(self) -> int: + return len(self._attributes) + + def __repr__(self) -> str: + return f"" + + +class Name: + @typing.overload + def __init__( + self, attributes: Iterable[NameAttribute[str | bytes]] + ) -> None: ... + + @typing.overload + def __init__( + self, attributes: Iterable[RelativeDistinguishedName] + ) -> None: ... + + def __init__( + self, + attributes: Iterable[ + NameAttribute[str | bytes] | RelativeDistinguishedName + ], + ) -> None: + attributes = list(attributes) + if all(isinstance(x, NameAttribute) for x in attributes): + self._attributes = [ + RelativeDistinguishedName([typing.cast(NameAttribute, x)]) + for x in attributes + ] + elif all(isinstance(x, RelativeDistinguishedName) for x in attributes): + self._attributes = typing.cast( + list[RelativeDistinguishedName], attributes + ) + else: + raise TypeError( + "attributes must be a list of NameAttribute" + " or a list RelativeDistinguishedName" + ) + + @classmethod + def from_rfc4514_string( + cls, + data: str, + attr_name_overrides: _NameOidMap | None = None, + ) -> Name: + return _RFC4514NameParser(data, attr_name_overrides or {}).parse() + + def rfc4514_string( + self, attr_name_overrides: _OidNameMap | None = None + ) -> str: + """ + Format as RFC4514 Distinguished Name string. + For example 'CN=foobar.com,O=Foo Corp,C=US' + + An X.509 name is a two-level structure: a list of sets of attributes. + Each list element is separated by ',' and within each list element, set + elements are separated by '+'. The latter is almost never used in + real world certificates. According to RFC4514 section 2.1 the + RDNSequence must be reversed when converting to string representation. + """ + return ",".join( + attr.rfc4514_string(attr_name_overrides) + for attr in reversed(self._attributes) + ) + + def get_attributes_for_oid( + self, + oid: ObjectIdentifier, + ) -> list[NameAttribute[str | bytes]]: + return [i for i in self if i.oid == oid] + + @property + def rdns(self) -> list[RelativeDistinguishedName]: + return self._attributes + + def public_bytes(self, backend: typing.Any = None) -> bytes: + return rust_x509.encode_name_bytes(self) + + def __eq__(self, other: object) -> bool: + if not isinstance(other, Name): + return NotImplemented + + return self._attributes == other._attributes + + def __hash__(self) -> int: + # TODO: this is relatively expensive, if this looks like a bottleneck + # for you, consider optimizing! + return hash(tuple(self._attributes)) + + def __iter__(self) -> Iterator[NameAttribute[str | bytes]]: + for rdn in self._attributes: + yield from rdn + + def __len__(self) -> int: + return sum(len(rdn) for rdn in self._attributes) + + def __repr__(self) -> str: + return f"" + + +class _RFC4514NameParser: + _OID_RE = re.compile(r"(0|([1-9]\d*))(\.(0|([1-9]\d*)))+") + _DESCR_RE = re.compile(r"[a-zA-Z][a-zA-Z\d-]*") + + _ESCAPE_SPECIAL = r"[\\ #=\"\+,;<>]" + _ESCAPE_HEX = r"[\da-zA-Z]{2}" + _PAIR = rf"\\({_ESCAPE_SPECIAL}|{_ESCAPE_HEX})" + _PAIR_MULTI_RE = re.compile(rf"(\\{_ESCAPE_SPECIAL})|((\\{_ESCAPE_HEX})+)") + _LUTF1 = r"[\x01-\x1f\x21\x24-\x2A\x2D-\x3A\x3D\x3F-\x5B\x5D-\x7F]" + _SUTF1 = r"[\x01-\x21\x23-\x2A\x2D-\x3A\x3D\x3F-\x5B\x5D-\x7F]" + _TUTF1 = r"[\x01-\x1F\x21\x23-\x2A\x2D-\x3A\x3D\x3F-\x5B\x5D-\x7F]" + _UTFMB = rf"[\x80-{chr(sys.maxunicode)}]" + _LEADCHAR = rf"{_LUTF1}|{_UTFMB}" + _STRINGCHAR = rf"{_SUTF1}|{_UTFMB}" + _TRAILCHAR = rf"{_TUTF1}|{_UTFMB}" + _STRING_RE = re.compile( + rf""" + ( + ({_LEADCHAR}|{_PAIR}) + ( + ({_STRINGCHAR}|{_PAIR})* + ({_TRAILCHAR}|{_PAIR}) + )? + )? + """, + re.VERBOSE, + ) + _HEXSTRING_RE = re.compile(r"#([\da-zA-Z]{2})+") + + def __init__(self, data: str, attr_name_overrides: _NameOidMap) -> None: + self._data = data + self._idx = 0 + + self._attr_name_overrides = attr_name_overrides + + def _has_data(self) -> bool: + return self._idx < len(self._data) + + def _peek(self) -> str | None: + if self._has_data(): + return self._data[self._idx] + return None + + def _read_char(self, ch: str) -> None: + if self._peek() != ch: + raise ValueError + self._idx += 1 + + def _read_re(self, pat) -> str: + match = pat.match(self._data, pos=self._idx) + if match is None: + raise ValueError + val = match.group() + self._idx += len(val) + return val + + def parse(self) -> Name: + """ + Parses the `data` string and converts it to a Name. + + According to RFC4514 section 2.1 the RDNSequence must be + reversed when converting to string representation. So, when + we parse it, we need to reverse again to get the RDNs on the + correct order. + """ + + if not self._has_data(): + return Name([]) + + rdns = [self._parse_rdn()] + + while self._has_data(): + self._read_char(",") + rdns.append(self._parse_rdn()) + + return Name(reversed(rdns)) + + def _parse_rdn(self) -> RelativeDistinguishedName: + nas = [self._parse_na()] + while self._peek() == "+": + self._read_char("+") + nas.append(self._parse_na()) + + return RelativeDistinguishedName(nas) + + def _parse_na(self) -> NameAttribute[str]: + try: + oid_value = self._read_re(self._OID_RE) + except ValueError: + name = self._read_re(self._DESCR_RE) + oid = self._attr_name_overrides.get( + name, _NAME_TO_NAMEOID.get(name) + ) + if oid is None: + raise ValueError + else: + oid = ObjectIdentifier(oid_value) + + self._read_char("=") + if self._peek() == "#": + value = self._read_re(self._HEXSTRING_RE) + value = binascii.unhexlify(value[1:]).decode() + else: + raw_value = self._read_re(self._STRING_RE) + value = _unescape_dn_value(raw_value) + + return NameAttribute(oid, value) diff --git a/python/user_packages/Python313/site-packages/cryptography/x509/ocsp.py b/python/user_packages/Python313/site-packages/cryptography/x509/ocsp.py new file mode 100644 index 0000000000000000000000000000000000000000..f61ed80b82bdea361b70d676a632f173368adc26 --- /dev/null +++ b/python/user_packages/Python313/site-packages/cryptography/x509/ocsp.py @@ -0,0 +1,379 @@ +# This file is dual licensed under the terms of the Apache License, Version +# 2.0, and the BSD License. See the LICENSE file in the root of this repository +# for complete details. + +from __future__ import annotations + +import datetime +from collections.abc import Iterable + +from cryptography import utils, x509 +from cryptography.hazmat.bindings._rust import ocsp +from cryptography.hazmat.primitives import hashes +from cryptography.hazmat.primitives.asymmetric.types import ( + CertificateIssuerPrivateKeyTypes, +) +from cryptography.x509.base import _reject_duplicate_extension + + +class OCSPResponderEncoding(utils.Enum): + HASH = "By Hash" + NAME = "By Name" + + +class OCSPResponseStatus(utils.Enum): + SUCCESSFUL = 0 + MALFORMED_REQUEST = 1 + INTERNAL_ERROR = 2 + TRY_LATER = 3 + SIG_REQUIRED = 5 + UNAUTHORIZED = 6 + + +_ALLOWED_HASHES = ( + hashes.SHA1, + hashes.SHA224, + hashes.SHA256, + hashes.SHA384, + hashes.SHA512, +) + + +def _verify_algorithm(algorithm: hashes.HashAlgorithm) -> None: + if not isinstance(algorithm, _ALLOWED_HASHES): + raise ValueError( + "Algorithm must be SHA1, SHA224, SHA256, SHA384, or SHA512" + ) + + +class OCSPCertStatus(utils.Enum): + GOOD = 0 + REVOKED = 1 + UNKNOWN = 2 + + +class _SingleResponse: + def __init__( + self, + resp: tuple[x509.Certificate, x509.Certificate] | None, + resp_hash: tuple[bytes, bytes, int] | None, + algorithm: hashes.HashAlgorithm, + cert_status: OCSPCertStatus, + this_update: datetime.datetime, + next_update: datetime.datetime | None, + revocation_time: datetime.datetime | None, + revocation_reason: x509.ReasonFlags | None, + ): + _verify_algorithm(algorithm) + if not isinstance(this_update, datetime.datetime): + raise TypeError("this_update must be a datetime object") + if next_update is not None and not isinstance( + next_update, datetime.datetime + ): + raise TypeError("next_update must be a datetime object or None") + + self._resp = resp + self._resp_hash = resp_hash + self._algorithm = algorithm + self._this_update = this_update + self._next_update = next_update + + if not isinstance(cert_status, OCSPCertStatus): + raise TypeError( + "cert_status must be an item from the OCSPCertStatus enum" + ) + if cert_status is not OCSPCertStatus.REVOKED: + if revocation_time is not None: + raise ValueError( + "revocation_time can only be provided if the certificate " + "is revoked" + ) + if revocation_reason is not None: + raise ValueError( + "revocation_reason can only be provided if the certificate" + " is revoked" + ) + else: + if not isinstance(revocation_time, datetime.datetime): + raise TypeError("revocation_time must be a datetime object") + + if revocation_reason is not None and not isinstance( + revocation_reason, x509.ReasonFlags + ): + raise TypeError( + "revocation_reason must be an item from the ReasonFlags " + "enum or None" + ) + + self._cert_status = cert_status + self._revocation_time = revocation_time + self._revocation_reason = revocation_reason + + +OCSPRequest = ocsp.OCSPRequest +OCSPResponse = ocsp.OCSPResponse +OCSPSingleResponse = ocsp.OCSPSingleResponse + + +class OCSPRequestBuilder: + def __init__( + self, + request: tuple[ + x509.Certificate, x509.Certificate, hashes.HashAlgorithm + ] + | None = None, + request_hash: tuple[bytes, bytes, int, hashes.HashAlgorithm] + | None = None, + extensions: list[x509.Extension[x509.ExtensionType]] = [], + ) -> None: + self._request = request + self._request_hash = request_hash + self._extensions = extensions + + def add_certificate( + self, + cert: x509.Certificate, + issuer: x509.Certificate, + algorithm: hashes.HashAlgorithm, + ) -> OCSPRequestBuilder: + if self._request is not None or self._request_hash is not None: + raise ValueError("Only one certificate can be added to a request") + + _verify_algorithm(algorithm) + if not isinstance(cert, x509.Certificate) or not isinstance( + issuer, x509.Certificate + ): + raise TypeError("cert and issuer must be a Certificate") + + return OCSPRequestBuilder( + (cert, issuer, algorithm), self._request_hash, self._extensions + ) + + def add_certificate_by_hash( + self, + issuer_name_hash: bytes, + issuer_key_hash: bytes, + serial_number: int, + algorithm: hashes.HashAlgorithm, + ) -> OCSPRequestBuilder: + if self._request is not None or self._request_hash is not None: + raise ValueError("Only one certificate can be added to a request") + + if not isinstance(serial_number, int): + raise TypeError("serial_number must be an integer") + + _verify_algorithm(algorithm) + utils._check_bytes("issuer_name_hash", issuer_name_hash) + utils._check_bytes("issuer_key_hash", issuer_key_hash) + if algorithm.digest_size != len( + issuer_name_hash + ) or algorithm.digest_size != len(issuer_key_hash): + raise ValueError( + "issuer_name_hash and issuer_key_hash must be the same length " + "as the digest size of the algorithm" + ) + + return OCSPRequestBuilder( + self._request, + (issuer_name_hash, issuer_key_hash, serial_number, algorithm), + self._extensions, + ) + + def add_extension( + self, extval: x509.ExtensionType, critical: bool + ) -> OCSPRequestBuilder: + if not isinstance(extval, x509.ExtensionType): + raise TypeError("extension must be an ExtensionType") + + extension = x509.Extension(extval.oid, critical, extval) + _reject_duplicate_extension(extension, self._extensions) + + return OCSPRequestBuilder( + self._request, self._request_hash, [*self._extensions, extension] + ) + + def build(self) -> OCSPRequest: + if self._request is None and self._request_hash is None: + raise ValueError("You must add a certificate before building") + + return ocsp.create_ocsp_request(self) + + +class OCSPResponseBuilder: + def __init__( + self, + response: _SingleResponse | None = None, + responder_id: tuple[x509.Certificate, OCSPResponderEncoding] + | None = None, + certs: list[x509.Certificate] | None = None, + extensions: list[x509.Extension[x509.ExtensionType]] = [], + ): + self._response = response + self._responder_id = responder_id + self._certs = certs + self._extensions = extensions + + def add_response( + self, + cert: x509.Certificate, + issuer: x509.Certificate, + algorithm: hashes.HashAlgorithm, + cert_status: OCSPCertStatus, + this_update: datetime.datetime, + next_update: datetime.datetime | None, + revocation_time: datetime.datetime | None, + revocation_reason: x509.ReasonFlags | None, + ) -> OCSPResponseBuilder: + if self._response is not None: + raise ValueError("Only one response per OCSPResponse.") + + if not isinstance(cert, x509.Certificate) or not isinstance( + issuer, x509.Certificate + ): + raise TypeError("cert and issuer must be a Certificate") + + singleresp = _SingleResponse( + (cert, issuer), + None, + algorithm, + cert_status, + this_update, + next_update, + revocation_time, + revocation_reason, + ) + return OCSPResponseBuilder( + singleresp, + self._responder_id, + self._certs, + self._extensions, + ) + + def add_response_by_hash( + self, + issuer_name_hash: bytes, + issuer_key_hash: bytes, + serial_number: int, + algorithm: hashes.HashAlgorithm, + cert_status: OCSPCertStatus, + this_update: datetime.datetime, + next_update: datetime.datetime | None, + revocation_time: datetime.datetime | None, + revocation_reason: x509.ReasonFlags | None, + ) -> OCSPResponseBuilder: + if self._response is not None: + raise ValueError("Only one response per OCSPResponse.") + + if not isinstance(serial_number, int): + raise TypeError("serial_number must be an integer") + + utils._check_bytes("issuer_name_hash", issuer_name_hash) + utils._check_bytes("issuer_key_hash", issuer_key_hash) + _verify_algorithm(algorithm) + if algorithm.digest_size != len( + issuer_name_hash + ) or algorithm.digest_size != len(issuer_key_hash): + raise ValueError( + "issuer_name_hash and issuer_key_hash must be the same length " + "as the digest size of the algorithm" + ) + + singleresp = _SingleResponse( + None, + (issuer_name_hash, issuer_key_hash, serial_number), + algorithm, + cert_status, + this_update, + next_update, + revocation_time, + revocation_reason, + ) + return OCSPResponseBuilder( + singleresp, + self._responder_id, + self._certs, + self._extensions, + ) + + def responder_id( + self, encoding: OCSPResponderEncoding, responder_cert: x509.Certificate + ) -> OCSPResponseBuilder: + if self._responder_id is not None: + raise ValueError("responder_id can only be set once") + if not isinstance(responder_cert, x509.Certificate): + raise TypeError("responder_cert must be a Certificate") + if not isinstance(encoding, OCSPResponderEncoding): + raise TypeError( + "encoding must be an element from OCSPResponderEncoding" + ) + + return OCSPResponseBuilder( + self._response, + (responder_cert, encoding), + self._certs, + self._extensions, + ) + + def certificates( + self, certs: Iterable[x509.Certificate] + ) -> OCSPResponseBuilder: + if self._certs is not None: + raise ValueError("certificates may only be set once") + certs = list(certs) + if len(certs) == 0: + raise ValueError("certs must not be an empty list") + if not all(isinstance(x, x509.Certificate) for x in certs): + raise TypeError("certs must be a list of Certificates") + return OCSPResponseBuilder( + self._response, + self._responder_id, + certs, + self._extensions, + ) + + def add_extension( + self, extval: x509.ExtensionType, critical: bool + ) -> OCSPResponseBuilder: + if not isinstance(extval, x509.ExtensionType): + raise TypeError("extension must be an ExtensionType") + + extension = x509.Extension(extval.oid, critical, extval) + _reject_duplicate_extension(extension, self._extensions) + + return OCSPResponseBuilder( + self._response, + self._responder_id, + self._certs, + [*self._extensions, extension], + ) + + def sign( + self, + private_key: CertificateIssuerPrivateKeyTypes, + algorithm: hashes.HashAlgorithm | None, + ) -> OCSPResponse: + if self._response is None: + raise ValueError("You must add a response before signing") + if self._responder_id is None: + raise ValueError("You must add a responder_id before signing") + + return ocsp.create_ocsp_response( + OCSPResponseStatus.SUCCESSFUL, self, private_key, algorithm + ) + + @classmethod + def build_unsuccessful( + cls, response_status: OCSPResponseStatus + ) -> OCSPResponse: + if not isinstance(response_status, OCSPResponseStatus): + raise TypeError( + "response_status must be an item from OCSPResponseStatus" + ) + if response_status is OCSPResponseStatus.SUCCESSFUL: + raise ValueError("response_status cannot be SUCCESSFUL") + + return ocsp.create_ocsp_response(response_status, None, None, None) + + +load_der_ocsp_request = ocsp.load_der_ocsp_request +load_der_ocsp_response = ocsp.load_der_ocsp_response diff --git a/python/user_packages/Python313/site-packages/cryptography/x509/oid.py b/python/user_packages/Python313/site-packages/cryptography/x509/oid.py new file mode 100644 index 0000000000000000000000000000000000000000..520fc7ab018c1b62132b957d332a83abef51b39e --- /dev/null +++ b/python/user_packages/Python313/site-packages/cryptography/x509/oid.py @@ -0,0 +1,37 @@ +# This file is dual licensed under the terms of the Apache License, Version +# 2.0, and the BSD License. See the LICENSE file in the root of this repository +# for complete details. + +from __future__ import annotations + +from cryptography.hazmat._oid import ( + AttributeOID, + AuthorityInformationAccessOID, + CertificatePoliciesOID, + CRLEntryExtensionOID, + ExtendedKeyUsageOID, + ExtensionOID, + NameOID, + ObjectIdentifier, + OCSPExtensionOID, + OtherNameFormOID, + PublicKeyAlgorithmOID, + SignatureAlgorithmOID, + SubjectInformationAccessOID, +) + +__all__ = [ + "AttributeOID", + "AuthorityInformationAccessOID", + "CRLEntryExtensionOID", + "CertificatePoliciesOID", + "ExtendedKeyUsageOID", + "ExtensionOID", + "NameOID", + "OCSPExtensionOID", + "ObjectIdentifier", + "OtherNameFormOID", + "PublicKeyAlgorithmOID", + "SignatureAlgorithmOID", + "SubjectInformationAccessOID", +] diff --git a/python/user_packages/Python313/site-packages/cryptography/x509/verification.py b/python/user_packages/Python313/site-packages/cryptography/x509/verification.py new file mode 100644 index 0000000000000000000000000000000000000000..2db4324d9615fb0d4dce6cd4dc5a9b55f4e28745 --- /dev/null +++ b/python/user_packages/Python313/site-packages/cryptography/x509/verification.py @@ -0,0 +1,34 @@ +# This file is dual licensed under the terms of the Apache License, Version +# 2.0, and the BSD License. See the LICENSE file in the root of this repository +# for complete details. + +from __future__ import annotations + +import typing + +from cryptography.hazmat.bindings._rust import x509 as rust_x509 +from cryptography.x509.general_name import DNSName, IPAddress + +__all__ = [ + "ClientVerifier", + "Criticality", + "ExtensionPolicy", + "Policy", + "PolicyBuilder", + "ServerVerifier", + "Store", + "Subject", + "VerificationError", + "VerifiedClient", +] + +Store = rust_x509.Store +Subject = typing.Union[DNSName, IPAddress] +VerifiedClient = rust_x509.VerifiedClient +ClientVerifier = rust_x509.ClientVerifier +ServerVerifier = rust_x509.ServerVerifier +PolicyBuilder = rust_x509.PolicyBuilder +Policy = rust_x509.Policy +ExtensionPolicy = rust_x509.ExtensionPolicy +Criticality = rust_x509.Criticality +VerificationError = rust_x509.VerificationError diff --git a/python/user_packages/Python313/site-packages/dataclasses_json/__pycache__/__init__.cpython-313.pyc b/python/user_packages/Python313/site-packages/dataclasses_json/__pycache__/__init__.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3adc543d78d60f7ed419803867dd2251269f8ff0 Binary files /dev/null and b/python/user_packages/Python313/site-packages/dataclasses_json/__pycache__/__init__.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/dataclasses_json/__pycache__/__version__.cpython-313.pyc b/python/user_packages/Python313/site-packages/dataclasses_json/__pycache__/__version__.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..db51fabfb1682889d3d52c351d9d2ca79a6cc5a0 Binary files /dev/null and b/python/user_packages/Python313/site-packages/dataclasses_json/__pycache__/__version__.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/dataclasses_json/__pycache__/api.cpython-313.pyc b/python/user_packages/Python313/site-packages/dataclasses_json/__pycache__/api.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6588053d22e0d770193e156691e9e11bd07d3d71 Binary files /dev/null and b/python/user_packages/Python313/site-packages/dataclasses_json/__pycache__/api.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/dataclasses_json/__pycache__/cfg.cpython-313.pyc b/python/user_packages/Python313/site-packages/dataclasses_json/__pycache__/cfg.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c17b25b37373635b9180589b238efe99947c3106 Binary files /dev/null and b/python/user_packages/Python313/site-packages/dataclasses_json/__pycache__/cfg.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/dataclasses_json/__pycache__/core.cpython-313.pyc b/python/user_packages/Python313/site-packages/dataclasses_json/__pycache__/core.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2b6c321aa2ae8747dba4050385dabd814f2e6e0f Binary files /dev/null and b/python/user_packages/Python313/site-packages/dataclasses_json/__pycache__/core.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/dataclasses_json/__pycache__/mm.cpython-313.pyc b/python/user_packages/Python313/site-packages/dataclasses_json/__pycache__/mm.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..07479a5e812c3c480d02e175d684008df1ae3d9a Binary files /dev/null and b/python/user_packages/Python313/site-packages/dataclasses_json/__pycache__/mm.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/dataclasses_json/__pycache__/stringcase.cpython-313.pyc b/python/user_packages/Python313/site-packages/dataclasses_json/__pycache__/stringcase.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..df502d0519c27b8b556840a94ba83e5fdc2a9858 Binary files /dev/null and b/python/user_packages/Python313/site-packages/dataclasses_json/__pycache__/stringcase.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/dataclasses_json/__pycache__/undefined.cpython-313.pyc b/python/user_packages/Python313/site-packages/dataclasses_json/__pycache__/undefined.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..12fecfffbef603b6d4b53d05def4a063a32a616b Binary files /dev/null and b/python/user_packages/Python313/site-packages/dataclasses_json/__pycache__/undefined.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/dataclasses_json/__pycache__/utils.cpython-313.pyc b/python/user_packages/Python313/site-packages/dataclasses_json/__pycache__/utils.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a0abfe31ead4232c6d61d2d18cef57ca97e52e50 Binary files /dev/null and b/python/user_packages/Python313/site-packages/dataclasses_json/__pycache__/utils.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/dateutil/__pycache__/__init__.cpython-313.pyc b/python/user_packages/Python313/site-packages/dateutil/__pycache__/__init__.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..746bfdf7fb4c861d824156ac37cc644deda14810 Binary files /dev/null and b/python/user_packages/Python313/site-packages/dateutil/__pycache__/__init__.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/dateutil/__pycache__/_common.cpython-313.pyc b/python/user_packages/Python313/site-packages/dateutil/__pycache__/_common.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1aff782fc84f6d85692a9500bd78247871a690c3 Binary files /dev/null and b/python/user_packages/Python313/site-packages/dateutil/__pycache__/_common.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/dateutil/__pycache__/_version.cpython-313.pyc b/python/user_packages/Python313/site-packages/dateutil/__pycache__/_version.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..799784c87a200ee5edcb3f3242d46eb542c81b2f Binary files /dev/null and b/python/user_packages/Python313/site-packages/dateutil/__pycache__/_version.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/dateutil/__pycache__/easter.cpython-313.pyc b/python/user_packages/Python313/site-packages/dateutil/__pycache__/easter.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6700e040829b683e4df7c2cf655cb9b1a798a5c5 Binary files /dev/null and b/python/user_packages/Python313/site-packages/dateutil/__pycache__/easter.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/dateutil/__pycache__/relativedelta.cpython-313.pyc b/python/user_packages/Python313/site-packages/dateutil/__pycache__/relativedelta.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f4267bbacfb3e63d83f5179785e4295cfb690c6c Binary files /dev/null and b/python/user_packages/Python313/site-packages/dateutil/__pycache__/relativedelta.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/dateutil/__pycache__/rrule.cpython-313.pyc b/python/user_packages/Python313/site-packages/dateutil/__pycache__/rrule.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2eee77d45934fcd43eecc61714db7b45b7f6d433 Binary files /dev/null and b/python/user_packages/Python313/site-packages/dateutil/__pycache__/rrule.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/dateutil/__pycache__/tzwin.cpython-313.pyc b/python/user_packages/Python313/site-packages/dateutil/__pycache__/tzwin.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2ff916167cb1d93808d6009f6e4edd4d7c717f26 Binary files /dev/null and b/python/user_packages/Python313/site-packages/dateutil/__pycache__/tzwin.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/dateutil/__pycache__/utils.cpython-313.pyc b/python/user_packages/Python313/site-packages/dateutil/__pycache__/utils.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a25bca46e271ea4b80bc88e1031720d9dbb7a986 Binary files /dev/null and b/python/user_packages/Python313/site-packages/dateutil/__pycache__/utils.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/dateutil/parser/__init__.py b/python/user_packages/Python313/site-packages/dateutil/parser/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..d174b0e4dcc472999b75e55ebb88af320ae38081 --- /dev/null +++ b/python/user_packages/Python313/site-packages/dateutil/parser/__init__.py @@ -0,0 +1,61 @@ +# -*- coding: utf-8 -*- +from ._parser import parse, parser, parserinfo, ParserError +from ._parser import DEFAULTPARSER, DEFAULTTZPARSER +from ._parser import UnknownTimezoneWarning + +from ._parser import __doc__ + +from .isoparser import isoparser, isoparse + +__all__ = ['parse', 'parser', 'parserinfo', + 'isoparse', 'isoparser', + 'ParserError', + 'UnknownTimezoneWarning'] + + +### +# Deprecate portions of the private interface so that downstream code that +# is improperly relying on it is given *some* notice. + + +def __deprecated_private_func(f): + from functools import wraps + import warnings + + msg = ('{name} is a private function and may break without warning, ' + 'it will be moved and or renamed in future versions.') + msg = msg.format(name=f.__name__) + + @wraps(f) + def deprecated_func(*args, **kwargs): + warnings.warn(msg, DeprecationWarning) + return f(*args, **kwargs) + + return deprecated_func + +def __deprecate_private_class(c): + import warnings + + msg = ('{name} is a private class and may break without warning, ' + 'it will be moved and or renamed in future versions.') + msg = msg.format(name=c.__name__) + + class private_class(c): + __doc__ = c.__doc__ + + def __init__(self, *args, **kwargs): + warnings.warn(msg, DeprecationWarning) + super(private_class, self).__init__(*args, **kwargs) + + private_class.__name__ = c.__name__ + + return private_class + + +from ._parser import _timelex, _resultbase +from ._parser import _tzparser, _parsetz + +_timelex = __deprecate_private_class(_timelex) +_tzparser = __deprecate_private_class(_tzparser) +_resultbase = __deprecate_private_class(_resultbase) +_parsetz = __deprecated_private_func(_parsetz) diff --git a/python/user_packages/Python313/site-packages/dateutil/parser/__pycache__/__init__.cpython-313.pyc b/python/user_packages/Python313/site-packages/dateutil/parser/__pycache__/__init__.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..249d38db220afd96a3f37e68e0c70b27e883cba9 Binary files /dev/null and b/python/user_packages/Python313/site-packages/dateutil/parser/__pycache__/__init__.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/dateutil/parser/__pycache__/_parser.cpython-313.pyc b/python/user_packages/Python313/site-packages/dateutil/parser/__pycache__/_parser.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b3d1830b7f875c2b84ebabc7bbb76c22c9d4ff82 Binary files /dev/null and b/python/user_packages/Python313/site-packages/dateutil/parser/__pycache__/_parser.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/dateutil/parser/__pycache__/isoparser.cpython-313.pyc b/python/user_packages/Python313/site-packages/dateutil/parser/__pycache__/isoparser.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..08b1bfe1511a81a269b030e4bb7dcdd51dd62b57 Binary files /dev/null and b/python/user_packages/Python313/site-packages/dateutil/parser/__pycache__/isoparser.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/dateutil/parser/_parser.py b/python/user_packages/Python313/site-packages/dateutil/parser/_parser.py new file mode 100644 index 0000000000000000000000000000000000000000..37d1663b2f72447800d9a553929e3de932244289 --- /dev/null +++ b/python/user_packages/Python313/site-packages/dateutil/parser/_parser.py @@ -0,0 +1,1613 @@ +# -*- coding: utf-8 -*- +""" +This module offers a generic date/time string parser which is able to parse +most known formats to represent a date and/or time. + +This module attempts to be forgiving with regards to unlikely input formats, +returning a datetime object even for dates which are ambiguous. If an element +of a date/time stamp is omitted, the following rules are applied: + +- If AM or PM is left unspecified, a 24-hour clock is assumed, however, an hour + on a 12-hour clock (``0 <= hour <= 12``) *must* be specified if AM or PM is + specified. +- If a time zone is omitted, a timezone-naive datetime is returned. + +If any other elements are missing, they are taken from the +:class:`datetime.datetime` object passed to the parameter ``default``. If this +results in a day number exceeding the valid number of days per month, the +value falls back to the end of the month. + +Additional resources about date/time string formats can be found below: + +- `A summary of the international standard date and time notation + `_ +- `W3C Date and Time Formats `_ +- `Time Formats (Planetary Rings Node) `_ +- `CPAN ParseDate module + `_ +- `Java SimpleDateFormat Class + `_ +""" +from __future__ import unicode_literals + +import datetime +import re +import string +import time +import warnings + +from calendar import monthrange +from io import StringIO + +import six +from six import integer_types, text_type + +from decimal import Decimal + +from warnings import warn + +from .. import relativedelta +from .. import tz + +__all__ = ["parse", "parserinfo", "ParserError"] + + +# TODO: pandas.core.tools.datetimes imports this explicitly. Might be worth +# making public and/or figuring out if there is something we can +# take off their plate. +class _timelex(object): + # Fractional seconds are sometimes split by a comma + _split_decimal = re.compile("([.,])") + + def __init__(self, instream): + if isinstance(instream, (bytes, bytearray)): + instream = instream.decode() + + if isinstance(instream, text_type): + instream = StringIO(instream) + elif getattr(instream, 'read', None) is None: + raise TypeError('Parser must be a string or character stream, not ' + '{itype}'.format(itype=instream.__class__.__name__)) + + self.instream = instream + self.charstack = [] + self.tokenstack = [] + self.eof = False + + def get_token(self): + """ + This function breaks the time string into lexical units (tokens), which + can be parsed by the parser. Lexical units are demarcated by changes in + the character set, so any continuous string of letters is considered + one unit, any continuous string of numbers is considered one unit. + + The main complication arises from the fact that dots ('.') can be used + both as separators (e.g. "Sep.20.2009") or decimal points (e.g. + "4:30:21.447"). As such, it is necessary to read the full context of + any dot-separated strings before breaking it into tokens; as such, this + function maintains a "token stack", for when the ambiguous context + demands that multiple tokens be parsed at once. + """ + if self.tokenstack: + return self.tokenstack.pop(0) + + seenletters = False + token = None + state = None + + while not self.eof: + # We only realize that we've reached the end of a token when we + # find a character that's not part of the current token - since + # that character may be part of the next token, it's stored in the + # charstack. + if self.charstack: + nextchar = self.charstack.pop(0) + else: + nextchar = self.instream.read(1) + while nextchar == '\x00': + nextchar = self.instream.read(1) + + if not nextchar: + self.eof = True + break + elif not state: + # First character of the token - determines if we're starting + # to parse a word, a number or something else. + token = nextchar + if self.isword(nextchar): + state = 'a' + elif self.isnum(nextchar): + state = '0' + elif self.isspace(nextchar): + token = ' ' + break # emit token + else: + break # emit token + elif state == 'a': + # If we've already started reading a word, we keep reading + # letters until we find something that's not part of a word. + seenletters = True + if self.isword(nextchar): + token += nextchar + elif nextchar == '.': + token += nextchar + state = 'a.' + else: + self.charstack.append(nextchar) + break # emit token + elif state == '0': + # If we've already started reading a number, we keep reading + # numbers until we find something that doesn't fit. + if self.isnum(nextchar): + token += nextchar + elif nextchar == '.' or (nextchar == ',' and len(token) >= 2): + token += nextchar + state = '0.' + else: + self.charstack.append(nextchar) + break # emit token + elif state == 'a.': + # If we've seen some letters and a dot separator, continue + # parsing, and the tokens will be broken up later. + seenletters = True + if nextchar == '.' or self.isword(nextchar): + token += nextchar + elif self.isnum(nextchar) and token[-1] == '.': + token += nextchar + state = '0.' + else: + self.charstack.append(nextchar) + break # emit token + elif state == '0.': + # If we've seen at least one dot separator, keep going, we'll + # break up the tokens later. + if nextchar == '.' or self.isnum(nextchar): + token += nextchar + elif self.isword(nextchar) and token[-1] == '.': + token += nextchar + state = 'a.' + else: + self.charstack.append(nextchar) + break # emit token + + if (state in ('a.', '0.') and (seenletters or token.count('.') > 1 or + token[-1] in '.,')): + l = self._split_decimal.split(token) + token = l[0] + for tok in l[1:]: + if tok: + self.tokenstack.append(tok) + + if state == '0.' and token.count('.') == 0: + token = token.replace(',', '.') + + return token + + def __iter__(self): + return self + + def __next__(self): + token = self.get_token() + if token is None: + raise StopIteration + + return token + + def next(self): + return self.__next__() # Python 2.x support + + @classmethod + def split(cls, s): + return list(cls(s)) + + @classmethod + def isword(cls, nextchar): + """ Whether or not the next character is part of a word """ + return nextchar.isalpha() + + @classmethod + def isnum(cls, nextchar): + """ Whether the next character is part of a number """ + return nextchar.isdigit() + + @classmethod + def isspace(cls, nextchar): + """ Whether the next character is whitespace """ + return nextchar.isspace() + + +class _resultbase(object): + + def __init__(self): + for attr in self.__slots__: + setattr(self, attr, None) + + def _repr(self, classname): + l = [] + for attr in self.__slots__: + value = getattr(self, attr) + if value is not None: + l.append("%s=%s" % (attr, repr(value))) + return "%s(%s)" % (classname, ", ".join(l)) + + def __len__(self): + return (sum(getattr(self, attr) is not None + for attr in self.__slots__)) + + def __repr__(self): + return self._repr(self.__class__.__name__) + + +class parserinfo(object): + """ + Class which handles what inputs are accepted. Subclass this to customize + the language and acceptable values for each parameter. + + :param dayfirst: + Whether to interpret the first value in an ambiguous 3-integer date + (e.g. 01/05/09) as the day (``True``) or month (``False``). If + ``yearfirst`` is set to ``True``, this distinguishes between YDM + and YMD. Default is ``False``. + + :param yearfirst: + Whether to interpret the first value in an ambiguous 3-integer date + (e.g. 01/05/09) as the year. If ``True``, the first number is taken + to be the year, otherwise the last number is taken to be the year. + Default is ``False``. + """ + + # m from a.m/p.m, t from ISO T separator + JUMP = [" ", ".", ",", ";", "-", "/", "'", + "at", "on", "and", "ad", "m", "t", "of", + "st", "nd", "rd", "th"] + + WEEKDAYS = [("Mon", "Monday"), + ("Tue", "Tuesday"), # TODO: "Tues" + ("Wed", "Wednesday"), + ("Thu", "Thursday"), # TODO: "Thurs" + ("Fri", "Friday"), + ("Sat", "Saturday"), + ("Sun", "Sunday")] + MONTHS = [("Jan", "January"), + ("Feb", "February"), # TODO: "Febr" + ("Mar", "March"), + ("Apr", "April"), + ("May", "May"), + ("Jun", "June"), + ("Jul", "July"), + ("Aug", "August"), + ("Sep", "Sept", "September"), + ("Oct", "October"), + ("Nov", "November"), + ("Dec", "December")] + HMS = [("h", "hour", "hours"), + ("m", "minute", "minutes"), + ("s", "second", "seconds")] + AMPM = [("am", "a"), + ("pm", "p")] + UTCZONE = ["UTC", "GMT", "Z", "z"] + PERTAIN = ["of"] + TZOFFSET = {} + # TODO: ERA = ["AD", "BC", "CE", "BCE", "Stardate", + # "Anno Domini", "Year of Our Lord"] + + def __init__(self, dayfirst=False, yearfirst=False): + self._jump = self._convert(self.JUMP) + self._weekdays = self._convert(self.WEEKDAYS) + self._months = self._convert(self.MONTHS) + self._hms = self._convert(self.HMS) + self._ampm = self._convert(self.AMPM) + self._utczone = self._convert(self.UTCZONE) + self._pertain = self._convert(self.PERTAIN) + + self.dayfirst = dayfirst + self.yearfirst = yearfirst + + self._year = time.localtime().tm_year + self._century = self._year // 100 * 100 + + def _convert(self, lst): + dct = {} + for i, v in enumerate(lst): + if isinstance(v, tuple): + for v in v: + dct[v.lower()] = i + else: + dct[v.lower()] = i + return dct + + def jump(self, name): + return name.lower() in self._jump + + def weekday(self, name): + try: + return self._weekdays[name.lower()] + except KeyError: + pass + return None + + def month(self, name): + try: + return self._months[name.lower()] + 1 + except KeyError: + pass + return None + + def hms(self, name): + try: + return self._hms[name.lower()] + except KeyError: + return None + + def ampm(self, name): + try: + return self._ampm[name.lower()] + except KeyError: + return None + + def pertain(self, name): + return name.lower() in self._pertain + + def utczone(self, name): + return name.lower() in self._utczone + + def tzoffset(self, name): + if name in self._utczone: + return 0 + + return self.TZOFFSET.get(name) + + def convertyear(self, year, century_specified=False): + """ + Converts two-digit years to year within [-50, 49] + range of self._year (current local time) + """ + + # Function contract is that the year is always positive + assert year >= 0 + + if year < 100 and not century_specified: + # assume current century to start + year += self._century + + if year >= self._year + 50: # if too far in future + year -= 100 + elif year < self._year - 50: # if too far in past + year += 100 + + return year + + def validate(self, res): + # move to info + if res.year is not None: + res.year = self.convertyear(res.year, res.century_specified) + + if ((res.tzoffset == 0 and not res.tzname) or + (res.tzname == 'Z' or res.tzname == 'z')): + res.tzname = "UTC" + res.tzoffset = 0 + elif res.tzoffset != 0 and res.tzname and self.utczone(res.tzname): + res.tzoffset = 0 + return True + + +class _ymd(list): + def __init__(self, *args, **kwargs): + super(self.__class__, self).__init__(*args, **kwargs) + self.century_specified = False + self.dstridx = None + self.mstridx = None + self.ystridx = None + + @property + def has_year(self): + return self.ystridx is not None + + @property + def has_month(self): + return self.mstridx is not None + + @property + def has_day(self): + return self.dstridx is not None + + def could_be_day(self, value): + if self.has_day: + return False + elif not self.has_month: + return 1 <= value <= 31 + elif not self.has_year: + # Be permissive, assume leap year + month = self[self.mstridx] + return 1 <= value <= monthrange(2000, month)[1] + else: + month = self[self.mstridx] + year = self[self.ystridx] + return 1 <= value <= monthrange(year, month)[1] + + def append(self, val, label=None): + if hasattr(val, '__len__'): + if val.isdigit() and len(val) > 2: + self.century_specified = True + if label not in [None, 'Y']: # pragma: no cover + raise ValueError(label) + label = 'Y' + elif val > 100: + self.century_specified = True + if label not in [None, 'Y']: # pragma: no cover + raise ValueError(label) + label = 'Y' + + super(self.__class__, self).append(int(val)) + + if label == 'M': + if self.has_month: + raise ValueError('Month is already set') + self.mstridx = len(self) - 1 + elif label == 'D': + if self.has_day: + raise ValueError('Day is already set') + self.dstridx = len(self) - 1 + elif label == 'Y': + if self.has_year: + raise ValueError('Year is already set') + self.ystridx = len(self) - 1 + + def _resolve_from_stridxs(self, strids): + """ + Try to resolve the identities of year/month/day elements using + ystridx, mstridx, and dstridx, if enough of these are specified. + """ + if len(self) == 3 and len(strids) == 2: + # we can back out the remaining stridx value + missing = [x for x in range(3) if x not in strids.values()] + key = [x for x in ['y', 'm', 'd'] if x not in strids] + assert len(missing) == len(key) == 1 + key = key[0] + val = missing[0] + strids[key] = val + + assert len(self) == len(strids) # otherwise this should not be called + out = {key: self[strids[key]] for key in strids} + return (out.get('y'), out.get('m'), out.get('d')) + + def resolve_ymd(self, yearfirst, dayfirst): + len_ymd = len(self) + year, month, day = (None, None, None) + + strids = (('y', self.ystridx), + ('m', self.mstridx), + ('d', self.dstridx)) + + strids = {key: val for key, val in strids if val is not None} + if (len(self) == len(strids) > 0 or + (len(self) == 3 and len(strids) == 2)): + return self._resolve_from_stridxs(strids) + + mstridx = self.mstridx + + if len_ymd > 3: + raise ValueError("More than three YMD values") + elif len_ymd == 1 or (mstridx is not None and len_ymd == 2): + # One member, or two members with a month string + if mstridx is not None: + month = self[mstridx] + # since mstridx is 0 or 1, self[mstridx-1] always + # looks up the other element + other = self[mstridx - 1] + else: + other = self[0] + + if len_ymd > 1 or mstridx is None: + if other > 31: + year = other + else: + day = other + + elif len_ymd == 2: + # Two members with numbers + if self[0] > 31: + # 99-01 + year, month = self + elif self[1] > 31: + # 01-99 + month, year = self + elif dayfirst and self[1] <= 12: + # 13-01 + day, month = self + else: + # 01-13 + month, day = self + + elif len_ymd == 3: + # Three members + if mstridx == 0: + if self[1] > 31: + # Apr-2003-25 + month, year, day = self + else: + month, day, year = self + elif mstridx == 1: + if self[0] > 31 or (yearfirst and self[2] <= 31): + # 99-Jan-01 + year, month, day = self + else: + # 01-Jan-01 + # Give precedence to day-first, since + # two-digit years is usually hand-written. + day, month, year = self + + elif mstridx == 2: + # WTF!? + if self[1] > 31: + # 01-99-Jan + day, year, month = self + else: + # 99-01-Jan + year, day, month = self + + else: + if (self[0] > 31 or + self.ystridx == 0 or + (yearfirst and self[1] <= 12 and self[2] <= 31)): + # 99-01-01 + if dayfirst and self[2] <= 12: + year, day, month = self + else: + year, month, day = self + elif self[0] > 12 or (dayfirst and self[1] <= 12): + # 13-01-01 + day, month, year = self + else: + # 01-13-01 + month, day, year = self + + return year, month, day + + +class parser(object): + def __init__(self, info=None): + self.info = info or parserinfo() + + def parse(self, timestr, default=None, + ignoretz=False, tzinfos=None, **kwargs): + """ + Parse the date/time string into a :class:`datetime.datetime` object. + + :param timestr: + Any date/time string using the supported formats. + + :param default: + The default datetime object, if this is a datetime object and not + ``None``, elements specified in ``timestr`` replace elements in the + default object. + + :param ignoretz: + If set ``True``, time zones in parsed strings are ignored and a + naive :class:`datetime.datetime` object is returned. + + :param tzinfos: + Additional time zone names / aliases which may be present in the + string. This argument maps time zone names (and optionally offsets + from those time zones) to time zones. This parameter can be a + dictionary with timezone aliases mapping time zone names to time + zones or a function taking two parameters (``tzname`` and + ``tzoffset``) and returning a time zone. + + The timezones to which the names are mapped can be an integer + offset from UTC in seconds or a :class:`tzinfo` object. + + .. doctest:: + :options: +NORMALIZE_WHITESPACE + + >>> from dateutil.parser import parse + >>> from dateutil.tz import gettz + >>> tzinfos = {"BRST": -7200, "CST": gettz("America/Chicago")} + >>> parse("2012-01-19 17:21:00 BRST", tzinfos=tzinfos) + datetime.datetime(2012, 1, 19, 17, 21, tzinfo=tzoffset(u'BRST', -7200)) + >>> parse("2012-01-19 17:21:00 CST", tzinfos=tzinfos) + datetime.datetime(2012, 1, 19, 17, 21, + tzinfo=tzfile('/usr/share/zoneinfo/America/Chicago')) + + This parameter is ignored if ``ignoretz`` is set. + + :param \\*\\*kwargs: + Keyword arguments as passed to ``_parse()``. + + :return: + Returns a :class:`datetime.datetime` object or, if the + ``fuzzy_with_tokens`` option is ``True``, returns a tuple, the + first element being a :class:`datetime.datetime` object, the second + a tuple containing the fuzzy tokens. + + :raises ParserError: + Raised for invalid or unknown string format, if the provided + :class:`tzinfo` is not in a valid format, or if an invalid date + would be created. + + :raises TypeError: + Raised for non-string or character stream input. + + :raises OverflowError: + Raised if the parsed date exceeds the largest valid C integer on + your system. + """ + + if default is None: + default = datetime.datetime.now().replace(hour=0, minute=0, + second=0, microsecond=0) + + res, skipped_tokens = self._parse(timestr, **kwargs) + + if res is None: + raise ParserError("Unknown string format: %s", timestr) + + if len(res) == 0: + raise ParserError("String does not contain a date: %s", timestr) + + try: + ret = self._build_naive(res, default) + except ValueError as e: + six.raise_from(ParserError(str(e) + ": %s", timestr), e) + + if not ignoretz: + ret = self._build_tzaware(ret, res, tzinfos) + + if kwargs.get('fuzzy_with_tokens', False): + return ret, skipped_tokens + else: + return ret + + class _result(_resultbase): + __slots__ = ["year", "month", "day", "weekday", + "hour", "minute", "second", "microsecond", + "tzname", "tzoffset", "ampm","any_unused_tokens"] + + def _parse(self, timestr, dayfirst=None, yearfirst=None, fuzzy=False, + fuzzy_with_tokens=False): + """ + Private method which performs the heavy lifting of parsing, called from + ``parse()``, which passes on its ``kwargs`` to this function. + + :param timestr: + The string to parse. + + :param dayfirst: + Whether to interpret the first value in an ambiguous 3-integer date + (e.g. 01/05/09) as the day (``True``) or month (``False``). If + ``yearfirst`` is set to ``True``, this distinguishes between YDM + and YMD. If set to ``None``, this value is retrieved from the + current :class:`parserinfo` object (which itself defaults to + ``False``). + + :param yearfirst: + Whether to interpret the first value in an ambiguous 3-integer date + (e.g. 01/05/09) as the year. If ``True``, the first number is taken + to be the year, otherwise the last number is taken to be the year. + If this is set to ``None``, the value is retrieved from the current + :class:`parserinfo` object (which itself defaults to ``False``). + + :param fuzzy: + Whether to allow fuzzy parsing, allowing for string like "Today is + January 1, 2047 at 8:21:00AM". + + :param fuzzy_with_tokens: + If ``True``, ``fuzzy`` is automatically set to True, and the parser + will return a tuple where the first element is the parsed + :class:`datetime.datetime` datetimestamp and the second element is + a tuple containing the portions of the string which were ignored: + + .. doctest:: + + >>> from dateutil.parser import parse + >>> parse("Today is January 1, 2047 at 8:21:00AM", fuzzy_with_tokens=True) + (datetime.datetime(2047, 1, 1, 8, 21), (u'Today is ', u' ', u'at ')) + + """ + if fuzzy_with_tokens: + fuzzy = True + + info = self.info + + if dayfirst is None: + dayfirst = info.dayfirst + + if yearfirst is None: + yearfirst = info.yearfirst + + res = self._result() + l = _timelex.split(timestr) # Splits the timestr into tokens + + skipped_idxs = [] + + # year/month/day list + ymd = _ymd() + + len_l = len(l) + i = 0 + try: + while i < len_l: + + # Check if it's a number + value_repr = l[i] + try: + value = float(value_repr) + except ValueError: + value = None + + if value is not None: + # Numeric token + i = self._parse_numeric_token(l, i, info, ymd, res, fuzzy) + + # Check weekday + elif info.weekday(l[i]) is not None: + value = info.weekday(l[i]) + res.weekday = value + + # Check month name + elif info.month(l[i]) is not None: + value = info.month(l[i]) + ymd.append(value, 'M') + + if i + 1 < len_l: + if l[i + 1] in ('-', '/'): + # Jan-01[-99] + sep = l[i + 1] + ymd.append(l[i + 2]) + + if i + 3 < len_l and l[i + 3] == sep: + # Jan-01-99 + ymd.append(l[i + 4]) + i += 2 + + i += 2 + + elif (i + 4 < len_l and l[i + 1] == l[i + 3] == ' ' and + info.pertain(l[i + 2])): + # Jan of 01 + # In this case, 01 is clearly year + if l[i + 4].isdigit(): + # Convert it here to become unambiguous + value = int(l[i + 4]) + year = str(info.convertyear(value)) + ymd.append(year, 'Y') + else: + # Wrong guess + pass + # TODO: not hit in tests + i += 4 + + # Check am/pm + elif info.ampm(l[i]) is not None: + value = info.ampm(l[i]) + val_is_ampm = self._ampm_valid(res.hour, res.ampm, fuzzy) + + if val_is_ampm: + res.hour = self._adjust_ampm(res.hour, value) + res.ampm = value + + elif fuzzy: + skipped_idxs.append(i) + + # Check for a timezone name + elif self._could_be_tzname(res.hour, res.tzname, res.tzoffset, l[i]): + res.tzname = l[i] + res.tzoffset = info.tzoffset(res.tzname) + + # Check for something like GMT+3, or BRST+3. Notice + # that it doesn't mean "I am 3 hours after GMT", but + # "my time +3 is GMT". If found, we reverse the + # logic so that timezone parsing code will get it + # right. + if i + 1 < len_l and l[i + 1] in ('+', '-'): + l[i + 1] = ('+', '-')[l[i + 1] == '+'] + res.tzoffset = None + if info.utczone(res.tzname): + # With something like GMT+3, the timezone + # is *not* GMT. + res.tzname = None + + # Check for a numbered timezone + elif res.hour is not None and l[i] in ('+', '-'): + signal = (-1, 1)[l[i] == '+'] + len_li = len(l[i + 1]) + + # TODO: check that l[i + 1] is integer? + if len_li == 4: + # -0300 + hour_offset = int(l[i + 1][:2]) + min_offset = int(l[i + 1][2:]) + elif i + 2 < len_l and l[i + 2] == ':': + # -03:00 + hour_offset = int(l[i + 1]) + min_offset = int(l[i + 3]) # TODO: Check that l[i+3] is minute-like? + i += 2 + elif len_li <= 2: + # -[0]3 + hour_offset = int(l[i + 1][:2]) + min_offset = 0 + else: + raise ValueError(timestr) + + res.tzoffset = signal * (hour_offset * 3600 + min_offset * 60) + + # Look for a timezone name between parenthesis + if (i + 5 < len_l and + info.jump(l[i + 2]) and l[i + 3] == '(' and + l[i + 5] == ')' and + 3 <= len(l[i + 4]) and + self._could_be_tzname(res.hour, res.tzname, + None, l[i + 4])): + # -0300 (BRST) + res.tzname = l[i + 4] + i += 4 + + i += 1 + + # Check jumps + elif not (info.jump(l[i]) or fuzzy): + raise ValueError(timestr) + + else: + skipped_idxs.append(i) + i += 1 + + # Process year/month/day + year, month, day = ymd.resolve_ymd(yearfirst, dayfirst) + + res.century_specified = ymd.century_specified + res.year = year + res.month = month + res.day = day + + except (IndexError, ValueError): + return None, None + + if not info.validate(res): + return None, None + + if fuzzy_with_tokens: + skipped_tokens = self._recombine_skipped(l, skipped_idxs) + return res, tuple(skipped_tokens) + else: + return res, None + + def _parse_numeric_token(self, tokens, idx, info, ymd, res, fuzzy): + # Token is a number + value_repr = tokens[idx] + try: + value = self._to_decimal(value_repr) + except Exception as e: + six.raise_from(ValueError('Unknown numeric token'), e) + + len_li = len(value_repr) + + len_l = len(tokens) + + if (len(ymd) == 3 and len_li in (2, 4) and + res.hour is None and + (idx + 1 >= len_l or + (tokens[idx + 1] != ':' and + info.hms(tokens[idx + 1]) is None))): + # 19990101T23[59] + s = tokens[idx] + res.hour = int(s[:2]) + + if len_li == 4: + res.minute = int(s[2:]) + + elif len_li == 6 or (len_li > 6 and tokens[idx].find('.') == 6): + # YYMMDD or HHMMSS[.ss] + s = tokens[idx] + + if not ymd and '.' not in tokens[idx]: + ymd.append(s[:2]) + ymd.append(s[2:4]) + ymd.append(s[4:]) + else: + # 19990101T235959[.59] + + # TODO: Check if res attributes already set. + res.hour = int(s[:2]) + res.minute = int(s[2:4]) + res.second, res.microsecond = self._parsems(s[4:]) + + elif len_li in (8, 12, 14): + # YYYYMMDD + s = tokens[idx] + ymd.append(s[:4], 'Y') + ymd.append(s[4:6]) + ymd.append(s[6:8]) + + if len_li > 8: + res.hour = int(s[8:10]) + res.minute = int(s[10:12]) + + if len_li > 12: + res.second = int(s[12:]) + + elif self._find_hms_idx(idx, tokens, info, allow_jump=True) is not None: + # HH[ ]h or MM[ ]m or SS[.ss][ ]s + hms_idx = self._find_hms_idx(idx, tokens, info, allow_jump=True) + (idx, hms) = self._parse_hms(idx, tokens, info, hms_idx) + if hms is not None: + # TODO: checking that hour/minute/second are not + # already set? + self._assign_hms(res, value_repr, hms) + + elif idx + 2 < len_l and tokens[idx + 1] == ':': + # HH:MM[:SS[.ss]] + res.hour = int(value) + value = self._to_decimal(tokens[idx + 2]) # TODO: try/except for this? + (res.minute, res.second) = self._parse_min_sec(value) + + if idx + 4 < len_l and tokens[idx + 3] == ':': + res.second, res.microsecond = self._parsems(tokens[idx + 4]) + + idx += 2 + + idx += 2 + + elif idx + 1 < len_l and tokens[idx + 1] in ('-', '/', '.'): + sep = tokens[idx + 1] + ymd.append(value_repr) + + if idx + 2 < len_l and not info.jump(tokens[idx + 2]): + if tokens[idx + 2].isdigit(): + # 01-01[-01] + ymd.append(tokens[idx + 2]) + else: + # 01-Jan[-01] + value = info.month(tokens[idx + 2]) + + if value is not None: + ymd.append(value, 'M') + else: + raise ValueError() + + if idx + 3 < len_l and tokens[idx + 3] == sep: + # We have three members + value = info.month(tokens[idx + 4]) + + if value is not None: + ymd.append(value, 'M') + else: + ymd.append(tokens[idx + 4]) + idx += 2 + + idx += 1 + idx += 1 + + elif idx + 1 >= len_l or info.jump(tokens[idx + 1]): + if idx + 2 < len_l and info.ampm(tokens[idx + 2]) is not None: + # 12 am + hour = int(value) + res.hour = self._adjust_ampm(hour, info.ampm(tokens[idx + 2])) + idx += 1 + else: + # Year, month or day + ymd.append(value) + idx += 1 + + elif info.ampm(tokens[idx + 1]) is not None and (0 <= value < 24): + # 12am + hour = int(value) + res.hour = self._adjust_ampm(hour, info.ampm(tokens[idx + 1])) + idx += 1 + + elif ymd.could_be_day(value): + ymd.append(value) + + elif not fuzzy: + raise ValueError() + + return idx + + def _find_hms_idx(self, idx, tokens, info, allow_jump): + len_l = len(tokens) + + if idx+1 < len_l and info.hms(tokens[idx+1]) is not None: + # There is an "h", "m", or "s" label following this token. We take + # assign the upcoming label to the current token. + # e.g. the "12" in 12h" + hms_idx = idx + 1 + + elif (allow_jump and idx+2 < len_l and tokens[idx+1] == ' ' and + info.hms(tokens[idx+2]) is not None): + # There is a space and then an "h", "m", or "s" label. + # e.g. the "12" in "12 h" + hms_idx = idx + 2 + + elif idx > 0 and info.hms(tokens[idx-1]) is not None: + # There is a "h", "m", or "s" preceding this token. Since neither + # of the previous cases was hit, there is no label following this + # token, so we use the previous label. + # e.g. the "04" in "12h04" + hms_idx = idx-1 + + elif (1 < idx == len_l-1 and tokens[idx-1] == ' ' and + info.hms(tokens[idx-2]) is not None): + # If we are looking at the final token, we allow for a + # backward-looking check to skip over a space. + # TODO: Are we sure this is the right condition here? + hms_idx = idx - 2 + + else: + hms_idx = None + + return hms_idx + + def _assign_hms(self, res, value_repr, hms): + # See GH issue #427, fixing float rounding + value = self._to_decimal(value_repr) + + if hms == 0: + # Hour + res.hour = int(value) + if value % 1: + res.minute = int(60*(value % 1)) + + elif hms == 1: + (res.minute, res.second) = self._parse_min_sec(value) + + elif hms == 2: + (res.second, res.microsecond) = self._parsems(value_repr) + + def _could_be_tzname(self, hour, tzname, tzoffset, token): + return (hour is not None and + tzname is None and + tzoffset is None and + len(token) <= 5 and + (all(x in string.ascii_uppercase for x in token) + or token in self.info.UTCZONE)) + + def _ampm_valid(self, hour, ampm, fuzzy): + """ + For fuzzy parsing, 'a' or 'am' (both valid English words) + may erroneously trigger the AM/PM flag. Deal with that + here. + """ + val_is_ampm = True + + # If there's already an AM/PM flag, this one isn't one. + if fuzzy and ampm is not None: + val_is_ampm = False + + # If AM/PM is found and hour is not, raise a ValueError + if hour is None: + if fuzzy: + val_is_ampm = False + else: + raise ValueError('No hour specified with AM or PM flag.') + elif not 0 <= hour <= 12: + # If AM/PM is found, it's a 12 hour clock, so raise + # an error for invalid range + if fuzzy: + val_is_ampm = False + else: + raise ValueError('Invalid hour specified for 12-hour clock.') + + return val_is_ampm + + def _adjust_ampm(self, hour, ampm): + if hour < 12 and ampm == 1: + hour += 12 + elif hour == 12 and ampm == 0: + hour = 0 + return hour + + def _parse_min_sec(self, value): + # TODO: Every usage of this function sets res.second to the return + # value. Are there any cases where second will be returned as None and + # we *don't* want to set res.second = None? + minute = int(value) + second = None + + sec_remainder = value % 1 + if sec_remainder: + second = int(60 * sec_remainder) + return (minute, second) + + def _parse_hms(self, idx, tokens, info, hms_idx): + # TODO: Is this going to admit a lot of false-positives for when we + # just happen to have digits and "h", "m" or "s" characters in non-date + # text? I guess hex hashes won't have that problem, but there's plenty + # of random junk out there. + if hms_idx is None: + hms = None + new_idx = idx + elif hms_idx > idx: + hms = info.hms(tokens[hms_idx]) + new_idx = hms_idx + else: + # Looking backwards, increment one. + hms = info.hms(tokens[hms_idx]) + 1 + new_idx = idx + + return (new_idx, hms) + + # ------------------------------------------------------------------ + # Handling for individual tokens. These are kept as methods instead + # of functions for the sake of customizability via subclassing. + + def _parsems(self, value): + """Parse a I[.F] seconds value into (seconds, microseconds).""" + if "." not in value: + return int(value), 0 + else: + i, f = value.split(".") + return int(i), int(f.ljust(6, "0")[:6]) + + def _to_decimal(self, val): + try: + decimal_value = Decimal(val) + # See GH 662, edge case, infinite value should not be converted + # via `_to_decimal` + if not decimal_value.is_finite(): + raise ValueError("Converted decimal value is infinite or NaN") + except Exception as e: + msg = "Could not convert %s to decimal" % val + six.raise_from(ValueError(msg), e) + else: + return decimal_value + + # ------------------------------------------------------------------ + # Post-Parsing construction of datetime output. These are kept as + # methods instead of functions for the sake of customizability via + # subclassing. + + def _build_tzinfo(self, tzinfos, tzname, tzoffset): + if callable(tzinfos): + tzdata = tzinfos(tzname, tzoffset) + else: + tzdata = tzinfos.get(tzname) + # handle case where tzinfo is paased an options that returns None + # eg tzinfos = {'BRST' : None} + if isinstance(tzdata, datetime.tzinfo) or tzdata is None: + tzinfo = tzdata + elif isinstance(tzdata, text_type): + tzinfo = tz.tzstr(tzdata) + elif isinstance(tzdata, integer_types): + tzinfo = tz.tzoffset(tzname, tzdata) + else: + raise TypeError("Offset must be tzinfo subclass, tz string, " + "or int offset.") + return tzinfo + + def _build_tzaware(self, naive, res, tzinfos): + if (callable(tzinfos) or (tzinfos and res.tzname in tzinfos)): + tzinfo = self._build_tzinfo(tzinfos, res.tzname, res.tzoffset) + aware = naive.replace(tzinfo=tzinfo) + aware = self._assign_tzname(aware, res.tzname) + + elif res.tzname and res.tzname in time.tzname: + aware = naive.replace(tzinfo=tz.tzlocal()) + + # Handle ambiguous local datetime + aware = self._assign_tzname(aware, res.tzname) + + # This is mostly relevant for winter GMT zones parsed in the UK + if (aware.tzname() != res.tzname and + res.tzname in self.info.UTCZONE): + aware = aware.replace(tzinfo=tz.UTC) + + elif res.tzoffset == 0: + aware = naive.replace(tzinfo=tz.UTC) + + elif res.tzoffset: + aware = naive.replace(tzinfo=tz.tzoffset(res.tzname, res.tzoffset)) + + elif not res.tzname and not res.tzoffset: + # i.e. no timezone information was found. + aware = naive + + elif res.tzname: + # tz-like string was parsed but we don't know what to do + # with it + warnings.warn("tzname {tzname} identified but not understood. " + "Pass `tzinfos` argument in order to correctly " + "return a timezone-aware datetime. In a future " + "version, this will raise an " + "exception.".format(tzname=res.tzname), + category=UnknownTimezoneWarning) + aware = naive + + return aware + + def _build_naive(self, res, default): + repl = {} + for attr in ("year", "month", "day", "hour", + "minute", "second", "microsecond"): + value = getattr(res, attr) + if value is not None: + repl[attr] = value + + if 'day' not in repl: + # If the default day exceeds the last day of the month, fall back + # to the end of the month. + cyear = default.year if res.year is None else res.year + cmonth = default.month if res.month is None else res.month + cday = default.day if res.day is None else res.day + + if cday > monthrange(cyear, cmonth)[1]: + repl['day'] = monthrange(cyear, cmonth)[1] + + naive = default.replace(**repl) + + if res.weekday is not None and not res.day: + naive = naive + relativedelta.relativedelta(weekday=res.weekday) + + return naive + + def _assign_tzname(self, dt, tzname): + if dt.tzname() != tzname: + new_dt = tz.enfold(dt, fold=1) + if new_dt.tzname() == tzname: + return new_dt + + return dt + + def _recombine_skipped(self, tokens, skipped_idxs): + """ + >>> tokens = ["foo", " ", "bar", " ", "19June2000", "baz"] + >>> skipped_idxs = [0, 1, 2, 5] + >>> _recombine_skipped(tokens, skipped_idxs) + ["foo bar", "baz"] + """ + skipped_tokens = [] + for i, idx in enumerate(sorted(skipped_idxs)): + if i > 0 and idx - 1 == skipped_idxs[i - 1]: + skipped_tokens[-1] = skipped_tokens[-1] + tokens[idx] + else: + skipped_tokens.append(tokens[idx]) + + return skipped_tokens + + +DEFAULTPARSER = parser() + + +def parse(timestr, parserinfo=None, **kwargs): + """ + + Parse a string in one of the supported formats, using the + ``parserinfo`` parameters. + + :param timestr: + A string containing a date/time stamp. + + :param parserinfo: + A :class:`parserinfo` object containing parameters for the parser. + If ``None``, the default arguments to the :class:`parserinfo` + constructor are used. + + The ``**kwargs`` parameter takes the following keyword arguments: + + :param default: + The default datetime object, if this is a datetime object and not + ``None``, elements specified in ``timestr`` replace elements in the + default object. + + :param ignoretz: + If set ``True``, time zones in parsed strings are ignored and a naive + :class:`datetime` object is returned. + + :param tzinfos: + Additional time zone names / aliases which may be present in the + string. This argument maps time zone names (and optionally offsets + from those time zones) to time zones. This parameter can be a + dictionary with timezone aliases mapping time zone names to time + zones or a function taking two parameters (``tzname`` and + ``tzoffset``) and returning a time zone. + + The timezones to which the names are mapped can be an integer + offset from UTC in seconds or a :class:`tzinfo` object. + + .. doctest:: + :options: +NORMALIZE_WHITESPACE + + >>> from dateutil.parser import parse + >>> from dateutil.tz import gettz + >>> tzinfos = {"BRST": -7200, "CST": gettz("America/Chicago")} + >>> parse("2012-01-19 17:21:00 BRST", tzinfos=tzinfos) + datetime.datetime(2012, 1, 19, 17, 21, tzinfo=tzoffset(u'BRST', -7200)) + >>> parse("2012-01-19 17:21:00 CST", tzinfos=tzinfos) + datetime.datetime(2012, 1, 19, 17, 21, + tzinfo=tzfile('/usr/share/zoneinfo/America/Chicago')) + + This parameter is ignored if ``ignoretz`` is set. + + :param dayfirst: + Whether to interpret the first value in an ambiguous 3-integer date + (e.g. 01/05/09) as the day (``True``) or month (``False``). If + ``yearfirst`` is set to ``True``, this distinguishes between YDM and + YMD. If set to ``None``, this value is retrieved from the current + :class:`parserinfo` object (which itself defaults to ``False``). + + :param yearfirst: + Whether to interpret the first value in an ambiguous 3-integer date + (e.g. 01/05/09) as the year. If ``True``, the first number is taken to + be the year, otherwise the last number is taken to be the year. If + this is set to ``None``, the value is retrieved from the current + :class:`parserinfo` object (which itself defaults to ``False``). + + :param fuzzy: + Whether to allow fuzzy parsing, allowing for string like "Today is + January 1, 2047 at 8:21:00AM". + + :param fuzzy_with_tokens: + If ``True``, ``fuzzy`` is automatically set to True, and the parser + will return a tuple where the first element is the parsed + :class:`datetime.datetime` datetimestamp and the second element is + a tuple containing the portions of the string which were ignored: + + .. doctest:: + + >>> from dateutil.parser import parse + >>> parse("Today is January 1, 2047 at 8:21:00AM", fuzzy_with_tokens=True) + (datetime.datetime(2047, 1, 1, 8, 21), (u'Today is ', u' ', u'at ')) + + :return: + Returns a :class:`datetime.datetime` object or, if the + ``fuzzy_with_tokens`` option is ``True``, returns a tuple, the + first element being a :class:`datetime.datetime` object, the second + a tuple containing the fuzzy tokens. + + :raises ParserError: + Raised for invalid or unknown string formats, if the provided + :class:`tzinfo` is not in a valid format, or if an invalid date would + be created. + + :raises OverflowError: + Raised if the parsed date exceeds the largest valid C integer on + your system. + """ + if parserinfo: + return parser(parserinfo).parse(timestr, **kwargs) + else: + return DEFAULTPARSER.parse(timestr, **kwargs) + + +class _tzparser(object): + + class _result(_resultbase): + + __slots__ = ["stdabbr", "stdoffset", "dstabbr", "dstoffset", + "start", "end"] + + class _attr(_resultbase): + __slots__ = ["month", "week", "weekday", + "yday", "jyday", "day", "time"] + + def __repr__(self): + return self._repr("") + + def __init__(self): + _resultbase.__init__(self) + self.start = self._attr() + self.end = self._attr() + + def parse(self, tzstr): + res = self._result() + l = [x for x in re.split(r'([,:.]|[a-zA-Z]+|[0-9]+)',tzstr) if x] + used_idxs = list() + try: + + len_l = len(l) + + i = 0 + while i < len_l: + # BRST+3[BRDT[+2]] + j = i + while j < len_l and not [x for x in l[j] + if x in "0123456789:,-+"]: + j += 1 + if j != i: + if not res.stdabbr: + offattr = "stdoffset" + res.stdabbr = "".join(l[i:j]) + else: + offattr = "dstoffset" + res.dstabbr = "".join(l[i:j]) + + for ii in range(j): + used_idxs.append(ii) + i = j + if (i < len_l and (l[i] in ('+', '-') or l[i][0] in + "0123456789")): + if l[i] in ('+', '-'): + # Yes, that's right. See the TZ variable + # documentation. + signal = (1, -1)[l[i] == '+'] + used_idxs.append(i) + i += 1 + else: + signal = -1 + len_li = len(l[i]) + if len_li == 4: + # -0300 + setattr(res, offattr, (int(l[i][:2]) * 3600 + + int(l[i][2:]) * 60) * signal) + elif i + 1 < len_l and l[i + 1] == ':': + # -03:00 + setattr(res, offattr, + (int(l[i]) * 3600 + + int(l[i + 2]) * 60) * signal) + used_idxs.append(i) + i += 2 + elif len_li <= 2: + # -[0]3 + setattr(res, offattr, + int(l[i][:2]) * 3600 * signal) + else: + return None + used_idxs.append(i) + i += 1 + if res.dstabbr: + break + else: + break + + + if i < len_l: + for j in range(i, len_l): + if l[j] == ';': + l[j] = ',' + + assert l[i] == ',' + + i += 1 + + if i >= len_l: + pass + elif (8 <= l.count(',') <= 9 and + not [y for x in l[i:] if x != ',' + for y in x if y not in "0123456789+-"]): + # GMT0BST,3,0,30,3600,10,0,26,7200[,3600] + for x in (res.start, res.end): + x.month = int(l[i]) + used_idxs.append(i) + i += 2 + if l[i] == '-': + value = int(l[i + 1]) * -1 + used_idxs.append(i) + i += 1 + else: + value = int(l[i]) + used_idxs.append(i) + i += 2 + if value: + x.week = value + x.weekday = (int(l[i]) - 1) % 7 + else: + x.day = int(l[i]) + used_idxs.append(i) + i += 2 + x.time = int(l[i]) + used_idxs.append(i) + i += 2 + if i < len_l: + if l[i] in ('-', '+'): + signal = (-1, 1)[l[i] == "+"] + used_idxs.append(i) + i += 1 + else: + signal = 1 + used_idxs.append(i) + res.dstoffset = (res.stdoffset + int(l[i]) * signal) + + # This was a made-up format that is not in normal use + warn(('Parsed time zone "%s"' % tzstr) + + 'is in a non-standard dateutil-specific format, which ' + + 'is now deprecated; support for parsing this format ' + + 'will be removed in future versions. It is recommended ' + + 'that you switch to a standard format like the GNU ' + + 'TZ variable format.', tz.DeprecatedTzFormatWarning) + elif (l.count(',') == 2 and l[i:].count('/') <= 2 and + not [y for x in l[i:] if x not in (',', '/', 'J', 'M', + '.', '-', ':') + for y in x if y not in "0123456789"]): + for x in (res.start, res.end): + if l[i] == 'J': + # non-leap year day (1 based) + used_idxs.append(i) + i += 1 + x.jyday = int(l[i]) + elif l[i] == 'M': + # month[-.]week[-.]weekday + used_idxs.append(i) + i += 1 + x.month = int(l[i]) + used_idxs.append(i) + i += 1 + assert l[i] in ('-', '.') + used_idxs.append(i) + i += 1 + x.week = int(l[i]) + if x.week == 5: + x.week = -1 + used_idxs.append(i) + i += 1 + assert l[i] in ('-', '.') + used_idxs.append(i) + i += 1 + x.weekday = (int(l[i]) - 1) % 7 + else: + # year day (zero based) + x.yday = int(l[i]) + 1 + + used_idxs.append(i) + i += 1 + + if i < len_l and l[i] == '/': + used_idxs.append(i) + i += 1 + # start time + len_li = len(l[i]) + if len_li == 4: + # -0300 + x.time = (int(l[i][:2]) * 3600 + + int(l[i][2:]) * 60) + elif i + 1 < len_l and l[i + 1] == ':': + # -03:00 + x.time = int(l[i]) * 3600 + int(l[i + 2]) * 60 + used_idxs.append(i) + i += 2 + if i + 1 < len_l and l[i + 1] == ':': + used_idxs.append(i) + i += 2 + x.time += int(l[i]) + elif len_li <= 2: + # -[0]3 + x.time = (int(l[i][:2]) * 3600) + else: + return None + used_idxs.append(i) + i += 1 + + assert i == len_l or l[i] == ',' + + i += 1 + + assert i >= len_l + + except (IndexError, ValueError, AssertionError): + return None + + unused_idxs = set(range(len_l)).difference(used_idxs) + res.any_unused_tokens = not {l[n] for n in unused_idxs}.issubset({",",":"}) + return res + + +DEFAULTTZPARSER = _tzparser() + + +def _parsetz(tzstr): + return DEFAULTTZPARSER.parse(tzstr) + + +class ParserError(ValueError): + """Exception subclass used for any failure to parse a datetime string. + + This is a subclass of :py:exc:`ValueError`, and should be raised any time + earlier versions of ``dateutil`` would have raised ``ValueError``. + + .. versionadded:: 2.8.1 + """ + def __str__(self): + try: + return self.args[0] % self.args[1:] + except (TypeError, IndexError): + return super(ParserError, self).__str__() + + def __repr__(self): + args = ", ".join("'%s'" % arg for arg in self.args) + return "%s(%s)" % (self.__class__.__name__, args) + + +class UnknownTimezoneWarning(RuntimeWarning): + """Raised when the parser finds a timezone it cannot parse into a tzinfo. + + .. versionadded:: 2.7.0 + """ +# vim:ts=4:sw=4:et diff --git a/python/user_packages/Python313/site-packages/dateutil/parser/isoparser.py b/python/user_packages/Python313/site-packages/dateutil/parser/isoparser.py new file mode 100644 index 0000000000000000000000000000000000000000..7060087df4776a07347cbb60127a70db393e3a65 --- /dev/null +++ b/python/user_packages/Python313/site-packages/dateutil/parser/isoparser.py @@ -0,0 +1,416 @@ +# -*- coding: utf-8 -*- +""" +This module offers a parser for ISO-8601 strings + +It is intended to support all valid date, time and datetime formats per the +ISO-8601 specification. + +..versionadded:: 2.7.0 +""" +from datetime import datetime, timedelta, time, date +import calendar +from dateutil import tz + +from functools import wraps + +import re +import six + +__all__ = ["isoparse", "isoparser"] + + +def _takes_ascii(f): + @wraps(f) + def func(self, str_in, *args, **kwargs): + # If it's a stream, read the whole thing + str_in = getattr(str_in, 'read', lambda: str_in)() + + # If it's unicode, turn it into bytes, since ISO-8601 only covers ASCII + if isinstance(str_in, six.text_type): + # ASCII is the same in UTF-8 + try: + str_in = str_in.encode('ascii') + except UnicodeEncodeError as e: + msg = 'ISO-8601 strings should contain only ASCII characters' + six.raise_from(ValueError(msg), e) + + return f(self, str_in, *args, **kwargs) + + return func + + +class isoparser(object): + def __init__(self, sep=None): + """ + :param sep: + A single character that separates date and time portions. If + ``None``, the parser will accept any single character. + For strict ISO-8601 adherence, pass ``'T'``. + """ + if sep is not None: + if (len(sep) != 1 or ord(sep) >= 128 or sep in '0123456789'): + raise ValueError('Separator must be a single, non-numeric ' + + 'ASCII character') + + sep = sep.encode('ascii') + + self._sep = sep + + @_takes_ascii + def isoparse(self, dt_str): + """ + Parse an ISO-8601 datetime string into a :class:`datetime.datetime`. + + An ISO-8601 datetime string consists of a date portion, followed + optionally by a time portion - the date and time portions are separated + by a single character separator, which is ``T`` in the official + standard. Incomplete date formats (such as ``YYYY-MM``) may *not* be + combined with a time portion. + + Supported date formats are: + + Common: + + - ``YYYY`` + - ``YYYY-MM`` + - ``YYYY-MM-DD`` or ``YYYYMMDD`` + + Uncommon: + + - ``YYYY-Www`` or ``YYYYWww`` - ISO week (day defaults to 0) + - ``YYYY-Www-D`` or ``YYYYWwwD`` - ISO week and day + + The ISO week and day numbering follows the same logic as + :func:`datetime.date.isocalendar`. + + Supported time formats are: + + - ``hh`` + - ``hh:mm`` or ``hhmm`` + - ``hh:mm:ss`` or ``hhmmss`` + - ``hh:mm:ss.ssssss`` (Up to 6 sub-second digits) + + Midnight is a special case for `hh`, as the standard supports both + 00:00 and 24:00 as a representation. The decimal separator can be + either a dot or a comma. + + + .. caution:: + + Support for fractional components other than seconds is part of the + ISO-8601 standard, but is not currently implemented in this parser. + + Supported time zone offset formats are: + + - `Z` (UTC) + - `±HH:MM` + - `±HHMM` + - `±HH` + + Offsets will be represented as :class:`dateutil.tz.tzoffset` objects, + with the exception of UTC, which will be represented as + :class:`dateutil.tz.tzutc`. Time zone offsets equivalent to UTC (such + as `+00:00`) will also be represented as :class:`dateutil.tz.tzutc`. + + :param dt_str: + A string or stream containing only an ISO-8601 datetime string + + :return: + Returns a :class:`datetime.datetime` representing the string. + Unspecified components default to their lowest value. + + .. warning:: + + As of version 2.7.0, the strictness of the parser should not be + considered a stable part of the contract. Any valid ISO-8601 string + that parses correctly with the default settings will continue to + parse correctly in future versions, but invalid strings that + currently fail (e.g. ``2017-01-01T00:00+00:00:00``) are not + guaranteed to continue failing in future versions if they encode + a valid date. + + .. versionadded:: 2.7.0 + """ + components, pos = self._parse_isodate(dt_str) + + if len(dt_str) > pos: + if self._sep is None or dt_str[pos:pos + 1] == self._sep: + components += self._parse_isotime(dt_str[pos + 1:]) + else: + raise ValueError('String contains unknown ISO components') + + if len(components) > 3 and components[3] == 24: + components[3] = 0 + return datetime(*components) + timedelta(days=1) + + return datetime(*components) + + @_takes_ascii + def parse_isodate(self, datestr): + """ + Parse the date portion of an ISO string. + + :param datestr: + The string portion of an ISO string, without a separator + + :return: + Returns a :class:`datetime.date` object + """ + components, pos = self._parse_isodate(datestr) + if pos < len(datestr): + raise ValueError('String contains unknown ISO ' + + 'components: {!r}'.format(datestr.decode('ascii'))) + return date(*components) + + @_takes_ascii + def parse_isotime(self, timestr): + """ + Parse the time portion of an ISO string. + + :param timestr: + The time portion of an ISO string, without a separator + + :return: + Returns a :class:`datetime.time` object + """ + components = self._parse_isotime(timestr) + if components[0] == 24: + components[0] = 0 + return time(*components) + + @_takes_ascii + def parse_tzstr(self, tzstr, zero_as_utc=True): + """ + Parse a valid ISO time zone string. + + See :func:`isoparser.isoparse` for details on supported formats. + + :param tzstr: + A string representing an ISO time zone offset + + :param zero_as_utc: + Whether to return :class:`dateutil.tz.tzutc` for zero-offset zones + + :return: + Returns :class:`dateutil.tz.tzoffset` for offsets and + :class:`dateutil.tz.tzutc` for ``Z`` and (if ``zero_as_utc`` is + specified) offsets equivalent to UTC. + """ + return self._parse_tzstr(tzstr, zero_as_utc=zero_as_utc) + + # Constants + _DATE_SEP = b'-' + _TIME_SEP = b':' + _FRACTION_REGEX = re.compile(b'[\\.,]([0-9]+)') + + def _parse_isodate(self, dt_str): + try: + return self._parse_isodate_common(dt_str) + except ValueError: + return self._parse_isodate_uncommon(dt_str) + + def _parse_isodate_common(self, dt_str): + len_str = len(dt_str) + components = [1, 1, 1] + + if len_str < 4: + raise ValueError('ISO string too short') + + # Year + components[0] = int(dt_str[0:4]) + pos = 4 + if pos >= len_str: + return components, pos + + has_sep = dt_str[pos:pos + 1] == self._DATE_SEP + if has_sep: + pos += 1 + + # Month + if len_str - pos < 2: + raise ValueError('Invalid common month') + + components[1] = int(dt_str[pos:pos + 2]) + pos += 2 + + if pos >= len_str: + if has_sep: + return components, pos + else: + raise ValueError('Invalid ISO format') + + if has_sep: + if dt_str[pos:pos + 1] != self._DATE_SEP: + raise ValueError('Invalid separator in ISO string') + pos += 1 + + # Day + if len_str - pos < 2: + raise ValueError('Invalid common day') + components[2] = int(dt_str[pos:pos + 2]) + return components, pos + 2 + + def _parse_isodate_uncommon(self, dt_str): + if len(dt_str) < 4: + raise ValueError('ISO string too short') + + # All ISO formats start with the year + year = int(dt_str[0:4]) + + has_sep = dt_str[4:5] == self._DATE_SEP + + pos = 4 + has_sep # Skip '-' if it's there + if dt_str[pos:pos + 1] == b'W': + # YYYY-?Www-?D? + pos += 1 + weekno = int(dt_str[pos:pos + 2]) + pos += 2 + + dayno = 1 + if len(dt_str) > pos: + if (dt_str[pos:pos + 1] == self._DATE_SEP) != has_sep: + raise ValueError('Inconsistent use of dash separator') + + pos += has_sep + + dayno = int(dt_str[pos:pos + 1]) + pos += 1 + + base_date = self._calculate_weekdate(year, weekno, dayno) + else: + # YYYYDDD or YYYY-DDD + if len(dt_str) - pos < 3: + raise ValueError('Invalid ordinal day') + + ordinal_day = int(dt_str[pos:pos + 3]) + pos += 3 + + if ordinal_day < 1 or ordinal_day > (365 + calendar.isleap(year)): + raise ValueError('Invalid ordinal day' + + ' {} for year {}'.format(ordinal_day, year)) + + base_date = date(year, 1, 1) + timedelta(days=ordinal_day - 1) + + components = [base_date.year, base_date.month, base_date.day] + return components, pos + + def _calculate_weekdate(self, year, week, day): + """ + Calculate the day of corresponding to the ISO year-week-day calendar. + + This function is effectively the inverse of + :func:`datetime.date.isocalendar`. + + :param year: + The year in the ISO calendar + + :param week: + The week in the ISO calendar - range is [1, 53] + + :param day: + The day in the ISO calendar - range is [1 (MON), 7 (SUN)] + + :return: + Returns a :class:`datetime.date` + """ + if not 0 < week < 54: + raise ValueError('Invalid week: {}'.format(week)) + + if not 0 < day < 8: # Range is 1-7 + raise ValueError('Invalid weekday: {}'.format(day)) + + # Get week 1 for the specific year: + jan_4 = date(year, 1, 4) # Week 1 always has January 4th in it + week_1 = jan_4 - timedelta(days=jan_4.isocalendar()[2] - 1) + + # Now add the specific number of weeks and days to get what we want + week_offset = (week - 1) * 7 + (day - 1) + return week_1 + timedelta(days=week_offset) + + def _parse_isotime(self, timestr): + len_str = len(timestr) + components = [0, 0, 0, 0, None] + pos = 0 + comp = -1 + + if len_str < 2: + raise ValueError('ISO time too short') + + has_sep = False + + while pos < len_str and comp < 5: + comp += 1 + + if timestr[pos:pos + 1] in b'-+Zz': + # Detect time zone boundary + components[-1] = self._parse_tzstr(timestr[pos:]) + pos = len_str + break + + if comp == 1 and timestr[pos:pos+1] == self._TIME_SEP: + has_sep = True + pos += 1 + elif comp == 2 and has_sep: + if timestr[pos:pos+1] != self._TIME_SEP: + raise ValueError('Inconsistent use of colon separator') + pos += 1 + + if comp < 3: + # Hour, minute, second + components[comp] = int(timestr[pos:pos + 2]) + pos += 2 + + if comp == 3: + # Fraction of a second + frac = self._FRACTION_REGEX.match(timestr[pos:]) + if not frac: + continue + + us_str = frac.group(1)[:6] # Truncate to microseconds + components[comp] = int(us_str) * 10**(6 - len(us_str)) + pos += len(frac.group()) + + if pos < len_str: + raise ValueError('Unused components in ISO string') + + if components[0] == 24: + # Standard supports 00:00 and 24:00 as representations of midnight + if any(component != 0 for component in components[1:4]): + raise ValueError('Hour may only be 24 at 24:00:00.000') + + return components + + def _parse_tzstr(self, tzstr, zero_as_utc=True): + if tzstr == b'Z' or tzstr == b'z': + return tz.UTC + + if len(tzstr) not in {3, 5, 6}: + raise ValueError('Time zone offset must be 1, 3, 5 or 6 characters') + + if tzstr[0:1] == b'-': + mult = -1 + elif tzstr[0:1] == b'+': + mult = 1 + else: + raise ValueError('Time zone offset requires sign') + + hours = int(tzstr[1:3]) + if len(tzstr) == 3: + minutes = 0 + else: + minutes = int(tzstr[(4 if tzstr[3:4] == self._TIME_SEP else 3):]) + + if zero_as_utc and hours == 0 and minutes == 0: + return tz.UTC + else: + if minutes > 59: + raise ValueError('Invalid minutes in time zone offset') + + if hours > 23: + raise ValueError('Invalid hours in time zone offset') + + return tz.tzoffset(None, mult * (hours * 60 + minutes) * 60) + + +DEFAULT_ISOPARSER = isoparser() +isoparse = DEFAULT_ISOPARSER.isoparse diff --git a/python/user_packages/Python313/site-packages/dateutil/tz/__init__.py b/python/user_packages/Python313/site-packages/dateutil/tz/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..af1352c47292f4eebc5cae8da45641b5544558e3 --- /dev/null +++ b/python/user_packages/Python313/site-packages/dateutil/tz/__init__.py @@ -0,0 +1,12 @@ +# -*- coding: utf-8 -*- +from .tz import * +from .tz import __doc__ + +__all__ = ["tzutc", "tzoffset", "tzlocal", "tzfile", "tzrange", + "tzstr", "tzical", "tzwin", "tzwinlocal", "gettz", + "enfold", "datetime_ambiguous", "datetime_exists", + "resolve_imaginary", "UTC", "DeprecatedTzFormatWarning"] + + +class DeprecatedTzFormatWarning(Warning): + """Warning raised when time zones are parsed from deprecated formats.""" diff --git a/python/user_packages/Python313/site-packages/dateutil/tz/__pycache__/__init__.cpython-313.pyc b/python/user_packages/Python313/site-packages/dateutil/tz/__pycache__/__init__.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d1bf2dde4f2cc740bdb1f124f85a29b315de3a29 Binary files /dev/null and b/python/user_packages/Python313/site-packages/dateutil/tz/__pycache__/__init__.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/dateutil/tz/__pycache__/_common.cpython-313.pyc b/python/user_packages/Python313/site-packages/dateutil/tz/__pycache__/_common.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..72704c85f05924f942499a3c23d890b06dc9454e Binary files /dev/null and b/python/user_packages/Python313/site-packages/dateutil/tz/__pycache__/_common.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/dateutil/tz/__pycache__/_factories.cpython-313.pyc b/python/user_packages/Python313/site-packages/dateutil/tz/__pycache__/_factories.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..140a3e52723dda520d951392f9f1395c10662bca Binary files /dev/null and b/python/user_packages/Python313/site-packages/dateutil/tz/__pycache__/_factories.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/dateutil/tz/__pycache__/tz.cpython-313.pyc b/python/user_packages/Python313/site-packages/dateutil/tz/__pycache__/tz.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7b4bbe8cbfa620e93cc3d228f9325bc23d7696a0 Binary files /dev/null and b/python/user_packages/Python313/site-packages/dateutil/tz/__pycache__/tz.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/dateutil/tz/__pycache__/win.cpython-313.pyc b/python/user_packages/Python313/site-packages/dateutil/tz/__pycache__/win.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6de0edeba6c2c06e5acd4f4fde1e6eba2f703928 Binary files /dev/null and b/python/user_packages/Python313/site-packages/dateutil/tz/__pycache__/win.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/dateutil/tz/_common.py b/python/user_packages/Python313/site-packages/dateutil/tz/_common.py new file mode 100644 index 0000000000000000000000000000000000000000..e6ac11831522b266114d5b68ee1da298e3aeb14a --- /dev/null +++ b/python/user_packages/Python313/site-packages/dateutil/tz/_common.py @@ -0,0 +1,419 @@ +from six import PY2 + +from functools import wraps + +from datetime import datetime, timedelta, tzinfo + + +ZERO = timedelta(0) + +__all__ = ['tzname_in_python2', 'enfold'] + + +def tzname_in_python2(namefunc): + """Change unicode output into bytestrings in Python 2 + + tzname() API changed in Python 3. It used to return bytes, but was changed + to unicode strings + """ + if PY2: + @wraps(namefunc) + def adjust_encoding(*args, **kwargs): + name = namefunc(*args, **kwargs) + if name is not None: + name = name.encode() + + return name + + return adjust_encoding + else: + return namefunc + + +# The following is adapted from Alexander Belopolsky's tz library +# https://github.com/abalkin/tz +if hasattr(datetime, 'fold'): + # This is the pre-python 3.6 fold situation + def enfold(dt, fold=1): + """ + Provides a unified interface for assigning the ``fold`` attribute to + datetimes both before and after the implementation of PEP-495. + + :param fold: + The value for the ``fold`` attribute in the returned datetime. This + should be either 0 or 1. + + :return: + Returns an object for which ``getattr(dt, 'fold', 0)`` returns + ``fold`` for all versions of Python. In versions prior to + Python 3.6, this is a ``_DatetimeWithFold`` object, which is a + subclass of :py:class:`datetime.datetime` with the ``fold`` + attribute added, if ``fold`` is 1. + + .. versionadded:: 2.6.0 + """ + return dt.replace(fold=fold) + +else: + class _DatetimeWithFold(datetime): + """ + This is a class designed to provide a PEP 495-compliant interface for + Python versions before 3.6. It is used only for dates in a fold, so + the ``fold`` attribute is fixed at ``1``. + + .. versionadded:: 2.6.0 + """ + __slots__ = () + + def replace(self, *args, **kwargs): + """ + Return a datetime with the same attributes, except for those + attributes given new values by whichever keyword arguments are + specified. Note that tzinfo=None can be specified to create a naive + datetime from an aware datetime with no conversion of date and time + data. + + This is reimplemented in ``_DatetimeWithFold`` because pypy3 will + return a ``datetime.datetime`` even if ``fold`` is unchanged. + """ + argnames = ( + 'year', 'month', 'day', 'hour', 'minute', 'second', + 'microsecond', 'tzinfo' + ) + + for arg, argname in zip(args, argnames): + if argname in kwargs: + raise TypeError('Duplicate argument: {}'.format(argname)) + + kwargs[argname] = arg + + for argname in argnames: + if argname not in kwargs: + kwargs[argname] = getattr(self, argname) + + dt_class = self.__class__ if kwargs.get('fold', 1) else datetime + + return dt_class(**kwargs) + + @property + def fold(self): + return 1 + + def enfold(dt, fold=1): + """ + Provides a unified interface for assigning the ``fold`` attribute to + datetimes both before and after the implementation of PEP-495. + + :param fold: + The value for the ``fold`` attribute in the returned datetime. This + should be either 0 or 1. + + :return: + Returns an object for which ``getattr(dt, 'fold', 0)`` returns + ``fold`` for all versions of Python. In versions prior to + Python 3.6, this is a ``_DatetimeWithFold`` object, which is a + subclass of :py:class:`datetime.datetime` with the ``fold`` + attribute added, if ``fold`` is 1. + + .. versionadded:: 2.6.0 + """ + if getattr(dt, 'fold', 0) == fold: + return dt + + args = dt.timetuple()[:6] + args += (dt.microsecond, dt.tzinfo) + + if fold: + return _DatetimeWithFold(*args) + else: + return datetime(*args) + + +def _validate_fromutc_inputs(f): + """ + The CPython version of ``fromutc`` checks that the input is a ``datetime`` + object and that ``self`` is attached as its ``tzinfo``. + """ + @wraps(f) + def fromutc(self, dt): + if not isinstance(dt, datetime): + raise TypeError("fromutc() requires a datetime argument") + if dt.tzinfo is not self: + raise ValueError("dt.tzinfo is not self") + + return f(self, dt) + + return fromutc + + +class _tzinfo(tzinfo): + """ + Base class for all ``dateutil`` ``tzinfo`` objects. + """ + + def is_ambiguous(self, dt): + """ + Whether or not the "wall time" of a given datetime is ambiguous in this + zone. + + :param dt: + A :py:class:`datetime.datetime`, naive or time zone aware. + + + :return: + Returns ``True`` if ambiguous, ``False`` otherwise. + + .. versionadded:: 2.6.0 + """ + + dt = dt.replace(tzinfo=self) + + wall_0 = enfold(dt, fold=0) + wall_1 = enfold(dt, fold=1) + + same_offset = wall_0.utcoffset() == wall_1.utcoffset() + same_dt = wall_0.replace(tzinfo=None) == wall_1.replace(tzinfo=None) + + return same_dt and not same_offset + + def _fold_status(self, dt_utc, dt_wall): + """ + Determine the fold status of a "wall" datetime, given a representation + of the same datetime as a (naive) UTC datetime. This is calculated based + on the assumption that ``dt.utcoffset() - dt.dst()`` is constant for all + datetimes, and that this offset is the actual number of hours separating + ``dt_utc`` and ``dt_wall``. + + :param dt_utc: + Representation of the datetime as UTC + + :param dt_wall: + Representation of the datetime as "wall time". This parameter must + either have a `fold` attribute or have a fold-naive + :class:`datetime.tzinfo` attached, otherwise the calculation may + fail. + """ + if self.is_ambiguous(dt_wall): + delta_wall = dt_wall - dt_utc + _fold = int(delta_wall == (dt_utc.utcoffset() - dt_utc.dst())) + else: + _fold = 0 + + return _fold + + def _fold(self, dt): + return getattr(dt, 'fold', 0) + + def _fromutc(self, dt): + """ + Given a timezone-aware datetime in a given timezone, calculates a + timezone-aware datetime in a new timezone. + + Since this is the one time that we *know* we have an unambiguous + datetime object, we take this opportunity to determine whether the + datetime is ambiguous and in a "fold" state (e.g. if it's the first + occurrence, chronologically, of the ambiguous datetime). + + :param dt: + A timezone-aware :class:`datetime.datetime` object. + """ + + # Re-implement the algorithm from Python's datetime.py + dtoff = dt.utcoffset() + if dtoff is None: + raise ValueError("fromutc() requires a non-None utcoffset() " + "result") + + # The original datetime.py code assumes that `dst()` defaults to + # zero during ambiguous times. PEP 495 inverts this presumption, so + # for pre-PEP 495 versions of python, we need to tweak the algorithm. + dtdst = dt.dst() + if dtdst is None: + raise ValueError("fromutc() requires a non-None dst() result") + delta = dtoff - dtdst + + dt += delta + # Set fold=1 so we can default to being in the fold for + # ambiguous dates. + dtdst = enfold(dt, fold=1).dst() + if dtdst is None: + raise ValueError("fromutc(): dt.dst gave inconsistent " + "results; cannot convert") + return dt + dtdst + + @_validate_fromutc_inputs + def fromutc(self, dt): + """ + Given a timezone-aware datetime in a given timezone, calculates a + timezone-aware datetime in a new timezone. + + Since this is the one time that we *know* we have an unambiguous + datetime object, we take this opportunity to determine whether the + datetime is ambiguous and in a "fold" state (e.g. if it's the first + occurrence, chronologically, of the ambiguous datetime). + + :param dt: + A timezone-aware :class:`datetime.datetime` object. + """ + dt_wall = self._fromutc(dt) + + # Calculate the fold status given the two datetimes. + _fold = self._fold_status(dt, dt_wall) + + # Set the default fold value for ambiguous dates + return enfold(dt_wall, fold=_fold) + + +class tzrangebase(_tzinfo): + """ + This is an abstract base class for time zones represented by an annual + transition into and out of DST. Child classes should implement the following + methods: + + * ``__init__(self, *args, **kwargs)`` + * ``transitions(self, year)`` - this is expected to return a tuple of + datetimes representing the DST on and off transitions in standard + time. + + A fully initialized ``tzrangebase`` subclass should also provide the + following attributes: + * ``hasdst``: Boolean whether or not the zone uses DST. + * ``_dst_offset`` / ``_std_offset``: :class:`datetime.timedelta` objects + representing the respective UTC offsets. + * ``_dst_abbr`` / ``_std_abbr``: Strings representing the timezone short + abbreviations in DST and STD, respectively. + * ``_hasdst``: Whether or not the zone has DST. + + .. versionadded:: 2.6.0 + """ + def __init__(self): + raise NotImplementedError('tzrangebase is an abstract base class') + + def utcoffset(self, dt): + isdst = self._isdst(dt) + + if isdst is None: + return None + elif isdst: + return self._dst_offset + else: + return self._std_offset + + def dst(self, dt): + isdst = self._isdst(dt) + + if isdst is None: + return None + elif isdst: + return self._dst_base_offset + else: + return ZERO + + @tzname_in_python2 + def tzname(self, dt): + if self._isdst(dt): + return self._dst_abbr + else: + return self._std_abbr + + def fromutc(self, dt): + """ Given a datetime in UTC, return local time """ + if not isinstance(dt, datetime): + raise TypeError("fromutc() requires a datetime argument") + + if dt.tzinfo is not self: + raise ValueError("dt.tzinfo is not self") + + # Get transitions - if there are none, fixed offset + transitions = self.transitions(dt.year) + if transitions is None: + return dt + self.utcoffset(dt) + + # Get the transition times in UTC + dston, dstoff = transitions + + dston -= self._std_offset + dstoff -= self._std_offset + + utc_transitions = (dston, dstoff) + dt_utc = dt.replace(tzinfo=None) + + isdst = self._naive_isdst(dt_utc, utc_transitions) + + if isdst: + dt_wall = dt + self._dst_offset + else: + dt_wall = dt + self._std_offset + + _fold = int(not isdst and self.is_ambiguous(dt_wall)) + + return enfold(dt_wall, fold=_fold) + + def is_ambiguous(self, dt): + """ + Whether or not the "wall time" of a given datetime is ambiguous in this + zone. + + :param dt: + A :py:class:`datetime.datetime`, naive or time zone aware. + + + :return: + Returns ``True`` if ambiguous, ``False`` otherwise. + + .. versionadded:: 2.6.0 + """ + if not self.hasdst: + return False + + start, end = self.transitions(dt.year) + + dt = dt.replace(tzinfo=None) + return (end <= dt < end + self._dst_base_offset) + + def _isdst(self, dt): + if not self.hasdst: + return False + elif dt is None: + return None + + transitions = self.transitions(dt.year) + + if transitions is None: + return False + + dt = dt.replace(tzinfo=None) + + isdst = self._naive_isdst(dt, transitions) + + # Handle ambiguous dates + if not isdst and self.is_ambiguous(dt): + return not self._fold(dt) + else: + return isdst + + def _naive_isdst(self, dt, transitions): + dston, dstoff = transitions + + dt = dt.replace(tzinfo=None) + + if dston < dstoff: + isdst = dston <= dt < dstoff + else: + isdst = not dstoff <= dt < dston + + return isdst + + @property + def _dst_base_offset(self): + return self._dst_offset - self._std_offset + + __hash__ = None + + def __ne__(self, other): + return not (self == other) + + def __repr__(self): + return "%s(...)" % self.__class__.__name__ + + __reduce__ = object.__reduce__ diff --git a/python/user_packages/Python313/site-packages/dateutil/tz/_factories.py b/python/user_packages/Python313/site-packages/dateutil/tz/_factories.py new file mode 100644 index 0000000000000000000000000000000000000000..f8a65891a023ebf9eb0c24d391ba67541b7133f1 --- /dev/null +++ b/python/user_packages/Python313/site-packages/dateutil/tz/_factories.py @@ -0,0 +1,80 @@ +from datetime import timedelta +import weakref +from collections import OrderedDict + +from six.moves import _thread + + +class _TzSingleton(type): + def __init__(cls, *args, **kwargs): + cls.__instance = None + super(_TzSingleton, cls).__init__(*args, **kwargs) + + def __call__(cls): + if cls.__instance is None: + cls.__instance = super(_TzSingleton, cls).__call__() + return cls.__instance + + +class _TzFactory(type): + def instance(cls, *args, **kwargs): + """Alternate constructor that returns a fresh instance""" + return type.__call__(cls, *args, **kwargs) + + +class _TzOffsetFactory(_TzFactory): + def __init__(cls, *args, **kwargs): + cls.__instances = weakref.WeakValueDictionary() + cls.__strong_cache = OrderedDict() + cls.__strong_cache_size = 8 + + cls._cache_lock = _thread.allocate_lock() + + def __call__(cls, name, offset): + if isinstance(offset, timedelta): + key = (name, offset.total_seconds()) + else: + key = (name, offset) + + instance = cls.__instances.get(key, None) + if instance is None: + instance = cls.__instances.setdefault(key, + cls.instance(name, offset)) + + # This lock may not be necessary in Python 3. See GH issue #901 + with cls._cache_lock: + cls.__strong_cache[key] = cls.__strong_cache.pop(key, instance) + + # Remove an item if the strong cache is overpopulated + if len(cls.__strong_cache) > cls.__strong_cache_size: + cls.__strong_cache.popitem(last=False) + + return instance + + +class _TzStrFactory(_TzFactory): + def __init__(cls, *args, **kwargs): + cls.__instances = weakref.WeakValueDictionary() + cls.__strong_cache = OrderedDict() + cls.__strong_cache_size = 8 + + cls.__cache_lock = _thread.allocate_lock() + + def __call__(cls, s, posix_offset=False): + key = (s, posix_offset) + instance = cls.__instances.get(key, None) + + if instance is None: + instance = cls.__instances.setdefault(key, + cls.instance(s, posix_offset)) + + # This lock may not be necessary in Python 3. See GH issue #901 + with cls.__cache_lock: + cls.__strong_cache[key] = cls.__strong_cache.pop(key, instance) + + # Remove an item if the strong cache is overpopulated + if len(cls.__strong_cache) > cls.__strong_cache_size: + cls.__strong_cache.popitem(last=False) + + return instance + diff --git a/python/user_packages/Python313/site-packages/dateutil/tz/tz.py b/python/user_packages/Python313/site-packages/dateutil/tz/tz.py new file mode 100644 index 0000000000000000000000000000000000000000..617591446bd92eb1cc7b7d67fa3f17435e691cdd --- /dev/null +++ b/python/user_packages/Python313/site-packages/dateutil/tz/tz.py @@ -0,0 +1,1849 @@ +# -*- coding: utf-8 -*- +""" +This module offers timezone implementations subclassing the abstract +:py:class:`datetime.tzinfo` type. There are classes to handle tzfile format +files (usually are in :file:`/etc/localtime`, :file:`/usr/share/zoneinfo`, +etc), TZ environment string (in all known formats), given ranges (with help +from relative deltas), local machine timezone, fixed offset timezone, and UTC +timezone. +""" +import datetime +import struct +import time +import sys +import os +import bisect +import weakref +from collections import OrderedDict + +import six +from six import string_types +from six.moves import _thread +from ._common import tzname_in_python2, _tzinfo +from ._common import tzrangebase, enfold +from ._common import _validate_fromutc_inputs + +from ._factories import _TzSingleton, _TzOffsetFactory +from ._factories import _TzStrFactory +try: + from .win import tzwin, tzwinlocal +except ImportError: + tzwin = tzwinlocal = None + +# For warning about rounding tzinfo +from warnings import warn + +ZERO = datetime.timedelta(0) +EPOCH = datetime.datetime(1970, 1, 1, 0, 0) +EPOCHORDINAL = EPOCH.toordinal() + + +@six.add_metaclass(_TzSingleton) +class tzutc(datetime.tzinfo): + """ + This is a tzinfo object that represents the UTC time zone. + + **Examples:** + + .. doctest:: + + >>> from datetime import * + >>> from dateutil.tz import * + + >>> datetime.now() + datetime.datetime(2003, 9, 27, 9, 40, 1, 521290) + + >>> datetime.now(tzutc()) + datetime.datetime(2003, 9, 27, 12, 40, 12, 156379, tzinfo=tzutc()) + + >>> datetime.now(tzutc()).tzname() + 'UTC' + + .. versionchanged:: 2.7.0 + ``tzutc()`` is now a singleton, so the result of ``tzutc()`` will + always return the same object. + + .. doctest:: + + >>> from dateutil.tz import tzutc, UTC + >>> tzutc() is tzutc() + True + >>> tzutc() is UTC + True + """ + def utcoffset(self, dt): + return ZERO + + def dst(self, dt): + return ZERO + + @tzname_in_python2 + def tzname(self, dt): + return "UTC" + + def is_ambiguous(self, dt): + """ + Whether or not the "wall time" of a given datetime is ambiguous in this + zone. + + :param dt: + A :py:class:`datetime.datetime`, naive or time zone aware. + + + :return: + Returns ``True`` if ambiguous, ``False`` otherwise. + + .. versionadded:: 2.6.0 + """ + return False + + @_validate_fromutc_inputs + def fromutc(self, dt): + """ + Fast track version of fromutc() returns the original ``dt`` object for + any valid :py:class:`datetime.datetime` object. + """ + return dt + + def __eq__(self, other): + if not isinstance(other, (tzutc, tzoffset)): + return NotImplemented + + return (isinstance(other, tzutc) or + (isinstance(other, tzoffset) and other._offset == ZERO)) + + __hash__ = None + + def __ne__(self, other): + return not (self == other) + + def __repr__(self): + return "%s()" % self.__class__.__name__ + + __reduce__ = object.__reduce__ + + +#: Convenience constant providing a :class:`tzutc()` instance +#: +#: .. versionadded:: 2.7.0 +UTC = tzutc() + + +@six.add_metaclass(_TzOffsetFactory) +class tzoffset(datetime.tzinfo): + """ + A simple class for representing a fixed offset from UTC. + + :param name: + The timezone name, to be returned when ``tzname()`` is called. + :param offset: + The time zone offset in seconds, or (since version 2.6.0, represented + as a :py:class:`datetime.timedelta` object). + """ + def __init__(self, name, offset): + self._name = name + + try: + # Allow a timedelta + offset = offset.total_seconds() + except (TypeError, AttributeError): + pass + + self._offset = datetime.timedelta(seconds=_get_supported_offset(offset)) + + def utcoffset(self, dt): + return self._offset + + def dst(self, dt): + return ZERO + + @tzname_in_python2 + def tzname(self, dt): + return self._name + + @_validate_fromutc_inputs + def fromutc(self, dt): + return dt + self._offset + + def is_ambiguous(self, dt): + """ + Whether or not the "wall time" of a given datetime is ambiguous in this + zone. + + :param dt: + A :py:class:`datetime.datetime`, naive or time zone aware. + :return: + Returns ``True`` if ambiguous, ``False`` otherwise. + + .. versionadded:: 2.6.0 + """ + return False + + def __eq__(self, other): + if not isinstance(other, tzoffset): + return NotImplemented + + return self._offset == other._offset + + __hash__ = None + + def __ne__(self, other): + return not (self == other) + + def __repr__(self): + return "%s(%s, %s)" % (self.__class__.__name__, + repr(self._name), + int(self._offset.total_seconds())) + + __reduce__ = object.__reduce__ + + +class tzlocal(_tzinfo): + """ + A :class:`tzinfo` subclass built around the ``time`` timezone functions. + """ + def __init__(self): + super(tzlocal, self).__init__() + + self._std_offset = datetime.timedelta(seconds=-time.timezone) + if time.daylight: + self._dst_offset = datetime.timedelta(seconds=-time.altzone) + else: + self._dst_offset = self._std_offset + + self._dst_saved = self._dst_offset - self._std_offset + self._hasdst = bool(self._dst_saved) + self._tznames = tuple(time.tzname) + + def utcoffset(self, dt): + if dt is None and self._hasdst: + return None + + if self._isdst(dt): + return self._dst_offset + else: + return self._std_offset + + def dst(self, dt): + if dt is None and self._hasdst: + return None + + if self._isdst(dt): + return self._dst_offset - self._std_offset + else: + return ZERO + + @tzname_in_python2 + def tzname(self, dt): + return self._tznames[self._isdst(dt)] + + def is_ambiguous(self, dt): + """ + Whether or not the "wall time" of a given datetime is ambiguous in this + zone. + + :param dt: + A :py:class:`datetime.datetime`, naive or time zone aware. + + + :return: + Returns ``True`` if ambiguous, ``False`` otherwise. + + .. versionadded:: 2.6.0 + """ + naive_dst = self._naive_is_dst(dt) + return (not naive_dst and + (naive_dst != self._naive_is_dst(dt - self._dst_saved))) + + def _naive_is_dst(self, dt): + timestamp = _datetime_to_timestamp(dt) + return time.localtime(timestamp + time.timezone).tm_isdst + + def _isdst(self, dt, fold_naive=True): + # We can't use mktime here. It is unstable when deciding if + # the hour near to a change is DST or not. + # + # timestamp = time.mktime((dt.year, dt.month, dt.day, dt.hour, + # dt.minute, dt.second, dt.weekday(), 0, -1)) + # return time.localtime(timestamp).tm_isdst + # + # The code above yields the following result: + # + # >>> import tz, datetime + # >>> t = tz.tzlocal() + # >>> datetime.datetime(2003,2,15,23,tzinfo=t).tzname() + # 'BRDT' + # >>> datetime.datetime(2003,2,16,0,tzinfo=t).tzname() + # 'BRST' + # >>> datetime.datetime(2003,2,15,23,tzinfo=t).tzname() + # 'BRST' + # >>> datetime.datetime(2003,2,15,22,tzinfo=t).tzname() + # 'BRDT' + # >>> datetime.datetime(2003,2,15,23,tzinfo=t).tzname() + # 'BRDT' + # + # Here is a more stable implementation: + # + if not self._hasdst: + return False + + # Check for ambiguous times: + dstval = self._naive_is_dst(dt) + fold = getattr(dt, 'fold', None) + + if self.is_ambiguous(dt): + if fold is not None: + return not self._fold(dt) + else: + return True + + return dstval + + def __eq__(self, other): + if isinstance(other, tzlocal): + return (self._std_offset == other._std_offset and + self._dst_offset == other._dst_offset) + elif isinstance(other, tzutc): + return (not self._hasdst and + self._tznames[0] in {'UTC', 'GMT'} and + self._std_offset == ZERO) + elif isinstance(other, tzoffset): + return (not self._hasdst and + self._tznames[0] == other._name and + self._std_offset == other._offset) + else: + return NotImplemented + + __hash__ = None + + def __ne__(self, other): + return not (self == other) + + def __repr__(self): + return "%s()" % self.__class__.__name__ + + __reduce__ = object.__reduce__ + + +class _ttinfo(object): + __slots__ = ["offset", "delta", "isdst", "abbr", + "isstd", "isgmt", "dstoffset"] + + def __init__(self): + for attr in self.__slots__: + setattr(self, attr, None) + + def __repr__(self): + l = [] + for attr in self.__slots__: + value = getattr(self, attr) + if value is not None: + l.append("%s=%s" % (attr, repr(value))) + return "%s(%s)" % (self.__class__.__name__, ", ".join(l)) + + def __eq__(self, other): + if not isinstance(other, _ttinfo): + return NotImplemented + + return (self.offset == other.offset and + self.delta == other.delta and + self.isdst == other.isdst and + self.abbr == other.abbr and + self.isstd == other.isstd and + self.isgmt == other.isgmt and + self.dstoffset == other.dstoffset) + + __hash__ = None + + def __ne__(self, other): + return not (self == other) + + def __getstate__(self): + state = {} + for name in self.__slots__: + state[name] = getattr(self, name, None) + return state + + def __setstate__(self, state): + for name in self.__slots__: + if name in state: + setattr(self, name, state[name]) + + +class _tzfile(object): + """ + Lightweight class for holding the relevant transition and time zone + information read from binary tzfiles. + """ + attrs = ['trans_list', 'trans_list_utc', 'trans_idx', 'ttinfo_list', + 'ttinfo_std', 'ttinfo_dst', 'ttinfo_before', 'ttinfo_first'] + + def __init__(self, **kwargs): + for attr in self.attrs: + setattr(self, attr, kwargs.get(attr, None)) + + +class tzfile(_tzinfo): + """ + This is a ``tzinfo`` subclass that allows one to use the ``tzfile(5)`` + format timezone files to extract current and historical zone information. + + :param fileobj: + This can be an opened file stream or a file name that the time zone + information can be read from. + + :param filename: + This is an optional parameter specifying the source of the time zone + information in the event that ``fileobj`` is a file object. If omitted + and ``fileobj`` is a file stream, this parameter will be set either to + ``fileobj``'s ``name`` attribute or to ``repr(fileobj)``. + + See `Sources for Time Zone and Daylight Saving Time Data + `_ for more information. + Time zone files can be compiled from the `IANA Time Zone database files + `_ with the `zic time zone compiler + `_ + + .. note:: + + Only construct a ``tzfile`` directly if you have a specific timezone + file on disk that you want to read into a Python ``tzinfo`` object. + If you want to get a ``tzfile`` representing a specific IANA zone, + (e.g. ``'America/New_York'``), you should call + :func:`dateutil.tz.gettz` with the zone identifier. + + + **Examples:** + + Using the US Eastern time zone as an example, we can see that a ``tzfile`` + provides time zone information for the standard Daylight Saving offsets: + + .. testsetup:: tzfile + + from dateutil.tz import gettz + from datetime import datetime + + .. doctest:: tzfile + + >>> NYC = gettz('America/New_York') + >>> NYC + tzfile('/usr/share/zoneinfo/America/New_York') + + >>> print(datetime(2016, 1, 3, tzinfo=NYC)) # EST + 2016-01-03 00:00:00-05:00 + + >>> print(datetime(2016, 7, 7, tzinfo=NYC)) # EDT + 2016-07-07 00:00:00-04:00 + + + The ``tzfile`` structure contains a fully history of the time zone, + so historical dates will also have the right offsets. For example, before + the adoption of the UTC standards, New York used local solar mean time: + + .. doctest:: tzfile + + >>> print(datetime(1901, 4, 12, tzinfo=NYC)) # LMT + 1901-04-12 00:00:00-04:56 + + And during World War II, New York was on "Eastern War Time", which was a + state of permanent daylight saving time: + + .. doctest:: tzfile + + >>> print(datetime(1944, 2, 7, tzinfo=NYC)) # EWT + 1944-02-07 00:00:00-04:00 + + """ + + def __init__(self, fileobj, filename=None): + super(tzfile, self).__init__() + + file_opened_here = False + if isinstance(fileobj, string_types): + self._filename = fileobj + fileobj = open(fileobj, 'rb') + file_opened_here = True + elif filename is not None: + self._filename = filename + elif hasattr(fileobj, "name"): + self._filename = fileobj.name + else: + self._filename = repr(fileobj) + + if fileobj is not None: + if not file_opened_here: + fileobj = _nullcontext(fileobj) + + with fileobj as file_stream: + tzobj = self._read_tzfile(file_stream) + + self._set_tzdata(tzobj) + + def _set_tzdata(self, tzobj): + """ Set the time zone data of this object from a _tzfile object """ + # Copy the relevant attributes over as private attributes + for attr in _tzfile.attrs: + setattr(self, '_' + attr, getattr(tzobj, attr)) + + def _read_tzfile(self, fileobj): + out = _tzfile() + + # From tzfile(5): + # + # The time zone information files used by tzset(3) + # begin with the magic characters "TZif" to identify + # them as time zone information files, followed by + # sixteen bytes reserved for future use, followed by + # six four-byte values of type long, written in a + # ``standard'' byte order (the high-order byte + # of the value is written first). + if fileobj.read(4).decode() != "TZif": + raise ValueError("magic not found") + + fileobj.read(16) + + ( + # The number of UTC/local indicators stored in the file. + ttisgmtcnt, + + # The number of standard/wall indicators stored in the file. + ttisstdcnt, + + # The number of leap seconds for which data is + # stored in the file. + leapcnt, + + # The number of "transition times" for which data + # is stored in the file. + timecnt, + + # The number of "local time types" for which data + # is stored in the file (must not be zero). + typecnt, + + # The number of characters of "time zone + # abbreviation strings" stored in the file. + charcnt, + + ) = struct.unpack(">6l", fileobj.read(24)) + + # The above header is followed by tzh_timecnt four-byte + # values of type long, sorted in ascending order. + # These values are written in ``standard'' byte order. + # Each is used as a transition time (as returned by + # time(2)) at which the rules for computing local time + # change. + + if timecnt: + out.trans_list_utc = list(struct.unpack(">%dl" % timecnt, + fileobj.read(timecnt*4))) + else: + out.trans_list_utc = [] + + # Next come tzh_timecnt one-byte values of type unsigned + # char; each one tells which of the different types of + # ``local time'' types described in the file is associated + # with the same-indexed transition time. These values + # serve as indices into an array of ttinfo structures that + # appears next in the file. + + if timecnt: + out.trans_idx = struct.unpack(">%dB" % timecnt, + fileobj.read(timecnt)) + else: + out.trans_idx = [] + + # Each ttinfo structure is written as a four-byte value + # for tt_gmtoff of type long, in a standard byte + # order, followed by a one-byte value for tt_isdst + # and a one-byte value for tt_abbrind. In each + # structure, tt_gmtoff gives the number of + # seconds to be added to UTC, tt_isdst tells whether + # tm_isdst should be set by localtime(3), and + # tt_abbrind serves as an index into the array of + # time zone abbreviation characters that follow the + # ttinfo structure(s) in the file. + + ttinfo = [] + + for i in range(typecnt): + ttinfo.append(struct.unpack(">lbb", fileobj.read(6))) + + abbr = fileobj.read(charcnt).decode() + + # Then there are tzh_leapcnt pairs of four-byte + # values, written in standard byte order; the + # first value of each pair gives the time (as + # returned by time(2)) at which a leap second + # occurs; the second gives the total number of + # leap seconds to be applied after the given time. + # The pairs of values are sorted in ascending order + # by time. + + # Not used, for now (but seek for correct file position) + if leapcnt: + fileobj.seek(leapcnt * 8, os.SEEK_CUR) + + # Then there are tzh_ttisstdcnt standard/wall + # indicators, each stored as a one-byte value; + # they tell whether the transition times associated + # with local time types were specified as standard + # time or wall clock time, and are used when + # a time zone file is used in handling POSIX-style + # time zone environment variables. + + if ttisstdcnt: + isstd = struct.unpack(">%db" % ttisstdcnt, + fileobj.read(ttisstdcnt)) + + # Finally, there are tzh_ttisgmtcnt UTC/local + # indicators, each stored as a one-byte value; + # they tell whether the transition times associated + # with local time types were specified as UTC or + # local time, and are used when a time zone file + # is used in handling POSIX-style time zone envi- + # ronment variables. + + if ttisgmtcnt: + isgmt = struct.unpack(">%db" % ttisgmtcnt, + fileobj.read(ttisgmtcnt)) + + # Build ttinfo list + out.ttinfo_list = [] + for i in range(typecnt): + gmtoff, isdst, abbrind = ttinfo[i] + gmtoff = _get_supported_offset(gmtoff) + tti = _ttinfo() + tti.offset = gmtoff + tti.dstoffset = datetime.timedelta(0) + tti.delta = datetime.timedelta(seconds=gmtoff) + tti.isdst = isdst + tti.abbr = abbr[abbrind:abbr.find('\x00', abbrind)] + tti.isstd = (ttisstdcnt > i and isstd[i] != 0) + tti.isgmt = (ttisgmtcnt > i and isgmt[i] != 0) + out.ttinfo_list.append(tti) + + # Replace ttinfo indexes for ttinfo objects. + out.trans_idx = [out.ttinfo_list[idx] for idx in out.trans_idx] + + # Set standard, dst, and before ttinfos. before will be + # used when a given time is before any transitions, + # and will be set to the first non-dst ttinfo, or to + # the first dst, if all of them are dst. + out.ttinfo_std = None + out.ttinfo_dst = None + out.ttinfo_before = None + if out.ttinfo_list: + if not out.trans_list_utc: + out.ttinfo_std = out.ttinfo_first = out.ttinfo_list[0] + else: + for i in range(timecnt-1, -1, -1): + tti = out.trans_idx[i] + if not out.ttinfo_std and not tti.isdst: + out.ttinfo_std = tti + elif not out.ttinfo_dst and tti.isdst: + out.ttinfo_dst = tti + + if out.ttinfo_std and out.ttinfo_dst: + break + else: + if out.ttinfo_dst and not out.ttinfo_std: + out.ttinfo_std = out.ttinfo_dst + + for tti in out.ttinfo_list: + if not tti.isdst: + out.ttinfo_before = tti + break + else: + out.ttinfo_before = out.ttinfo_list[0] + + # Now fix transition times to become relative to wall time. + # + # I'm not sure about this. In my tests, the tz source file + # is setup to wall time, and in the binary file isstd and + # isgmt are off, so it should be in wall time. OTOH, it's + # always in gmt time. Let me know if you have comments + # about this. + lastdst = None + lastoffset = None + lastdstoffset = None + lastbaseoffset = None + out.trans_list = [] + + for i, tti in enumerate(out.trans_idx): + offset = tti.offset + dstoffset = 0 + + if lastdst is not None: + if tti.isdst: + if not lastdst: + dstoffset = offset - lastoffset + + if not dstoffset and lastdstoffset: + dstoffset = lastdstoffset + + tti.dstoffset = datetime.timedelta(seconds=dstoffset) + lastdstoffset = dstoffset + + # If a time zone changes its base offset during a DST transition, + # then you need to adjust by the previous base offset to get the + # transition time in local time. Otherwise you use the current + # base offset. Ideally, I would have some mathematical proof of + # why this is true, but I haven't really thought about it enough. + baseoffset = offset - dstoffset + adjustment = baseoffset + if (lastbaseoffset is not None and baseoffset != lastbaseoffset + and tti.isdst != lastdst): + # The base DST has changed + adjustment = lastbaseoffset + + lastdst = tti.isdst + lastoffset = offset + lastbaseoffset = baseoffset + + out.trans_list.append(out.trans_list_utc[i] + adjustment) + + out.trans_idx = tuple(out.trans_idx) + out.trans_list = tuple(out.trans_list) + out.trans_list_utc = tuple(out.trans_list_utc) + + return out + + def _find_last_transition(self, dt, in_utc=False): + # If there's no list, there are no transitions to find + if not self._trans_list: + return None + + timestamp = _datetime_to_timestamp(dt) + + # Find where the timestamp fits in the transition list - if the + # timestamp is a transition time, it's part of the "after" period. + trans_list = self._trans_list_utc if in_utc else self._trans_list + idx = bisect.bisect_right(trans_list, timestamp) + + # We want to know when the previous transition was, so subtract off 1 + return idx - 1 + + def _get_ttinfo(self, idx): + # For no list or after the last transition, default to _ttinfo_std + if idx is None or (idx + 1) >= len(self._trans_list): + return self._ttinfo_std + + # If there is a list and the time is before it, return _ttinfo_before + if idx < 0: + return self._ttinfo_before + + return self._trans_idx[idx] + + def _find_ttinfo(self, dt): + idx = self._resolve_ambiguous_time(dt) + + return self._get_ttinfo(idx) + + def fromutc(self, dt): + """ + The ``tzfile`` implementation of :py:func:`datetime.tzinfo.fromutc`. + + :param dt: + A :py:class:`datetime.datetime` object. + + :raises TypeError: + Raised if ``dt`` is not a :py:class:`datetime.datetime` object. + + :raises ValueError: + Raised if this is called with a ``dt`` which does not have this + ``tzinfo`` attached. + + :return: + Returns a :py:class:`datetime.datetime` object representing the + wall time in ``self``'s time zone. + """ + # These isinstance checks are in datetime.tzinfo, so we'll preserve + # them, even if we don't care about duck typing. + if not isinstance(dt, datetime.datetime): + raise TypeError("fromutc() requires a datetime argument") + + if dt.tzinfo is not self: + raise ValueError("dt.tzinfo is not self") + + # First treat UTC as wall time and get the transition we're in. + idx = self._find_last_transition(dt, in_utc=True) + tti = self._get_ttinfo(idx) + + dt_out = dt + datetime.timedelta(seconds=tti.offset) + + fold = self.is_ambiguous(dt_out, idx=idx) + + return enfold(dt_out, fold=int(fold)) + + def is_ambiguous(self, dt, idx=None): + """ + Whether or not the "wall time" of a given datetime is ambiguous in this + zone. + + :param dt: + A :py:class:`datetime.datetime`, naive or time zone aware. + + + :return: + Returns ``True`` if ambiguous, ``False`` otherwise. + + .. versionadded:: 2.6.0 + """ + if idx is None: + idx = self._find_last_transition(dt) + + # Calculate the difference in offsets from current to previous + timestamp = _datetime_to_timestamp(dt) + tti = self._get_ttinfo(idx) + + if idx is None or idx <= 0: + return False + + od = self._get_ttinfo(idx - 1).offset - tti.offset + tt = self._trans_list[idx] # Transition time + + return timestamp < tt + od + + def _resolve_ambiguous_time(self, dt): + idx = self._find_last_transition(dt) + + # If we have no transitions, return the index + _fold = self._fold(dt) + if idx is None or idx == 0: + return idx + + # If it's ambiguous and we're in a fold, shift to a different index. + idx_offset = int(not _fold and self.is_ambiguous(dt, idx)) + + return idx - idx_offset + + def utcoffset(self, dt): + if dt is None: + return None + + if not self._ttinfo_std: + return ZERO + + return self._find_ttinfo(dt).delta + + def dst(self, dt): + if dt is None: + return None + + if not self._ttinfo_dst: + return ZERO + + tti = self._find_ttinfo(dt) + + if not tti.isdst: + return ZERO + + # The documentation says that utcoffset()-dst() must + # be constant for every dt. + return tti.dstoffset + + @tzname_in_python2 + def tzname(self, dt): + if not self._ttinfo_std or dt is None: + return None + return self._find_ttinfo(dt).abbr + + def __eq__(self, other): + if not isinstance(other, tzfile): + return NotImplemented + return (self._trans_list == other._trans_list and + self._trans_idx == other._trans_idx and + self._ttinfo_list == other._ttinfo_list) + + __hash__ = None + + def __ne__(self, other): + return not (self == other) + + def __repr__(self): + return "%s(%s)" % (self.__class__.__name__, repr(self._filename)) + + def __reduce__(self): + return self.__reduce_ex__(None) + + def __reduce_ex__(self, protocol): + return (self.__class__, (None, self._filename), self.__dict__) + + +class tzrange(tzrangebase): + """ + The ``tzrange`` object is a time zone specified by a set of offsets and + abbreviations, equivalent to the way the ``TZ`` variable can be specified + in POSIX-like systems, but using Python delta objects to specify DST + start, end and offsets. + + :param stdabbr: + The abbreviation for standard time (e.g. ``'EST'``). + + :param stdoffset: + An integer or :class:`datetime.timedelta` object or equivalent + specifying the base offset from UTC. + + If unspecified, +00:00 is used. + + :param dstabbr: + The abbreviation for DST / "Summer" time (e.g. ``'EDT'``). + + If specified, with no other DST information, DST is assumed to occur + and the default behavior or ``dstoffset``, ``start`` and ``end`` is + used. If unspecified and no other DST information is specified, it + is assumed that this zone has no DST. + + If this is unspecified and other DST information is *is* specified, + DST occurs in the zone but the time zone abbreviation is left + unchanged. + + :param dstoffset: + A an integer or :class:`datetime.timedelta` object or equivalent + specifying the UTC offset during DST. If unspecified and any other DST + information is specified, it is assumed to be the STD offset +1 hour. + + :param start: + A :class:`relativedelta.relativedelta` object or equivalent specifying + the time and time of year that daylight savings time starts. To + specify, for example, that DST starts at 2AM on the 2nd Sunday in + March, pass: + + ``relativedelta(hours=2, month=3, day=1, weekday=SU(+2))`` + + If unspecified and any other DST information is specified, the default + value is 2 AM on the first Sunday in April. + + :param end: + A :class:`relativedelta.relativedelta` object or equivalent + representing the time and time of year that daylight savings time + ends, with the same specification method as in ``start``. One note is + that this should point to the first time in the *standard* zone, so if + a transition occurs at 2AM in the DST zone and the clocks are set back + 1 hour to 1AM, set the ``hours`` parameter to +1. + + + **Examples:** + + .. testsetup:: tzrange + + from dateutil.tz import tzrange, tzstr + + .. doctest:: tzrange + + >>> tzstr('EST5EDT') == tzrange("EST", -18000, "EDT") + True + + >>> from dateutil.relativedelta import * + >>> range1 = tzrange("EST", -18000, "EDT") + >>> range2 = tzrange("EST", -18000, "EDT", -14400, + ... relativedelta(hours=+2, month=4, day=1, + ... weekday=SU(+1)), + ... relativedelta(hours=+1, month=10, day=31, + ... weekday=SU(-1))) + >>> tzstr('EST5EDT') == range1 == range2 + True + + """ + def __init__(self, stdabbr, stdoffset=None, + dstabbr=None, dstoffset=None, + start=None, end=None): + + global relativedelta + from dateutil import relativedelta + + self._std_abbr = stdabbr + self._dst_abbr = dstabbr + + try: + stdoffset = stdoffset.total_seconds() + except (TypeError, AttributeError): + pass + + try: + dstoffset = dstoffset.total_seconds() + except (TypeError, AttributeError): + pass + + if stdoffset is not None: + self._std_offset = datetime.timedelta(seconds=stdoffset) + else: + self._std_offset = ZERO + + if dstoffset is not None: + self._dst_offset = datetime.timedelta(seconds=dstoffset) + elif dstabbr and stdoffset is not None: + self._dst_offset = self._std_offset + datetime.timedelta(hours=+1) + else: + self._dst_offset = ZERO + + if dstabbr and start is None: + self._start_delta = relativedelta.relativedelta( + hours=+2, month=4, day=1, weekday=relativedelta.SU(+1)) + else: + self._start_delta = start + + if dstabbr and end is None: + self._end_delta = relativedelta.relativedelta( + hours=+1, month=10, day=31, weekday=relativedelta.SU(-1)) + else: + self._end_delta = end + + self._dst_base_offset_ = self._dst_offset - self._std_offset + self.hasdst = bool(self._start_delta) + + def transitions(self, year): + """ + For a given year, get the DST on and off transition times, expressed + always on the standard time side. For zones with no transitions, this + function returns ``None``. + + :param year: + The year whose transitions you would like to query. + + :return: + Returns a :class:`tuple` of :class:`datetime.datetime` objects, + ``(dston, dstoff)`` for zones with an annual DST transition, or + ``None`` for fixed offset zones. + """ + if not self.hasdst: + return None + + base_year = datetime.datetime(year, 1, 1) + + start = base_year + self._start_delta + end = base_year + self._end_delta + + return (start, end) + + def __eq__(self, other): + if not isinstance(other, tzrange): + return NotImplemented + + return (self._std_abbr == other._std_abbr and + self._dst_abbr == other._dst_abbr and + self._std_offset == other._std_offset and + self._dst_offset == other._dst_offset and + self._start_delta == other._start_delta and + self._end_delta == other._end_delta) + + @property + def _dst_base_offset(self): + return self._dst_base_offset_ + + +@six.add_metaclass(_TzStrFactory) +class tzstr(tzrange): + """ + ``tzstr`` objects are time zone objects specified by a time-zone string as + it would be passed to a ``TZ`` variable on POSIX-style systems (see + the `GNU C Library: TZ Variable`_ for more details). + + There is one notable exception, which is that POSIX-style time zones use an + inverted offset format, so normally ``GMT+3`` would be parsed as an offset + 3 hours *behind* GMT. The ``tzstr`` time zone object will parse this as an + offset 3 hours *ahead* of GMT. If you would like to maintain the POSIX + behavior, pass a ``True`` value to ``posix_offset``. + + The :class:`tzrange` object provides the same functionality, but is + specified using :class:`relativedelta.relativedelta` objects. rather than + strings. + + :param s: + A time zone string in ``TZ`` variable format. This can be a + :class:`bytes` (2.x: :class:`str`), :class:`str` (2.x: + :class:`unicode`) or a stream emitting unicode characters + (e.g. :class:`StringIO`). + + :param posix_offset: + Optional. If set to ``True``, interpret strings such as ``GMT+3`` or + ``UTC+3`` as being 3 hours *behind* UTC rather than ahead, per the + POSIX standard. + + .. caution:: + + Prior to version 2.7.0, this function also supported time zones + in the format: + + * ``EST5EDT,4,0,6,7200,10,0,26,7200,3600`` + * ``EST5EDT,4,1,0,7200,10,-1,0,7200,3600`` + + This format is non-standard and has been deprecated; this function + will raise a :class:`DeprecatedTZFormatWarning` until + support is removed in a future version. + + .. _`GNU C Library: TZ Variable`: + https://www.gnu.org/software/libc/manual/html_node/TZ-Variable.html + """ + def __init__(self, s, posix_offset=False): + global parser + from dateutil.parser import _parser as parser + + self._s = s + + res = parser._parsetz(s) + if res is None or res.any_unused_tokens: + raise ValueError("unknown string format") + + # Here we break the compatibility with the TZ variable handling. + # GMT-3 actually *means* the timezone -3. + if res.stdabbr in ("GMT", "UTC") and not posix_offset: + res.stdoffset *= -1 + + # We must initialize it first, since _delta() needs + # _std_offset and _dst_offset set. Use False in start/end + # to avoid building it two times. + tzrange.__init__(self, res.stdabbr, res.stdoffset, + res.dstabbr, res.dstoffset, + start=False, end=False) + + if not res.dstabbr: + self._start_delta = None + self._end_delta = None + else: + self._start_delta = self._delta(res.start) + if self._start_delta: + self._end_delta = self._delta(res.end, isend=1) + + self.hasdst = bool(self._start_delta) + + def _delta(self, x, isend=0): + from dateutil import relativedelta + kwargs = {} + if x.month is not None: + kwargs["month"] = x.month + if x.weekday is not None: + kwargs["weekday"] = relativedelta.weekday(x.weekday, x.week) + if x.week > 0: + kwargs["day"] = 1 + else: + kwargs["day"] = 31 + elif x.day: + kwargs["day"] = x.day + elif x.yday is not None: + kwargs["yearday"] = x.yday + elif x.jyday is not None: + kwargs["nlyearday"] = x.jyday + if not kwargs: + # Default is to start on first sunday of april, and end + # on last sunday of october. + if not isend: + kwargs["month"] = 4 + kwargs["day"] = 1 + kwargs["weekday"] = relativedelta.SU(+1) + else: + kwargs["month"] = 10 + kwargs["day"] = 31 + kwargs["weekday"] = relativedelta.SU(-1) + if x.time is not None: + kwargs["seconds"] = x.time + else: + # Default is 2AM. + kwargs["seconds"] = 7200 + if isend: + # Convert to standard time, to follow the documented way + # of working with the extra hour. See the documentation + # of the tzinfo class. + delta = self._dst_offset - self._std_offset + kwargs["seconds"] -= delta.seconds + delta.days * 86400 + return relativedelta.relativedelta(**kwargs) + + def __repr__(self): + return "%s(%s)" % (self.__class__.__name__, repr(self._s)) + + +class _tzicalvtzcomp(object): + def __init__(self, tzoffsetfrom, tzoffsetto, isdst, + tzname=None, rrule=None): + self.tzoffsetfrom = datetime.timedelta(seconds=tzoffsetfrom) + self.tzoffsetto = datetime.timedelta(seconds=tzoffsetto) + self.tzoffsetdiff = self.tzoffsetto - self.tzoffsetfrom + self.isdst = isdst + self.tzname = tzname + self.rrule = rrule + + +class _tzicalvtz(_tzinfo): + def __init__(self, tzid, comps=[]): + super(_tzicalvtz, self).__init__() + + self._tzid = tzid + self._comps = comps + self._cachedate = [] + self._cachecomp = [] + self._cache_lock = _thread.allocate_lock() + + def _find_comp(self, dt): + if len(self._comps) == 1: + return self._comps[0] + + dt = dt.replace(tzinfo=None) + + try: + with self._cache_lock: + return self._cachecomp[self._cachedate.index( + (dt, self._fold(dt)))] + except ValueError: + pass + + lastcompdt = None + lastcomp = None + + for comp in self._comps: + compdt = self._find_compdt(comp, dt) + + if compdt and (not lastcompdt or lastcompdt < compdt): + lastcompdt = compdt + lastcomp = comp + + if not lastcomp: + # RFC says nothing about what to do when a given + # time is before the first onset date. We'll look for the + # first standard component, or the first component, if + # none is found. + for comp in self._comps: + if not comp.isdst: + lastcomp = comp + break + else: + lastcomp = comp[0] + + with self._cache_lock: + self._cachedate.insert(0, (dt, self._fold(dt))) + self._cachecomp.insert(0, lastcomp) + + if len(self._cachedate) > 10: + self._cachedate.pop() + self._cachecomp.pop() + + return lastcomp + + def _find_compdt(self, comp, dt): + if comp.tzoffsetdiff < ZERO and self._fold(dt): + dt -= comp.tzoffsetdiff + + compdt = comp.rrule.before(dt, inc=True) + + return compdt + + def utcoffset(self, dt): + if dt is None: + return None + + return self._find_comp(dt).tzoffsetto + + def dst(self, dt): + comp = self._find_comp(dt) + if comp.isdst: + return comp.tzoffsetdiff + else: + return ZERO + + @tzname_in_python2 + def tzname(self, dt): + return self._find_comp(dt).tzname + + def __repr__(self): + return "" % repr(self._tzid) + + __reduce__ = object.__reduce__ + + +class tzical(object): + """ + This object is designed to parse an iCalendar-style ``VTIMEZONE`` structure + as set out in `RFC 5545`_ Section 4.6.5 into one or more `tzinfo` objects. + + :param `fileobj`: + A file or stream in iCalendar format, which should be UTF-8 encoded + with CRLF endings. + + .. _`RFC 5545`: https://tools.ietf.org/html/rfc5545 + """ + def __init__(self, fileobj): + global rrule + from dateutil import rrule + + if isinstance(fileobj, string_types): + self._s = fileobj + # ical should be encoded in UTF-8 with CRLF + fileobj = open(fileobj, 'r') + else: + self._s = getattr(fileobj, 'name', repr(fileobj)) + fileobj = _nullcontext(fileobj) + + self._vtz = {} + + with fileobj as fobj: + self._parse_rfc(fobj.read()) + + def keys(self): + """ + Retrieves the available time zones as a list. + """ + return list(self._vtz.keys()) + + def get(self, tzid=None): + """ + Retrieve a :py:class:`datetime.tzinfo` object by its ``tzid``. + + :param tzid: + If there is exactly one time zone available, omitting ``tzid`` + or passing :py:const:`None` value returns it. Otherwise a valid + key (which can be retrieved from :func:`keys`) is required. + + :raises ValueError: + Raised if ``tzid`` is not specified but there are either more + or fewer than 1 zone defined. + + :returns: + Returns either a :py:class:`datetime.tzinfo` object representing + the relevant time zone or :py:const:`None` if the ``tzid`` was + not found. + """ + if tzid is None: + if len(self._vtz) == 0: + raise ValueError("no timezones defined") + elif len(self._vtz) > 1: + raise ValueError("more than one timezone available") + tzid = next(iter(self._vtz)) + + return self._vtz.get(tzid) + + def _parse_offset(self, s): + s = s.strip() + if not s: + raise ValueError("empty offset") + if s[0] in ('+', '-'): + signal = (-1, +1)[s[0] == '+'] + s = s[1:] + else: + signal = +1 + if len(s) == 4: + return (int(s[:2]) * 3600 + int(s[2:]) * 60) * signal + elif len(s) == 6: + return (int(s[:2]) * 3600 + int(s[2:4]) * 60 + int(s[4:])) * signal + else: + raise ValueError("invalid offset: " + s) + + def _parse_rfc(self, s): + lines = s.splitlines() + if not lines: + raise ValueError("empty string") + + # Unfold + i = 0 + while i < len(lines): + line = lines[i].rstrip() + if not line: + del lines[i] + elif i > 0 and line[0] == " ": + lines[i-1] += line[1:] + del lines[i] + else: + i += 1 + + tzid = None + comps = [] + invtz = False + comptype = None + for line in lines: + if not line: + continue + name, value = line.split(':', 1) + parms = name.split(';') + if not parms: + raise ValueError("empty property name") + name = parms[0].upper() + parms = parms[1:] + if invtz: + if name == "BEGIN": + if value in ("STANDARD", "DAYLIGHT"): + # Process component + pass + else: + raise ValueError("unknown component: "+value) + comptype = value + founddtstart = False + tzoffsetfrom = None + tzoffsetto = None + rrulelines = [] + tzname = None + elif name == "END": + if value == "VTIMEZONE": + if comptype: + raise ValueError("component not closed: "+comptype) + if not tzid: + raise ValueError("mandatory TZID not found") + if not comps: + raise ValueError( + "at least one component is needed") + # Process vtimezone + self._vtz[tzid] = _tzicalvtz(tzid, comps) + invtz = False + elif value == comptype: + if not founddtstart: + raise ValueError("mandatory DTSTART not found") + if tzoffsetfrom is None: + raise ValueError( + "mandatory TZOFFSETFROM not found") + if tzoffsetto is None: + raise ValueError( + "mandatory TZOFFSETFROM not found") + # Process component + rr = None + if rrulelines: + rr = rrule.rrulestr("\n".join(rrulelines), + compatible=True, + ignoretz=True, + cache=True) + comp = _tzicalvtzcomp(tzoffsetfrom, tzoffsetto, + (comptype == "DAYLIGHT"), + tzname, rr) + comps.append(comp) + comptype = None + else: + raise ValueError("invalid component end: "+value) + elif comptype: + if name == "DTSTART": + # DTSTART in VTIMEZONE takes a subset of valid RRULE + # values under RFC 5545. + for parm in parms: + if parm != 'VALUE=DATE-TIME': + msg = ('Unsupported DTSTART param in ' + + 'VTIMEZONE: ' + parm) + raise ValueError(msg) + rrulelines.append(line) + founddtstart = True + elif name in ("RRULE", "RDATE", "EXRULE", "EXDATE"): + rrulelines.append(line) + elif name == "TZOFFSETFROM": + if parms: + raise ValueError( + "unsupported %s parm: %s " % (name, parms[0])) + tzoffsetfrom = self._parse_offset(value) + elif name == "TZOFFSETTO": + if parms: + raise ValueError( + "unsupported TZOFFSETTO parm: "+parms[0]) + tzoffsetto = self._parse_offset(value) + elif name == "TZNAME": + if parms: + raise ValueError( + "unsupported TZNAME parm: "+parms[0]) + tzname = value + elif name == "COMMENT": + pass + else: + raise ValueError("unsupported property: "+name) + else: + if name == "TZID": + if parms: + raise ValueError( + "unsupported TZID parm: "+parms[0]) + tzid = value + elif name in ("TZURL", "LAST-MODIFIED", "COMMENT"): + pass + else: + raise ValueError("unsupported property: "+name) + elif name == "BEGIN" and value == "VTIMEZONE": + tzid = None + comps = [] + invtz = True + + def __repr__(self): + return "%s(%s)" % (self.__class__.__name__, repr(self._s)) + + +if sys.platform != "win32": + TZFILES = ["/etc/localtime", "localtime"] + TZPATHS = ["/usr/share/zoneinfo", + "/usr/lib/zoneinfo", + "/usr/share/lib/zoneinfo", + "/etc/zoneinfo"] +else: + TZFILES = [] + TZPATHS = [] + + +def __get_gettz(): + tzlocal_classes = (tzlocal,) + if tzwinlocal is not None: + tzlocal_classes += (tzwinlocal,) + + class GettzFunc(object): + """ + Retrieve a time zone object from a string representation + + This function is intended to retrieve the :py:class:`tzinfo` subclass + that best represents the time zone that would be used if a POSIX + `TZ variable`_ were set to the same value. + + If no argument or an empty string is passed to ``gettz``, local time + is returned: + + .. code-block:: python3 + + >>> gettz() + tzfile('/etc/localtime') + + This function is also the preferred way to map IANA tz database keys + to :class:`tzfile` objects: + + .. code-block:: python3 + + >>> gettz('Pacific/Kiritimati') + tzfile('/usr/share/zoneinfo/Pacific/Kiritimati') + + On Windows, the standard is extended to include the Windows-specific + zone names provided by the operating system: + + .. code-block:: python3 + + >>> gettz('Egypt Standard Time') + tzwin('Egypt Standard Time') + + Passing a GNU ``TZ`` style string time zone specification returns a + :class:`tzstr` object: + + .. code-block:: python3 + + >>> gettz('AEST-10AEDT-11,M10.1.0/2,M4.1.0/3') + tzstr('AEST-10AEDT-11,M10.1.0/2,M4.1.0/3') + + :param name: + A time zone name (IANA, or, on Windows, Windows keys), location of + a ``tzfile(5)`` zoneinfo file or ``TZ`` variable style time zone + specifier. An empty string, no argument or ``None`` is interpreted + as local time. + + :return: + Returns an instance of one of ``dateutil``'s :py:class:`tzinfo` + subclasses. + + .. versionchanged:: 2.7.0 + + After version 2.7.0, any two calls to ``gettz`` using the same + input strings will return the same object: + + .. code-block:: python3 + + >>> tz.gettz('America/Chicago') is tz.gettz('America/Chicago') + True + + In addition to improving performance, this ensures that + `"same zone" semantics`_ are used for datetimes in the same zone. + + + .. _`TZ variable`: + https://www.gnu.org/software/libc/manual/html_node/TZ-Variable.html + + .. _`"same zone" semantics`: + https://blog.ganssle.io/articles/2018/02/aware-datetime-arithmetic.html + """ + def __init__(self): + + self.__instances = weakref.WeakValueDictionary() + self.__strong_cache_size = 8 + self.__strong_cache = OrderedDict() + self._cache_lock = _thread.allocate_lock() + + def __call__(self, name=None): + with self._cache_lock: + rv = self.__instances.get(name, None) + + if rv is None: + rv = self.nocache(name=name) + if not (name is None + or isinstance(rv, tzlocal_classes) + or rv is None): + # tzlocal is slightly more complicated than the other + # time zone providers because it depends on environment + # at construction time, so don't cache that. + # + # We also cannot store weak references to None, so we + # will also not store that. + self.__instances[name] = rv + else: + # No need for strong caching, return immediately + return rv + + self.__strong_cache[name] = self.__strong_cache.pop(name, rv) + + if len(self.__strong_cache) > self.__strong_cache_size: + self.__strong_cache.popitem(last=False) + + return rv + + def set_cache_size(self, size): + with self._cache_lock: + self.__strong_cache_size = size + while len(self.__strong_cache) > size: + self.__strong_cache.popitem(last=False) + + def cache_clear(self): + with self._cache_lock: + self.__instances = weakref.WeakValueDictionary() + self.__strong_cache.clear() + + @staticmethod + def nocache(name=None): + """A non-cached version of gettz""" + tz = None + if not name: + try: + name = os.environ["TZ"] + except KeyError: + pass + if name is None or name in ("", ":"): + for filepath in TZFILES: + if not os.path.isabs(filepath): + filename = filepath + for path in TZPATHS: + filepath = os.path.join(path, filename) + if os.path.isfile(filepath): + break + else: + continue + if os.path.isfile(filepath): + try: + tz = tzfile(filepath) + break + except (IOError, OSError, ValueError): + pass + else: + tz = tzlocal() + else: + try: + if name.startswith(":"): + name = name[1:] + except TypeError as e: + if isinstance(name, bytes): + new_msg = "gettz argument should be str, not bytes" + six.raise_from(TypeError(new_msg), e) + else: + raise + if os.path.isabs(name): + if os.path.isfile(name): + tz = tzfile(name) + else: + tz = None + else: + for path in TZPATHS: + filepath = os.path.join(path, name) + if not os.path.isfile(filepath): + filepath = filepath.replace(' ', '_') + if not os.path.isfile(filepath): + continue + try: + tz = tzfile(filepath) + break + except (IOError, OSError, ValueError): + pass + else: + tz = None + if tzwin is not None: + try: + tz = tzwin(name) + except (WindowsError, UnicodeEncodeError): + # UnicodeEncodeError is for Python 2.7 compat + tz = None + + if not tz: + from dateutil.zoneinfo import get_zonefile_instance + tz = get_zonefile_instance().get(name) + + if not tz: + for c in name: + # name is not a tzstr unless it has at least + # one offset. For short values of "name", an + # explicit for loop seems to be the fastest way + # To determine if a string contains a digit + if c in "0123456789": + try: + tz = tzstr(name) + except ValueError: + pass + break + else: + if name in ("GMT", "UTC"): + tz = UTC + elif name in time.tzname: + tz = tzlocal() + return tz + + return GettzFunc() + + +gettz = __get_gettz() +del __get_gettz + + +def datetime_exists(dt, tz=None): + """ + Given a datetime and a time zone, determine whether or not a given datetime + would fall in a gap. + + :param dt: + A :class:`datetime.datetime` (whose time zone will be ignored if ``tz`` + is provided.) + + :param tz: + A :class:`datetime.tzinfo` with support for the ``fold`` attribute. If + ``None`` or not provided, the datetime's own time zone will be used. + + :return: + Returns a boolean value whether or not the "wall time" exists in + ``tz``. + + .. versionadded:: 2.7.0 + """ + if tz is None: + if dt.tzinfo is None: + raise ValueError('Datetime is naive and no time zone provided.') + tz = dt.tzinfo + + dt = dt.replace(tzinfo=None) + + # This is essentially a test of whether or not the datetime can survive + # a round trip to UTC. + dt_rt = dt.replace(tzinfo=tz).astimezone(UTC).astimezone(tz) + dt_rt = dt_rt.replace(tzinfo=None) + + return dt == dt_rt + + +def datetime_ambiguous(dt, tz=None): + """ + Given a datetime and a time zone, determine whether or not a given datetime + is ambiguous (i.e if there are two times differentiated only by their DST + status). + + :param dt: + A :class:`datetime.datetime` (whose time zone will be ignored if ``tz`` + is provided.) + + :param tz: + A :class:`datetime.tzinfo` with support for the ``fold`` attribute. If + ``None`` or not provided, the datetime's own time zone will be used. + + :return: + Returns a boolean value whether or not the "wall time" is ambiguous in + ``tz``. + + .. versionadded:: 2.6.0 + """ + if tz is None: + if dt.tzinfo is None: + raise ValueError('Datetime is naive and no time zone provided.') + + tz = dt.tzinfo + + # If a time zone defines its own "is_ambiguous" function, we'll use that. + is_ambiguous_fn = getattr(tz, 'is_ambiguous', None) + if is_ambiguous_fn is not None: + try: + return tz.is_ambiguous(dt) + except Exception: + pass + + # If it doesn't come out and tell us it's ambiguous, we'll just check if + # the fold attribute has any effect on this particular date and time. + dt = dt.replace(tzinfo=tz) + wall_0 = enfold(dt, fold=0) + wall_1 = enfold(dt, fold=1) + + same_offset = wall_0.utcoffset() == wall_1.utcoffset() + same_dst = wall_0.dst() == wall_1.dst() + + return not (same_offset and same_dst) + + +def resolve_imaginary(dt): + """ + Given a datetime that may be imaginary, return an existing datetime. + + This function assumes that an imaginary datetime represents what the + wall time would be in a zone had the offset transition not occurred, so + it will always fall forward by the transition's change in offset. + + .. doctest:: + + >>> from dateutil import tz + >>> from datetime import datetime + >>> NYC = tz.gettz('America/New_York') + >>> print(tz.resolve_imaginary(datetime(2017, 3, 12, 2, 30, tzinfo=NYC))) + 2017-03-12 03:30:00-04:00 + + >>> KIR = tz.gettz('Pacific/Kiritimati') + >>> print(tz.resolve_imaginary(datetime(1995, 1, 1, 12, 30, tzinfo=KIR))) + 1995-01-02 12:30:00+14:00 + + As a note, :func:`datetime.astimezone` is guaranteed to produce a valid, + existing datetime, so a round-trip to and from UTC is sufficient to get + an extant datetime, however, this generally "falls back" to an earlier time + rather than falling forward to the STD side (though no guarantees are made + about this behavior). + + :param dt: + A :class:`datetime.datetime` which may or may not exist. + + :return: + Returns an existing :class:`datetime.datetime`. If ``dt`` was not + imaginary, the datetime returned is guaranteed to be the same object + passed to the function. + + .. versionadded:: 2.7.0 + """ + if dt.tzinfo is not None and not datetime_exists(dt): + + curr_offset = (dt + datetime.timedelta(hours=24)).utcoffset() + old_offset = (dt - datetime.timedelta(hours=24)).utcoffset() + + dt += curr_offset - old_offset + + return dt + + +def _datetime_to_timestamp(dt): + """ + Convert a :class:`datetime.datetime` object to an epoch timestamp in + seconds since January 1, 1970, ignoring the time zone. + """ + return (dt.replace(tzinfo=None) - EPOCH).total_seconds() + + +if sys.version_info >= (3, 6): + def _get_supported_offset(second_offset): + return second_offset +else: + def _get_supported_offset(second_offset): + # For python pre-3.6, round to full-minutes if that's not the case. + # Python's datetime doesn't accept sub-minute timezones. Check + # http://python.org/sf/1447945 or https://bugs.python.org/issue5288 + # for some information. + old_offset = second_offset + calculated_offset = 60 * ((second_offset + 30) // 60) + return calculated_offset + + +try: + # Python 3.7 feature + from contextlib import nullcontext as _nullcontext +except ImportError: + class _nullcontext(object): + """ + Class for wrapping contexts so that they are passed through in a + with statement. + """ + def __init__(self, context): + self.context = context + + def __enter__(self): + return self.context + + def __exit__(*args, **kwargs): + pass + +# vim:ts=4:sw=4:et diff --git a/python/user_packages/Python313/site-packages/dateutil/tz/win.py b/python/user_packages/Python313/site-packages/dateutil/tz/win.py new file mode 100644 index 0000000000000000000000000000000000000000..cde07ba792c40903f0c334839140173b39fd8124 --- /dev/null +++ b/python/user_packages/Python313/site-packages/dateutil/tz/win.py @@ -0,0 +1,370 @@ +# -*- coding: utf-8 -*- +""" +This module provides an interface to the native time zone data on Windows, +including :py:class:`datetime.tzinfo` implementations. + +Attempting to import this module on a non-Windows platform will raise an +:py:obj:`ImportError`. +""" +# This code was originally contributed by Jeffrey Harris. +import datetime +import struct + +from six.moves import winreg +from six import text_type + +try: + import ctypes + from ctypes import wintypes +except ValueError: + # ValueError is raised on non-Windows systems for some horrible reason. + raise ImportError("Running tzwin on non-Windows system") + +from ._common import tzrangebase + +__all__ = ["tzwin", "tzwinlocal", "tzres"] + +ONEWEEK = datetime.timedelta(7) + +TZKEYNAMENT = r"SOFTWARE\Microsoft\Windows NT\CurrentVersion\Time Zones" +TZKEYNAME9X = r"SOFTWARE\Microsoft\Windows\CurrentVersion\Time Zones" +TZLOCALKEYNAME = r"SYSTEM\CurrentControlSet\Control\TimeZoneInformation" + + +def _settzkeyname(): + handle = winreg.ConnectRegistry(None, winreg.HKEY_LOCAL_MACHINE) + try: + winreg.OpenKey(handle, TZKEYNAMENT).Close() + TZKEYNAME = TZKEYNAMENT + except WindowsError: + TZKEYNAME = TZKEYNAME9X + handle.Close() + return TZKEYNAME + + +TZKEYNAME = _settzkeyname() + + +class tzres(object): + """ + Class for accessing ``tzres.dll``, which contains timezone name related + resources. + + .. versionadded:: 2.5.0 + """ + p_wchar = ctypes.POINTER(wintypes.WCHAR) # Pointer to a wide char + + def __init__(self, tzres_loc='tzres.dll'): + # Load the user32 DLL so we can load strings from tzres + user32 = ctypes.WinDLL('user32') + + # Specify the LoadStringW function + user32.LoadStringW.argtypes = (wintypes.HINSTANCE, + wintypes.UINT, + wintypes.LPWSTR, + ctypes.c_int) + + self.LoadStringW = user32.LoadStringW + self._tzres = ctypes.WinDLL(tzres_loc) + self.tzres_loc = tzres_loc + + def load_name(self, offset): + """ + Load a timezone name from a DLL offset (integer). + + >>> from dateutil.tzwin import tzres + >>> tzr = tzres() + >>> print(tzr.load_name(112)) + 'Eastern Standard Time' + + :param offset: + A positive integer value referring to a string from the tzres dll. + + .. note:: + + Offsets found in the registry are generally of the form + ``@tzres.dll,-114``. The offset in this case is 114, not -114. + + """ + resource = self.p_wchar() + lpBuffer = ctypes.cast(ctypes.byref(resource), wintypes.LPWSTR) + nchar = self.LoadStringW(self._tzres._handle, offset, lpBuffer, 0) + return resource[:nchar] + + def name_from_string(self, tzname_str): + """ + Parse strings as returned from the Windows registry into the time zone + name as defined in the registry. + + >>> from dateutil.tzwin import tzres + >>> tzr = tzres() + >>> print(tzr.name_from_string('@tzres.dll,-251')) + 'Dateline Daylight Time' + >>> print(tzr.name_from_string('Eastern Standard Time')) + 'Eastern Standard Time' + + :param tzname_str: + A timezone name string as returned from a Windows registry key. + + :return: + Returns the localized timezone string from tzres.dll if the string + is of the form `@tzres.dll,-offset`, else returns the input string. + """ + if not tzname_str.startswith('@'): + return tzname_str + + name_splt = tzname_str.split(',-') + try: + offset = int(name_splt[1]) + except: + raise ValueError("Malformed timezone string.") + + return self.load_name(offset) + + +class tzwinbase(tzrangebase): + """tzinfo class based on win32's timezones available in the registry.""" + def __init__(self): + raise NotImplementedError('tzwinbase is an abstract base class') + + def __eq__(self, other): + # Compare on all relevant dimensions, including name. + if not isinstance(other, tzwinbase): + return NotImplemented + + return (self._std_offset == other._std_offset and + self._dst_offset == other._dst_offset and + self._stddayofweek == other._stddayofweek and + self._dstdayofweek == other._dstdayofweek and + self._stdweeknumber == other._stdweeknumber and + self._dstweeknumber == other._dstweeknumber and + self._stdhour == other._stdhour and + self._dsthour == other._dsthour and + self._stdminute == other._stdminute and + self._dstminute == other._dstminute and + self._std_abbr == other._std_abbr and + self._dst_abbr == other._dst_abbr) + + @staticmethod + def list(): + """Return a list of all time zones known to the system.""" + with winreg.ConnectRegistry(None, winreg.HKEY_LOCAL_MACHINE) as handle: + with winreg.OpenKey(handle, TZKEYNAME) as tzkey: + result = [winreg.EnumKey(tzkey, i) + for i in range(winreg.QueryInfoKey(tzkey)[0])] + return result + + def display(self): + """ + Return the display name of the time zone. + """ + return self._display + + def transitions(self, year): + """ + For a given year, get the DST on and off transition times, expressed + always on the standard time side. For zones with no transitions, this + function returns ``None``. + + :param year: + The year whose transitions you would like to query. + + :return: + Returns a :class:`tuple` of :class:`datetime.datetime` objects, + ``(dston, dstoff)`` for zones with an annual DST transition, or + ``None`` for fixed offset zones. + """ + + if not self.hasdst: + return None + + dston = picknthweekday(year, self._dstmonth, self._dstdayofweek, + self._dsthour, self._dstminute, + self._dstweeknumber) + + dstoff = picknthweekday(year, self._stdmonth, self._stddayofweek, + self._stdhour, self._stdminute, + self._stdweeknumber) + + # Ambiguous dates default to the STD side + dstoff -= self._dst_base_offset + + return dston, dstoff + + def _get_hasdst(self): + return self._dstmonth != 0 + + @property + def _dst_base_offset(self): + return self._dst_base_offset_ + + +class tzwin(tzwinbase): + """ + Time zone object created from the zone info in the Windows registry + + These are similar to :py:class:`dateutil.tz.tzrange` objects in that + the time zone data is provided in the format of a single offset rule + for either 0 or 2 time zone transitions per year. + + :param: name + The name of a Windows time zone key, e.g. "Eastern Standard Time". + The full list of keys can be retrieved with :func:`tzwin.list`. + """ + + def __init__(self, name): + self._name = name + + with winreg.ConnectRegistry(None, winreg.HKEY_LOCAL_MACHINE) as handle: + tzkeyname = text_type("{kn}\\{name}").format(kn=TZKEYNAME, name=name) + with winreg.OpenKey(handle, tzkeyname) as tzkey: + keydict = valuestodict(tzkey) + + self._std_abbr = keydict["Std"] + self._dst_abbr = keydict["Dlt"] + + self._display = keydict["Display"] + + # See http://ww_winreg.jsiinc.com/SUBA/tip0300/rh0398.htm + tup = struct.unpack("=3l16h", keydict["TZI"]) + stdoffset = -tup[0]-tup[1] # Bias + StandardBias * -1 + dstoffset = stdoffset-tup[2] # + DaylightBias * -1 + self._std_offset = datetime.timedelta(minutes=stdoffset) + self._dst_offset = datetime.timedelta(minutes=dstoffset) + + # for the meaning see the win32 TIME_ZONE_INFORMATION structure docs + # http://msdn.microsoft.com/en-us/library/windows/desktop/ms725481(v=vs.85).aspx + (self._stdmonth, + self._stddayofweek, # Sunday = 0 + self._stdweeknumber, # Last = 5 + self._stdhour, + self._stdminute) = tup[4:9] + + (self._dstmonth, + self._dstdayofweek, # Sunday = 0 + self._dstweeknumber, # Last = 5 + self._dsthour, + self._dstminute) = tup[12:17] + + self._dst_base_offset_ = self._dst_offset - self._std_offset + self.hasdst = self._get_hasdst() + + def __repr__(self): + return "tzwin(%s)" % repr(self._name) + + def __reduce__(self): + return (self.__class__, (self._name,)) + + +class tzwinlocal(tzwinbase): + """ + Class representing the local time zone information in the Windows registry + + While :class:`dateutil.tz.tzlocal` makes system calls (via the :mod:`time` + module) to retrieve time zone information, ``tzwinlocal`` retrieves the + rules directly from the Windows registry and creates an object like + :class:`dateutil.tz.tzwin`. + + Because Windows does not have an equivalent of :func:`time.tzset`, on + Windows, :class:`dateutil.tz.tzlocal` instances will always reflect the + time zone settings *at the time that the process was started*, meaning + changes to the machine's time zone settings during the run of a program + on Windows will **not** be reflected by :class:`dateutil.tz.tzlocal`. + Because ``tzwinlocal`` reads the registry directly, it is unaffected by + this issue. + """ + def __init__(self): + with winreg.ConnectRegistry(None, winreg.HKEY_LOCAL_MACHINE) as handle: + with winreg.OpenKey(handle, TZLOCALKEYNAME) as tzlocalkey: + keydict = valuestodict(tzlocalkey) + + self._std_abbr = keydict["StandardName"] + self._dst_abbr = keydict["DaylightName"] + + try: + tzkeyname = text_type('{kn}\\{sn}').format(kn=TZKEYNAME, + sn=self._std_abbr) + with winreg.OpenKey(handle, tzkeyname) as tzkey: + _keydict = valuestodict(tzkey) + self._display = _keydict["Display"] + except OSError: + self._display = None + + stdoffset = -keydict["Bias"]-keydict["StandardBias"] + dstoffset = stdoffset-keydict["DaylightBias"] + + self._std_offset = datetime.timedelta(minutes=stdoffset) + self._dst_offset = datetime.timedelta(minutes=dstoffset) + + # For reasons unclear, in this particular key, the day of week has been + # moved to the END of the SYSTEMTIME structure. + tup = struct.unpack("=8h", keydict["StandardStart"]) + + (self._stdmonth, + self._stdweeknumber, # Last = 5 + self._stdhour, + self._stdminute) = tup[1:5] + + self._stddayofweek = tup[7] + + tup = struct.unpack("=8h", keydict["DaylightStart"]) + + (self._dstmonth, + self._dstweeknumber, # Last = 5 + self._dsthour, + self._dstminute) = tup[1:5] + + self._dstdayofweek = tup[7] + + self._dst_base_offset_ = self._dst_offset - self._std_offset + self.hasdst = self._get_hasdst() + + def __repr__(self): + return "tzwinlocal()" + + def __str__(self): + # str will return the standard name, not the daylight name. + return "tzwinlocal(%s)" % repr(self._std_abbr) + + def __reduce__(self): + return (self.__class__, ()) + + +def picknthweekday(year, month, dayofweek, hour, minute, whichweek): + """ dayofweek == 0 means Sunday, whichweek 5 means last instance """ + first = datetime.datetime(year, month, 1, hour, minute) + + # This will work if dayofweek is ISO weekday (1-7) or Microsoft-style (0-6), + # Because 7 % 7 = 0 + weekdayone = first.replace(day=((dayofweek - first.isoweekday()) % 7) + 1) + wd = weekdayone + ((whichweek - 1) * ONEWEEK) + if (wd.month != month): + wd -= ONEWEEK + + return wd + + +def valuestodict(key): + """Convert a registry key's values to a dictionary.""" + dout = {} + size = winreg.QueryInfoKey(key)[1] + tz_res = None + + for i in range(size): + key_name, value, dtype = winreg.EnumValue(key, i) + if dtype == winreg.REG_DWORD or dtype == winreg.REG_DWORD_LITTLE_ENDIAN: + # If it's a DWORD (32-bit integer), it's stored as unsigned - convert + # that to a proper signed integer + if value & (1 << 31): + value = value - (1 << 32) + elif dtype == winreg.REG_SZ: + # If it's a reference to the tzres DLL, load the actual string + if value.startswith('@tzres'): + tz_res = tz_res or tzres() + value = tz_res.name_from_string(value) + + value = value.rstrip('\x00') # Remove trailing nulls + + dout[key_name] = value + + return dout diff --git a/python/user_packages/Python313/site-packages/dateutil/zoneinfo/__init__.py b/python/user_packages/Python313/site-packages/dateutil/zoneinfo/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..34f11ad66c88047f2c049a4cdcc937b4b78ea6d6 --- /dev/null +++ b/python/user_packages/Python313/site-packages/dateutil/zoneinfo/__init__.py @@ -0,0 +1,167 @@ +# -*- coding: utf-8 -*- +import warnings +import json + +from tarfile import TarFile +from pkgutil import get_data +from io import BytesIO + +from dateutil.tz import tzfile as _tzfile + +__all__ = ["get_zonefile_instance", "gettz", "gettz_db_metadata"] + +ZONEFILENAME = "dateutil-zoneinfo.tar.gz" +METADATA_FN = 'METADATA' + + +class tzfile(_tzfile): + def __reduce__(self): + return (gettz, (self._filename,)) + + +def getzoneinfofile_stream(): + try: + return BytesIO(get_data(__name__, ZONEFILENAME)) + except IOError as e: # TODO switch to FileNotFoundError? + warnings.warn("I/O error({0}): {1}".format(e.errno, e.strerror)) + return None + + +class ZoneInfoFile(object): + def __init__(self, zonefile_stream=None): + if zonefile_stream is not None: + with TarFile.open(fileobj=zonefile_stream) as tf: + self.zones = {zf.name: tzfile(tf.extractfile(zf), filename=zf.name) + for zf in tf.getmembers() + if zf.isfile() and zf.name != METADATA_FN} + # deal with links: They'll point to their parent object. Less + # waste of memory + links = {zl.name: self.zones[zl.linkname] + for zl in tf.getmembers() if + zl.islnk() or zl.issym()} + self.zones.update(links) + try: + metadata_json = tf.extractfile(tf.getmember(METADATA_FN)) + metadata_str = metadata_json.read().decode('UTF-8') + self.metadata = json.loads(metadata_str) + except KeyError: + # no metadata in tar file + self.metadata = None + else: + self.zones = {} + self.metadata = None + + def get(self, name, default=None): + """ + Wrapper for :func:`ZoneInfoFile.zones.get`. This is a convenience method + for retrieving zones from the zone dictionary. + + :param name: + The name of the zone to retrieve. (Generally IANA zone names) + + :param default: + The value to return in the event of a missing key. + + .. versionadded:: 2.6.0 + + """ + return self.zones.get(name, default) + + +# The current API has gettz as a module function, although in fact it taps into +# a stateful class. So as a workaround for now, without changing the API, we +# will create a new "global" class instance the first time a user requests a +# timezone. Ugly, but adheres to the api. +# +# TODO: Remove after deprecation period. +_CLASS_ZONE_INSTANCE = [] + + +def get_zonefile_instance(new_instance=False): + """ + This is a convenience function which provides a :class:`ZoneInfoFile` + instance using the data provided by the ``dateutil`` package. By default, it + caches a single instance of the ZoneInfoFile object and returns that. + + :param new_instance: + If ``True``, a new instance of :class:`ZoneInfoFile` is instantiated and + used as the cached instance for the next call. Otherwise, new instances + are created only as necessary. + + :return: + Returns a :class:`ZoneInfoFile` object. + + .. versionadded:: 2.6 + """ + if new_instance: + zif = None + else: + zif = getattr(get_zonefile_instance, '_cached_instance', None) + + if zif is None: + zif = ZoneInfoFile(getzoneinfofile_stream()) + + get_zonefile_instance._cached_instance = zif + + return zif + + +def gettz(name): + """ + This retrieves a time zone from the local zoneinfo tarball that is packaged + with dateutil. + + :param name: + An IANA-style time zone name, as found in the zoneinfo file. + + :return: + Returns a :class:`dateutil.tz.tzfile` time zone object. + + .. warning:: + It is generally inadvisable to use this function, and it is only + provided for API compatibility with earlier versions. This is *not* + equivalent to ``dateutil.tz.gettz()``, which selects an appropriate + time zone based on the inputs, favoring system zoneinfo. This is ONLY + for accessing the dateutil-specific zoneinfo (which may be out of + date compared to the system zoneinfo). + + .. deprecated:: 2.6 + If you need to use a specific zoneinfofile over the system zoneinfo, + instantiate a :class:`dateutil.zoneinfo.ZoneInfoFile` object and call + :func:`dateutil.zoneinfo.ZoneInfoFile.get(name)` instead. + + Use :func:`get_zonefile_instance` to retrieve an instance of the + dateutil-provided zoneinfo. + """ + warnings.warn("zoneinfo.gettz() will be removed in future versions, " + "to use the dateutil-provided zoneinfo files, instantiate a " + "ZoneInfoFile object and use ZoneInfoFile.zones.get() " + "instead. See the documentation for details.", + DeprecationWarning) + + if len(_CLASS_ZONE_INSTANCE) == 0: + _CLASS_ZONE_INSTANCE.append(ZoneInfoFile(getzoneinfofile_stream())) + return _CLASS_ZONE_INSTANCE[0].zones.get(name) + + +def gettz_db_metadata(): + """ Get the zonefile metadata + + See `zonefile_metadata`_ + + :returns: + A dictionary with the database metadata + + .. deprecated:: 2.6 + See deprecation warning in :func:`zoneinfo.gettz`. To get metadata, + query the attribute ``zoneinfo.ZoneInfoFile.metadata``. + """ + warnings.warn("zoneinfo.gettz_db_metadata() will be removed in future " + "versions, to use the dateutil-provided zoneinfo files, " + "ZoneInfoFile object and query the 'metadata' attribute " + "instead. See the documentation for details.", + DeprecationWarning) + + if len(_CLASS_ZONE_INSTANCE) == 0: + _CLASS_ZONE_INSTANCE.append(ZoneInfoFile(getzoneinfofile_stream())) + return _CLASS_ZONE_INSTANCE[0].metadata diff --git a/python/user_packages/Python313/site-packages/dateutil/zoneinfo/__pycache__/__init__.cpython-313.pyc b/python/user_packages/Python313/site-packages/dateutil/zoneinfo/__pycache__/__init__.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d5ed0a0961b9b379e3bb7256c958f008bd881e72 Binary files /dev/null and b/python/user_packages/Python313/site-packages/dateutil/zoneinfo/__pycache__/__init__.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/dateutil/zoneinfo/__pycache__/rebuild.cpython-313.pyc b/python/user_packages/Python313/site-packages/dateutil/zoneinfo/__pycache__/rebuild.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9d0919a6b72ac3c8eb73328b3aab64169ca8f3bf Binary files /dev/null and b/python/user_packages/Python313/site-packages/dateutil/zoneinfo/__pycache__/rebuild.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/dateutil/zoneinfo/rebuild.py b/python/user_packages/Python313/site-packages/dateutil/zoneinfo/rebuild.py new file mode 100644 index 0000000000000000000000000000000000000000..684c6586f091350c347f2b6150935f5214ffec27 --- /dev/null +++ b/python/user_packages/Python313/site-packages/dateutil/zoneinfo/rebuild.py @@ -0,0 +1,75 @@ +import logging +import os +import tempfile +import shutil +import json +from subprocess import check_call, check_output +from tarfile import TarFile + +from dateutil.zoneinfo import METADATA_FN, ZONEFILENAME + + +def rebuild(filename, tag=None, format="gz", zonegroups=[], metadata=None): + """Rebuild the internal timezone info in dateutil/zoneinfo/zoneinfo*tar* + + filename is the timezone tarball from ``ftp.iana.org/tz``. + + """ + tmpdir = tempfile.mkdtemp() + zonedir = os.path.join(tmpdir, "zoneinfo") + moduledir = os.path.dirname(__file__) + try: + with TarFile.open(filename) as tf: + for name in zonegroups: + tf.extract(name, tmpdir) + filepaths = [os.path.join(tmpdir, n) for n in zonegroups] + + _run_zic(zonedir, filepaths) + + # write metadata file + with open(os.path.join(zonedir, METADATA_FN), 'w') as f: + json.dump(metadata, f, indent=4, sort_keys=True) + target = os.path.join(moduledir, ZONEFILENAME) + with TarFile.open(target, "w:%s" % format) as tf: + for entry in os.listdir(zonedir): + entrypath = os.path.join(zonedir, entry) + tf.add(entrypath, entry) + finally: + shutil.rmtree(tmpdir) + + +def _run_zic(zonedir, filepaths): + """Calls the ``zic`` compiler in a compatible way to get a "fat" binary. + + Recent versions of ``zic`` default to ``-b slim``, while older versions + don't even have the ``-b`` option (but default to "fat" binaries). The + current version of dateutil does not support Version 2+ TZif files, which + causes problems when used in conjunction with "slim" binaries, so this + function is used to ensure that we always get a "fat" binary. + """ + + try: + help_text = check_output(["zic", "--help"]) + except OSError as e: + _print_on_nosuchfile(e) + raise + + if b"-b " in help_text: + bloat_args = ["-b", "fat"] + else: + bloat_args = [] + + check_call(["zic"] + bloat_args + ["-d", zonedir] + filepaths) + + +def _print_on_nosuchfile(e): + """Print helpful troubleshooting message + + e is an exception raised by subprocess.check_call() + + """ + if e.errno == 2: + logging.error( + "Could not find zic. Perhaps you need to install " + "libc-bin or some other package that provides it, " + "or it's not in your PATH?") diff --git a/python/user_packages/Python313/site-packages/defusedxml/__pycache__/ElementTree.cpython-313.pyc b/python/user_packages/Python313/site-packages/defusedxml/__pycache__/ElementTree.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..af58f0f389c4291c125f01cabd814d4bb09d80ca Binary files /dev/null and b/python/user_packages/Python313/site-packages/defusedxml/__pycache__/ElementTree.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/defusedxml/__pycache__/__init__.cpython-313.pyc b/python/user_packages/Python313/site-packages/defusedxml/__pycache__/__init__.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7410270835f50110b2d2de84bc9864bbd55326b0 Binary files /dev/null and b/python/user_packages/Python313/site-packages/defusedxml/__pycache__/__init__.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/defusedxml/__pycache__/cElementTree.cpython-313.pyc b/python/user_packages/Python313/site-packages/defusedxml/__pycache__/cElementTree.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6f7e9352a318abcd41a9354af00f406fa3a7961e Binary files /dev/null and b/python/user_packages/Python313/site-packages/defusedxml/__pycache__/cElementTree.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/defusedxml/__pycache__/common.cpython-313.pyc b/python/user_packages/Python313/site-packages/defusedxml/__pycache__/common.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4bdab18ca3b3f152ed97d2bd23d2679e035b3690 Binary files /dev/null and b/python/user_packages/Python313/site-packages/defusedxml/__pycache__/common.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/defusedxml/__pycache__/expatbuilder.cpython-313.pyc b/python/user_packages/Python313/site-packages/defusedxml/__pycache__/expatbuilder.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..baa64a2e598b32075d461549ad42bf6a7d9b87f3 Binary files /dev/null and b/python/user_packages/Python313/site-packages/defusedxml/__pycache__/expatbuilder.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/defusedxml/__pycache__/expatreader.cpython-313.pyc b/python/user_packages/Python313/site-packages/defusedxml/__pycache__/expatreader.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c254d0962a80f8d5ff3175eb3cc52f1f53901e6e Binary files /dev/null and b/python/user_packages/Python313/site-packages/defusedxml/__pycache__/expatreader.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/defusedxml/__pycache__/lxml.cpython-313.pyc b/python/user_packages/Python313/site-packages/defusedxml/__pycache__/lxml.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7eea81fdc4de1009b41d552382966c4e48872c31 Binary files /dev/null and b/python/user_packages/Python313/site-packages/defusedxml/__pycache__/lxml.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/defusedxml/__pycache__/minidom.cpython-313.pyc b/python/user_packages/Python313/site-packages/defusedxml/__pycache__/minidom.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ceda7f937532115ebcae006a9c1a0171ca90167e Binary files /dev/null and b/python/user_packages/Python313/site-packages/defusedxml/__pycache__/minidom.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/defusedxml/__pycache__/pulldom.cpython-313.pyc b/python/user_packages/Python313/site-packages/defusedxml/__pycache__/pulldom.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..be6bcce2e9987167de028baa64167115f9ec11b7 Binary files /dev/null and b/python/user_packages/Python313/site-packages/defusedxml/__pycache__/pulldom.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/defusedxml/__pycache__/sax.cpython-313.pyc b/python/user_packages/Python313/site-packages/defusedxml/__pycache__/sax.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..39c6b8af197a000949577872c6b948948156b130 Binary files /dev/null and b/python/user_packages/Python313/site-packages/defusedxml/__pycache__/sax.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/defusedxml/__pycache__/xmlrpc.cpython-313.pyc b/python/user_packages/Python313/site-packages/defusedxml/__pycache__/xmlrpc.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..fc70432339a722b47a6c4033485603227b3f2d46 Binary files /dev/null and b/python/user_packages/Python313/site-packages/defusedxml/__pycache__/xmlrpc.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/dotenv/__pycache__/__init__.cpython-313.pyc b/python/user_packages/Python313/site-packages/dotenv/__pycache__/__init__.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8b5852e746a05ec38c61fdb0d63501f488145844 Binary files /dev/null and b/python/user_packages/Python313/site-packages/dotenv/__pycache__/__init__.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/dotenv/__pycache__/__main__.cpython-313.pyc b/python/user_packages/Python313/site-packages/dotenv/__pycache__/__main__.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..39b61aa17501b65ee37022babf692049aef43099 Binary files /dev/null and b/python/user_packages/Python313/site-packages/dotenv/__pycache__/__main__.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/dotenv/__pycache__/cli.cpython-313.pyc b/python/user_packages/Python313/site-packages/dotenv/__pycache__/cli.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c6c2a803966cc74fed83c701f4954de01c5b4053 Binary files /dev/null and b/python/user_packages/Python313/site-packages/dotenv/__pycache__/cli.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/dotenv/__pycache__/ipython.cpython-313.pyc b/python/user_packages/Python313/site-packages/dotenv/__pycache__/ipython.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4496730b911f22da1042f6be264fdc1beabad0f6 Binary files /dev/null and b/python/user_packages/Python313/site-packages/dotenv/__pycache__/ipython.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/dotenv/__pycache__/main.cpython-313.pyc b/python/user_packages/Python313/site-packages/dotenv/__pycache__/main.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8dc2fdf30b56fe53074efa6e3ba07480d3bab5f8 Binary files /dev/null and b/python/user_packages/Python313/site-packages/dotenv/__pycache__/main.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/dotenv/__pycache__/parser.cpython-313.pyc b/python/user_packages/Python313/site-packages/dotenv/__pycache__/parser.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1c4fb52503792429388eea4b5e0fe443f9479385 Binary files /dev/null and b/python/user_packages/Python313/site-packages/dotenv/__pycache__/parser.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/dotenv/__pycache__/variables.cpython-313.pyc b/python/user_packages/Python313/site-packages/dotenv/__pycache__/variables.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a885c4ccf69ff2229db79c2a4bc00518adfa5f7f Binary files /dev/null and b/python/user_packages/Python313/site-packages/dotenv/__pycache__/variables.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/dotenv/__pycache__/version.cpython-313.pyc b/python/user_packages/Python313/site-packages/dotenv/__pycache__/version.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..87574a7990aaa4fc52e5aaf4f8453b1b3bb8e9d8 Binary files /dev/null and b/python/user_packages/Python313/site-packages/dotenv/__pycache__/version.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/durationpy/__pycache__/__init__.cpython-313.pyc b/python/user_packages/Python313/site-packages/durationpy/__pycache__/__init__.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..fa1bd51cfbfd0e88779f5d359806fe5914a2c6ce Binary files /dev/null and b/python/user_packages/Python313/site-packages/durationpy/__pycache__/__init__.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/durationpy/__pycache__/duration.cpython-313.pyc b/python/user_packages/Python313/site-packages/durationpy/__pycache__/duration.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9f6a49d2d4f248072836d1f5bc6e12f8562db47e Binary files /dev/null and b/python/user_packages/Python313/site-packages/durationpy/__pycache__/duration.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/fastembed-0.8.0.dist-info/licenses/LICENSE b/python/user_packages/Python313/site-packages/fastembed-0.8.0.dist-info/licenses/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..261eeb9e9f8b2b4b0d119366dda99c6fd7d35c64 --- /dev/null +++ b/python/user_packages/Python313/site-packages/fastembed-0.8.0.dist-info/licenses/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + 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/python/user_packages/Python313/site-packages/fastembed-0.8.0.dist-info/licenses/NOTICE b/python/user_packages/Python313/site-packages/fastembed-0.8.0.dist-info/licenses/NOTICE new file mode 100644 index 0000000000000000000000000000000000000000..2d3d3b298dd2dd510a4e18ba173e7fc79f67d9cf --- /dev/null +++ b/python/user_packages/Python313/site-packages/fastembed-0.8.0.dist-info/licenses/NOTICE @@ -0,0 +1,22 @@ +Copyright 2024 Qdrant + +This product includes software developed by Qdrant + +This distribution includes the following Jina AI models, each with its respective license: +- jinaai/jina-colbert-v2 + - License: cc-by-nc-4.0 +- jinaai/jina-reranker-v2-base-multilingual + - License: cc-by-nc-4.0 +- jinaai/jina-embeddings-v3 + - License: cc-by-nc-4.0 + +These models are developed by Jina (https://jina.ai/) and are subject to Jina AI's licensing terms. + +This distribution includes the following Google models, each with its respective license: +- vidore/colpali-v1.3 + - License: gemma + +Gemma is provided under and subject to the Gemma Terms of Use found at ai.google.dev/gemma/terms + +Additional Notes: +This project also includes third-party libraries with their respective licenses. Please refer to the documentation of each library for details regarding its usage and licensing terms. diff --git a/python/user_packages/Python313/site-packages/fastembed/__pycache__/__init__.cpython-313.pyc b/python/user_packages/Python313/site-packages/fastembed/__pycache__/__init__.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..02bcef1392791b59a7b3fcce5854c821ce5f0bdc Binary files /dev/null and b/python/user_packages/Python313/site-packages/fastembed/__pycache__/__init__.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/fastembed/__pycache__/embedding.cpython-313.pyc b/python/user_packages/Python313/site-packages/fastembed/__pycache__/embedding.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f67bf76636fe05fdd6816e9dc94ded4d256ce13f Binary files /dev/null and b/python/user_packages/Python313/site-packages/fastembed/__pycache__/embedding.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/fastembed/__pycache__/parallel_processor.cpython-313.pyc b/python/user_packages/Python313/site-packages/fastembed/__pycache__/parallel_processor.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..45f3f0f35ae4bd05f8567450f72f8826987437f6 Binary files /dev/null and b/python/user_packages/Python313/site-packages/fastembed/__pycache__/parallel_processor.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/fastembed/common/__init__.py b/python/user_packages/Python313/site-packages/fastembed/common/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..5caf45f3eff47116599708fce7f2154237c97e16 --- /dev/null +++ b/python/user_packages/Python313/site-packages/fastembed/common/__init__.py @@ -0,0 +1,3 @@ +from fastembed.common.types import ImageInput, OnnxProvider, PathInput + +__all__ = ["OnnxProvider", "ImageInput", "PathInput"] diff --git a/python/user_packages/Python313/site-packages/fastembed/common/__pycache__/__init__.cpython-313.pyc b/python/user_packages/Python313/site-packages/fastembed/common/__pycache__/__init__.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b2643335b6c2de029fe84bf8cf470a812767d51a Binary files /dev/null and b/python/user_packages/Python313/site-packages/fastembed/common/__pycache__/__init__.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/fastembed/common/__pycache__/model_description.cpython-313.pyc b/python/user_packages/Python313/site-packages/fastembed/common/__pycache__/model_description.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5c98d899358939719b25736bf688068dbca1c940 Binary files /dev/null and b/python/user_packages/Python313/site-packages/fastembed/common/__pycache__/model_description.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/fastembed/common/__pycache__/model_management.cpython-313.pyc b/python/user_packages/Python313/site-packages/fastembed/common/__pycache__/model_management.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..bcada23d823b83e88683be067d5f4bbb87e0eb6e Binary files /dev/null and b/python/user_packages/Python313/site-packages/fastembed/common/__pycache__/model_management.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/fastembed/common/__pycache__/onnx_model.cpython-313.pyc b/python/user_packages/Python313/site-packages/fastembed/common/__pycache__/onnx_model.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0f644f5cf7a5570b012cdd759d069bc483afa89e Binary files /dev/null and b/python/user_packages/Python313/site-packages/fastembed/common/__pycache__/onnx_model.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/fastembed/common/__pycache__/preprocessor_utils.cpython-313.pyc b/python/user_packages/Python313/site-packages/fastembed/common/__pycache__/preprocessor_utils.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e4bdc450f7eeeee56b0f7fd5a536bc93b51b195e Binary files /dev/null and b/python/user_packages/Python313/site-packages/fastembed/common/__pycache__/preprocessor_utils.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/fastembed/common/__pycache__/types.cpython-313.pyc b/python/user_packages/Python313/site-packages/fastembed/common/__pycache__/types.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d56a389c961f4f13ab3b48691abfe72efca8225f Binary files /dev/null and b/python/user_packages/Python313/site-packages/fastembed/common/__pycache__/types.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/fastembed/common/__pycache__/utils.cpython-313.pyc b/python/user_packages/Python313/site-packages/fastembed/common/__pycache__/utils.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c110f9bfdb995ad504dcae543d4a1391c9a698ea Binary files /dev/null and b/python/user_packages/Python313/site-packages/fastembed/common/__pycache__/utils.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/fastembed/common/model_description.py b/python/user_packages/Python313/site-packages/fastembed/common/model_description.py new file mode 100644 index 0000000000000000000000000000000000000000..caa17710f0f79171c385055282f95f9c323e8141 --- /dev/null +++ b/python/user_packages/Python313/site-packages/fastembed/common/model_description.py @@ -0,0 +1,52 @@ +from dataclasses import dataclass, field +from enum import Enum +from typing import Any + + +@dataclass(frozen=True) +class ModelSource: + hf: str | None = None + url: str | None = None + _deprecated_tar_struct: bool = False + + @property + def deprecated_tar_struct(self) -> bool: + return self._deprecated_tar_struct + + def __post_init__(self) -> None: + if self.hf is None and self.url is None: + raise ValueError( + f"At least one source should be set, current sources: hf={self.hf}, url={self.url}" + ) + + +@dataclass(frozen=True) +class BaseModelDescription: + model: str + sources: ModelSource + model_file: str + description: str + license: str + size_in_GB: float + additional_files: list[str] = field(default_factory=list) + + +@dataclass(frozen=True) +class DenseModelDescription(BaseModelDescription): + dim: int | None = None + tasks: dict[str, Any] | None = field(default_factory=dict) + + def __post_init__(self) -> None: + assert self.dim is not None, "dim is required for dense model description" + + +@dataclass(frozen=True) +class SparseModelDescription(BaseModelDescription): + requires_idf: bool | None = None + vocab_size: int | None = None + + +class PoolingType(str, Enum): + CLS = "CLS" + MEAN = "MEAN" + DISABLED = "DISABLED" diff --git a/python/user_packages/Python313/site-packages/fastembed/common/model_management.py b/python/user_packages/Python313/site-packages/fastembed/common/model_management.py new file mode 100644 index 0000000000000000000000000000000000000000..bfcf27cec9c044ad4182189ceefe4d6362473011 --- /dev/null +++ b/python/user_packages/Python313/site-packages/fastembed/common/model_management.py @@ -0,0 +1,475 @@ +import os +import time +import json +import shutil +import tarfile +from copy import deepcopy +from pathlib import Path +from typing import Any, TypeVar, Generic + +import requests +from huggingface_hub import snapshot_download, model_info, list_repo_tree +from huggingface_hub.hf_api import RepoFile +from huggingface_hub.utils import ( + RepositoryNotFoundError, + disable_progress_bars, + enable_progress_bars, +) +from loguru import logger +from tqdm import tqdm +from fastembed.common.model_description import BaseModelDescription + +T = TypeVar("T", bound=BaseModelDescription) + + +class ModelManagement(Generic[T]): + METADATA_FILE = "files_metadata.json" + + @classmethod + def list_supported_models(cls) -> list[dict[str, Any]]: + """Lists the supported models. + + Returns: + list[T]: A list of dictionaries containing the model information. + """ + raise NotImplementedError() + + @classmethod + def add_custom_model( + cls, + *args: Any, + **kwargs: Any, + ) -> None: + """Add a custom model to the existing embedding classes based on the passed model descriptions + + Model description dict should contain the fields same as in one of the model descriptions presented + in fastembed.common.model_description + + E.g. for BaseModelDescription: + model: str + sources: ModelSource + model_file: str + description: str + license: str + size_in_GB: float + additional_files: list[str] + + Returns: + None + """ + raise NotImplementedError() + + @classmethod + def _list_supported_models(cls) -> list[T]: + raise NotImplementedError() + + @classmethod + def _get_model_description(cls, model_name: str) -> T: + """ + Gets the model description from the model_name. + + Args: + model_name (str): The name of the model. + + raises: + ValueError: If the model_name is not supported. + + Returns: + T: The model description. + """ + for model in cls._list_supported_models(): + if model_name.lower() == model.model.lower(): + return model + + raise ValueError(f"Model {model_name} is not supported in {cls.__name__}.") + + @classmethod + def download_file_from_gcs(cls, url: str, output_path: str, show_progress: bool = True) -> str: + """ + Downloads a file from Google Cloud Storage. + + Args: + url (str): The URL to download the file from. + output_path (str): The path to save the downloaded file to. + show_progress (bool, optional): Whether to show a progress bar. Defaults to True. + + Returns: + str: The path to the downloaded file. + """ + + if os.path.exists(output_path): + return output_path + response = requests.get(url, stream=True) + + # Handle HTTP errors + if response.status_code == 403: + raise PermissionError( + "Authentication Error: You do not have permission to access this resource. " + "Please check your credentials." + ) + + # Get the total size of the file + total_size_in_bytes = int(response.headers.get("content-length", 0)) + + # Warn if the total size is zero + if total_size_in_bytes == 0: + print(f"Warning: Content-length header is missing or zero in the response from {url}.") + + show_progress = bool(total_size_in_bytes and show_progress) + + with tqdm( + total=total_size_in_bytes, + unit="iB", + unit_scale=True, + disable=not show_progress, + ) as progress_bar: + with open(output_path, "wb") as file: + for chunk in response.iter_content(chunk_size=1024): + if chunk: # Filter out keep-alive new chunks + progress_bar.update(len(chunk)) + file.write(chunk) + return output_path + + @classmethod + def download_files_from_huggingface( + cls, + hf_source_repo: str, + cache_dir: str, + extra_patterns: list[str], + local_files_only: bool = False, + **kwargs: Any, + ) -> str: + """ + Downloads a model from HuggingFace Hub. + Args: + hf_source_repo (str): Name of the model on HuggingFace Hub, e.g. "qdrant/all-MiniLM-L6-v2-onnx". + cache_dir (Optional[str]): The path to the cache directory. + extra_patterns (list[str]): extra patterns to allow in the snapshot download, typically + includes the required model files. + local_files_only (bool, optional): Whether to only use local files. Defaults to False. + Returns: + Path: The path to the model directory. + """ + + def _verify_files_from_metadata( + model_dir: Path, stored_metadata: dict[str, Any], repo_files: list[RepoFile] + ) -> bool: + try: + for rel_path, meta in stored_metadata.items(): + file_path = model_dir / rel_path + + if not file_path.exists(): + return False + + if repo_files: # online verification + file_info = next((f for f in repo_files if f.path == file_path.name), None) + if ( + not file_info + or file_info.size != meta["size"] + or file_info.blob_id != meta["blob_id"] + ): + return False + + else: # offline verification + if file_path.stat().st_size != meta["size"]: + return False + return True + except (OSError, KeyError) as e: + logger.error(f"Error verifying files: {str(e)}") + return False + + def _collect_file_metadata( + model_dir: Path, repo_files: list[RepoFile] + ) -> dict[str, dict[str, int | str]]: + meta: dict[str, dict[str, int | str]] = {} + file_info_map = {f.path: f for f in repo_files} + for file_path in model_dir.rglob("*"): + if file_path.is_file() and file_path.name != cls.METADATA_FILE: + repo_file = file_info_map.get(file_path.name) + if repo_file: + meta[str(file_path.relative_to(model_dir))] = { + "size": repo_file.size, + "blob_id": repo_file.blob_id, + } + return meta + + def _save_file_metadata(model_dir: Path, meta: dict[str, dict[str, int | str]]) -> None: + try: + if not model_dir.exists(): + model_dir.mkdir(parents=True, exist_ok=True) + (model_dir / cls.METADATA_FILE).write_text(json.dumps(meta)) + except (OSError, ValueError) as e: + logger.warning(f"Error saving metadata: {str(e)}") + + allow_patterns = [ + "config.json", + "tokenizer.json", + "tokenizer_config.json", + "special_tokens_map.json", + "preprocessor_config.json", + ] + + allow_patterns.extend(extra_patterns) + + snapshot_dir = Path(cache_dir) / f"models--{hf_source_repo.replace('/', '--')}" + metadata_file = snapshot_dir / cls.METADATA_FILE + + if local_files_only: + disable_progress_bars() + if metadata_file.exists(): + metadata = json.loads(metadata_file.read_text()) + verified = _verify_files_from_metadata(snapshot_dir, metadata, repo_files=[]) + if not verified: + logger.warning( + "Local file sizes do not match the metadata." + ) # do not raise, still make an attempt to load the model + result = snapshot_download( + repo_id=hf_source_repo, + allow_patterns=allow_patterns, + cache_dir=cache_dir, + local_files_only=local_files_only, + **kwargs, + ) + return result + + repo_revision = model_info(hf_source_repo).sha + repo_tree = list(list_repo_tree(hf_source_repo, revision=repo_revision, repo_type="model")) + + allowed_extensions = {".json", ".onnx", ".txt"} + repo_files = ( + [ + f + for f in repo_tree + if isinstance(f, RepoFile) and Path(f.path).suffix in allowed_extensions + ] + if repo_tree + else [] + ) + + verified_metadata = False + + if snapshot_dir.exists() and metadata_file.exists(): + metadata = json.loads(metadata_file.read_text()) + verified_metadata = _verify_files_from_metadata(snapshot_dir, metadata, repo_files) + + if verified_metadata: + disable_progress_bars() + + result = snapshot_download( + repo_id=hf_source_repo, + allow_patterns=allow_patterns, + cache_dir=cache_dir, + local_files_only=local_files_only, + **kwargs, + ) + + if ( + not verified_metadata + ): # metadata is not up-to-date, update it and check whether the files have been + # downloaded correctly + metadata = _collect_file_metadata(snapshot_dir, repo_files) + + download_successful = _verify_files_from_metadata( + snapshot_dir, metadata, repo_files=[] + ) # offline verification + if not download_successful: + raise ValueError( + "Files have been corrupted during downloading process. " + "Please check your internet connection and try again." + ) + _save_file_metadata(snapshot_dir, metadata) + + return result + + @classmethod + def decompress_to_cache(cls, targz_path: str, cache_dir: str) -> str: + """ + Decompresses a .tar.gz file to a cache directory. + + Args: + targz_path (str): Path to the .tar.gz file. + cache_dir (str): Path to the cache directory. + + Returns: + cache_dir (str): Path to the cache directory. + """ + # Check if targz_path exists and is a file + if not os.path.isfile(targz_path): + raise ValueError(f"{targz_path} does not exist or is not a file.") + + # Check if targz_path is a .tar.gz file + if not targz_path.endswith(".tar.gz"): + raise ValueError(f"{targz_path} is not a .tar.gz file.") + + try: + # Open the tar.gz file + with tarfile.open(targz_path, "r:gz") as tar: + # Extract all files into the cache directory + tar.extractall( + path=cache_dir, + ) + except tarfile.TarError as e: + # If any error occurs while opening or extracting the tar.gz file, + # delete the cache directory (if it was created in this function) + # and raise the error again + if "tmp" in cache_dir: + shutil.rmtree(cache_dir) + raise ValueError(f"An error occurred while decompressing {targz_path}: {e}") + + return cache_dir + + @classmethod + def retrieve_model_gcs( + cls, + model_name: str, + source_url: str, + cache_dir: str, + deprecated_tar_struct: bool = False, + local_files_only: bool = False, + ) -> Path: + fast_model_name = f"{'fast-' if deprecated_tar_struct else ''}{model_name.split('/')[-1]}" + cache_tmp_dir = Path(cache_dir) / "tmp" + model_tmp_dir = cache_tmp_dir / fast_model_name + model_dir = Path(cache_dir) / fast_model_name + + # check if the model_dir and the model files are both present for macOS + if model_dir.exists() and len(list(model_dir.glob("*"))) > 0: + return model_dir + + if model_tmp_dir.exists(): + shutil.rmtree(model_tmp_dir) + + cache_tmp_dir.mkdir(parents=True, exist_ok=True) + + model_tar_gz = Path(cache_dir) / f"{fast_model_name}.tar.gz" + + if model_tar_gz.exists(): + model_tar_gz.unlink() + + if not local_files_only: + cls.download_file_from_gcs( + source_url, + output_path=str(model_tar_gz), + ) + + cls.decompress_to_cache(targz_path=str(model_tar_gz), cache_dir=str(cache_tmp_dir)) + assert model_tmp_dir.exists(), f"Could not find {model_tmp_dir} in {cache_tmp_dir}" + + model_tar_gz.unlink() + # Rename from tmp to final name is atomic + model_tmp_dir.rename(model_dir) + else: + logger.error( + f"Could not find the model tar.gz file at {model_dir} and local_files_only=True." + ) + raise ValueError( + f"Could not find the model tar.gz file at {model_dir} and local_files_only=True." + ) + + return model_dir + + @classmethod + def download_model(cls, model: T, cache_dir: str, retries: int = 3, **kwargs: Any) -> Path: + """ + Downloads a model from HuggingFace Hub or Google Cloud Storage. + + Args: + model (T): The model description. + Example: + ``` + { + "model": "BAAI/bge-base-en-v1.5", + "dim": 768, + "description": "Base English model, v1.5", + "size_in_GB": 0.44, + "sources": { + "url": "https://storage.googleapis.com/qdrant-fastembed/fast-bge-base-en-v1.5.tar.gz", + "hf": "qdrant/bge-base-en-v1.5-onnx-q", + } + } + ``` + cache_dir (str): The path to the cache directory. + retries: (int): The number of times to retry (including the first attempt) + + Returns: + Path: The path to the downloaded model directory. + """ + local_files_only = kwargs.get("local_files_only", False) + hf_offline = os.environ.get("HF_HUB_OFFLINE", "").strip().upper() + if not local_files_only and hf_offline in {"1", "TRUE", "YES", "ON"}: + local_files_only = True + kwargs["local_files_only"] = True + specific_model_path: str | None = kwargs.pop("specific_model_path", None) + if specific_model_path: + return Path(specific_model_path) + retries = 1 if local_files_only else retries + hf_source = model.sources.hf + url_source = model.sources.url + + extra_patterns = [model.model_file] + extra_patterns.extend(model.additional_files) + + if hf_source: + try: + cache_kwargs = deepcopy(kwargs) + cache_kwargs["local_files_only"] = True + return Path( + cls.download_files_from_huggingface( + hf_source, + cache_dir=cache_dir, + extra_patterns=extra_patterns, + **cache_kwargs, + ) + ) + except Exception: + pass + finally: + enable_progress_bars() + + sleep = 3.0 + while retries > 0: + retries -= 1 + + if hf_source and not local_files_only: + # we have already tried loading with `local_files_only=True` via hf and we failed + try: + return Path( + cls.download_files_from_huggingface( + hf_source, + cache_dir=cache_dir, + extra_patterns=extra_patterns, + **kwargs, + ) + ) + except (EnvironmentError, RepositoryNotFoundError, ValueError) as e: + if not local_files_only: + logger.error( + f"Could not download model from HuggingFace: {e} " + "Falling back to other sources." + ) + finally: + enable_progress_bars() + if url_source or local_files_only: + try: + return cls.retrieve_model_gcs( + model.model, + str(url_source), + str(cache_dir), + deprecated_tar_struct=model.sources.deprecated_tar_struct, + local_files_only=local_files_only, + ) + except Exception: + if not local_files_only: + logger.error(f"Could not download model from url: {url_source}") + + if local_files_only: + logger.error("Could not find model in cache_dir") + break + else: + logger.error( + f"Could not download model from either source, sleeping for {sleep} seconds, {retries} retries left." + ) + time.sleep(sleep) + sleep *= 3 + + raise ValueError(f"Could not load model {model.model} from any source.") diff --git a/python/user_packages/Python313/site-packages/fastembed/common/onnx_model.py b/python/user_packages/Python313/site-packages/fastembed/common/onnx_model.py new file mode 100644 index 0000000000000000000000000000000000000000..d357f2c1ff8d82d9f31d8808e847198a9212e9ed --- /dev/null +++ b/python/user_packages/Python313/site-packages/fastembed/common/onnx_model.py @@ -0,0 +1,188 @@ +import warnings +from dataclasses import dataclass +from pathlib import Path +from typing import Any, Generic, Iterable, Sequence, Type, TypeVar + +import numpy as np +import onnxruntime as ort + +from numpy.typing import NDArray +from tokenizers import Tokenizer + +from fastembed.common.types import OnnxProvider, NumpyArray, Device +from fastembed.parallel_processor import Worker + +# Holds type of the embedding result +T = TypeVar("T") + + +@dataclass +class OnnxOutputContext: + model_output: NumpyArray + attention_mask: NDArray[np.int64] | None = None + input_ids: NDArray[np.int64] | None = None + metadata: dict[str, Any] | None = None + + +class OnnxModel(Generic[T]): + EXPOSED_SESSION_OPTIONS = ("enable_cpu_mem_arena",) + + @classmethod + def _get_worker_class(cls) -> Type["EmbeddingWorker[T]"]: + raise NotImplementedError("Subclasses must implement this method") + + def _post_process_onnx_output(self, output: OnnxOutputContext, **kwargs: Any) -> Iterable[T]: + """Post-process the ONNX model output to convert it into a usable format. + + Args: + output (OnnxOutputContext): The raw output from the ONNX model. + **kwargs: Additional keyword arguments that may be needed by specific implementations. + + Returns: + Iterable[T]: Post-processed output as an iterable of type T. + """ + raise NotImplementedError("Subclasses must implement this method") + + def __init__(self) -> None: + self.model: ort.InferenceSession | None = None + self.tokenizer: Tokenizer | None = None + + def _preprocess_onnx_input( + self, onnx_input: dict[str, NumpyArray], **kwargs: Any + ) -> dict[str, NumpyArray]: + """ + Preprocess the onnx input. + """ + return onnx_input + + def _load_onnx_model( + self, + model_dir: Path, + model_file: str, + threads: int | None, + providers: Sequence[OnnxProvider] | None = None, + cuda: bool | Device = Device.AUTO, + device_id: int | None = None, + extra_session_options: dict[str, Any] | None = None, + ) -> None: + model_path = model_dir / model_file + # List of Execution Providers: https://onnxruntime.ai/docs/execution-providers + available_providers = ort.get_available_providers() + cuda_available = "CUDAExecutionProvider" in available_providers + explicit_cuda = cuda is True or cuda == Device.CUDA + + if explicit_cuda and providers is not None: + warnings.warn( + f"`cuda` and `providers` are mutually exclusive parameters, " + f"cuda: {cuda}, providers: {providers}. If you'd like to use providers, cuda should be one of " + f"[False, Device.CPU, Device.AUTO].", + category=UserWarning, + stacklevel=6, + ) + + if providers is not None: + onnx_providers = list(providers) + elif explicit_cuda or (cuda == Device.AUTO and cuda_available): + if device_id is None: + onnx_providers = ["CUDAExecutionProvider"] + else: + onnx_providers = [("CUDAExecutionProvider", {"device_id": device_id})] + else: + onnx_providers = ["CPUExecutionProvider"] + + requested_provider_names: list[str] = [] + for provider in onnx_providers: + # check providers available + provider_name = provider if isinstance(provider, str) else provider[0] + requested_provider_names.append(provider_name) + if provider_name not in available_providers: + raise ValueError( + f"Provider {provider_name} is not available. Available providers: {available_providers}" + ) + + so = ort.SessionOptions() + so.graph_optimization_level = ort.GraphOptimizationLevel.ORT_ENABLE_ALL + + if threads is not None: + so.intra_op_num_threads = threads + so.inter_op_num_threads = threads + + if extra_session_options is not None: + self.add_extra_session_options(so, extra_session_options) + + self.model = ort.InferenceSession( + str(model_path), providers=onnx_providers, sess_options=so + ) + if "CUDAExecutionProvider" in requested_provider_names: + assert self.model is not None + current_providers = self.model.get_providers() + if "CUDAExecutionProvider" not in current_providers: + warnings.warn( + f"Attempt to set CUDAExecutionProvider failed. Current providers: {current_providers}." + "If you are using CUDA 12.x, install onnxruntime-gpu via " + "`pip install onnxruntime-gpu --extra-index-url https://aiinfra.pkgs.visualstudio.com/PublicPackages/_packaging/onnxruntime-cuda-12/pypi/simple/`", + RuntimeWarning, + ) + + @classmethod + def _select_exposed_session_options(cls, model_kwargs: dict[str, Any]) -> dict[str, Any]: + """A convenience method to select the exposed session options in models + + Args: + model_kwargs (dict[str, Any]): The model kwargs. + + Returns: + dict[str, Any]: a dict with filtered exposed session options. + """ + return {k: v for k, v in model_kwargs.items() if k in cls.EXPOSED_SESSION_OPTIONS} + + @classmethod + def add_extra_session_options( + cls, session_options: ort.SessionOptions, extra_options: dict[str, Any] + ) -> None: + """Add extra session options to the existing options object in-place + + Args: + session_options (ort.SessionOptions): The existing session options object. + extra_options (dict[str, Any]): The extra session options available in cls.EXPOSED_SESSION_OPTIONS. + + Returns: + None + """ + for option in extra_options: + assert ( + option in cls.EXPOSED_SESSION_OPTIONS + ), f"{option} is unknown or not exposed (exposed options: {cls.EXPOSED_SESSION_OPTIONS})" + if "enable_cpu_mem_arena" in extra_options: + session_options.enable_cpu_mem_arena = extra_options["enable_cpu_mem_arena"] + + def load_onnx_model(self) -> None: + raise NotImplementedError("Subclasses must implement this method") + + def onnx_embed(self, *args: Any, **kwargs: Any) -> OnnxOutputContext: + raise NotImplementedError("Subclasses must implement this method") + + +class EmbeddingWorker(Worker, Generic[T]): + def init_embedding( + self, + model_name: str, + cache_dir: str, + **kwargs: Any, + ) -> OnnxModel[T]: + raise NotImplementedError() + + def __init__( + self, + model_name: str, + cache_dir: str, + **kwargs: Any, + ): + self.model = self.init_embedding(model_name, cache_dir, **kwargs) + + @classmethod + def start(cls, model_name: str, cache_dir: str, **kwargs: Any) -> "EmbeddingWorker[T]": + return cls(model_name=model_name, cache_dir=cache_dir, **kwargs) + + def process(self, items: Iterable[tuple[int, Any]]) -> Iterable[tuple[int, Any]]: + raise NotImplementedError("Subclasses must implement this method") diff --git a/python/user_packages/Python313/site-packages/fastembed/common/preprocessor_utils.py b/python/user_packages/Python313/site-packages/fastembed/common/preprocessor_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..3b702f799de92670447657dcd550b7e089f6b295 --- /dev/null +++ b/python/user_packages/Python313/site-packages/fastembed/common/preprocessor_utils.py @@ -0,0 +1,84 @@ +import json +from typing import Any +from pathlib import Path + +from tokenizers import AddedToken, Tokenizer + +from fastembed.image.transform.operators import Compose + + +def load_special_tokens(model_dir: Path) -> dict[str, Any]: + tokens_map_path = model_dir / "special_tokens_map.json" + if not tokens_map_path.exists(): + raise ValueError(f"Could not find special_tokens_map.json in {model_dir}") + + with open(str(tokens_map_path)) as tokens_map_file: + tokens_map = json.load(tokens_map_file) + + return tokens_map + + +def load_tokenizer(model_dir: Path) -> tuple[Tokenizer, dict[str, int]]: + config_path = model_dir / "config.json" + if not config_path.exists(): + raise ValueError(f"Could not find config.json in {model_dir}") + + tokenizer_path = model_dir / "tokenizer.json" + if not tokenizer_path.exists(): + raise ValueError(f"Could not find tokenizer.json in {model_dir}") + + tokenizer_config_path = model_dir / "tokenizer_config.json" + if not tokenizer_config_path.exists(): + raise ValueError(f"Could not find tokenizer_config.json in {model_dir}") + + with open(str(config_path)) as config_file: + config = json.load(config_file) + + with open(str(tokenizer_config_path)) as tokenizer_config_file: + tokenizer_config = json.load(tokenizer_config_file) + assert "model_max_length" in tokenizer_config or "max_length" in tokenizer_config, ( + "Models without model_max_length or max_length are not supported." + ) + if "model_max_length" not in tokenizer_config: + max_context = tokenizer_config["max_length"] + elif "max_length" not in tokenizer_config: + max_context = tokenizer_config["model_max_length"] + else: + max_context = min(tokenizer_config["model_max_length"], tokenizer_config["max_length"]) + + tokens_map = load_special_tokens(model_dir) + + tokenizer = Tokenizer.from_file(str(tokenizer_path)) + tokenizer.enable_truncation(max_length=max_context) + if not tokenizer.padding: + tokenizer.enable_padding( + pad_id=config.get("pad_token_id", 0), pad_token=tokenizer_config["pad_token"] + ) + + for token in tokens_map.values(): + if isinstance(token, str): + tokenizer.add_special_tokens([token]) + elif isinstance(token, dict): + tokenizer.add_special_tokens([AddedToken(**token)]) + + special_token_to_id: dict[str, int] = {} + + for token in tokens_map.values(): + if isinstance(token, str): + special_token_to_id[token] = tokenizer.token_to_id(token) + elif isinstance(token, dict): + token_str = token.get("content", "") + special_token_to_id[token_str] = tokenizer.token_to_id(token_str) + + return tokenizer, special_token_to_id + + +def load_preprocessor(model_dir: Path) -> Compose: + preprocessor_config_path = model_dir / "preprocessor_config.json" + if not preprocessor_config_path.exists(): + raise ValueError(f"Could not find preprocessor_config.json in {model_dir}") + + with open(str(preprocessor_config_path)) as preprocessor_config_file: + preprocessor_config = json.load(preprocessor_config_file) + transforms = Compose.from_config(preprocessor_config) + return transforms diff --git a/python/user_packages/Python313/site-packages/fastembed/common/types.py b/python/user_packages/Python313/site-packages/fastembed/common/types.py new file mode 100644 index 0000000000000000000000000000000000000000..80dee021c515f1eecd8fd69dbd0ac057826806dd --- /dev/null +++ b/python/user_packages/Python313/site-packages/fastembed/common/types.py @@ -0,0 +1,27 @@ +from enum import Enum +from pathlib import Path +from typing import Any, TypeAlias + +import numpy as np +from numpy.typing import NDArray +from PIL import Image + + +class Device(str, Enum): + CPU = "cpu" + CUDA = "cuda" + AUTO = "auto" + + +PathInput: TypeAlias = str | Path +ImageInput: TypeAlias = PathInput | Image.Image + +OnnxProvider: TypeAlias = str | tuple[str, dict[Any, Any]] +NumpyArray: TypeAlias = ( + NDArray[np.float64] + | NDArray[np.float32] + | NDArray[np.float16] + | NDArray[np.int8] + | NDArray[np.int64] + | NDArray[np.int32] +) diff --git a/python/user_packages/Python313/site-packages/fastembed/common/utils.py b/python/user_packages/Python313/site-packages/fastembed/common/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..b61a8b9ced0fa4749848c7849f3647f7589f3e0a --- /dev/null +++ b/python/user_packages/Python313/site-packages/fastembed/common/utils.py @@ -0,0 +1,69 @@ +import os +import sys +import re +import tempfile +import unicodedata +from pathlib import Path +from itertools import islice +from typing import Iterable, TypeVar + +import numpy as np +from numpy.typing import NDArray + +from fastembed.common.types import NumpyArray + +T = TypeVar("T") + + +def normalize(input_array: NumpyArray, p: int = 2, dim: int = 1, eps: float = 1e-12) -> NumpyArray: + # Calculate the Lp norm along the specified dimension + norm = np.linalg.norm(input_array, ord=p, axis=dim, keepdims=True) + norm = np.maximum(norm, eps) # Avoid division by zero + normalized_array = input_array / norm + return normalized_array + + +def mean_pooling(input_array: NumpyArray, attention_mask: NDArray[np.int64]) -> NumpyArray: + input_mask_expanded = np.expand_dims(attention_mask, axis=-1).astype(np.int64) + input_mask_expanded = np.tile(input_mask_expanded, (1, 1, input_array.shape[-1])) + sum_embeddings = np.sum(input_array * input_mask_expanded, axis=1) + sum_mask = np.sum(input_mask_expanded, axis=1) + pooled_embeddings = sum_embeddings / np.maximum(sum_mask, 1e-9) + return pooled_embeddings + + +def iter_batch(iterable: Iterable[T], size: int) -> Iterable[list[T]]: + """ + >>> list(iter_batch([1,2,3,4,5], 3)) + [[1, 2, 3], [4, 5]] + """ + source_iter = iter(iterable) + while source_iter: + b = list(islice(source_iter, size)) + if len(b) == 0: + break + yield b + + +def define_cache_dir(cache_dir: str | None = None) -> Path: + """ + Define the cache directory for fastembed + """ + if cache_dir is None: + default_cache_dir = os.path.join(tempfile.gettempdir(), "fastembed_cache") + cache_path = Path(os.getenv("FASTEMBED_CACHE_PATH", default_cache_dir)) + else: + cache_path = Path(cache_dir) + cache_path.mkdir(parents=True, exist_ok=True) + + return cache_path + + +def get_all_punctuation() -> set[str]: + return set( + chr(i) for i in range(sys.maxunicode) if unicodedata.category(chr(i)).startswith("P") + ) + + +def remove_non_alphanumeric(text: str) -> str: + return re.sub(r"[^\w\s]", " ", text, flags=re.UNICODE) diff --git a/python/user_packages/Python313/site-packages/fastembed/image/__init__.py b/python/user_packages/Python313/site-packages/fastembed/image/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..cc4f140b35b9bdfa5dce7812e3a716352f289d82 --- /dev/null +++ b/python/user_packages/Python313/site-packages/fastembed/image/__init__.py @@ -0,0 +1,3 @@ +from fastembed.image.image_embedding import ImageEmbedding + +__all__ = ["ImageEmbedding"] diff --git a/python/user_packages/Python313/site-packages/fastembed/image/__pycache__/__init__.cpython-313.pyc b/python/user_packages/Python313/site-packages/fastembed/image/__pycache__/__init__.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..052659e34cac43e30c5c580e0bf35148b01c8d2e Binary files /dev/null and b/python/user_packages/Python313/site-packages/fastembed/image/__pycache__/__init__.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/fastembed/image/__pycache__/image_embedding.cpython-313.pyc b/python/user_packages/Python313/site-packages/fastembed/image/__pycache__/image_embedding.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..06ed40bd7280239f0ab3badad8a74b0fd18508bf Binary files /dev/null and b/python/user_packages/Python313/site-packages/fastembed/image/__pycache__/image_embedding.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/fastembed/image/__pycache__/image_embedding_base.cpython-313.pyc b/python/user_packages/Python313/site-packages/fastembed/image/__pycache__/image_embedding_base.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9661ae096b9cb5d912221f7f9ecb58ed2d5dd16d Binary files /dev/null and b/python/user_packages/Python313/site-packages/fastembed/image/__pycache__/image_embedding_base.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/fastembed/image/__pycache__/onnx_embedding.cpython-313.pyc b/python/user_packages/Python313/site-packages/fastembed/image/__pycache__/onnx_embedding.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6f0395da2bd6b3eeecd11d1a8e277c3018639b0b Binary files /dev/null and b/python/user_packages/Python313/site-packages/fastembed/image/__pycache__/onnx_embedding.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/fastembed/image/__pycache__/onnx_image_model.cpython-313.pyc b/python/user_packages/Python313/site-packages/fastembed/image/__pycache__/onnx_image_model.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0937c20474ba0400ed5412b8d634e5edc3bc0036 Binary files /dev/null and b/python/user_packages/Python313/site-packages/fastembed/image/__pycache__/onnx_image_model.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/fastembed/image/image_embedding.py b/python/user_packages/Python313/site-packages/fastembed/image/image_embedding.py new file mode 100644 index 0000000000000000000000000000000000000000..a3630345685b3a1238f21adc685e16f7048a6cab --- /dev/null +++ b/python/user_packages/Python313/site-packages/fastembed/image/image_embedding.py @@ -0,0 +1,135 @@ +from typing import Any, Iterable, Sequence, Type +from dataclasses import asdict + +from fastembed.common.types import NumpyArray, Device +from fastembed.common import ImageInput, OnnxProvider +from fastembed.image.image_embedding_base import ImageEmbeddingBase +from fastembed.image.onnx_embedding import OnnxImageEmbedding +from fastembed.common.model_description import DenseModelDescription + + +class ImageEmbedding(ImageEmbeddingBase): + EMBEDDINGS_REGISTRY: list[Type[ImageEmbeddingBase]] = [OnnxImageEmbedding] + + @classmethod + def list_supported_models(cls) -> list[dict[str, Any]]: + """ + Lists the supported models. + + Returns: + list[dict[str, Any]]: A list of dictionaries containing the model information. + + Example: + ``` + [ + { + "model": "Qdrant/clip-ViT-B-32-vision", + "dim": 512, + "description": "CLIP vision encoder based on ViT-B/32", + "license": "mit", + "size_in_GB": 0.33, + "sources": { + "hf": "Qdrant/clip-ViT-B-32-vision", + }, + "model_file": "model.onnx", + } + ] + ``` + """ + return [asdict(model) for model in cls._list_supported_models()] + + @classmethod + def _list_supported_models(cls) -> list[DenseModelDescription]: + result: list[DenseModelDescription] = [] + for embedding in cls.EMBEDDINGS_REGISTRY: + result.extend(embedding._list_supported_models()) + return result + + def __init__( + self, + model_name: str, + cache_dir: str | None = None, + threads: int | None = None, + providers: Sequence[OnnxProvider] | None = None, + cuda: bool | Device = Device.AUTO, + device_ids: list[int] | None = None, + lazy_load: bool = False, + **kwargs: Any, + ): + super().__init__(model_name, cache_dir, threads, **kwargs) + for EMBEDDING_MODEL_TYPE in self.EMBEDDINGS_REGISTRY: + supported_models = EMBEDDING_MODEL_TYPE._list_supported_models() + if any(model_name.lower() == model.model.lower() for model in supported_models): + self.model = EMBEDDING_MODEL_TYPE( + model_name, + cache_dir, + threads=threads, + providers=providers, + cuda=cuda, + device_ids=device_ids, + lazy_load=lazy_load, + **kwargs, + ) + return + + raise ValueError( + f"Model {model_name} is not supported in ImageEmbedding." + "Please check the supported models using `ImageEmbedding.list_supported_models()`" + ) + + @property + def embedding_size(self) -> int: + """Get the embedding size of the current model""" + if self._embedding_size is None: + self._embedding_size = self.get_embedding_size(self.model_name) + return self._embedding_size + + @classmethod + def get_embedding_size(cls, model_name: str) -> int: + """Get the embedding size of the passed model + + Args: + model_name (str): The name of the model to get embedding size for. + + Returns: + int: The size of the embedding. + + Raises: + ValueError: If the model name is not found in the supported models. + """ + descriptions = cls._list_supported_models() + embedding_size: int | None = None + for description in descriptions: + if description.model.lower() == model_name.lower(): + embedding_size = description.dim + break + if embedding_size is None: + model_names = [description.model for description in descriptions] + raise ValueError( + f"Embedding size for model {model_name} was None. " + f"Available model names: {model_names}" + ) + return embedding_size + + def embed( + self, + images: ImageInput | Iterable[ImageInput], + batch_size: int = 16, + parallel: int | None = None, + **kwargs: Any, + ) -> Iterable[NumpyArray]: + """ + Encode a list of images into list of embeddings. + + Args: + images: Iterator of image paths or single image path to embed + batch_size: Batch size for encoding -- higher values will use more memory, but be faster + parallel: + If > 1, data-parallel encoding will be used, recommended for offline encoding of large datasets. + If 0, use all available cores. + If None, don't use data-parallel processing, use default onnxruntime threading instead. + + Returns: + List of embeddings, one per document + """ + yield from self.model.embed(images, batch_size, parallel, **kwargs) diff --git a/python/user_packages/Python313/site-packages/fastembed/image/image_embedding_base.py b/python/user_packages/Python313/site-packages/fastembed/image/image_embedding_base.py new file mode 100644 index 0000000000000000000000000000000000000000..3601d1e57ba4f5d2fe8d98a9cb72bee7c5a371bd --- /dev/null +++ b/python/user_packages/Python313/site-packages/fastembed/image/image_embedding_base.py @@ -0,0 +1,55 @@ +from typing import Iterable, Any + +from fastembed.common.model_description import DenseModelDescription +from fastembed.common.types import NumpyArray +from fastembed.common.model_management import ModelManagement +from fastembed.common.types import ImageInput + + +class ImageEmbeddingBase(ModelManagement[DenseModelDescription]): + def __init__( + self, + model_name: str, + cache_dir: str | None = None, + threads: int | None = None, + **kwargs: Any, + ): + self.model_name = model_name + self.cache_dir = cache_dir + self.threads = threads + self._local_files_only = kwargs.pop("local_files_only", False) + self._embedding_size: int | None = None + + def embed( + self, + images: ImageInput | Iterable[ImageInput], + batch_size: int = 16, + parallel: int | None = None, + **kwargs: Any, + ) -> Iterable[NumpyArray]: + """ + Embeds a list of images into a list of embeddings. + + Args: + images: The list of image paths to preprocess and embed. + batch_size: Batch size for encoding + parallel: + If > 1, data-parallel encoding will be used, recommended for offline encoding of large datasets. + If 0, use all available cores. + If None, don't use data-parallel processing, use default onnxruntime threading instead. + **kwargs: Additional keyword argument to pass to the embed method. + + Yields: + Iterable[NdArray]: The embeddings. + """ + raise NotImplementedError() + + @classmethod + def get_embedding_size(cls, model_name: str) -> int: + """Returns embedding size of the chosen model.""" + raise NotImplementedError("Subclasses must implement this method") + + @property + def embedding_size(self) -> int: + """Returns embedding size for the current model""" + raise NotImplementedError("Subclasses must implement this method") diff --git a/python/user_packages/Python313/site-packages/fastembed/image/onnx_embedding.py b/python/user_packages/Python313/site-packages/fastembed/image/onnx_embedding.py new file mode 100644 index 0000000000000000000000000000000000000000..3e17399510707d59da084e325293a34ca2cc6ae7 --- /dev/null +++ b/python/user_packages/Python313/site-packages/fastembed/image/onnx_embedding.py @@ -0,0 +1,217 @@ +from typing import Any, Iterable, Sequence, Type + + +from fastembed.common.types import NumpyArray, Device +from fastembed.common import ImageInput, OnnxProvider +from fastembed.common.onnx_model import OnnxOutputContext +from fastembed.common.utils import define_cache_dir, normalize +from fastembed.image.image_embedding_base import ImageEmbeddingBase +from fastembed.image.onnx_image_model import ImageEmbeddingWorker, OnnxImageModel + +from fastembed.common.model_description import DenseModelDescription, ModelSource + +supported_onnx_models: list[DenseModelDescription] = [ + DenseModelDescription( + model="Qdrant/clip-ViT-B-32-vision", + dim=512, + description="Image embeddings, Multimodal (text&image), 2021 year", + license="mit", + size_in_GB=0.34, + sources=ModelSource(hf="Qdrant/clip-ViT-B-32-vision"), + model_file="model.onnx", + ), + DenseModelDescription( + model="Qdrant/resnet50-onnx", + dim=2048, + description="Image embeddings, Unimodal (image), 2016 year", + license="apache-2.0", + size_in_GB=0.1, + sources=ModelSource(hf="Qdrant/resnet50-onnx"), + model_file="model.onnx", + ), + DenseModelDescription( + model="Qdrant/Unicom-ViT-B-16", + dim=768, + description="Image embeddings (more detailed than Unicom-ViT-B-32), Multimodal (text&image), 2023 year", + license="apache-2.0", + size_in_GB=0.82, + sources=ModelSource(hf="Qdrant/Unicom-ViT-B-16"), + model_file="model.onnx", + ), + DenseModelDescription( + model="Qdrant/Unicom-ViT-B-32", + dim=512, + description="Image embeddings, Multimodal (text&image), 2023 year", + license="apache-2.0", + size_in_GB=0.48, + sources=ModelSource(hf="Qdrant/Unicom-ViT-B-32"), + model_file="model.onnx", + ), + DenseModelDescription( + model="jinaai/jina-clip-v1", + dim=768, + description="Image embeddings, Multimodal (text&image), 2024 year", + license="apache-2.0", + size_in_GB=0.34, + sources=ModelSource(hf="jinaai/jina-clip-v1"), + model_file="onnx/vision_model.onnx", + ), +] + + +class OnnxImageEmbedding(ImageEmbeddingBase, OnnxImageModel[NumpyArray]): + def __init__( + self, + model_name: str, + + cache_dir: str | None = None, + threads: int | None = None, + providers: Sequence[OnnxProvider] | None = None, + cuda: bool | Device = Device.AUTO, + device_ids: list[int] | None = None, + lazy_load: bool = False, + device_id: int | None = None, + specific_model_path: str | None = None, + **kwargs: Any, + ): + """ + Args: + model_name (str): The name of the model to use. + cache_dir (str, optional): The path to the cache directory. + Can be set using the `FASTEMBED_CACHE_PATH` env variable. + Defaults to `fastembed_cache` in the system's temp directory. + threads (int, optional): The number of threads single onnxruntime session can use. Defaults to None. + providers (Optional[Sequence[OnnxProvider]], optional): The list of onnxruntime providers to use. + Mutually exclusive with the `cuda` and `device_ids` arguments. Defaults to None. + cuda (Union[bool, Device], optional): Whether to use cuda for inference. Mutually exclusive with `providers` + Defaults to Device.AUTO. + device_ids (Optional[list[int]], optional): The list of device ids to use for data parallel processing in + workers. Should be used with `cuda` equals to `True`, `Device.AUTO` or `Device.CUDA`, mutually exclusive + with `providers`. Defaults to None. + lazy_load (bool, optional): Whether to load the model during class initialization or on demand. + Should be set to True when using multiple-gpu and parallel encoding. Defaults to False. + device_id (Optional[int], optional): The device id to use for loading the model in the worker process. + specific_model_path (Optional[str], optional): The specific path to the onnx model dir if it should be imported from somewhere else + + Raises: + ValueError: If the model_name is not in the format / e.g. BAAI/bge-base-en. + """ + + super().__init__(model_name, cache_dir, threads, **kwargs) + self.providers = providers + self.lazy_load = lazy_load + self._extra_session_options = self._select_exposed_session_options(kwargs) + + # List of device ids, that can be used for data parallel processing in workers + self.device_ids = device_ids + self.cuda = cuda + + # This device_id will be used if we need to load model in current process + self.device_id: int | None = None + if device_id is not None: + self.device_id = device_id + elif self.device_ids is not None: + self.device_id = self.device_ids[0] + + self.model_description = self._get_model_description(model_name) + self.cache_dir = str(define_cache_dir(cache_dir)) + self._specific_model_path = specific_model_path + self._model_dir = self.download_model( + self.model_description, + self.cache_dir, + local_files_only=self._local_files_only, + specific_model_path=self._specific_model_path, + ) + + if not self.lazy_load: + self.load_onnx_model() + + def load_onnx_model(self) -> None: + """ + Load the onnx model. + """ + self._load_onnx_model( + model_dir=self._model_dir, + model_file=self.model_description.model_file, + threads=self.threads, + providers=self.providers, + cuda=self.cuda, + device_id=self.device_id, + extra_session_options=self._extra_session_options, + ) + + @classmethod + def _list_supported_models(cls) -> list[DenseModelDescription]: + """ + Lists the supported models. + + Returns: + list[DenseModelDescription]: A list of DenseModelDescription objects containing the model information. + """ + return supported_onnx_models + + def embed( + self, + images: ImageInput | Iterable[ImageInput], + batch_size: int = 16, + parallel: int | None = None, + **kwargs: Any, + ) -> Iterable[NumpyArray]: + """ + Encode a list of images into list of embeddings. + We use mean pooling with attention so that the model can handle variable-length inputs. + + Args: + images: Iterator of image paths or single image path to embed + batch_size: Batch size for encoding -- higher values will use more memory, but be faster + parallel: + If > 1, data-parallel encoding will be used, recommended for offline encoding of large datasets. + If 0, use all available cores. + If None, don't use data-parallel processing, use default onnxruntime threading instead. + + Returns: + List of embeddings, one per document + """ + + yield from self._embed_images( + model_name=self.model_name, + cache_dir=str(self.cache_dir), + images=images, + batch_size=batch_size, + parallel=parallel, + providers=self.providers, + cuda=self.cuda, + device_ids=self.device_ids, + local_files_only=self._local_files_only, + specific_model_path=self._specific_model_path, + extra_session_options=self._extra_session_options, + **kwargs, + ) + + @classmethod + def _get_worker_class(cls) -> Type["ImageEmbeddingWorker[NumpyArray]"]: + return OnnxImageEmbeddingWorker + + def _preprocess_onnx_input( + self, onnx_input: dict[str, NumpyArray], **kwargs: Any + ) -> dict[str, NumpyArray]: + """ + Preprocess the onnx input. + """ + + return onnx_input + + def _post_process_onnx_output( + self, output: OnnxOutputContext, **kwargs: Any + ) -> Iterable[NumpyArray]: + return normalize(output.model_output) + + +class OnnxImageEmbeddingWorker(ImageEmbeddingWorker[NumpyArray]): + def init_embedding(self, model_name: str, cache_dir: str, **kwargs: Any) -> OnnxImageEmbedding: + return OnnxImageEmbedding( + model_name=model_name, + cache_dir=cache_dir, + threads=1, + **kwargs, + ) diff --git a/python/user_packages/Python313/site-packages/fastembed/image/onnx_image_model.py b/python/user_packages/Python313/site-packages/fastembed/image/onnx_image_model.py new file mode 100644 index 0000000000000000000000000000000000000000..deddcf73c999d50d5afbd7c2617cc9dbbe877f05 --- /dev/null +++ b/python/user_packages/Python313/site-packages/fastembed/image/onnx_image_model.py @@ -0,0 +1,156 @@ +import contextlib +import os +from multiprocessing import get_all_start_methods +from pathlib import Path +from typing import Any, Iterable, Sequence, Type + +import numpy as np +from PIL import Image + +from fastembed.image.transform.operators import Compose +from fastembed.common.types import NumpyArray, Device +from fastembed.common import ImageInput, OnnxProvider +from fastembed.common.onnx_model import EmbeddingWorker, OnnxModel, OnnxOutputContext, T +from fastembed.common.preprocessor_utils import load_preprocessor +from fastembed.common.utils import iter_batch +from fastembed.parallel_processor import ParallelWorkerPool + +# Holds type of the embedding result + + +class OnnxImageModel(OnnxModel[T]): + @classmethod + def _get_worker_class(cls) -> Type["ImageEmbeddingWorker[T]"]: + raise NotImplementedError("Subclasses must implement this method") + + def _post_process_onnx_output(self, output: OnnxOutputContext, **kwargs: Any) -> Iterable[T]: + """Post-process the ONNX model output to convert it into a usable format. + + Args: + output (OnnxOutputContext): The raw output from the ONNX model. + **kwargs: Additional keyword arguments that may be needed by specific implementations. + + Returns: + Iterable[T]: Post-processed output as an iterable of type T. + """ + raise NotImplementedError("Subclasses must implement this method") + + def __init__(self) -> None: + super().__init__() + self.processor: Compose | None = None + + def _preprocess_onnx_input( + self, onnx_input: dict[str, NumpyArray], **kwargs: Any + ) -> dict[str, NumpyArray]: + """ + Preprocess the onnx input. + """ + return onnx_input + + def _load_onnx_model( + self, + model_dir: Path, + model_file: str, + threads: int | None, + providers: Sequence[OnnxProvider] | None = None, + cuda: bool | Device = Device.AUTO, + device_id: int | None = None, + extra_session_options: dict[str, Any] | None = None, + ) -> None: + super()._load_onnx_model( + model_dir=model_dir, + model_file=model_file, + threads=threads, + providers=providers, + cuda=cuda, + device_id=device_id, + extra_session_options=extra_session_options, + ) + self.processor = load_preprocessor(model_dir=model_dir) + + def load_onnx_model(self) -> None: + raise NotImplementedError("Subclasses must implement this method") + + def _build_onnx_input(self, encoded: NumpyArray) -> dict[str, NumpyArray]: + input_name = self.model.get_inputs()[0].name # type: ignore[union-attr] + return {input_name: encoded} + + def onnx_embed(self, images: list[ImageInput], **kwargs: Any) -> OnnxOutputContext: + with contextlib.ExitStack() as stack: + image_files = [ + stack.enter_context(Image.open(image)) + if not isinstance(image, Image.Image) + else image + for image in images + ] + assert self.processor is not None, "Processor is not initialized" + encoded = np.array(self.processor(image_files)) + onnx_input = self._build_onnx_input(encoded) + onnx_input = self._preprocess_onnx_input(onnx_input) + model_output = self.model.run(None, onnx_input) # type: ignore[union-attr] + embeddings = model_output[0].reshape(len(images), -1) + return OnnxOutputContext(model_output=embeddings) + + def _embed_images( + self, + model_name: str, + cache_dir: str, + images: ImageInput | Iterable[ImageInput], + batch_size: int = 256, + parallel: int | None = None, + providers: Sequence[OnnxProvider] | None = None, + cuda: bool | Device = Device.AUTO, + device_ids: list[int] | None = None, + local_files_only: bool = False, + specific_model_path: str | None = None, + extra_session_options: dict[str, Any] | None = None, + **kwargs: Any, + ) -> Iterable[T]: + is_small = False + + if isinstance(images, (str, Path, Image.Image)): + images = [images] + is_small = True + + if isinstance(images, list) and len(images) < batch_size: + is_small = True + + if parallel is None or is_small: + if not hasattr(self, "model") or self.model is None: + self.load_onnx_model() + + for batch in iter_batch(images, batch_size): + yield from self._post_process_onnx_output(self.onnx_embed(batch), **kwargs) + else: + if parallel == 0: + parallel = os.cpu_count() + + start_method = "forkserver" if "forkserver" in get_all_start_methods() else "spawn" + params = { + "model_name": model_name, + "cache_dir": cache_dir, + "providers": providers, + "local_files_only": local_files_only, + "specific_model_path": specific_model_path, + **kwargs, + } + + if extra_session_options is not None: + params.update(extra_session_options) + + pool = ParallelWorkerPool( + num_workers=parallel or 1, + worker=self._get_worker_class(), + cuda=cuda, + device_ids=device_ids, + start_method=start_method, + ) + for batch in pool.ordered_map(iter_batch(images, batch_size), **params): + yield from self._post_process_onnx_output(batch, **kwargs) # type: ignore + + +class ImageEmbeddingWorker(EmbeddingWorker[T]): + def process(self, items: Iterable[tuple[int, Any]]) -> Iterable[tuple[int, Any]]: + for idx, batch in items: + embeddings = self.model.onnx_embed(batch) + yield idx, embeddings diff --git a/python/user_packages/Python313/site-packages/fastembed/image/transform/__pycache__/functional.cpython-313.pyc b/python/user_packages/Python313/site-packages/fastembed/image/transform/__pycache__/functional.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..778bca2be8ec1c185a9b9fe51e77587db0bcb1de Binary files /dev/null and b/python/user_packages/Python313/site-packages/fastembed/image/transform/__pycache__/functional.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/fastembed/image/transform/__pycache__/operators.cpython-313.pyc b/python/user_packages/Python313/site-packages/fastembed/image/transform/__pycache__/operators.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8d7c73c21a4fc069857f7637a8245f61107a9af7 Binary files /dev/null and b/python/user_packages/Python313/site-packages/fastembed/image/transform/__pycache__/operators.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/fastembed/image/transform/functional.py b/python/user_packages/Python313/site-packages/fastembed/image/transform/functional.py new file mode 100644 index 0000000000000000000000000000000000000000..9d9e2197e853a34021ea3cefaa5a78b462fe66df --- /dev/null +++ b/python/user_packages/Python313/site-packages/fastembed/image/transform/functional.py @@ -0,0 +1,221 @@ +import numpy as np +from PIL import Image + +from fastembed.common.types import NumpyArray + + +def convert_to_rgb(image: Image.Image) -> Image.Image: + if image.mode == "RGB": + return image + + image = image.convert("RGB") + return image + + +def center_crop( + image: Image.Image | NumpyArray, + size: tuple[int, int], +) -> NumpyArray: + if isinstance(image, np.ndarray): + _, orig_height, orig_width = image.shape + else: + orig_height, orig_width = image.height, image.width + # (H, W, C) -> (C, H, W) + image = np.array(image).transpose((2, 0, 1)) + + crop_height, crop_width = size + + # left upper corner (0, 0) + top = (orig_height - crop_height) // 2 + bottom = top + crop_height + left = (orig_width - crop_width) // 2 + right = left + crop_width + + # Check if cropped area is within image boundaries + if top >= 0 and bottom <= orig_height and left >= 0 and right <= orig_width: + image = image[..., top:bottom, left:right] + return image + + # Padding with zeros + new_height = max(crop_height, orig_height) + new_width = max(crop_width, orig_width) + new_shape = image.shape[:-2] + (new_height, new_width) + new_image = np.zeros_like(image, shape=new_shape, dtype=np.float32) + + top_pad = (new_height - orig_height) // 2 + bottom_pad = top_pad + orig_height + left_pad = (new_width - orig_width) // 2 + right_pad = left_pad + orig_width + new_image[..., top_pad:bottom_pad, left_pad:right_pad] = image + + top += top_pad + bottom += top_pad + left += left_pad + right += left_pad + + new_image = new_image[ + ..., max(0, top) : min(new_height, bottom), max(0, left) : min(new_width, right) + ] + + return new_image + + +def normalize( + image: NumpyArray, + mean: float | list[float], + std: float | list[float], +) -> NumpyArray: + num_channels = image.shape[1] if len(image.shape) == 4 else image.shape[0] + + if not np.issubdtype(image.dtype, np.floating): + image = image.astype(np.float32) + + mean_list = mean if isinstance(mean, list) else [mean] * num_channels + + if len(mean_list) != num_channels: + raise ValueError( + f"mean must have the same number of channels as the image, image has {num_channels} channels, got " + f"{len(mean_list)}" + ) + + mean_arr = np.array(mean_list, dtype=np.float32) + + std_list = std if isinstance(std, list) else [std] * num_channels + if len(std_list) != num_channels: + raise ValueError( + f"std must have the same number of channels as the image, image has {num_channels} channels, got {len(std_list)}" + ) + + std_arr = np.array(std_list, dtype=np.float32) + + image_upd = ((image.T - mean_arr) / std_arr).T + return image_upd + + +def resize( + image: Image.Image, + size: int | tuple[int, int], + resample: int | Image.Resampling = Image.Resampling.BILINEAR, +) -> Image.Image: + if isinstance(size, tuple): + return image.resize(size, resample) + + height, width = image.height, image.width + short, long = (width, height) if width <= height else (height, width) + + new_short, new_long = size, int(size * long / short) + if width <= height: + new_size = (new_short, new_long) + else: + new_size = (new_long, new_short) + return image.resize(new_size, resample) + + +def rescale(image: NumpyArray, scale: float, dtype: type = np.float32) -> NumpyArray: + return (image * scale).astype(dtype) + + +def pil2ndarray(image: Image.Image | NumpyArray) -> NumpyArray: + if isinstance(image, Image.Image): + return np.asarray(image).transpose((2, 0, 1)) + return image + + +def pad2square( + image: Image.Image, + size: int, + fill_color: str | int | tuple[int, ...] = 0, +) -> Image.Image: + height, width = image.height, image.width + + left, right = 0, width + top, bottom = 0, height + + crop_required = False + if width > size: + left = (width - size) // 2 + right = left + size + crop_required = True + + if height > size: + top = (height - size) // 2 + bottom = top + size + crop_required = True + + new_image = Image.new(mode="RGB", size=(size, size), color=fill_color) + new_image.paste(image.crop((left, top, right, bottom)) if crop_required else image) + return new_image + + +def resize_longest_edge( + image: Image.Image, + max_size: int, + resample: int | Image.Resampling = Image.Resampling.LANCZOS, +) -> Image.Image: + height, width = image.height, image.width + aspect_ratio = width / height + + if width >= height: + # Width is longer + new_width = max_size + new_height = int(new_width / aspect_ratio) + else: + # Height is longer + new_height = max_size + new_width = int(new_height * aspect_ratio) + + # Ensure even dimensions + if new_height % 2 != 0: + new_height += 1 + if new_width % 2 != 0: + new_width += 1 + + return image.resize((new_width, new_height), resample) + + +def crop_ndarray( + image: NumpyArray, + x1: int, + y1: int, + x2: int, + y2: int, + channel_first: bool = True, +) -> NumpyArray: + if channel_first: + # (C, H, W) format + return image[:, y1:y2, x1:x2] + else: + # (H, W, C) format + return image[y1:y2, x1:x2, :] + + +def resize_ndarray( + image: NumpyArray, + size: tuple[int, int], + resample: int | Image.Resampling = Image.Resampling.LANCZOS, + channel_first: bool = True, +) -> NumpyArray: + # Convert to PIL-friendly format (H, W, C) + if channel_first: + img_hwc = image.transpose((1, 2, 0)) + else: + img_hwc = image + + # Handle different dtypes + if img_hwc.dtype == np.float32 or img_hwc.dtype == np.float64: + # Assume normalized, scale to 0-255 for PIL + img_hwc_scaled = (img_hwc * 255).astype(np.uint8) + pil_img = Image.fromarray(img_hwc_scaled, mode="RGB") + resized = pil_img.resize(size, resample) + result = np.array(resized).astype(np.float32) / 255.0 + else: + # uint8 or similar + pil_img = Image.fromarray(img_hwc.astype(np.uint8), mode="RGB") + resized = pil_img.resize(size, resample) + result = np.array(resized) + + # Convert back to original format + if channel_first: + result = result.transpose((2, 0, 1)) + + return result diff --git a/python/user_packages/Python313/site-packages/fastembed/image/transform/operators.py b/python/user_packages/Python313/site-packages/fastembed/image/transform/operators.py new file mode 100644 index 0000000000000000000000000000000000000000..e6ba4d95f283576358999473e606ed0a039c29f1 --- /dev/null +++ b/python/user_packages/Python313/site-packages/fastembed/image/transform/operators.py @@ -0,0 +1,499 @@ +from typing import Any +import math + +from PIL import Image + +from fastembed.common.types import NumpyArray +from fastembed.image.transform.functional import ( + center_crop, + convert_to_rgb, + crop_ndarray, + normalize, + pil2ndarray, + rescale, + resize, + resize_longest_edge, + resize_ndarray, + pad2square, +) + + +class Transform: + def __call__(self, images: list[Any]) -> list[Image.Image] | list[NumpyArray]: + raise NotImplementedError("Subclasses must implement this method") + + +class ConvertToRGB(Transform): + def __call__(self, images: list[Image.Image]) -> list[Image.Image]: + return [convert_to_rgb(image=image) for image in images] + + +class CenterCrop(Transform): + def __init__(self, size: tuple[int, int]): + self.size = size + + def __call__(self, images: list[Image.Image]) -> list[NumpyArray]: + return [center_crop(image=image, size=self.size) for image in images] + + +class Normalize(Transform): + def __init__(self, mean: float | list[float], std: float | list[float]): + self.mean = mean + self.std = std + + def __call__( # type: ignore[override] + self, images: list[NumpyArray] | list[list[NumpyArray]] + ) -> list[NumpyArray] | list[list[NumpyArray]]: + if images and isinstance(images[0], list): + # Nested structure from ImageSplitter + return [ + [normalize(image, mean=self.mean, std=self.std) for image in img_patches] # type: ignore[arg-type] + for img_patches in images + ] + else: + # Flat structure (backward compatibility) + return [normalize(image, mean=self.mean, std=self.std) for image in images] # type: ignore[arg-type] + + +class Resize(Transform): + def __init__( + self, + size: int | tuple[int, int], + resample: Image.Resampling = Image.Resampling.BICUBIC, + ): + self.size = size + self.resample = resample + + def __call__(self, images: list[Image.Image]) -> list[Image.Image]: + return [resize(image, size=self.size, resample=self.resample) for image in images] + + +class Rescale(Transform): + def __init__(self, scale: float = 1 / 255): + self.scale = scale + + def __call__( # type: ignore[override] + self, images: list[NumpyArray] | list[list[NumpyArray]] + ) -> list[NumpyArray] | list[list[NumpyArray]]: + if images and isinstance(images[0], list): + # Nested structure from ImageSplitter + return [ + [rescale(image, scale=self.scale) for image in img_patches] # type: ignore[arg-type] + for img_patches in images + ] + else: + # Flat structure (backward compatibility) + return [rescale(image, scale=self.scale) for image in images] # type: ignore[arg-type] + + +class PILtoNDarray(Transform): + def __call__(self, images: list[Image.Image | NumpyArray]) -> list[NumpyArray]: + return [pil2ndarray(image) for image in images] + + +class PadtoSquare(Transform): + def __init__( + self, + size: int, + fill_color: str | int | tuple[int, ...], + ): + self.size = size + self.fill_color = fill_color + + def __call__(self, images: list[Image.Image]) -> list[Image.Image]: + return [ + pad2square(image=image, size=self.size, fill_color=self.fill_color) for image in images + ] + + +class ResizeLongestEdge(Transform): + """Resize images so the longest edge equals target size, preserving aspect ratio.""" + + def __init__( + self, + size: int, + resample: Image.Resampling = Image.Resampling.LANCZOS, + ): + self.size = size + self.resample = resample + + def __call__(self, images: list[Image.Image]) -> list[Image.Image]: + return [resize_longest_edge(image, self.size, self.resample) for image in images] + + +class ResizeForVisionEncoder(Transform): + """ + Resize both dimensions to be multiples of vision_encoder_max_size. + Preserves aspect ratio approximately. + Works on numpy arrays in (C, H, W) format. + """ + + def __init__( + self, + max_size: int, + resample: Image.Resampling = Image.Resampling.LANCZOS, + ): + self.max_size = max_size + self.resample = resample + + def __call__(self, images: list[NumpyArray]) -> list[NumpyArray]: + result = [] + for image in images: + # Assume (C, H, W) format + _, height, width = image.shape + + aspect_ratio = width / height + + if width >= height: + # Calculate new width as multiple of max_size + new_width = math.ceil(width / self.max_size) * self.max_size + new_height = int(new_width / aspect_ratio) + new_height = math.ceil(new_height / self.max_size) * self.max_size + else: + # Calculate new height as multiple of max_size + new_height = math.ceil(height / self.max_size) * self.max_size + new_width = int(new_height * aspect_ratio) + new_width = math.ceil(new_width / self.max_size) * self.max_size + + # Resize using the ndarray resize function + resized = resize_ndarray( + image, + size=(new_width, new_height), # PIL expects (width, height) + resample=self.resample, + channel_first=True, + ) + result.append(resized) + + return result + + +class ImageSplitter(Transform): + """ + Split images into grid of patches plus a global view. + + If image dimensions exceed max_size: + - Divide into ceil(H/max_size) x ceil(W/max_size) patches + - Each patch is cropped from the image + - Add a global view (original resized to max_size x max_size) + + If image is smaller than max_size: + - Return single image unchanged + + Works on numpy arrays in (C, H, W) format. + """ + + def __init__( + self, + max_size: int, + resample: Image.Resampling = Image.Resampling.LANCZOS, + ): + self.max_size = max_size + self.resample = resample + + def __call__(self, images: list[NumpyArray]) -> list[list[NumpyArray]]: # type: ignore[override] + result = [] + + for image in images: + # Assume (C, H, W) format + _, height, width = image.shape + max_height = max_width = self.max_size + + frames = [] + + if height > max_height or width > max_width: + # Calculate the number of splits needed + num_splits_h = math.ceil(height / max_height) + num_splits_w = math.ceil(width / max_width) + + # Calculate optimal patch dimensions + optimal_height = math.ceil(height / num_splits_h) + optimal_width = math.ceil(width / num_splits_w) + + # Generate patches in grid order (row by row) + for r in range(num_splits_h): + for c in range(num_splits_w): + # Calculate crop coordinates + start_x = c * optimal_width + start_y = r * optimal_height + end_x = min(start_x + optimal_width, width) + end_y = min(start_y + optimal_height, height) + + # Crop the patch + cropped = crop_ndarray( + image, x1=start_x, y1=start_y, x2=end_x, y2=end_y, channel_first=True + ) + frames.append(cropped) + + # Add global view (resized to max_size x max_size) + global_view = resize_ndarray( + image, + size=(max_width, max_height), # PIL expects (width, height) + resample=self.resample, + channel_first=True, + ) + frames.append(global_view) + else: + # Image is small enough, no splitting needed + frames.append(image) + + # Append (not extend) to preserve per-image grouping + result.append(frames) + + return result + + +class SquareResize(Transform): + """ + Resize images to square dimensions (max_size x max_size). + Works on numpy arrays in (C, H, W) format. + """ + + def __init__( + self, + size: int, + resample: Image.Resampling = Image.Resampling.LANCZOS, + ): + self.size = size + self.resample = resample + + def __call__(self, images: list[NumpyArray]) -> list[list[NumpyArray]]: # type: ignore[override] + return [ + [ + resize_ndarray( + image, size=(self.size, self.size), resample=self.resample, channel_first=True + ) + ] + for image in images + ] + + +class Compose: + def __init__(self, transforms: list[Transform]): + self.transforms = transforms + + def __call__( + self, images: list[Image.Image] | list[NumpyArray] + ) -> list[NumpyArray] | list[Image.Image]: + for transform in self.transforms: + images = transform(images) + return images + + @classmethod + def from_config(cls, config: dict[str, Any]) -> "Compose": + """Creates processor from a config dict. + Args: + config (dict[str, Any]): Configuration dictionary. + + Valid keys: + - do_resize + - resize_mode + - size + - fill_color + - do_center_crop + - crop_size + - do_rescale + - rescale_factor + - do_normalize + - image_mean + - mean + - image_std + - std + - resample + - interpolation + Valid size keys (nested): + - {"height", "width"} + - {"shortest_edge"} + - {"longest_edge"} + + Returns: + Compose: Image processor. + """ + transforms: list[Transform] = [] + cls._get_convert_to_rgb(transforms, config) + cls._get_resize(transforms, config) + cls._get_pad2square(transforms, config) + cls._get_center_crop(transforms, config) + cls._get_pil2ndarray(transforms, config) + cls._get_image_splitting(transforms, config) + cls._get_rescale(transforms, config) + cls._get_normalize(transforms, config) + return cls(transforms=transforms) + + @staticmethod + def _get_convert_to_rgb(transforms: list[Transform], config: dict[str, Any]) -> None: + transforms.append(ConvertToRGB()) + + @classmethod + def _get_resize(cls, transforms: list[Transform], config: dict[str, Any]) -> None: + mode = config.get("image_processor_type", "CLIPImageProcessor") + if mode in ("CLIPImageProcessor", "SiglipImageProcessor"): + if config.get("do_resize", False): + size = config["size"] + if "shortest_edge" in size: + size = size["shortest_edge"] + elif "height" in size and "width" in size: + size = (size["height"], size["width"]) + else: + raise ValueError( + "Size must contain either 'shortest_edge' or 'height' and 'width'." + ) + transforms.append( + Resize( + size=size, + resample=config.get("resample", Image.Resampling.BICUBIC), + ) + ) + elif mode == "ConvNextFeatureExtractor": + if "size" in config and "shortest_edge" not in config["size"]: + raise ValueError( + f"Size dictionary must contain 'shortest_edge' key. Got {config['size'].keys()}" + ) + shortest_edge = config["size"]["shortest_edge"] + crop_pct = config.get("crop_pct", 0.875) + if shortest_edge < 384: + # maintain same ratio, resizing shortest edge to shortest_edge/crop_pct + resize_shortest_edge = int(shortest_edge / crop_pct) + transforms.append( + Resize( + size=resize_shortest_edge, + resample=config.get("resample", Image.Resampling.BICUBIC), + ) + ) + transforms.append(CenterCrop(size=(shortest_edge, shortest_edge))) + else: + transforms.append( + Resize( + size=(shortest_edge, shortest_edge), + resample=config.get("resample", Image.Resampling.BICUBIC), + ) + ) + elif mode == "JinaCLIPImageProcessor": + interpolation = config.get("interpolation") + if isinstance(interpolation, str): + resample = cls._interpolation_resolver(interpolation) + else: + resample = interpolation or Image.Resampling.BICUBIC + + if "size" in config: + resize_mode = config.get("resize_mode", "shortest") + if resize_mode == "shortest": + transforms.append( + Resize( + size=config["size"], + resample=resample, + ) + ) + elif mode == "Idefics3ImageProcessor": + if config.get("do_resize", False): + size = config.get("size", {}) + if "longest_edge" not in size: + raise ValueError( + "Size dictionary must contain 'longest_edge' key for Idefics3ImageProcessor" + ) + + # Handle resample parameter - can be int enum or PIL.Image.Resampling + resample = config.get("resample", Image.Resampling.LANCZOS) + if isinstance(resample, int): + resample = Image.Resampling(resample) + + transforms.append( + ResizeLongestEdge( + size=size["longest_edge"], + resample=resample, + ) + ) + else: + raise ValueError(f"Preprocessor {mode} is not supported") + + @staticmethod + def _get_center_crop(transforms: list[Transform], config: dict[str, Any]) -> None: + mode = config.get("image_processor_type", "CLIPImageProcessor") + if mode in ("CLIPImageProcessor", "SiglipImageProcessor"): + if config.get("do_center_crop", False): + crop_size_raw = config["crop_size"] + crop_size: tuple[int, int] + if isinstance(crop_size_raw, int): + crop_size = (crop_size_raw, crop_size_raw) + elif isinstance(crop_size_raw, dict): + crop_size = (crop_size_raw["height"], crop_size_raw["width"]) + else: + raise ValueError(f"Invalid crop size: {crop_size_raw}") + transforms.append(CenterCrop(size=crop_size)) + elif mode == "ConvNextFeatureExtractor": + pass + elif mode == "JinaCLIPImageProcessor": + pass + elif mode == "Idefics3ImageProcessor": + pass + else: + raise ValueError(f"Preprocessor {mode} is not supported") + + @staticmethod + def _get_pil2ndarray(transforms: list[Transform], config: dict[str, Any]) -> None: + transforms.append(PILtoNDarray()) + + @classmethod + def _get_image_splitting(cls, transforms: list[Transform], config: dict[str, Any]) -> None: + """ + Add image splitting transforms for Idefics3. + Handles conditional logic: splitting vs square resize. + Must be called AFTER PILtoNDarray. + """ + mode = config.get("image_processor_type", "CLIPImageProcessor") + + if mode == "Idefics3ImageProcessor": + do_splitting = config.get("do_image_splitting", False) + max_size = config.get("max_image_size", {}).get("longest_edge", 512) + resample = config.get("resample", Image.Resampling.LANCZOS) + if isinstance(resample, int): + resample = Image.Resampling(resample) + + if do_splitting: + transforms.append(ResizeForVisionEncoder(max_size, resample)) + transforms.append(ImageSplitter(max_size, resample)) + else: + transforms.append(SquareResize(max_size, resample)) + + @staticmethod + def _get_rescale(transforms: list[Transform], config: dict[str, Any]) -> None: + if config.get("do_rescale", True): + rescale_factor = config.get("rescale_factor", 1 / 255) + transforms.append(Rescale(scale=rescale_factor)) + + @staticmethod + def _get_normalize(transforms: list[Transform], config: dict[str, Any]) -> None: + if config.get("do_normalize", False): + transforms.append(Normalize(mean=config["image_mean"], std=config["image_std"])) + elif "mean" in config and "std" in config: + transforms.append(Normalize(mean=config["mean"], std=config["std"])) + + @staticmethod + def _get_pad2square(transforms: list[Transform], config: dict[str, Any]) -> None: + mode = config.get("image_processor_type", "CLIPImageProcessor") + if mode == "CLIPImageProcessor": + pass + elif mode == "ConvNextFeatureExtractor": + pass + elif mode == "JinaCLIPImageProcessor": + transforms.append( + PadtoSquare( + size=config["size"], + fill_color=config.get("fill_color", 0), + ) + ) + + @staticmethod + def _interpolation_resolver(resample: str | None = None) -> Image.Resampling: + interpolation_map = { + "nearest": Image.Resampling.NEAREST, + "lanczos": Image.Resampling.LANCZOS, + "bilinear": Image.Resampling.BILINEAR, + "bicubic": Image.Resampling.BICUBIC, + "box": Image.Resampling.BOX, + "hamming": Image.Resampling.HAMMING, + } + + if resample and (method := interpolation_map.get(resample.lower())): + return method + + raise ValueError(f"Unknown interpolation method: {resample}") diff --git a/python/user_packages/Python313/site-packages/fastembed/late_interaction/__init__.py b/python/user_packages/Python313/site-packages/fastembed/late_interaction/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..eae5d03547f9d0acb995338270652a6967d0fc07 --- /dev/null +++ b/python/user_packages/Python313/site-packages/fastembed/late_interaction/__init__.py @@ -0,0 +1,5 @@ +from fastembed.late_interaction.late_interaction_text_embedding import ( + LateInteractionTextEmbedding, +) + +__all__ = ["LateInteractionTextEmbedding"] diff --git a/python/user_packages/Python313/site-packages/fastembed/late_interaction/__pycache__/__init__.cpython-313.pyc b/python/user_packages/Python313/site-packages/fastembed/late_interaction/__pycache__/__init__.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..da8033bc59d80bf997929284713b737c8617b1bb Binary files /dev/null and b/python/user_packages/Python313/site-packages/fastembed/late_interaction/__pycache__/__init__.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/fastembed/late_interaction/__pycache__/colbert.cpython-313.pyc b/python/user_packages/Python313/site-packages/fastembed/late_interaction/__pycache__/colbert.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..70f258f689c345e13b5df6a9175cabf1abd93cfc Binary files /dev/null and b/python/user_packages/Python313/site-packages/fastembed/late_interaction/__pycache__/colbert.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/fastembed/late_interaction/__pycache__/jina_colbert.cpython-313.pyc b/python/user_packages/Python313/site-packages/fastembed/late_interaction/__pycache__/jina_colbert.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1b07d49dc52097979cc16fc06c412dfe16430b8f Binary files /dev/null and b/python/user_packages/Python313/site-packages/fastembed/late_interaction/__pycache__/jina_colbert.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/fastembed/late_interaction/__pycache__/late_interaction_embedding_base.cpython-313.pyc b/python/user_packages/Python313/site-packages/fastembed/late_interaction/__pycache__/late_interaction_embedding_base.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8cefec4772991da256b37a939ca8abfe8d6ad227 Binary files /dev/null and b/python/user_packages/Python313/site-packages/fastembed/late_interaction/__pycache__/late_interaction_embedding_base.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/fastembed/late_interaction/__pycache__/late_interaction_text_embedding.cpython-313.pyc b/python/user_packages/Python313/site-packages/fastembed/late_interaction/__pycache__/late_interaction_text_embedding.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4eb9dd532f271e73e95a7128471ddb63cd940da1 Binary files /dev/null and b/python/user_packages/Python313/site-packages/fastembed/late_interaction/__pycache__/late_interaction_text_embedding.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/fastembed/late_interaction/__pycache__/token_embeddings.cpython-313.pyc b/python/user_packages/Python313/site-packages/fastembed/late_interaction/__pycache__/token_embeddings.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..258796cfcdf1c1bc4e2ef3052cecd2415f9c4ad3 Binary files /dev/null and b/python/user_packages/Python313/site-packages/fastembed/late_interaction/__pycache__/token_embeddings.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/fastembed/late_interaction/colbert.py b/python/user_packages/Python313/site-packages/fastembed/late_interaction/colbert.py new file mode 100644 index 0000000000000000000000000000000000000000..b8b92542959ad0a35060d3989aff984c5870610b --- /dev/null +++ b/python/user_packages/Python313/site-packages/fastembed/late_interaction/colbert.py @@ -0,0 +1,301 @@ +import string +from typing import Any, Iterable, Sequence, Type + +import numpy as np +from tokenizers import Encoding, Tokenizer + +from fastembed.common.preprocessor_utils import load_tokenizer +from fastembed.common.types import NumpyArray, Device +from fastembed.common import OnnxProvider +from fastembed.common.onnx_model import OnnxOutputContext +from fastembed.common.utils import define_cache_dir, iter_batch +from fastembed.late_interaction.late_interaction_embedding_base import ( + LateInteractionTextEmbeddingBase, +) +from fastembed.text.onnx_text_model import OnnxTextModel, TextEmbeddingWorker +from fastembed.common.model_description import DenseModelDescription, ModelSource + +supported_colbert_models: list[DenseModelDescription] = [ + DenseModelDescription( + model="colbert-ir/colbertv2.0", + dim=128, + description="Text embeddings, Unimodal (text), English, 512 input tokens truncation, 2023 year", + license="mit", + size_in_GB=0.44, + sources=ModelSource(hf="colbert-ir/colbertv2.0"), + model_file="model.onnx", + ), + DenseModelDescription( + model="answerdotai/answerai-colbert-small-v1", + dim=96, + description="Text embeddings, Unimodal (text), English, 512 input tokens truncation, 2024 year", + license="apache-2.0", + size_in_GB=0.13, + sources=ModelSource(hf="answerdotai/answerai-colbert-small-v1"), + model_file="vespa_colbert.onnx", + ), +] + + +class Colbert(LateInteractionTextEmbeddingBase, OnnxTextModel[NumpyArray]): + QUERY_MARKER_TOKEN_ID = 1 + DOCUMENT_MARKER_TOKEN_ID = 2 + MIN_QUERY_LENGTH = 31 # it's 32, we add one additional special token in the beginning + MASK_TOKEN = "[MASK]" + + def _post_process_onnx_output( + self, output: OnnxOutputContext, is_doc: bool = True, **kwargs: Any + ) -> Iterable[NumpyArray]: + if not is_doc: + for embedding in output.model_output: + yield embedding + else: + if output.input_ids is None or output.attention_mask is None: + raise ValueError( + "input_ids and attention_mask must be provided for document post-processing" + ) + + for i, token_sequence in enumerate(output.input_ids): + for j, token_id in enumerate(token_sequence): # type: ignore + if token_id in self.skip_list or token_id == self.pad_token_id: + output.attention_mask[i, j] = 0 + + output.model_output *= np.expand_dims(output.attention_mask, 2) + norm = np.linalg.norm(output.model_output, ord=2, axis=2, keepdims=True) + norm_clamped = np.maximum(norm, 1e-12) + output.model_output /= norm_clamped + + for embedding, attention_mask in zip(output.model_output, output.attention_mask): + yield embedding[attention_mask == 1] + + def _preprocess_onnx_input( + self, onnx_input: dict[str, NumpyArray], is_doc: bool = True, **kwargs: Any + ) -> dict[str, NumpyArray]: + marker_token = self.DOCUMENT_MARKER_TOKEN_ID if is_doc else self.QUERY_MARKER_TOKEN_ID + onnx_input["input_ids"] = np.insert( + onnx_input["input_ids"].astype(np.int64), 1, marker_token, axis=1 + ) + onnx_input["attention_mask"] = np.insert( + onnx_input["attention_mask"].astype(np.int64), 1, 1, axis=1 + ) + return onnx_input + + def tokenize(self, documents: list[str], is_doc: bool = True, **kwargs: Any) -> list[Encoding]: + return ( + self._tokenize_documents(documents=documents) + if is_doc + else self._tokenize_query(query=next(iter(documents))) + ) + + def _tokenize_query(self, query: str) -> list[Encoding]: + assert self.query_tokenizer is not None + encoded = self.query_tokenizer.encode_batch([query]) + return encoded + + def _tokenize_documents(self, documents: list[str]) -> list[Encoding]: + encoded = self.tokenizer.encode_batch(documents) # type: ignore[union-attr] + return encoded + + def token_count( + self, + texts: str | Iterable[str], + batch_size: int = 1024, + is_doc: bool = True, + include_extension: bool = False, + **kwargs: Any, + ) -> int: + if not hasattr(self, "model") or self.model is None: + self.load_onnx_model() # loads the tokenizer as well + token_num = 0 + texts = [texts] if isinstance(texts, str) else texts + tokenizer = self.tokenizer if is_doc else self.query_tokenizer + assert tokenizer is not None + for batch in iter_batch(texts, batch_size): + for tokens in tokenizer.encode_batch(batch): + if is_doc: + token_num += sum(tokens.attention_mask) + else: + attend_count = sum(tokens.attention_mask) + if include_extension: + token_num += max(attend_count, self.MIN_QUERY_LENGTH) + + else: + token_num += attend_count + if include_extension: + token_num += len( + batch + ) # add 1 for each cls.DOC_MARKER_TOKEN_ID or cls.QUERY_MARKER_TOKEN_ID + + return token_num + + @classmethod + def _list_supported_models(cls) -> list[DenseModelDescription]: + """Lists the supported models. + + Returns: + list[DenseModelDescription]: A list of DenseModelDescription objects containing the model information. + """ + return supported_colbert_models + + def __init__( + self, + model_name: str, + cache_dir: str | None = None, + threads: int | None = None, + providers: Sequence[OnnxProvider] | None = None, + cuda: bool | Device = Device.AUTO, + device_ids: list[int] | None = None, + lazy_load: bool = False, + device_id: int | None = None, + specific_model_path: str | None = None, + **kwargs: Any, + ): + """ + Args: + model_name (str): The name of the model to use. + cache_dir (str, optional): The path to the cache directory. + Can be set using the `FASTEMBED_CACHE_PATH` env variable. + Defaults to `fastembed_cache` in the system's temp directory. + threads (int, optional): The number of threads single onnxruntime session can use. Defaults to None. + providers (Optional[Sequence[OnnxProvider]], optional): The list of onnxruntime providers to use. + Mutually exclusive with the `cuda` and `device_ids` arguments. Defaults to None. + cuda (Union[bool, Device], optional): Whether to use cuda for inference. Mutually exclusive with `providers` + Defaults to Device.AUTO. + device_ids (Optional[list[int]], optional): The list of device ids to use for data parallel processing in + workers. Should be used with `cuda` equals to `True`, `Device.AUTO` or `Device.CUDA`, mutually exclusive + with `providers`. Defaults to None. + lazy_load (bool, optional): Whether to load the model during class initialization or on demand. + Should be set to True when using multiple-gpu and parallel encoding. Defaults to False. + device_id (Optional[int], optional): The device id to use for loading the model in the worker process. + specific_model_path (Optional[str], optional): The specific path to the onnx model dir if it should be imported from somewhere else + + Raises: + ValueError: If the model_name is not in the format / e.g. BAAI/bge-base-en. + """ + + super().__init__(model_name, cache_dir, threads, **kwargs) + self.providers = providers + self.lazy_load = lazy_load + self._extra_session_options = self._select_exposed_session_options(kwargs) + + # List of device ids, that can be used for data parallel processing in workers + self.device_ids = device_ids + self.cuda = cuda + + # This device_id will be used if we need to load model in current process + self.device_id: int | None = None + if device_id is not None: + self.device_id = device_id + elif self.device_ids is not None: + self.device_id = self.device_ids[0] + + self.model_description = self._get_model_description(model_name) + self.cache_dir = str(define_cache_dir(cache_dir)) + + self._specific_model_path = specific_model_path + self._model_dir = self.download_model( + self.model_description, + self.cache_dir, + local_files_only=self._local_files_only, + specific_model_path=self._specific_model_path, + ) + self.mask_token_id: int | None = None + self.pad_token_id: int | None = None + self.skip_list: set[int] = set() + + self.query_tokenizer: Tokenizer | None = None + + if not self.lazy_load: + self.load_onnx_model() + + def load_onnx_model(self) -> None: + self._load_onnx_model( + model_dir=self._model_dir, + model_file=self.model_description.model_file, + threads=self.threads, + providers=self.providers, + cuda=self.cuda, + device_id=self.device_id, + extra_session_options=self._extra_session_options, + ) + self.query_tokenizer, _ = load_tokenizer(model_dir=self._model_dir) + + assert self.tokenizer is not None + self.mask_token_id = self.special_token_to_id[self.MASK_TOKEN] + self.pad_token_id = self.tokenizer.padding["pad_id"] + self.skip_list = { + self.tokenizer.encode(symbol, add_special_tokens=False).ids[0] + for symbol in string.punctuation + } + current_max_length = self.tokenizer.truncation["max_length"] + # ensure not to overflow after adding document-marker + self.tokenizer.enable_truncation(max_length=current_max_length - 1) + self.query_tokenizer.enable_truncation(max_length=current_max_length - 1) + self.query_tokenizer.enable_padding( + pad_token=self.MASK_TOKEN, + pad_id=self.mask_token_id, + length=self.MIN_QUERY_LENGTH, + ) + + def embed( + self, + documents: str | Iterable[str], + batch_size: int = 256, + parallel: int | None = None, + **kwargs: Any, + ) -> Iterable[NumpyArray]: + """ + Encode a list of documents into list of embeddings. + We use mean pooling with attention so that the model can handle variable-length inputs. + + Args: + documents: Iterator of documents or single document to embed + batch_size: Batch size for encoding -- higher values will use more memory, but be faster + parallel: + If > 1, data-parallel encoding will be used, recommended for offline encoding of large datasets. + If 0, use all available cores. + If None, don't use data-parallel processing, use default onnxruntime threading instead. + + Returns: + List of embeddings, one per document + """ + yield from self._embed_documents( + model_name=self.model_name, + cache_dir=str(self.cache_dir), + documents=documents, + batch_size=batch_size, + parallel=parallel, + providers=self.providers, + cuda=self.cuda, + device_ids=self.device_ids, + local_files_only=self._local_files_only, + specific_model_path=self._specific_model_path, + extra_session_options=self._extra_session_options, + **kwargs, + ) + + def query_embed(self, query: str | Iterable[str], **kwargs: Any) -> Iterable[NumpyArray]: + if isinstance(query, str): + query = [query] + + if not hasattr(self, "model") or self.model is None: + self.load_onnx_model() + + for text in query: + yield from self._post_process_onnx_output( + self.onnx_embed([text], is_doc=False), is_doc=False + ) + + @classmethod + def _get_worker_class(cls) -> Type[TextEmbeddingWorker[NumpyArray]]: + return ColbertEmbeddingWorker + + +class ColbertEmbeddingWorker(TextEmbeddingWorker[NumpyArray]): + def init_embedding(self, model_name: str, cache_dir: str, **kwargs: Any) -> Colbert: + return Colbert( + model_name=model_name, + cache_dir=cache_dir, + threads=1, + **kwargs, + ) diff --git a/python/user_packages/Python313/site-packages/fastembed/late_interaction/jina_colbert.py b/python/user_packages/Python313/site-packages/fastembed/late_interaction/jina_colbert.py new file mode 100644 index 0000000000000000000000000000000000000000..3ef89c63c75e6221455e433eba51091d33819545 --- /dev/null +++ b/python/user_packages/Python313/site-packages/fastembed/late_interaction/jina_colbert.py @@ -0,0 +1,58 @@ +from typing import Any, Type + +from fastembed.common.types import NumpyArray +from fastembed.late_interaction.colbert import Colbert, ColbertEmbeddingWorker +from fastembed.common.model_description import DenseModelDescription, ModelSource + +supported_jina_colbert_models: list[DenseModelDescription] = [ + DenseModelDescription( + model="jinaai/jina-colbert-v2", + dim=128, + description="New model that expands capabilities of colbert-v1 with multilingual and context length of 8192, 2024 year", + license="cc-by-nc-4.0", + size_in_GB=2.24, + sources=ModelSource(hf="jinaai/jina-colbert-v2"), + model_file="onnx/model.onnx", + additional_files=["onnx/model.onnx_data"], + ) +] + + +class JinaColbert(Colbert): + QUERY_MARKER_TOKEN_ID = 250002 + DOCUMENT_MARKER_TOKEN_ID = 250003 + MIN_QUERY_LENGTH = 31 # it's 32, we add one additional special token in the beginning + MASK_TOKEN = "" + + @classmethod + def _get_worker_class(cls) -> Type[ColbertEmbeddingWorker]: + return JinaColbertEmbeddingWorker + + @classmethod + def _list_supported_models(cls) -> list[DenseModelDescription]: + """Lists the supported models. + + Returns: + list[DenseModelDescription]: A list of DenseModelDescription objects containing the model information. + """ + return supported_jina_colbert_models + + def _preprocess_onnx_input( + self, onnx_input: dict[str, NumpyArray], is_doc: bool = True, **kwargs: Any + ) -> dict[str, NumpyArray]: + onnx_input = super()._preprocess_onnx_input(onnx_input, is_doc) + + # the attention mask for jina-colbert-v2 is always 1 in queries + if not is_doc: + onnx_input["attention_mask"][:] = 1 + return onnx_input + + +class JinaColbertEmbeddingWorker(ColbertEmbeddingWorker): + def init_embedding(self, model_name: str, cache_dir: str, **kwargs: Any) -> JinaColbert: + return JinaColbert( + model_name=model_name, + cache_dir=cache_dir, + threads=1, + **kwargs, + ) diff --git a/python/user_packages/Python313/site-packages/fastembed/late_interaction/late_interaction_embedding_base.py b/python/user_packages/Python313/site-packages/fastembed/late_interaction/late_interaction_embedding_base.py new file mode 100644 index 0000000000000000000000000000000000000000..1ba7909e5fdfae019eb8a11de59c366788ca1376 --- /dev/null +++ b/python/user_packages/Python313/site-packages/fastembed/late_interaction/late_interaction_embedding_base.py @@ -0,0 +1,80 @@ +from typing import Iterable, Any + +from fastembed.common.model_description import DenseModelDescription +from fastembed.common.types import NumpyArray +from fastembed.common.model_management import ModelManagement + + +class LateInteractionTextEmbeddingBase(ModelManagement[DenseModelDescription]): + def __init__( + self, + model_name: str, + cache_dir: str | None = None, + threads: int | None = None, + **kwargs: Any, + ): + self.model_name = model_name + self.cache_dir = cache_dir + self.threads = threads + self._local_files_only = kwargs.pop("local_files_only", False) + self._embedding_size: int | None = None + + def embed( + self, + documents: str | Iterable[str], + batch_size: int = 256, + parallel: int | None = None, + **kwargs: Any, + ) -> Iterable[NumpyArray]: + raise NotImplementedError() + + def passage_embed(self, texts: Iterable[str], **kwargs: Any) -> Iterable[NumpyArray]: + """ + Embeds a list of text passages into a list of embeddings. + + Args: + texts (Iterable[str]): The list of texts to embed. + **kwargs: Additional keyword argument to pass to the embed method. + + Yields: + Iterable[NdArray]: The embeddings. + """ + + # This is model-specific, so that different models can have specialized implementations + yield from self.embed(texts, **kwargs) + + def query_embed(self, query: str | Iterable[str], **kwargs: Any) -> Iterable[NumpyArray]: + """ + Embeds queries + + Args: + query (Union[str, Iterable[str]]): The query to embed, or an iterable e.g. list of queries. + + Returns: + Iterable[NdArray]: The embeddings. + """ + + # This is model-specific, so that different models can have specialized implementations + if isinstance(query, str): + yield from self.embed([query], **kwargs) + else: + yield from self.embed(query, **kwargs) + + @classmethod + def get_embedding_size(cls, model_name: str) -> int: + """Returns embedding size of the chosen model.""" + raise NotImplementedError("Subclasses must implement this method") + + @property + def embedding_size(self) -> int: + """Returns embedding size for the current model""" + raise NotImplementedError("Subclasses must implement this method") + + def token_count( + self, + texts: str | Iterable[str], + batch_size: int = 1024, + **kwargs: Any, + ) -> int: + """Returns the number of tokens in the texts.""" + raise NotImplementedError("Subclasses must implement this method") diff --git a/python/user_packages/Python313/site-packages/fastembed/late_interaction/late_interaction_text_embedding.py b/python/user_packages/Python313/site-packages/fastembed/late_interaction/late_interaction_text_embedding.py new file mode 100644 index 0000000000000000000000000000000000000000..30c8b70d6efcda5713c6750b92efd684f0613934 --- /dev/null +++ b/python/user_packages/Python313/site-packages/fastembed/late_interaction/late_interaction_text_embedding.py @@ -0,0 +1,180 @@ +from typing import Any, Iterable, Sequence, Type +from dataclasses import asdict + +from fastembed.common.model_description import DenseModelDescription +from fastembed.common.types import NumpyArray, Device +from fastembed.common import OnnxProvider +from fastembed.late_interaction.colbert import Colbert +from fastembed.late_interaction.jina_colbert import JinaColbert +from fastembed.late_interaction.late_interaction_embedding_base import ( + LateInteractionTextEmbeddingBase, +) + + +class LateInteractionTextEmbedding(LateInteractionTextEmbeddingBase): + EMBEDDINGS_REGISTRY: list[Type[LateInteractionTextEmbeddingBase]] = [Colbert, JinaColbert] + + @classmethod + def list_supported_models(cls) -> list[dict[str, Any]]: + """ + Lists the supported models. + + Returns: + list[dict[str, Any]]: A list of dictionaries containing the model information. + + Example: + ``` + [ + { + "model": "colbert-ir/colbertv2.0", + "dim": 128, + "description": "Late interaction model", + "license": "mit", + "size_in_GB": 0.44, + "sources": { + "hf": "colbert-ir/colbertv2.0", + }, + "model_file": "model.onnx", + }, + ] + ``` + """ + return [asdict(model) for model in cls._list_supported_models()] + + @classmethod + def _list_supported_models(cls) -> list[DenseModelDescription]: + result: list[DenseModelDescription] = [] + for embedding in cls.EMBEDDINGS_REGISTRY: + result.extend(embedding._list_supported_models()) + return result + + def __init__( + self, + model_name: str, + cache_dir: str | None = None, + threads: int | None = None, + providers: Sequence[OnnxProvider] | None = None, + cuda: bool | Device = Device.AUTO, + device_ids: list[int] | None = None, + lazy_load: bool = False, + **kwargs: Any, + ): + super().__init__(model_name, cache_dir, threads, **kwargs) + for EMBEDDING_MODEL_TYPE in self.EMBEDDINGS_REGISTRY: + supported_models = EMBEDDING_MODEL_TYPE._list_supported_models() + if any(model_name.lower() == model.model.lower() for model in supported_models): + self.model = EMBEDDING_MODEL_TYPE( + model_name, + cache_dir, + threads=threads, + providers=providers, + cuda=cuda, + device_ids=device_ids, + lazy_load=lazy_load, + **kwargs, + ) + return + + raise ValueError( + f"Model {model_name} is not supported in LateInteractionTextEmbedding." + "Please check the supported models using `LateInteractionTextEmbedding.list_supported_models()`" + ) + + @property + def embedding_size(self) -> int: + """Get the embedding size of the current model""" + if self._embedding_size is None: + self._embedding_size = self.get_embedding_size(self.model_name) + return self._embedding_size + + @classmethod + def get_embedding_size(cls, model_name: str) -> int: + """Get the embedding size of the passed model + + Args: + model_name (str): The name of the model to get embedding size for. + + Returns: + int: The size of the embedding. + + Raises: + ValueError: If the model name is not found in the supported models. + """ + descriptions = cls._list_supported_models() + embedding_size: int | None = None + for description in descriptions: + if description.model.lower() == model_name.lower(): + embedding_size = description.dim + break + if embedding_size is None: + model_names = [description.model for description in descriptions] + raise ValueError( + f"Embedding size for model {model_name} was None. " + f"Available model names: {model_names}" + ) + return embedding_size + + def embed( + self, + documents: str | Iterable[str], + batch_size: int = 256, + parallel: int | None = None, + **kwargs: Any, + ) -> Iterable[NumpyArray]: + """ + Encode a list of documents into list of embeddings. + We use mean pooling with attention so that the model can handle variable-length inputs. + + Args: + documents: Iterator of documents or single document to embed + batch_size: Batch size for encoding -- higher values will use more memory, but be faster + parallel: + If > 1, data-parallel encoding will be used, recommended for offline encoding of large datasets. + If 0, use all available cores. + If None, don't use data-parallel processing, use default onnxruntime threading instead. + + Returns: + List of embeddings, one per document + """ + yield from self.model.embed(documents, batch_size, parallel, **kwargs) + + def query_embed(self, query: str | Iterable[str], **kwargs: Any) -> Iterable[NumpyArray]: + """ + Embeds queries + + Args: + query (Union[str, Iterable[str]]): The query to embed, or an iterable e.g. list of queries. + + Returns: + Iterable[NdArray]: The embeddings. + """ + + # This is model-specific, so that different models can have specialized implementations + yield from self.model.query_embed(query, **kwargs) + + def token_count( + self, + texts: str | Iterable[str], + batch_size: int = 1024, + is_doc: bool = True, + include_extension: bool = False, + **kwargs: Any, + ) -> int: + """Returns the number of tokens in the texts. + + Args: + texts (str | Iterable[str]): The list of texts to embed. + batch_size (int): Batch size for encoding + is_doc (bool): Whether the texts are documents (disable embedding a query with include_mask=True). + include_extension (bool): Turn on to count DOC / QUERY marker tokens, and [MASK] token in query mode. + + Returns: + int: Sum of number of tokens in the texts. + """ + return self.model.token_count( + texts, + batch_size=batch_size, + is_doc=is_doc, + include_extension=include_extension, + **kwargs, + ) diff --git a/python/user_packages/Python313/site-packages/fastembed/late_interaction/token_embeddings.py b/python/user_packages/Python313/site-packages/fastembed/late_interaction/token_embeddings.py new file mode 100644 index 0000000000000000000000000000000000000000..55d3cd94e743a0c48dc33f85d22e682e5275d0e6 --- /dev/null +++ b/python/user_packages/Python313/site-packages/fastembed/late_interaction/token_embeddings.py @@ -0,0 +1,83 @@ +from dataclasses import asdict +from typing import Iterable, Any, Type + +from fastembed.common.model_description import DenseModelDescription, ModelSource +from fastembed.common.onnx_model import OnnxOutputContext +from fastembed.common.types import NumpyArray +from fastembed.late_interaction.late_interaction_embedding_base import ( + LateInteractionTextEmbeddingBase, +) +from fastembed.text.onnx_embedding import OnnxTextEmbedding +from fastembed.text.onnx_text_model import TextEmbeddingWorker + + +supported_token_embeddings_models = [ + DenseModelDescription( + model="jinaai/jina-embeddings-v2-small-en-tokens", + dim=512, + description="Text embeddings, Unimodal (text), English, 8192 input tokens truncation," + " Prefixes for queries/documents: not necessary, 2023 year.", + license="apache-2.0", + size_in_GB=0.12, + sources=ModelSource(hf="xenova/jina-embeddings-v2-small-en"), + model_file="onnx/model.onnx", + ), +] + + +class TokenEmbeddingsModel(OnnxTextEmbedding, LateInteractionTextEmbeddingBase): + @classmethod + def _list_supported_models(cls) -> list[DenseModelDescription]: + """Lists the supported models. + + Returns: + list[DenseModelDescription]: A list of DenseModelDescription objects containing the model information. + """ + return supported_token_embeddings_models + + @classmethod + def list_supported_models(cls) -> list[dict[str, Any]]: + """Lists the supported models. + + Returns: + list[dict[str, Any]]: A list of dictionaries containing the model information. + """ + return [asdict(model) for model in cls._list_supported_models()] + + @classmethod + def _get_worker_class(cls) -> Type[TextEmbeddingWorker[NumpyArray]]: + return TokensEmbeddingWorker + + def _post_process_onnx_output( + self, output: OnnxOutputContext, **kwargs: Any + ) -> Iterable[NumpyArray]: + # Size: (batch_size, sequence_length, hidden_size) + embeddings = output.model_output + # Size: (batch_size, sequence_length) + assert output.attention_mask is not None + masks = output.attention_mask + + # For each document we only select those embeddings that are not masked out + for i in range(embeddings.shape[0]): + yield embeddings[i, masks[i] == 1] + + def embed( + self, + documents: str | Iterable[str], + batch_size: int = 256, + parallel: int | None = None, + **kwargs: Any, + ) -> Iterable[NumpyArray]: + yield from super().embed(documents, batch_size=batch_size, parallel=parallel, **kwargs) + + +class TokensEmbeddingWorker(TextEmbeddingWorker[NumpyArray]): + def init_embedding( + self, model_name: str, cache_dir: str, **kwargs: Any + ) -> TokenEmbeddingsModel: + return TokenEmbeddingsModel( + model_name=model_name, + cache_dir=cache_dir, + threads=1, + **kwargs, + ) diff --git a/python/user_packages/Python313/site-packages/fastembed/late_interaction_multimodal/__init__.py b/python/user_packages/Python313/site-packages/fastembed/late_interaction_multimodal/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..50588cdefbcbdc765fa688a2a3adb4fd4f22bd5d --- /dev/null +++ b/python/user_packages/Python313/site-packages/fastembed/late_interaction_multimodal/__init__.py @@ -0,0 +1,5 @@ +from fastembed.late_interaction_multimodal.late_interaction_multimodal_embedding import ( + LateInteractionMultimodalEmbedding, +) + +__all__ = ["LateInteractionMultimodalEmbedding"] diff --git a/python/user_packages/Python313/site-packages/fastembed/late_interaction_multimodal/__pycache__/__init__.cpython-313.pyc b/python/user_packages/Python313/site-packages/fastembed/late_interaction_multimodal/__pycache__/__init__.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a9760a0bdca9158a1cde35b4d413591b572b2156 Binary files /dev/null and b/python/user_packages/Python313/site-packages/fastembed/late_interaction_multimodal/__pycache__/__init__.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/fastembed/late_interaction_multimodal/__pycache__/colmodernvbert.cpython-313.pyc b/python/user_packages/Python313/site-packages/fastembed/late_interaction_multimodal/__pycache__/colmodernvbert.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..275a832a9f0c14632b628a0f52fdb1abdba03b1e Binary files /dev/null and b/python/user_packages/Python313/site-packages/fastembed/late_interaction_multimodal/__pycache__/colmodernvbert.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/fastembed/late_interaction_multimodal/__pycache__/colpali.cpython-313.pyc b/python/user_packages/Python313/site-packages/fastembed/late_interaction_multimodal/__pycache__/colpali.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1fa65cd9322beddb108a70cfc7a65b62bc856801 Binary files /dev/null and b/python/user_packages/Python313/site-packages/fastembed/late_interaction_multimodal/__pycache__/colpali.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/fastembed/late_interaction_multimodal/__pycache__/late_interaction_multimodal_embedding.cpython-313.pyc b/python/user_packages/Python313/site-packages/fastembed/late_interaction_multimodal/__pycache__/late_interaction_multimodal_embedding.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..fb9968670fe79a7db30c9480ebf2e45bfcece49b Binary files /dev/null and b/python/user_packages/Python313/site-packages/fastembed/late_interaction_multimodal/__pycache__/late_interaction_multimodal_embedding.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/fastembed/late_interaction_multimodal/__pycache__/late_interaction_multimodal_embedding_base.cpython-313.pyc b/python/user_packages/Python313/site-packages/fastembed/late_interaction_multimodal/__pycache__/late_interaction_multimodal_embedding_base.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..43de20c1d1518bcf4545e320400794e54f88d924 Binary files /dev/null and b/python/user_packages/Python313/site-packages/fastembed/late_interaction_multimodal/__pycache__/late_interaction_multimodal_embedding_base.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/fastembed/late_interaction_multimodal/__pycache__/onnx_multimodal_model.cpython-313.pyc b/python/user_packages/Python313/site-packages/fastembed/late_interaction_multimodal/__pycache__/onnx_multimodal_model.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ace77e6c7f42e824fa070727f17bc29da4d33894 Binary files /dev/null and b/python/user_packages/Python313/site-packages/fastembed/late_interaction_multimodal/__pycache__/onnx_multimodal_model.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/fastembed/late_interaction_multimodal/colmodernvbert.py b/python/user_packages/Python313/site-packages/fastembed/late_interaction_multimodal/colmodernvbert.py new file mode 100644 index 0000000000000000000000000000000000000000..20b8e4f7bc0cecd2727336b8dca16e53ec7a2f17 --- /dev/null +++ b/python/user_packages/Python313/site-packages/fastembed/late_interaction_multimodal/colmodernvbert.py @@ -0,0 +1,532 @@ +import contextlib +from typing import Any, Iterable, Type, Optional, Sequence +import json + +import numpy as np +from tokenizers import Encoding +from PIL import Image + +from fastembed.common import ImageInput +from fastembed.common.model_description import DenseModelDescription, ModelSource +from fastembed.common.onnx_model import OnnxOutputContext +from fastembed.common.types import NumpyArray, OnnxProvider +from fastembed.common.utils import define_cache_dir, iter_batch +from fastembed.late_interaction_multimodal.late_interaction_multimodal_embedding_base import ( + LateInteractionMultimodalEmbeddingBase, +) +from fastembed.late_interaction_multimodal.onnx_multimodal_model import ( + OnnxMultimodalModel, + TextEmbeddingWorker, + ImageEmbeddingWorker, +) + +supported_colmodernvbert_models: list[DenseModelDescription] = [ + DenseModelDescription( + model="Qdrant/colmodernvbert", + dim=128, + description="The late-interaction version of ModernVBERT, CPU friendly, English, 2025.", + license="mit", + size_in_GB=1.0, + sources=ModelSource(hf="Qdrant/colmodernvbert"), + additional_files=["processor_config.json"], + model_file="model.onnx", + ), +] + + +class ColModernVBERT(LateInteractionMultimodalEmbeddingBase, OnnxMultimodalModel[NumpyArray]): + """ + The ModernVBERT/colmodernvbert model implementation. This model uses + bidirectional attention, which proves to work better for retrieval. + + See: https://huggingface.co/ModernVBERT/colmodernvbert + """ + + VISUAL_PROMPT_PREFIX = ( + "<|begin_of_text|>User:Describe the image.\nAssistant:" + ) + QUERY_AUGMENTATION_TOKEN = "" + + def __init__( + self, + model_name: str, + cache_dir: Optional[str] = None, + threads: Optional[int] = None, + providers: Optional[Sequence[OnnxProvider]] = None, + cuda: bool = False, + device_ids: Optional[list[int]] = None, + lazy_load: bool = False, + device_id: Optional[int] = None, + specific_model_path: Optional[str] = None, + **kwargs: Any, + ): + """ + Args: + model_name (str): The name of the model to use. + cache_dir (str, optional): The path to the cache directory. + Can be set using the `FASTEMBED_CACHE_PATH` env variable. + Defaults to `fastembed_cache` in the system's temp directory. + threads (int, optional): The number of threads single onnxruntime session can use. Defaults to None. + providers (Optional[Sequence[OnnxProvider]], optional): The list of onnxruntime providers to use. + Mutually exclusive with the `cuda` and `device_ids` arguments. Defaults to None. + cuda (bool, optional): Whether to use cuda for inference. Mutually exclusive with `providers` + Defaults to False. + device_ids (Optional[list[int]], optional): The list of device ids to use for data parallel processing in + workers. Should be used with `cuda=True`, mutually exclusive with `providers`. Defaults to None. + lazy_load (bool, optional): Whether to load the model during class initialization or on demand. + Should be set to True when using multiple-gpu and parallel encoding. Defaults to False. + device_id (Optional[int], optional): The device id to use for loading the model in the worker process. + + Raises: + ValueError: If the model_name is not in the format / e.g. BAAI/bge-base-en. + """ + super().__init__(model_name, cache_dir, threads, **kwargs) + self.providers = providers + self.lazy_load = lazy_load + self._extra_session_options = self._select_exposed_session_options(kwargs) + + # List of device ids, that can be used for data parallel processing in workers + self.device_ids = device_ids + self.cuda = cuda + + # This device_id will be used if we need to load model in current process + self.device_id: Optional[int] = None + if device_id is not None: + self.device_id = device_id + elif self.device_ids is not None: + self.device_id = self.device_ids[0] + + self.model_description = self._get_model_description(model_name) + self.cache_dir = str(define_cache_dir(cache_dir)) + + self._specific_model_path = specific_model_path + self._model_dir = self.download_model( + self.model_description, + self.cache_dir, + local_files_only=self._local_files_only, + specific_model_path=self._specific_model_path, + ) + self.mask_token_id = None + self.pad_token_id = None + self.image_seq_len: Optional[int] = None + self.max_image_size: Optional[int] = None + self.image_size: Optional[int] = None + + if not self.lazy_load: + self.load_onnx_model() + + @classmethod + def _list_supported_models(cls) -> list[DenseModelDescription]: + """Lists the supported models. + + Returns: + list[DenseModelDescription]: A list of DenseModelDescription objects containing the model information. + """ + return supported_colmodernvbert_models + + def load_onnx_model(self) -> None: + self._load_onnx_model( + model_dir=self._model_dir, + model_file=self.model_description.model_file, + threads=self.threads, + providers=self.providers, + cuda=self.cuda, + device_id=self.device_id, + extra_session_options=self._extra_session_options, + ) + + # Load image processing configuration + processor_config_path = self._model_dir / "processor_config.json" + with open(processor_config_path) as f: + processor_config = json.load(f) + self.image_seq_len = processor_config.get("image_seq_len", 64) + + preprocessor_config_path = self._model_dir / "preprocessor_config.json" + with open(preprocessor_config_path) as f: + preprocessor_config = json.load(f) + self.max_image_size = preprocessor_config.get("max_image_size", {}).get( + "longest_edge", 512 + ) + + # Load model configuration + config_path = self._model_dir / "config.json" + with open(config_path) as f: + model_config = json.load(f) + vision_config = model_config.get("vision_config", {}) + self.image_size = vision_config.get("image_size", 512) + + def _preprocess_onnx_text_input( + self, onnx_input: dict[str, NumpyArray], **kwargs: Any + ) -> dict[str, NumpyArray]: + """ + Post-process the ONNX model output to convert it into a usable format. + + Args: + output (OnnxOutputContext): The raw output from the ONNX model. + + Returns: + Iterable[NumpyArray]: Post-processed output as NumPy arrays. + """ + batch_size, seq_length = onnx_input["input_ids"].shape + empty_image_placeholder: NumpyArray = np.zeros( + (batch_size, seq_length, 3, self.image_size, self.image_size), + dtype=np.float32, # type: ignore[type-var,arg-type,assignment] + ) + onnx_input["pixel_values"] = empty_image_placeholder + return onnx_input + + def _post_process_onnx_text_output( + self, + output: OnnxOutputContext, + ) -> Iterable[NumpyArray]: + """ + Post-process the ONNX model output to convert it into a usable format. + + Args: + output (OnnxOutputContext): The raw output from the ONNX model. + + Returns: + Iterable[NumpyArray]: Post-processed output as NumPy arrays. + """ + return output.model_output + + def tokenize(self, documents: list[str], **kwargs: Any) -> list[Encoding]: + # Add query augmentation tokens (matching process_queries logic from colpali-engine) + augmented_queries = [doc + self.QUERY_AUGMENTATION_TOKEN * 10 for doc in documents] + encoded = self.tokenizer.encode_batch(augmented_queries) # type: ignore[union-attr] + return encoded + + def token_count( + self, + texts: str | Iterable[str], + batch_size: int = 1024, + include_extension: bool = False, + **kwargs: Any, + ) -> int: + if not hasattr(self, "model") or self.model is None: + self.load_onnx_model() # loads the tokenizer as well + token_num = 0 + texts = [texts] if isinstance(texts, str) else texts + assert self.tokenizer is not None + tokenize_func = self.tokenize if include_extension else self.tokenizer.encode_batch + for batch in iter_batch(texts, batch_size): + token_num += sum([sum(encoding.attention_mask) for encoding in tokenize_func(batch)]) + return token_num + + def onnx_embed_image(self, images: list[ImageInput], **kwargs: Any) -> OnnxOutputContext: + with contextlib.ExitStack() as stack: + image_files = [ + stack.enter_context(Image.open(image)) + if not isinstance(image, Image.Image) + else image + for image in images + ] + assert self.processor is not None, "Processor is not initialized" + processed = self.processor(image_files) + encoded, attention_mask, metadata = self._process_nested_patches(processed) # type: ignore[arg-type] + + onnx_input = {"pixel_values": encoded, "attention_mask": attention_mask} + onnx_input = self._preprocess_onnx_image_input(onnx_input, **kwargs) + model_output = self.model.run(None, onnx_input) # type: ignore[union-attr] + + return OnnxOutputContext( + model_output=model_output[0], + attention_mask=attention_mask, # type: ignore[arg-type] + metadata=metadata, + ) + + @staticmethod + def _process_nested_patches( + processed: list[list[NumpyArray]], + ) -> tuple[NumpyArray, NumpyArray, dict[str, Any]]: + """ + Process nested image patches (from ImageSplitter). + + Args: + processed: List of patch lists, one per image [[img1_patches], [img2_patches], ...] + + Returns: + tuple: (encoded array, attention_mask, metadata) + - encoded: (batch_size, max_patches, C, H, W) + - attention_mask: (batch_size, max_patches) with 1 for real patches, 0 for padding + - metadata: Dict with 'patch_counts' key + """ + patch_counts = [len(patches) for patches in processed] + max_patches = max(patch_counts) + + # Get dimensions from first patch + channels, height, width = processed[0][0].shape + batch_size = len(processed) + + # Create padded array + encoded = np.zeros( + (batch_size, max_patches, channels, height, width), dtype=processed[0][0].dtype + ) + + # Create attention mask (1 for real patches, 0 for padding) + attention_mask = np.zeros((batch_size, max_patches), dtype=np.int64) + + # Fill in patches and attention mask + for i, patches in enumerate(processed): + for j, patch in enumerate(patches): + encoded[i, j] = patch + attention_mask[i, j] = 1 + + metadata = {"patch_counts": patch_counts} + return encoded, attention_mask, metadata # type: ignore[return-value] + + def _preprocess_onnx_image_input( + self, onnx_input: dict[str, np.ndarray], **kwargs: Any + ) -> dict[str, NumpyArray]: + """ + Add text input placeholders for image data, following Idefics3 processing logic. + + Constructs input_ids dynamically based on the actual number of image patches, + using the same token expansion logic as Idefics3Processor. + + Args: + onnx_input: Dict with 'pixel_values' (batch, num_patches, C, H, W) + and 'attention_mask' (batch, num_patches) indicating real patches + **kwargs: Additional arguments + + Returns: + Updated onnx_input with 'input_ids' and updated 'attention_mask' for token sequence + """ + # The attention_mask in onnx_input has a shape of (batch_size, num_patches), + # and should be used to create an attention mask matching the input_ids shape. + patch_attention_mask = onnx_input["attention_mask"] + pixel_values = onnx_input["pixel_values"] + + batch_size = pixel_values.shape[0] + batch_input_ids = [] + + # Build input_ids for each image based on its actual patch count + for i in range(batch_size): + # Count real patches (non-padded) from attention mask + patch_count = int(np.sum(patch_attention_mask[i])) + + # Compute rows/cols from patch count + rows, cols = self._compute_rows_cols_from_patches(patch_count) + + # Build input_ids for this image + input_ids = self._build_input_ids_for_image(rows, cols) + batch_input_ids.append(input_ids) + + # Pad sequences to max length in batch + max_len = max(len(ids) for ids in batch_input_ids) + + # Get padding config from tokenizer + padding_direction = self.tokenizer.padding["direction"] # type: ignore[index,union-attr] + pad_token_id = self.tokenizer.padding["pad_id"] # type: ignore[index,union-attr] + + # Initialize with pad token + padded_input_ids = np.full((batch_size, max_len), pad_token_id, dtype=np.int64) + attention_mask = np.zeros((batch_size, max_len), dtype=np.int64) + + for i, input_ids in enumerate(batch_input_ids): + seq_len = len(input_ids) + if padding_direction == "left": + # Left padding: place tokens at the END of the array + start_idx = max_len - seq_len + padded_input_ids[i, start_idx:] = input_ids + attention_mask[i, start_idx:] = 1 + else: + # Right padding: place tokens at the START of the array + padded_input_ids[i, :seq_len] = input_ids + attention_mask[i, :seq_len] = 1 + + onnx_input["input_ids"] = padded_input_ids + # Update attention_mask with token-level data + onnx_input["attention_mask"] = attention_mask + return onnx_input + + @staticmethod + def _compute_rows_cols_from_patches(patch_count: int) -> tuple[int, int]: + if patch_count <= 1: + return 0, 0 + + # Subtract 1 for the global image + grid_patches = patch_count - 1 + + # Find rows and cols (assume square or near-square grid) + rows = int(grid_patches**0.5) + cols = grid_patches // rows + + # Verify the calculation + if rows * cols + 1 != patch_count: + # Handle non-square grids + for r in range(1, grid_patches + 1): + if grid_patches % r == 0: + c = grid_patches // r + if r * c + 1 == patch_count: + return r, c + # Fallback: treat as unsplit + return 0, 0 + + return rows, cols + + def _create_single_image_prompt_string(self) -> str: + return ( + "" + + "" + + "" * self.image_seq_len # type: ignore[operator] + + "" + ) + + def _create_split_image_prompt_string(self, rows: int, cols: int) -> str: + text_split_images = "" + + # Add tokens for each patch in the grid + for n_h in range(rows): + for n_w in range(cols): + text_split_images += ( + "" + + f"" + + "" * self.image_seq_len # type: ignore[operator] + ) + text_split_images += "\n" + + # Add global image at the end + text_split_images += ( + "\n" + + "" + + "" * self.image_seq_len # type: ignore[operator] + + "" + ) + + return text_split_images + + def _build_input_ids_for_image(self, rows: int, cols: int) -> np.ndarray: + # Create the appropriate image prompt string + if rows == 0 and cols == 0: + image_prompt_tokens = self._create_single_image_prompt_string() + else: + image_prompt_tokens = self._create_split_image_prompt_string(rows, cols) + + # Replace in visual prompt with expanded tokens + # The visual prompt is: "<|begin_of_text|>User:Describe the image.\nAssistant:" + expanded_prompt = self.VISUAL_PROMPT_PREFIX.replace("", image_prompt_tokens) + + # Tokenize the complete prompt + encoded = self.tokenizer.encode(expanded_prompt) # type: ignore[union-attr] + + # Convert to numpy array + return np.array(encoded.ids, dtype=np.int64) + + def _post_process_onnx_image_output( + self, + output: OnnxOutputContext, + ) -> Iterable[NumpyArray]: + """ + Post-process the ONNX model output to convert it into a usable format. + + Args: + output (OnnxOutputContext): The raw output from the ONNX model. + + Returns: + Iterable[NumpyArray]: Post-processed output as NumPy arrays. + """ + assert self.model_description.dim is not None, "Model dim is not defined" + return output.model_output.reshape( + output.model_output.shape[0], -1, self.model_description.dim + ) + + def embed_text( + self, + documents: str | Iterable[str], + batch_size: int = 256, + parallel: Optional[int] = None, + **kwargs: Any, + ) -> Iterable[NumpyArray]: + """ + Encode a list of documents into list of embeddings. + + Args: + documents: Iterator of documents or single document to embed + batch_size: Batch size for encoding -- higher values will use more memory, but be faster + parallel: + If > 1, data-parallel encoding will be used, recommended for offline encoding of large datasets. + If 0, use all available cores. + If None, don't use data-parallel processing, use default onnxruntime threading instead. + + Returns: + List of embeddings, one per document + """ + yield from self._embed_documents( + model_name=self.model_name, + cache_dir=str(self.cache_dir), + documents=documents, + batch_size=batch_size, + parallel=parallel, + providers=self.providers, + cuda=self.cuda, + device_ids=self.device_ids, + local_files_only=self._local_files_only, + specific_model_path=self._specific_model_path, + extra_session_options=self._extra_session_options, + **kwargs, + ) + + def embed_image( + self, + images: ImageInput | Iterable[ImageInput], + batch_size: int = 16, + parallel: Optional[int] = None, + **kwargs: Any, + ) -> Iterable[NumpyArray]: + """ + Encode a list of images into list of embeddings. + + Args: + images: Iterator of image paths or single image path to embed + batch_size: Batch size for encoding -- higher values will use more memory, but be faster + parallel: + If > 1, data-parallel encoding will be used, recommended for offline encoding of large datasets. + If 0, use all available cores. + If None, don't use data-parallel processing, use default onnxruntime threading instead. + + Returns: + List of embeddings, one per document + """ + yield from self._embed_images( + model_name=self.model_name, + cache_dir=str(self.cache_dir), + images=images, + batch_size=batch_size, + parallel=parallel, + providers=self.providers, + cuda=self.cuda, + device_ids=self.device_ids, + local_files_only=self._local_files_only, + specific_model_path=self._specific_model_path, + extra_session_options=self._extra_session_options, + **kwargs, + ) + + @classmethod + def _get_text_worker_class(cls) -> Type[TextEmbeddingWorker[NumpyArray]]: + return ColModernVBERTTextEmbeddingWorker + + @classmethod + def _get_image_worker_class(cls) -> Type[ImageEmbeddingWorker[NumpyArray]]: + return ColModernVBERTImageEmbeddingWorker + + +class ColModernVBERTTextEmbeddingWorker(TextEmbeddingWorker[NumpyArray]): + def init_embedding(self, model_name: str, cache_dir: str, **kwargs: Any) -> ColModernVBERT: + return ColModernVBERT( + model_name=model_name, + cache_dir=cache_dir, + threads=1, + **kwargs, + ) + + +class ColModernVBERTImageEmbeddingWorker(ImageEmbeddingWorker[NumpyArray]): + def init_embedding(self, model_name: str, cache_dir: str, **kwargs: Any) -> ColModernVBERT: + return ColModernVBERT( + model_name=model_name, + cache_dir=cache_dir, + threads=1, + **kwargs, + ) diff --git a/python/user_packages/Python313/site-packages/fastembed/late_interaction_multimodal/colpali.py b/python/user_packages/Python313/site-packages/fastembed/late_interaction_multimodal/colpali.py new file mode 100644 index 0000000000000000000000000000000000000000..85fbcd06bf04cfa1cf8abc0e64e53053af809c0a --- /dev/null +++ b/python/user_packages/Python313/site-packages/fastembed/late_interaction_multimodal/colpali.py @@ -0,0 +1,327 @@ +from typing import Any, Iterable, Sequence, Type + +import numpy as np +from tokenizers import Encoding + +from fastembed.common import OnnxProvider, ImageInput +from fastembed.common.onnx_model import OnnxOutputContext +from fastembed.common.types import NumpyArray, Device +from fastembed.common.utils import define_cache_dir, iter_batch +from fastembed.late_interaction_multimodal.late_interaction_multimodal_embedding_base import ( + LateInteractionMultimodalEmbeddingBase, +) +from fastembed.late_interaction_multimodal.onnx_multimodal_model import ( + OnnxMultimodalModel, + TextEmbeddingWorker, + ImageEmbeddingWorker, +) +from fastembed.common.model_description import DenseModelDescription, ModelSource + +supported_colpali_models: list[DenseModelDescription] = [ + DenseModelDescription( + model="Qdrant/colpali-v1.3-fp16", + dim=128, + description="Text embeddings, Multimodal (text&image), English, 50 tokens query length truncation, 2024.", + license="mit", + size_in_GB=6.5, + sources=ModelSource(hf="Qdrant/colpali-v1.3-fp16"), + additional_files=["model.onnx_data"], + model_file="model.onnx", + ), +] + + +class ColPali(LateInteractionMultimodalEmbeddingBase, OnnxMultimodalModel[NumpyArray]): + QUERY_PREFIX = "Query: " + BOS_TOKEN = "" + PAD_TOKEN = "" + QUERY_MARKER_TOKEN_ID = [2, 5098] + IMAGE_PLACEHOLDER_SIZE = (3, 448, 448) + EMPTY_TEXT_PLACEHOLDER = np.array( + [257152] * 1024 + [2, 50721, 573, 2416, 235265, 108] + ) # This is a tokenization of '' * 1024 + 'Describe the image.\n' line which is used as placeholder + # while processing an image + EVEN_ATTENTION_MASK = np.array([1] * 1030) + + def __init__( + self, + model_name: str, + cache_dir: str | None = None, + threads: int | None = None, + providers: Sequence[OnnxProvider] | None = None, + cuda: bool | Device = Device.AUTO, + device_ids: list[int] | None = None, + lazy_load: bool = False, + device_id: int | None = None, + specific_model_path: str | None = None, + **kwargs: Any, + ): + """ + Args: + model_name (str): The name of the model to use. + cache_dir (str, optional): The path to the cache directory. + Can be set using the `FASTEMBED_CACHE_PATH` env variable. + Defaults to `fastembed_cache` in the system's temp directory. + threads (int, optional): The number of threads single onnxruntime session can use. Defaults to None. + providers (Optional[Sequence[OnnxProvider]], optional): The list of onnxruntime providers to use. + Mutually exclusive with the `cuda` and `device_ids` arguments. Defaults to None. + cuda (Union[bool, Device], optional): Whether to use cuda for inference. Mutually exclusive with `providers` + Defaults to Device.AUTO. + device_ids (Optional[list[int]], optional): The list of device ids to use for data parallel processing in + workers. Should be used with `cuda` equals to `True`, `Device.AUTO` or `Device.CUDA`, mutually exclusive + with `providers`. Defaults to None. + lazy_load (bool, optional): Whether to load the model during class initialization or on demand. + Should be set to True when using multiple-gpu and parallel encoding. Defaults to False. + device_id (Optional[int], optional): The device id to use for loading the model in the worker process. + + Raises: + ValueError: If the model_name is not in the format / e.g. BAAI/bge-base-en. + """ + + super().__init__(model_name, cache_dir, threads, **kwargs) + self.providers = providers + self.lazy_load = lazy_load + self._extra_session_options = self._select_exposed_session_options(kwargs) + + # List of device ids, that can be used for data parallel processing in workers + self.device_ids = device_ids + self.cuda = cuda + + # This device_id will be used if we need to load model in current process + self.device_id: int | None = None + if device_id is not None: + self.device_id = device_id + elif self.device_ids is not None: + self.device_id = self.device_ids[0] + + self.model_description = self._get_model_description(model_name) + self.cache_dir = str(define_cache_dir(cache_dir)) + + self._specific_model_path = specific_model_path + self._model_dir = self.download_model( + self.model_description, + self.cache_dir, + local_files_only=self._local_files_only, + specific_model_path=self._specific_model_path, + ) + self.mask_token_id = None + self.pad_token_id = None + + if not self.lazy_load: + self.load_onnx_model() + + @classmethod + def _list_supported_models(cls) -> list[DenseModelDescription]: + """Lists the supported models. + + Returns: + list[DenseModelDescription]: A list of DenseModelDescription objects containing the model information. + """ + return supported_colpali_models + + def load_onnx_model(self) -> None: + self._load_onnx_model( + model_dir=self._model_dir, + model_file=self.model_description.model_file, + threads=self.threads, + providers=self.providers, + cuda=self.cuda, + device_id=self.device_id, + extra_session_options=self._extra_session_options, + ) + + def _post_process_onnx_image_output( + self, + output: OnnxOutputContext, + ) -> Iterable[NumpyArray]: + """ + Post-process the ONNX model output to convert it into a usable format. + + Args: + output (OnnxOutputContext): The raw output from the ONNX model. + + Returns: + Iterable[NumpyArray]: Post-processed output as NumPy arrays. + """ + assert self.model_description.dim is not None, "Model dim is not defined" + return output.model_output.reshape( + output.model_output.shape[0], -1, self.model_description.dim + ) + + def _post_process_onnx_text_output( + self, + output: OnnxOutputContext, + ) -> Iterable[NumpyArray]: + """ + Post-process the ONNX model output to convert it into a usable format. + + Args: + output (OnnxOutputContext): The raw output from the ONNX model. + + Returns: + Iterable[NumpyArray]: Post-processed output as NumPy arrays. + """ + return output.model_output + + def tokenize(self, documents: list[str], **kwargs: Any) -> list[Encoding]: + texts_query: list[str] = [] + for query in documents: + query = self.BOS_TOKEN + self.QUERY_PREFIX + query + self.PAD_TOKEN * 10 + query += "\n" + + texts_query.append(query) + encoded = self.tokenizer.encode_batch(texts_query) # type: ignore[union-attr] + return encoded + + def token_count( + self, + texts: str | Iterable[str], + batch_size: int = 1024, + include_extension: bool = False, + **kwargs: Any, + ) -> int: + if not hasattr(self, "model") or self.model is None: + self.load_onnx_model() # loads the tokenizer as well + token_num = 0 + texts = [texts] if isinstance(texts, str) else texts + assert self.tokenizer is not None + tokenize_func = self.tokenize if include_extension else self.tokenizer.encode_batch + for batch in iter_batch(texts, batch_size): + token_num += sum([sum(encoding.attention_mask) for encoding in tokenize_func(batch)]) + return token_num + + def _preprocess_onnx_text_input( + self, onnx_input: dict[str, NumpyArray], **kwargs: Any + ) -> dict[str, NumpyArray]: + onnx_input["input_ids"] = np.array( + [ + self.QUERY_MARKER_TOKEN_ID + input_ids[2:].tolist() # type: ignore[index] + for input_ids in onnx_input["input_ids"] + ] + ) + empty_image_placeholder: NumpyArray = np.zeros( + self.IMAGE_PLACEHOLDER_SIZE, dtype=np.float32 + ) + onnx_input["pixel_values"] = np.array( + [empty_image_placeholder for _ in onnx_input["input_ids"]], + ) + return onnx_input + + def _preprocess_onnx_image_input( + self, onnx_input: dict[str, np.ndarray], **kwargs: Any + ) -> dict[str, NumpyArray]: + """ + Add placeholders for text input when processing image data for ONNX. + Args: + onnx_input (Dict[str, NumpyArray]): Preprocessed image inputs. + **kwargs: Additional arguments. + Returns: + Dict[str, NumpyArray]: ONNX input with text placeholders. + """ + onnx_input["input_ids"] = np.array( + [self.EMPTY_TEXT_PLACEHOLDER for _ in onnx_input["pixel_values"]] + ) + onnx_input["attention_mask"] = np.array( + [self.EVEN_ATTENTION_MASK for _ in onnx_input["pixel_values"]] + ) + return onnx_input + + def embed_text( + self, + documents: str | Iterable[str], + batch_size: int = 256, + parallel: int | None = None, + **kwargs: Any, + ) -> Iterable[NumpyArray]: + """ + Encode a list of documents into list of embeddings. + + Args: + documents: Iterator of documents or single document to embed + batch_size: Batch size for encoding -- higher values will use more memory, but be faster + parallel: + If > 1, data-parallel encoding will be used, recommended for offline encoding of large datasets. + If 0, use all available cores. + If None, don't use data-parallel processing, use default onnxruntime threading instead. + + Returns: + List of embeddings, one per document + """ + yield from self._embed_documents( + model_name=self.model_name, + cache_dir=str(self.cache_dir), + documents=documents, + batch_size=batch_size, + parallel=parallel, + providers=self.providers, + cuda=self.cuda, + device_ids=self.device_ids, + local_files_only=self._local_files_only, + specific_model_path=self._specific_model_path, + extra_session_options=self._extra_session_options, + **kwargs, + ) + + def embed_image( + self, + images: ImageInput | Iterable[ImageInput], + batch_size: int = 16, + parallel: int | None = None, + **kwargs: Any, + ) -> Iterable[NumpyArray]: + """ + Encode a list of images into list of embeddings. + + Args: + images: Iterator of image paths or single image path to embed + batch_size: Batch size for encoding -- higher values will use more memory, but be faster + parallel: + If > 1, data-parallel encoding will be used, recommended for offline encoding of large datasets. + If 0, use all available cores. + If None, don't use data-parallel processing, use default onnxruntime threading instead. + + Returns: + List of embeddings, one per document + """ + yield from self._embed_images( + model_name=self.model_name, + cache_dir=str(self.cache_dir), + images=images, + batch_size=batch_size, + parallel=parallel, + providers=self.providers, + cuda=self.cuda, + device_ids=self.device_ids, + local_files_only=self._local_files_only, + specific_model_path=self._specific_model_path, + extra_session_options=self._extra_session_options, + **kwargs, + ) + + @classmethod + def _get_text_worker_class(cls) -> Type[TextEmbeddingWorker[NumpyArray]]: + return ColPaliTextEmbeddingWorker + + @classmethod + def _get_image_worker_class(cls) -> Type[ImageEmbeddingWorker[NumpyArray]]: + return ColPaliImageEmbeddingWorker + + +class ColPaliTextEmbeddingWorker(TextEmbeddingWorker[NumpyArray]): + def init_embedding(self, model_name: str, cache_dir: str, **kwargs: Any) -> ColPali: + return ColPali( + model_name=model_name, + cache_dir=cache_dir, + threads=1, + **kwargs, + ) + + +class ColPaliImageEmbeddingWorker(ImageEmbeddingWorker[NumpyArray]): + def init_embedding(self, model_name: str, cache_dir: str, **kwargs: Any) -> ColPali: + return ColPali( + model_name=model_name, + cache_dir=cache_dir, + threads=1, + **kwargs, + ) diff --git a/python/user_packages/Python313/site-packages/fastembed/late_interaction_multimodal/late_interaction_multimodal_embedding.py b/python/user_packages/Python313/site-packages/fastembed/late_interaction_multimodal/late_interaction_multimodal_embedding.py new file mode 100644 index 0000000000000000000000000000000000000000..10d426d0d9ce43733207cdfc8c08dd1a57be3f33 --- /dev/null +++ b/python/user_packages/Python313/site-packages/fastembed/late_interaction_multimodal/late_interaction_multimodal_embedding.py @@ -0,0 +1,189 @@ +from typing import Any, Iterable, Sequence, Type +from dataclasses import asdict + +from fastembed.common import OnnxProvider, ImageInput +from fastembed.common.types import NumpyArray, Device +from fastembed.late_interaction_multimodal.colpali import ColPali +from fastembed.late_interaction_multimodal.colmodernvbert import ColModernVBERT + +from fastembed.late_interaction_multimodal.late_interaction_multimodal_embedding_base import ( + LateInteractionMultimodalEmbeddingBase, +) +from fastembed.common.model_description import DenseModelDescription + + +class LateInteractionMultimodalEmbedding(LateInteractionMultimodalEmbeddingBase): + EMBEDDINGS_REGISTRY: list[Type[LateInteractionMultimodalEmbeddingBase]] = [ + ColPali, + ColModernVBERT, + ] + + @classmethod + def list_supported_models(cls) -> list[dict[str, Any]]: + """ + Lists the supported models. + + Returns: + list[dict[str, Any]]: A list of dictionaries containing the model information. + + Example: + ``` + [ + { + "model": "Qdrant/colpali-v1.3-fp16", + "dim": 128, + "description": "Text embeddings, Unimodal (text), Aligned to image latent space, ColBERT-compatible, 512 tokens max, 2024.", + "license": "mit", + "size_in_GB": 6.06, + "sources": { + "hf": "Qdrant/colpali-v1.3-fp16", + }, + "additional_files": [ + "model.onnx_data", + ], + "model_file": "model.onnx", + }, + ] + ``` + """ + return [asdict(model) for model in cls._list_supported_models()] + + @classmethod + def _list_supported_models(cls) -> list[DenseModelDescription]: + result: list[DenseModelDescription] = [] + for embedding in cls.EMBEDDINGS_REGISTRY: + result.extend(embedding._list_supported_models()) + return result + + def __init__( + self, + model_name: str, + cache_dir: str | None = None, + threads: int | None = None, + providers: Sequence[OnnxProvider] | None = None, + cuda: bool | Device = Device.AUTO, + device_ids: list[int] | None = None, + lazy_load: bool = False, + **kwargs: Any, + ): + super().__init__(model_name, cache_dir, threads, **kwargs) + for EMBEDDING_MODEL_TYPE in self.EMBEDDINGS_REGISTRY: + supported_models = EMBEDDING_MODEL_TYPE._list_supported_models() + if any(model_name.lower() == model.model.lower() for model in supported_models): + self.model = EMBEDDING_MODEL_TYPE( + model_name, + cache_dir, + threads=threads, + providers=providers, + cuda=cuda, + device_ids=device_ids, + lazy_load=lazy_load, + **kwargs, + ) + return + + raise ValueError( + f"Model {model_name} is not supported in LateInteractionMultimodalEmbedding." + "Please check the supported models using `LateInteractionMultimodalEmbedding.list_supported_models()`" + ) + + @property + def embedding_size(self) -> int: + """Get the embedding size of the current model""" + if self._embedding_size is None: + self._embedding_size = self.get_embedding_size(self.model_name) + return self._embedding_size + + @classmethod + def get_embedding_size(cls, model_name: str) -> int: + """Get the embedding size of the passed model + + Args: + model_name (str): The name of the model to get embedding size for. + + Returns: + int: The size of the embedding. + + Raises: + ValueError: If the model name is not found in the supported models. + """ + descriptions = cls._list_supported_models() + embedding_size: int | None = None + for description in descriptions: + if description.model.lower() == model_name.lower(): + embedding_size = description.dim + break + if embedding_size is None: + model_names = [description.model for description in descriptions] + raise ValueError( + f"Embedding size for model {model_name} was None. " + f"Available model names: {model_names}" + ) + return embedding_size + + def embed_text( + self, + documents: str | Iterable[str], + batch_size: int = 256, + parallel: int | None = None, + **kwargs: Any, + ) -> Iterable[NumpyArray]: + """ + Encode a list of documents into list of embeddings. + + Args: + documents: Iterator of documents or single document to embed + batch_size: Batch size for encoding -- higher values will use more memory, but be faster + parallel: + If > 1, data-parallel encoding will be used, recommended for offline encoding of large datasets. + If 0, use all available cores. + If None, don't use data-parallel processing, use default onnxruntime threading instead. + + Returns: + List of embeddings, one per document + """ + yield from self.model.embed_text(documents, batch_size, parallel, **kwargs) + + def embed_image( + self, + images: ImageInput | Iterable[ImageInput], + batch_size: int = 16, + parallel: int | None = None, + **kwargs: Any, + ) -> Iterable[NumpyArray]: + """ + Encode a list of images into list of embeddings. + + Args: + images: Iterator of image paths or single image path to embed + batch_size: Batch size for encoding -- higher values will use more memory, but be faster + parallel: + If > 1, data-parallel encoding will be used, recommended for offline encoding of large datasets. + If 0, use all available cores. + If None, don't use data-parallel processing, use default onnxruntime threading instead. + + Returns: + List of embeddings, one per image + """ + yield from self.model.embed_image(images, batch_size, parallel, **kwargs) + + def token_count( + self, + texts: str | Iterable[str], + batch_size: int = 1024, + include_extension: bool = False, + **kwargs: Any, + ) -> int: + """Returns the number of tokens in the texts. + + Args: + texts (str | Iterable[str]): The list of texts to embed. + batch_size (int): Batch size for encoding + include_extension (bool): Whether to include tokens added by preprocessing + + Returns: + int: Sum of number of tokens in the texts. + """ + return self.model.token_count( + texts, batch_size=batch_size, include_extension=include_extension, **kwargs + ) diff --git a/python/user_packages/Python313/site-packages/fastembed/late_interaction_multimodal/late_interaction_multimodal_embedding_base.py b/python/user_packages/Python313/site-packages/fastembed/late_interaction_multimodal/late_interaction_multimodal_embedding_base.py new file mode 100644 index 0000000000000000000000000000000000000000..72a87fe5eb6bb265a4fa87a3e4e5e048f884e4c9 --- /dev/null +++ b/python/user_packages/Python313/site-packages/fastembed/late_interaction_multimodal/late_interaction_multimodal_embedding_base.py @@ -0,0 +1,86 @@ +from typing import Iterable, Any + + +from fastembed.common import ImageInput +from fastembed.common.model_description import DenseModelDescription +from fastembed.common.model_management import ModelManagement +from fastembed.common.types import NumpyArray + + +class LateInteractionMultimodalEmbeddingBase(ModelManagement[DenseModelDescription]): + def __init__( + self, + model_name: str, + cache_dir: str | None = None, + threads: int | None = None, + **kwargs: Any, + ): + self.model_name = model_name + self.cache_dir = cache_dir + self.threads = threads + self._local_files_only = kwargs.pop("local_files_only", False) + self._embedding_size: int | None = None + + def embed_text( + self, + documents: str | Iterable[str], + batch_size: int = 256, + parallel: int | None = None, + **kwargs: Any, + ) -> Iterable[NumpyArray]: + """ + Embeds a list of documents into a list of embeddings. + + Args: + documents (Iterable[str]): The list of texts to embed. + batch_size: Batch size for encoding -- higher values will use more memory, but be faster + parallel: + If > 1, data-parallel encoding will be used, recommended for offline encoding of large datasets. + If 0, use all available cores. + If None, don't use data-parallel processing, use default onnxruntime threading instead. + **kwargs: Additional keyword argument to pass to the embed method. + + Yields: + Iterable[NumpyArray]: The embeddings. + """ + raise NotImplementedError() + + def embed_image( + self, + images: ImageInput | Iterable[ImageInput], + batch_size: int = 16, + parallel: int | None = None, + **kwargs: Any, + ) -> Iterable[NumpyArray]: + """ + Encode a list of images into list of embeddings. + Args: + images: Iterator of image paths or single image path to embed + batch_size: Batch size for encoding -- higher values will use more memory, but be faster + parallel: + If > 1, data-parallel encoding will be used, recommended for offline encoding of large datasets. + If 0, use all available cores. + If None, don't use data-parallel processing, use default onnxruntime threading instead. + + Returns: + List of embeddings, one per image + """ + raise NotImplementedError() + + @classmethod + def get_embedding_size(cls, model_name: str) -> int: + """Returns embedding size of the chosen model.""" + raise NotImplementedError("Subclasses must implement this method") + + @property + def embedding_size(self) -> int: + """Returns embedding size for the current model""" + raise NotImplementedError("Subclasses must implement this method") + + def token_count( + self, + texts: str | Iterable[str], + **kwargs: Any, + ) -> int: + """Returns the number of tokens in the texts.""" + raise NotImplementedError("Subclasses must implement this method") diff --git a/python/user_packages/Python313/site-packages/fastembed/late_interaction_multimodal/onnx_multimodal_model.py b/python/user_packages/Python313/site-packages/fastembed/late_interaction_multimodal/onnx_multimodal_model.py new file mode 100644 index 0000000000000000000000000000000000000000..9343689575dc6bc322abef3fc03887fca7882390 --- /dev/null +++ b/python/user_packages/Python313/site-packages/fastembed/late_interaction_multimodal/onnx_multimodal_model.py @@ -0,0 +1,291 @@ +import contextlib +import os +from multiprocessing import get_all_start_methods +from pathlib import Path +from typing import Any, Iterable, Sequence, Type + +import numpy as np +from PIL import Image +from tokenizers import Encoding, Tokenizer + +from fastembed.common import OnnxProvider, ImageInput +from fastembed.common.onnx_model import EmbeddingWorker, OnnxModel, OnnxOutputContext, T +from fastembed.common.preprocessor_utils import load_tokenizer, load_preprocessor +from fastembed.common.types import NumpyArray, Device +from fastembed.common.utils import iter_batch +from fastembed.image.transform.operators import Compose +from fastembed.parallel_processor import ParallelWorkerPool + + +class OnnxMultimodalModel(OnnxModel[T]): + ONNX_OUTPUT_NAMES: list[str] | None = None + + def __init__(self) -> None: + super().__init__() + self.tokenizer: Tokenizer | None = None + self.processor: Compose | None = None + self.special_token_to_id: dict[str, int] = {} + + def _preprocess_onnx_text_input( + self, onnx_input: dict[str, NumpyArray], **kwargs: Any + ) -> dict[str, NumpyArray]: + """ + Preprocess the onnx input. + """ + return onnx_input + + def _preprocess_onnx_image_input( + self, onnx_input: dict[str, NumpyArray], **kwargs: Any + ) -> dict[str, NumpyArray]: + """ + Preprocess the onnx input. + """ + return onnx_input + + @classmethod + def _get_text_worker_class(cls) -> Type["TextEmbeddingWorker[T]"]: + raise NotImplementedError("Subclasses must implement this method") + + @classmethod + def _get_image_worker_class(cls) -> Type["ImageEmbeddingWorker[T]"]: + raise NotImplementedError("Subclasses must implement this method") + + def _post_process_onnx_image_output(self, output: OnnxOutputContext) -> Iterable[T]: + raise NotImplementedError("Subclasses must implement this method") + + def _post_process_onnx_text_output(self, output: OnnxOutputContext) -> Iterable[T]: + raise NotImplementedError("Subclasses must implement this method") + + def _load_onnx_model( + self, + model_dir: Path, + model_file: str, + threads: int | None, + providers: Sequence[OnnxProvider] | None = None, + cuda: bool | Device = Device.AUTO, + device_id: int | None = None, + extra_session_options: dict[str, Any] | None = None, + ) -> None: + super()._load_onnx_model( + model_dir=model_dir, + model_file=model_file, + threads=threads, + providers=providers, + cuda=cuda, + device_id=device_id, + extra_session_options=extra_session_options, + ) + self.tokenizer, self.special_token_to_id = load_tokenizer(model_dir=model_dir) + assert self.tokenizer is not None + self.processor = load_preprocessor(model_dir=model_dir) + + def load_onnx_model(self) -> None: + raise NotImplementedError("Subclasses must implement this method") + + def tokenize(self, documents: list[str], **kwargs: Any) -> list[Encoding]: + return self.tokenizer.encode_batch(documents) # type: ignore[union-attr] + + def onnx_embed_text( + self, + documents: list[str], + **kwargs: Any, + ) -> OnnxOutputContext: + encoded = self.tokenize(documents, **kwargs) + input_ids = np.array([e.ids for e in encoded]) + attention_mask = np.array([e.attention_mask for e in encoded]) # type: ignore[union-attr] + input_names = {node.name for node in self.model.get_inputs()} # type: ignore[union-attr] + onnx_input: dict[str, NumpyArray] = { + "input_ids": np.array(input_ids, dtype=np.int64), + } + if "attention_mask" in input_names: + onnx_input["attention_mask"] = np.array(attention_mask, dtype=np.int64) + if "token_type_ids" in input_names: + onnx_input["token_type_ids"] = np.array( + [np.zeros(len(e), dtype=np.int64) for e in input_ids], dtype=np.int64 + ) + + onnx_input = self._preprocess_onnx_text_input(onnx_input, **kwargs) + model_output = self.model.run(self.ONNX_OUTPUT_NAMES, onnx_input) # type: ignore[union-attr] + return OnnxOutputContext( + model_output=model_output[0], + attention_mask=onnx_input.get("attention_mask", attention_mask), + input_ids=onnx_input.get("input_ids", input_ids), + ) + + def _embed_documents( + self, + model_name: str, + cache_dir: str, + documents: str | Iterable[str], + batch_size: int = 256, + parallel: int | None = None, + providers: Sequence[OnnxProvider] | None = None, + cuda: bool | Device = Device.AUTO, + device_ids: list[int] | None = None, + local_files_only: bool = False, + specific_model_path: str | None = None, + extra_session_options: dict[str, Any] | None = None, + **kwargs: Any, + ) -> Iterable[T]: + is_small = False + + if isinstance(documents, str): + documents = [documents] + is_small = True + + if isinstance(documents, list): + if len(documents) < batch_size: + is_small = True + + if parallel is None or is_small: + if not hasattr(self, "model") or self.model is None: + self.load_onnx_model() + for batch in iter_batch(documents, batch_size): + yield from self._post_process_onnx_text_output(self.onnx_embed_text(batch)) + else: + if parallel == 0: + parallel = os.cpu_count() + + start_method = "forkserver" if "forkserver" in get_all_start_methods() else "spawn" + params = { + "model_name": model_name, + "cache_dir": cache_dir, + "providers": providers, + "local_files_only": local_files_only, + "specific_model_path": specific_model_path, + **kwargs, + } + + if extra_session_options is not None: + params.update(extra_session_options) + + pool = ParallelWorkerPool( + num_workers=parallel or 1, + worker=self._get_text_worker_class(), + cuda=cuda, + device_ids=device_ids, + start_method=start_method, + ) + for batch in pool.ordered_map(iter_batch(documents, batch_size), **params): + yield from self._post_process_onnx_text_output(batch) # type: ignore + + def onnx_embed_image(self, images: list[ImageInput], **kwargs: Any) -> OnnxOutputContext: + with contextlib.ExitStack() as stack: + image_files = [ + stack.enter_context(Image.open(image)) + if not isinstance(image, Image.Image) + else image + for image in images + ] + assert self.processor is not None, "Processor is not initialized" + encoded = np.array(self.processor(image_files)) + onnx_input = {"pixel_values": encoded} + onnx_input = self._preprocess_onnx_image_input(onnx_input, **kwargs) + model_output = self.model.run(None, onnx_input) # type: ignore[union-attr] + embeddings = model_output[0].reshape(len(images), -1) + return OnnxOutputContext(model_output=embeddings) + + def _embed_images( + self, + model_name: str, + cache_dir: str, + images: Iterable[ImageInput] | ImageInput, + batch_size: int = 256, + parallel: int | None = None, + providers: Sequence[OnnxProvider] | None = None, + cuda: bool | Device = Device.AUTO, + device_ids: list[int] | None = None, + local_files_only: bool = False, + specific_model_path: str | None = None, + extra_session_options: dict[str, Any] | None = None, + **kwargs: Any, + ) -> Iterable[T]: + is_small = False + + if isinstance(images, (str, Path, Image.Image)): + images = [images] + is_small = True + + if isinstance(images, list) and len(images) < batch_size: + is_small = True + + if parallel is None or is_small: + if not hasattr(self, "model") or self.model is None: + self.load_onnx_model() + + for batch in iter_batch(images, batch_size): + yield from self._post_process_onnx_image_output(self.onnx_embed_image(batch)) + else: + if parallel == 0: + parallel = os.cpu_count() + + start_method = "forkserver" if "forkserver" in get_all_start_methods() else "spawn" + params = { + "model_name": model_name, + "cache_dir": cache_dir, + "providers": providers, + "local_files_only": local_files_only, + "specific_model_path": specific_model_path, + **kwargs, + } + + if extra_session_options is not None: + params.update(extra_session_options) + + pool = ParallelWorkerPool( + num_workers=parallel or 1, + worker=self._get_image_worker_class(), + cuda=cuda, + device_ids=device_ids, + start_method=start_method, + ) + for batch in pool.ordered_map(iter_batch(images, batch_size), **params): + yield from self._post_process_onnx_image_output(batch) # type: ignore + + +class TextEmbeddingWorker(EmbeddingWorker[T]): + def __init__( + self, + model_name: str, + cache_dir: str, + **kwargs: Any, + ): + self.model: OnnxMultimodalModel + super().__init__(model_name, cache_dir, **kwargs) + + def init_embedding( + self, + model_name: str, + cache_dir: str, + **kwargs: Any, + ) -> OnnxMultimodalModel: + raise NotImplementedError() + + def process(self, items: Iterable[tuple[int, Any]]) -> Iterable[tuple[int, Any]]: + for idx, batch in items: + onnx_output = self.model.onnx_embed_text(batch) + yield idx, onnx_output + + +class ImageEmbeddingWorker(EmbeddingWorker[T]): + def __init__( + self, + model_name: str, + cache_dir: str, + **kwargs: Any, + ): + self.model: OnnxMultimodalModel + super().__init__(model_name, cache_dir, **kwargs) + + def init_embedding( + self, + model_name: str, + cache_dir: str, + **kwargs: Any, + ) -> OnnxMultimodalModel: + raise NotImplementedError() + + def process(self, items: Iterable[tuple[int, Any]]) -> Iterable[tuple[int, Any]]: + for idx, batch in items: + embeddings = self.model.onnx_embed_image(batch) + yield idx, embeddings diff --git a/python/user_packages/Python313/site-packages/fastembed/postprocess/__init__.py b/python/user_packages/Python313/site-packages/fastembed/postprocess/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..5d03c50e84b21f926dbce8cebe089210b63a5684 --- /dev/null +++ b/python/user_packages/Python313/site-packages/fastembed/postprocess/__init__.py @@ -0,0 +1,3 @@ +from fastembed.postprocess.muvera import Muvera + +__all__ = ["Muvera"] diff --git a/python/user_packages/Python313/site-packages/fastembed/postprocess/__pycache__/__init__.cpython-313.pyc b/python/user_packages/Python313/site-packages/fastembed/postprocess/__pycache__/__init__.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..fee2e62e9a53cd4b08fbfdecfcdcaa1d1e9ef133 Binary files /dev/null and b/python/user_packages/Python313/site-packages/fastembed/postprocess/__pycache__/__init__.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/fastembed/postprocess/__pycache__/muvera.cpython-313.pyc b/python/user_packages/Python313/site-packages/fastembed/postprocess/__pycache__/muvera.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5aeed2562a5ab19683c45544ce07ce13812b8538 Binary files /dev/null and b/python/user_packages/Python313/site-packages/fastembed/postprocess/__pycache__/muvera.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/fastembed/postprocess/muvera.py b/python/user_packages/Python313/site-packages/fastembed/postprocess/muvera.py new file mode 100644 index 0000000000000000000000000000000000000000..3c6476795639d9ce1e0f732b2a23180eb00222e4 --- /dev/null +++ b/python/user_packages/Python313/site-packages/fastembed/postprocess/muvera.py @@ -0,0 +1,362 @@ +import numpy as np + +from fastembed.common.types import NumpyArray +from fastembed.late_interaction.late_interaction_embedding_base import ( + LateInteractionTextEmbeddingBase, +) +from fastembed.late_interaction_multimodal.late_interaction_multimodal_embedding_base import ( + LateInteractionMultimodalEmbeddingBase, +) + + +MultiVectorModel = LateInteractionTextEmbeddingBase | LateInteractionMultimodalEmbeddingBase +MAX_HAMMING_DISTANCE = 65 # 64 bits + 1 +POPCOUNT_LUT = np.array([bin(x).count("1") for x in range(256)], dtype=np.uint8) + + +def hamming_distance_matrix(ids: np.ndarray) -> np.ndarray: + """Compute full Hamming distance matrix + + Args: + ids: shape (n,) - array of ids, only size of the array matters + + Return: + np.ndarray (n, n) - hamming distance matrix + """ + n = len(ids) + xor_vals = np.bitwise_xor(ids[:, None], ids[None, :]) # (n, n) uint64 + bytes_view = xor_vals.view(np.uint8).reshape(n, n, 8) # (n, n, 8) + return POPCOUNT_LUT[bytes_view].sum(axis=2) + + +class SimHashProjection: + """ + SimHash projection component for MUVERA clustering. + + This class implements locality-sensitive hashing using random hyperplanes + to partition the vector space into 2^k_sim clusters. Each vector is assigned + to a cluster based on which side of k_sim random hyperplanes it falls on. + + Attributes: + k_sim (int): Number of SimHash functions (hyperplanes) + dim (int): Dimensionality of input vectors + simhash_vectors (np.ndarray): Random hyperplane normal vectors of shape (dim, k_sim) + """ + + def __init__(self, k_sim: int, dim: int, random_generator: np.random.Generator): + """ + Initialize SimHash projection with random hyperplanes. + + Args: + k_sim (int): Number of SimHash functions, determines 2^k_sim clusters + dim (int): Dimensionality of input vectors + random_generator (np.random.Generator): Random number generator for reproducibility + """ + self.k_sim = k_sim + self.dim = dim + # Generate k_sim random hyperplanes (normal vectors) from standard normal distribution + self.simhash_vectors = random_generator.normal(size=(dim, k_sim)) + + def get_cluster_ids(self, vectors: np.ndarray) -> np.ndarray: + """ + Compute the cluster IDs for a given vector using SimHash. + + The cluster ID is determined by computing the dot product of the vector + with each hyperplane normal vector, taking the sign, and interpreting + the resulting binary string as an integer. + + Args: + vectors (np.ndarray): Input vectors of shape (n, dim,) + + Returns: + np.ndarray: Cluster IDs in range [0, 2^k_sim - 1] + + Raises: + AssertionError: If a vector shape doesn't match expected dimensionality + """ + dot_product = ( + vectors @ self.simhash_vectors + ) # (token_num, dim) x (dim, k_sim) -> (token_num, k_sim) + cluster_ids = (dot_product > 0) @ (1 << np.arange(self.k_sim)) + return cluster_ids + + +class Muvera: + """ + MUVERA (Multi-Vector Retrieval Architecture) algorithm implementation. + + This class creates Fixed Dimensional Encodings (FDEs) from variable-length + sequences of vectors by using SimHash clustering and random projections. + The process involves: + 1. Clustering vectors using multiple SimHash projections + 2. Computing cluster centers (with different strategies for docs vs queries) + 3. Applying random projections for dimensionality reduction + 4. Concatenating results from all projections + + Attributes: + k_sim (int): Number of SimHash functions per projection + dim (int): Input vector dimensionality + dim_proj (int): Output dimensionality after random projection + r_reps (int): Number of random projection repetitions + random_seed (int): Random seed for consistent random matrix generation + simhash_projections (List[SimHashProjection]): SimHash instances for clustering + dim_reduction_projections (np.ndarray): Random projection matrices of shape (R_reps, d, d_proj) + """ + + def __init__( + self, + dim: int, + k_sim: int = 5, + dim_proj: int = 16, + r_reps: int = 20, + random_seed: int = 42, + ): + """ + Initialize MUVERA algorithm with specified parameters. + + Args: + dim (int): Dimensionality of individual input vectors + k_sim (int, optional): Number of SimHash functions (creates 2^k_sim clusters). + Defaults to 5. + dim_proj (int, optional): Dimensionality after random projection (must be <= dim). + Defaults to 16. + r_reps (int, optional): Number of random projection repetitions for robustness. + Defaults to 20. + random_seed (int, optional): Seed for random number generator to ensure + reproducible results. Defaults to 42. + + Raises: + ValueError: If dim_proj > dim (cannot project to higher dimensionality) + """ + if dim_proj > dim: + raise ValueError( + f"Cannot project to a higher dimensionality (dim_proj={dim_proj} > dim={dim})" + ) + + self.k_sim = k_sim + self.dim = dim + self.dim_proj = dim_proj + self.r_reps = r_reps + # Create r_reps independent SimHash projections for robustness + generator = np.random.default_rng(random_seed) + self.simhash_projections = [ + SimHashProjection(k_sim=self.k_sim, dim=self.dim, random_generator=generator) + for _ in range(r_reps) + ] + # Random projection matrices with entries from {-1, +1} for each repetition + self.dim_reduction_projections = generator.choice([-1, 1], size=(r_reps, dim, dim_proj)) + + @classmethod + def from_multivector_model( + cls, + model: MultiVectorModel, + k_sim: int = 5, + dim_proj: int = 16, + r_reps: int = 20, # noqa[naming] + random_seed: int = 42, + ) -> "Muvera": + """ + Create a Muvera instance from a multi-vector embedding model. + + This class method provides a convenient way to initialize a MUVERA + that is compatible with a given multi-vector model by automatically extracting + the embedding dimensionality from the model. + + Args: + model (MultiVectorModel): A late interaction text or multimodal embedding model + that provides multi-vector embeddings. Must have an + `embedding_size` attribute specifying the dimensionality + of individual vectors. + k_sim (int, optional): Number of SimHash functions (creates 2^k_sim clusters). + Defaults to 5. + dim_proj (int, optional): Dimensionality after random projection (must be <= model's + embedding_size). Defaults to 16. + r_reps (int, optional): Number of random projection repetitions for robustness. + Defaults to 20. + random_seed (int, optional): Seed for random number generator to ensure + reproducible results. Defaults to 42. + + Returns: + Muvera: A configured MUVERA instance ready to process embeddings from the given model. + + Raises: + ValueError: If dim_proj > model.embedding_size (cannot project to higher dimensionality) + + Example: + >>> from fastembed import LateInteractionTextEmbedding + >>> model = LateInteractionTextEmbedding(model_name="colbert-ir/colbertv2.0") + >>> muvera = Muvera.from_multivector_model( + ... model=model, + ... k_sim=6, + ... dim_proj=32 + ... ) + >>> # Now use postprocessor with embeddings from the model + >>> embeddings = np.array(list(model.embed(["sample text"]))) + >>> fde = muvera.process_document(embeddings[0]) + """ + return cls( + dim=model.embedding_size, + k_sim=k_sim, + dim_proj=dim_proj, + r_reps=r_reps, + random_seed=random_seed, + ) + + def _get_output_dimension(self) -> int: + """ + Get the output dimension of the MUVERA algorithm. + + Returns: + int: Output dimension (r_reps * num_partitions * dim_proj) where b = 2^k_sim + """ + num_partitions = 2**self.k_sim + return self.r_reps * num_partitions * self.dim_proj + + @property + def embedding_size(self) -> int: + return self._get_output_dimension() + + def process_document(self, vectors: NumpyArray) -> NumpyArray: + """ + Encode a document's vectors into a Fixed Dimensional Encoding (FDE). + + Uses document-specific settings: normalizes cluster centers by vector count + and fills empty clusters using Hamming distance-based selection. + + Args: + vectors (NumpyArray): Document vectors of shape (n_tokens, dim) + + Returns: + NumpyArray: Fixed dimensional encodings of shape (r_reps * b * dim_proj,) + """ + return self.process(vectors, fill_empty_clusters=True, normalize_by_count=True) + + def process_query(self, vectors: NumpyArray) -> NumpyArray: + """ + Encode a query's vectors into a Fixed Dimensional Encoding (FDE). + + Uses query-specific settings: no normalization by count and no empty + cluster filling to preserve query vector magnitudes. + + Args: + vectors (NumpyArray]): Query vectors of shape (n_tokens, dim) + + Returns: + NumpyArray: Fixed dimensional encoding of shape (r_reps * b * dim_proj,) + """ + return self.process(vectors, fill_empty_clusters=False, normalize_by_count=False) + + def process( + self, + vectors: NumpyArray, + fill_empty_clusters: bool = True, + normalize_by_count: bool = True, + ) -> NumpyArray: + """ + Core encoding method that transforms variable-length vector sequences into FDEs. + + The encoding process: + 1. For each of r_reps random projections: + a. Assign vectors to clusters using SimHash + b. Compute cluster centers (sum of vectors in each cluster) + c. Optionally normalize by cluster size + d. Fill empty clusters using Hamming distance if requested + e. Apply random projection for dimensionality reduction + f. Flatten cluster centers into a vector + 2. Concatenate all projection results + + Args: + vectors (np.ndarray): Input vectors of shape (n_vectors, dim) + fill_empty_clusters (bool): Whether to fill empty clusters using nearest + vectors based on Hamming distance of cluster IDs + normalize_by_count (bool): Whether to normalize cluster centers by the + number of vectors assigned to each cluster + + Returns: + np.ndarray: Fixed dimensional encoding of shape (r_reps * b * dim_proj) + where B = 2^k_sim is the number of clusters + + Raises: + AssertionError: If input vectors don't have expected dimensionality + """ + assert ( + vectors.shape[1] == self.dim + ), f"Expected vectors of shape (n, {self.dim}), got {vectors.shape}" + + # Store results from each random projection + output_vectors = [] + + # num of space partitions in SimHash + num_partitions = 2**self.k_sim + cluster_center_ids = np.arange(num_partitions) + precomputed_hamming_matrix = ( + hamming_distance_matrix(cluster_center_ids) if fill_empty_clusters else None + ) + + for projection_index, simhash in enumerate(self.simhash_projections): + # Initialize cluster centers and count vectors assigned to each cluster + cluster_centers = np.zeros((num_partitions, self.dim)) + cluster_center_id_to_vectors: dict[int, list[int]] = { + cluster_center_id: [] for cluster_center_id in cluster_center_ids + } + cluster_vector_counts = None + empty_mask = None + + # Assign each vector to its cluster and accumulate cluster centers + vector_cluster_ids = simhash.get_cluster_ids(vectors) + for cluster_id, (vec_idx, vec) in zip(vector_cluster_ids, enumerate(vectors)): + cluster_centers[cluster_id] += vec + cluster_center_id_to_vectors[cluster_id].append(vec_idx) + + if normalize_by_count or fill_empty_clusters: + cluster_vector_counts = np.bincount(vector_cluster_ids, minlength=num_partitions) + empty_mask = cluster_vector_counts == 0 + + if normalize_by_count: + assert empty_mask is not None + assert cluster_vector_counts is not None + non_empty_mask = ~empty_mask + cluster_centers[non_empty_mask] /= cluster_vector_counts[non_empty_mask][:, None] + + # Fill empty clusters using vectors with minimum Hamming distance + if fill_empty_clusters: + assert empty_mask is not None + assert precomputed_hamming_matrix is not None + masked_hamming = np.where( + empty_mask[None, :], MAX_HAMMING_DISTANCE, precomputed_hamming_matrix + ) + nearest_non_empty = np.argmin(masked_hamming, axis=1) + fill_vectors = np.array( + [ + vectors[cluster_center_id_to_vectors[cluster_id][0]] + for cluster_id in nearest_non_empty[empty_mask] + ] + ).reshape(-1, self.dim) + cluster_centers[empty_mask] = fill_vectors + + # Apply random projection for dimensionality reduction if needed + if self.dim_proj < self.dim: + dim_reduction_projection = self.dim_reduction_projections[ + projection_index + ] # Get projection matrix for this repetition + projected_centers = (1 / np.sqrt(self.dim_proj)) * ( + cluster_centers @ dim_reduction_projection + ) + + # Flatten cluster centers into a single vector and add to output + output_vectors.append(projected_centers.flatten()) + continue + + # If no projection needed (dim_proj == dim), use original cluster centers + output_vectors.append(cluster_centers.flatten()) + + # Concatenate results from all R_reps projections into final FDE + return np.concatenate(output_vectors) + + +if __name__ == "__main__": + v_arrs = np.random.randn(10, 100, 128) + muvera = Muvera(128, 4, 8, 20, 42) + + for v_arr in v_arrs: + muvera.process(v_arr) # type: ignore diff --git a/python/user_packages/Python313/site-packages/fastembed/rerank/cross_encoder/__init__.py b/python/user_packages/Python313/site-packages/fastembed/rerank/cross_encoder/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..23c1e35916725b18a960a573bbe0253ae2676415 --- /dev/null +++ b/python/user_packages/Python313/site-packages/fastembed/rerank/cross_encoder/__init__.py @@ -0,0 +1,3 @@ +from fastembed.rerank.cross_encoder.text_cross_encoder import TextCrossEncoder + +__all__ = ["TextCrossEncoder"] diff --git a/python/user_packages/Python313/site-packages/fastembed/rerank/cross_encoder/__pycache__/__init__.cpython-313.pyc b/python/user_packages/Python313/site-packages/fastembed/rerank/cross_encoder/__pycache__/__init__.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6313f77f7859699d4b866a4b674c91a0b478c2c2 Binary files /dev/null and b/python/user_packages/Python313/site-packages/fastembed/rerank/cross_encoder/__pycache__/__init__.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/fastembed/rerank/cross_encoder/__pycache__/custom_text_cross_encoder.cpython-313.pyc b/python/user_packages/Python313/site-packages/fastembed/rerank/cross_encoder/__pycache__/custom_text_cross_encoder.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7fa68f27b4de91b090fcb038493fc97dff786273 Binary files /dev/null and b/python/user_packages/Python313/site-packages/fastembed/rerank/cross_encoder/__pycache__/custom_text_cross_encoder.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/fastembed/rerank/cross_encoder/__pycache__/onnx_text_cross_encoder.cpython-313.pyc b/python/user_packages/Python313/site-packages/fastembed/rerank/cross_encoder/__pycache__/onnx_text_cross_encoder.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8f184250fdb159be34931693e5ca4fc71bc61ae2 Binary files /dev/null and b/python/user_packages/Python313/site-packages/fastembed/rerank/cross_encoder/__pycache__/onnx_text_cross_encoder.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/fastembed/rerank/cross_encoder/__pycache__/onnx_text_model.cpython-313.pyc b/python/user_packages/Python313/site-packages/fastembed/rerank/cross_encoder/__pycache__/onnx_text_model.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0275667af30260749d302ed0a9faad5900ae3c00 Binary files /dev/null and b/python/user_packages/Python313/site-packages/fastembed/rerank/cross_encoder/__pycache__/onnx_text_model.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/fastembed/rerank/cross_encoder/__pycache__/text_cross_encoder.cpython-313.pyc b/python/user_packages/Python313/site-packages/fastembed/rerank/cross_encoder/__pycache__/text_cross_encoder.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d0413498e0b26e76a078af859a08cc735bdb69e4 Binary files /dev/null and b/python/user_packages/Python313/site-packages/fastembed/rerank/cross_encoder/__pycache__/text_cross_encoder.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/fastembed/rerank/cross_encoder/__pycache__/text_cross_encoder_base.cpython-313.pyc b/python/user_packages/Python313/site-packages/fastembed/rerank/cross_encoder/__pycache__/text_cross_encoder_base.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..584b7b53ab9bd11b848bc69046f670e5f2f21e74 Binary files /dev/null and b/python/user_packages/Python313/site-packages/fastembed/rerank/cross_encoder/__pycache__/text_cross_encoder_base.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/fastembed/rerank/cross_encoder/custom_text_cross_encoder.py b/python/user_packages/Python313/site-packages/fastembed/rerank/cross_encoder/custom_text_cross_encoder.py new file mode 100644 index 0000000000000000000000000000000000000000..fc1f6e9643cc39977e1e313416f191f0a7b15650 --- /dev/null +++ b/python/user_packages/Python313/site-packages/fastembed/rerank/cross_encoder/custom_text_cross_encoder.py @@ -0,0 +1,47 @@ +from typing import Sequence, Any + +from fastembed.common import OnnxProvider +from fastembed.common.model_description import BaseModelDescription +from fastembed.common.types import Device +from fastembed.rerank.cross_encoder.onnx_text_cross_encoder import OnnxTextCrossEncoder + + +class CustomTextCrossEncoder(OnnxTextCrossEncoder): + SUPPORTED_MODELS: list[BaseModelDescription] = [] + + def __init__( + self, + model_name: str, + cache_dir: str | None = None, + threads: int | None = None, + providers: Sequence[OnnxProvider] | None = None, + cuda: bool | Device = Device.AUTO, + device_ids: list[int] | None = None, + lazy_load: bool = False, + device_id: int | None = None, + specific_model_path: str | None = None, + **kwargs: Any, + ): + super().__init__( + model_name=model_name, + cache_dir=cache_dir, + threads=threads, + providers=providers, + cuda=cuda, + device_ids=device_ids, + lazy_load=lazy_load, + device_id=device_id, + specific_model_path=specific_model_path, + **kwargs, + ) + + @classmethod + def _list_supported_models(cls) -> list[BaseModelDescription]: + return cls.SUPPORTED_MODELS + + @classmethod + def add_model( + cls, + model_description: BaseModelDescription, + ) -> None: + cls.SUPPORTED_MODELS.append(model_description) diff --git a/python/user_packages/Python313/site-packages/fastembed/rerank/cross_encoder/onnx_text_cross_encoder.py b/python/user_packages/Python313/site-packages/fastembed/rerank/cross_encoder/onnx_text_cross_encoder.py new file mode 100644 index 0000000000000000000000000000000000000000..212315513e318821bf89f417429cf375aa4d05c7 --- /dev/null +++ b/python/user_packages/Python313/site-packages/fastembed/rerank/cross_encoder/onnx_text_cross_encoder.py @@ -0,0 +1,239 @@ +from typing import Any, Iterable, Sequence, Type + +from loguru import logger + +from fastembed.common import OnnxProvider +from fastembed.common.onnx_model import OnnxOutputContext +from fastembed.common.types import Device +from fastembed.common.utils import define_cache_dir +from fastembed.rerank.cross_encoder.onnx_text_model import ( + OnnxCrossEncoderModel, + TextRerankerWorker, +) +from fastembed.rerank.cross_encoder.text_cross_encoder_base import TextCrossEncoderBase +from fastembed.common.model_description import BaseModelDescription, ModelSource + +supported_onnx_models: list[BaseModelDescription] = [ + BaseModelDescription( + model="Xenova/ms-marco-MiniLM-L-6-v2", + description="MiniLM-L-6-v2 model optimized for re-ranking tasks.", + license="apache-2.0", + size_in_GB=0.08, + sources=ModelSource(hf="Xenova/ms-marco-MiniLM-L-6-v2"), + model_file="onnx/model.onnx", + ), + BaseModelDescription( + model="Xenova/ms-marco-MiniLM-L-12-v2", + description="MiniLM-L-12-v2 model optimized for re-ranking tasks.", + license="apache-2.0", + size_in_GB=0.12, + sources=ModelSource(hf="Xenova/ms-marco-MiniLM-L-12-v2"), + model_file="onnx/model.onnx", + ), + BaseModelDescription( + model="BAAI/bge-reranker-base", + description="BGE reranker base model for cross-encoder re-ranking.", + license="mit", + size_in_GB=1.04, + sources=ModelSource(hf="BAAI/bge-reranker-base"), + model_file="onnx/model.onnx", + ), + BaseModelDescription( + model="jinaai/jina-reranker-v1-tiny-en", + description="Designed for blazing-fast re-ranking with 8K context length and fewer parameters than jina-reranker-v1-turbo-en.", + license="apache-2.0", + size_in_GB=0.13, + sources=ModelSource(hf="jinaai/jina-reranker-v1-tiny-en"), + model_file="onnx/model.onnx", + ), + BaseModelDescription( + model="jinaai/jina-reranker-v1-turbo-en", + description="Designed for blazing-fast re-ranking with 8K context length.", + license="apache-2.0", + size_in_GB=0.15, + sources=ModelSource(hf="jinaai/jina-reranker-v1-turbo-en"), + model_file="onnx/model.onnx", + ), + BaseModelDescription( + model="jinaai/jina-reranker-v2-base-multilingual", + description="A multi-lingual reranker model for cross-encoder re-ranking with 1K context length and sliding window", + license="cc-by-nc-4.0", + size_in_GB=1.11, + sources=ModelSource(hf="jinaai/jina-reranker-v2-base-multilingual"), + model_file="onnx/model.onnx", + ), +] + + +class OnnxTextCrossEncoder(TextCrossEncoderBase, OnnxCrossEncoderModel): + @classmethod + def _list_supported_models(cls) -> list[BaseModelDescription]: + """Lists the supported models. + + Returns: + list[BaseModelDescription]: A list of BaseModelDescription objects containing the model information. + """ + return supported_onnx_models + + def __init__( + self, + model_name: str, + cache_dir: str | None = None, + threads: int | None = None, + providers: Sequence[OnnxProvider] | None = None, + cuda: bool | Device = Device.AUTO, + device_ids: list[int] | None = None, + lazy_load: bool = False, + device_id: int | None = None, + specific_model_path: str | None = None, + **kwargs: Any, + ): + """ + Args: + model_name (str): The name of the model to use. + cache_dir (str, optional): The path to the cache directory. + Can be set using the `FASTEMBED_CACHE_PATH` env variable. + Defaults to `fastembed_cache` in the system's temp directory. + threads (int, optional): The number of threads single onnxruntime session can use. Defaults to None. + providers (Optional[Sequence[OnnxProvider]], optional): The list of onnxruntime providers to use. + Mutually exclusive with the `cuda` and `device_ids` arguments. Defaults to None. + cuda (Union[bool, Device], optional): Whether to use cuda for inference. Mutually exclusive with `providers` + Defaults to Device.AUTO. + device_ids (Optional[list[int]], optional): The list of device ids to use for data parallel processing in + workers. Should be used with `cuda` equals to `True`, `Device.AUTO` or `Device.CUDA`, mutually exclusive + with `providers`. Defaults to None. + lazy_load (bool, optional): Whether to load the model during class initialization or on demand. + Should be set to True when using multiple-gpu and parallel encoding. Defaults to False. + device_id (Optional[int], optional): The device id to use for loading the model in the worker process. + specific_model_path (Optional[str], optional): The specific path to the onnx model dir if it should be imported from somewhere else + + Raises: + ValueError: If the model_name is not in the format / e.g. Xenova/ms-marco-MiniLM-L-6-v2. + """ + super().__init__(model_name, cache_dir, threads, **kwargs) + self.providers = providers + self.lazy_load = lazy_load + self._extra_session_options = self._select_exposed_session_options(kwargs) + + # List of device ids, that can be used for data parallel processing in workers + self.device_ids = device_ids + self.cuda = cuda + + if self.device_ids is not None and len(self.device_ids) > 1: + logger.warning( + "Parallel execution is currently not supported for cross encoders, " + f"only the first device will be used for inference: {self.device_ids[0]}." + ) + + # This device_id will be used if we need to load model in current process + self.device_id: int | None = None + if device_id is not None: + self.device_id = device_id + elif self.device_ids is not None: + self.device_id = self.device_ids[0] + + self.model_description = self._get_model_description(model_name) + self.cache_dir = str(define_cache_dir(cache_dir)) + self._specific_model_path = specific_model_path + self._model_dir = self.download_model( + self.model_description, + self.cache_dir, + local_files_only=self._local_files_only, + specific_model_path=self._specific_model_path, + ) + + if not self.lazy_load: + self.load_onnx_model() + + def load_onnx_model(self) -> None: + self._load_onnx_model( + model_dir=self._model_dir, + model_file=self.model_description.model_file, + threads=self.threads, + providers=self.providers, + cuda=self.cuda, + device_id=self.device_id, + extra_session_options=self._extra_session_options, + ) + + def rerank( + self, + query: str, + documents: Iterable[str], + batch_size: int = 64, + **kwargs: Any, + ) -> Iterable[float]: + """Reranks documents based on their relevance to a given query. + + Args: + query (str): The query string to which document relevance is calculated. + documents (Iterable[str]): Iterable of documents to be reranked. + batch_size (int, optional): The number of documents processed in each batch. Higher batch sizes improve speed + but require more memory. Default is 64. + Returns: + Iterable[float]: An iterable of relevance scores for each document. + """ + + yield from self._rerank_documents( + query=query, documents=documents, batch_size=batch_size, **kwargs + ) + + def rerank_pairs( + self, + pairs: Iterable[tuple[str, str]], + batch_size: int = 64, + parallel: int | None = None, + **kwargs: Any, + ) -> Iterable[float]: + yield from self._rerank_pairs( + model_name=self.model_name, + cache_dir=str(self.cache_dir), + pairs=pairs, + batch_size=batch_size, + parallel=parallel, + providers=self.providers, + cuda=self.cuda, + device_ids=self.device_ids, + local_files_only=self._local_files_only, + specific_model_path=self._specific_model_path, + extra_session_options=self._extra_session_options, + **kwargs, + ) + + @classmethod + def _get_worker_class(cls) -> Type[TextRerankerWorker]: + return TextCrossEncoderWorker + + def _post_process_onnx_output( + self, output: OnnxOutputContext, **kwargs: Any + ) -> Iterable[float]: + return (float(elem) for elem in output.model_output) + + def token_count( + self, pairs: Iterable[tuple[str, str]], batch_size: int = 1024, **kwargs: Any + ) -> int: + """Returns the number of tokens in the pairs. + + Args: + pairs: Iterable of tuples, where each tuple contains a query and a document to be tokenized + batch_size: Batch size for tokenizing + + Returns: + token count: overall number of tokens in the pairs + """ + return self._token_count(pairs, batch_size=batch_size, **kwargs) + + +class TextCrossEncoderWorker(TextRerankerWorker): + def init_embedding( + self, + model_name: str, + cache_dir: str, + **kwargs: Any, + ) -> OnnxTextCrossEncoder: + return OnnxTextCrossEncoder( + model_name=model_name, + cache_dir=cache_dir, + threads=1, + **kwargs, + ) diff --git a/python/user_packages/Python313/site-packages/fastembed/rerank/cross_encoder/onnx_text_model.py b/python/user_packages/Python313/site-packages/fastembed/rerank/cross_encoder/onnx_text_model.py new file mode 100644 index 0000000000000000000000000000000000000000..55f3ea85c947558c223d879b3140e9e026dcf528 --- /dev/null +++ b/python/user_packages/Python313/site-packages/fastembed/rerank/cross_encoder/onnx_text_model.py @@ -0,0 +1,204 @@ +import os +from multiprocessing import get_all_start_methods +from pathlib import Path +from typing import Any, Iterable, Sequence, Type + +import numpy as np +from tokenizers import Encoding + +from fastembed.common.onnx_model import ( + EmbeddingWorker, + OnnxModel, + OnnxOutputContext, + OnnxProvider, +) +from fastembed.common.types import NumpyArray, Device +from fastembed.common.preprocessor_utils import load_tokenizer +from fastembed.common.utils import iter_batch +from fastembed.parallel_processor import ParallelWorkerPool + + +class OnnxCrossEncoderModel(OnnxModel[float]): + ONNX_OUTPUT_NAMES: list[str] | None = None + + @classmethod + def _get_worker_class(cls) -> Type["TextRerankerWorker"]: + raise NotImplementedError("Subclasses must implement this method") + + def _load_onnx_model( + self, + model_dir: Path, + model_file: str, + threads: int | None, + providers: Sequence[OnnxProvider] | None = None, + cuda: bool | Device = Device.AUTO, + device_id: int | None = None, + extra_session_options: dict[str, Any] | None = None, + ) -> None: + super()._load_onnx_model( + model_dir=model_dir, + model_file=model_file, + threads=threads, + providers=providers, + cuda=cuda, + device_id=device_id, + extra_session_options=extra_session_options, + ) + self.tokenizer, _ = load_tokenizer(model_dir=model_dir) + assert self.tokenizer is not None + + def tokenize(self, pairs: list[tuple[str, str]], **_: Any) -> list[Encoding]: + return self.tokenizer.encode_batch(pairs) # type: ignore[union-attr] + + def _build_onnx_input(self, tokenized_input: list[Encoding]) -> dict[str, NumpyArray]: + input_names: set[str] = {node.name for node in self.model.get_inputs()} # type: ignore[union-attr] + inputs: dict[str, NumpyArray] = { + "input_ids": np.array([enc.ids for enc in tokenized_input], dtype=np.int64), + } + if "token_type_ids" in input_names: + inputs["token_type_ids"] = np.array( + [enc.type_ids for enc in tokenized_input], dtype=np.int64 + ) + if "attention_mask" in input_names: + inputs["attention_mask"] = np.array( + [enc.attention_mask for enc in tokenized_input], dtype=np.int64 + ) + return inputs + + def onnx_embed(self, query: str, documents: list[str], **kwargs: Any) -> OnnxOutputContext: + pairs = [(query, doc) for doc in documents] + return self.onnx_embed_pairs(pairs, **kwargs) + + def onnx_embed_pairs(self, pairs: list[tuple[str, str]], **kwargs: Any) -> OnnxOutputContext: + tokenized_input = self.tokenize(pairs, **kwargs) + inputs = self._build_onnx_input(tokenized_input) + onnx_input = self._preprocess_onnx_input(inputs, **kwargs) + outputs = self.model.run(self.ONNX_OUTPUT_NAMES, onnx_input) # type: ignore[union-attr] + relevant_output = outputs[0] + scores: NumpyArray = relevant_output[:, 0] + return OnnxOutputContext(model_output=scores) + + def _rerank_documents( + self, query: str, documents: Iterable[str], batch_size: int, **kwargs: Any + ) -> Iterable[float]: + if not hasattr(self, "model") or self.model is None: + self.load_onnx_model() + for batch in iter_batch(documents, batch_size): + yield from self._post_process_onnx_output(self.onnx_embed(query, batch, **kwargs)) + + def _rerank_pairs( + self, + model_name: str, + cache_dir: str, + pairs: Iterable[tuple[str, str]], + batch_size: int, + parallel: int | None = None, + providers: Sequence[OnnxProvider] | None = None, + cuda: bool | Device = Device.AUTO, + device_ids: list[int] | None = None, + local_files_only: bool = False, + specific_model_path: str | None = None, + extra_session_options: dict[str, Any] | None = None, + **kwargs: Any, + ) -> Iterable[float]: + is_small = False + + if isinstance(pairs, tuple): + pairs = [pairs] + is_small = True + + if isinstance(pairs, list): + if len(pairs) < batch_size: + is_small = True + + if parallel is None or is_small: + if not hasattr(self, "model") or self.model is None: + self.load_onnx_model() + for batch in iter_batch(pairs, batch_size): + yield from self._post_process_onnx_output(self.onnx_embed_pairs(batch, **kwargs)) + else: + if parallel == 0: + parallel = os.cpu_count() + + start_method = "forkserver" if "forkserver" in get_all_start_methods() else "spawn" + params = { + "model_name": model_name, + "cache_dir": cache_dir, + "providers": providers, + "local_files_only": local_files_only, + "specific_model_path": specific_model_path, + **kwargs, + } + + if extra_session_options is not None: + params.update(extra_session_options) + + pool = ParallelWorkerPool( + num_workers=parallel or 1, + worker=self._get_worker_class(), + cuda=cuda, + device_ids=device_ids, + start_method=start_method, + ) + for batch in pool.ordered_map(iter_batch(pairs, batch_size), **params): + yield from self._post_process_onnx_output(batch) # type: ignore + + def _post_process_onnx_output( + self, output: OnnxOutputContext, **kwargs: Any + ) -> Iterable[float]: + """Post-process the ONNX model output to convert it into a usable format. + + Args: + output (OnnxOutputContext): The raw output from the ONNX model. + **kwargs: Additional keyword arguments that may be needed by specific implementations. + + Returns: + Iterable[float]: Post-processed output as an iterable of float values. + """ + raise NotImplementedError("Subclasses must implement this method") + + def _preprocess_onnx_input( + self, onnx_input: dict[str, NumpyArray], **kwargs: Any + ) -> dict[str, NumpyArray]: + """ + Preprocess the onnx input. + """ + return onnx_input + + def _token_count( + self, pairs: Iterable[tuple[str, str]], batch_size: int = 1024, **_: Any + ) -> int: + if not hasattr(self, "model") or self.model is None: + self.load_onnx_model() # loads the tokenizer as well + + token_num = 0 + assert self.tokenizer is not None + for batch in iter_batch(pairs, batch_size): + for tokens in self.tokenizer.encode_batch(batch): + token_num += sum(tokens.attention_mask) + + return token_num + + +class TextRerankerWorker(EmbeddingWorker[float]): + def __init__( + self, + model_name: str, + cache_dir: str, + **kwargs: Any, + ): + self.model: OnnxCrossEncoderModel + super().__init__(model_name, cache_dir, **kwargs) + + def init_embedding( + self, + model_name: str, + cache_dir: str, + **kwargs: Any, + ) -> OnnxCrossEncoderModel: + raise NotImplementedError() + + def process(self, items: Iterable[tuple[int, Any]]) -> Iterable[tuple[int, Any]]: + for idx, batch in items: + onnx_output = self.model.onnx_embed_pairs(batch) + yield idx, onnx_output diff --git a/python/user_packages/Python313/site-packages/fastembed/rerank/cross_encoder/text_cross_encoder.py b/python/user_packages/Python313/site-packages/fastembed/rerank/cross_encoder/text_cross_encoder.py new file mode 100644 index 0000000000000000000000000000000000000000..6f98cb24acdefc7c1ab3af4dc4bab3d62b1d99de --- /dev/null +++ b/python/user_packages/Python313/site-packages/fastembed/rerank/cross_encoder/text_cross_encoder.py @@ -0,0 +1,178 @@ +from typing import Any, Iterable, Sequence, Type +from dataclasses import asdict + +from fastembed.common import OnnxProvider +from fastembed.common.types import Device +from fastembed.rerank.cross_encoder.onnx_text_cross_encoder import OnnxTextCrossEncoder +from fastembed.rerank.cross_encoder.custom_text_cross_encoder import CustomTextCrossEncoder + +from fastembed.rerank.cross_encoder.text_cross_encoder_base import TextCrossEncoderBase +from fastembed.common.model_description import ( + ModelSource, + BaseModelDescription, +) + + +class TextCrossEncoder(TextCrossEncoderBase): + CROSS_ENCODER_REGISTRY: list[Type[TextCrossEncoderBase]] = [ + OnnxTextCrossEncoder, + CustomTextCrossEncoder, + ] + + @classmethod + def list_supported_models(cls) -> list[dict[str, Any]]: + """Lists the supported models. + + Returns: + list[BaseModelDescription]: A list of dictionaries containing the model information. + + Example: + ``` + [ + { + "model": "Xenova/ms-marco-MiniLM-L-6-v2", + "size_in_GB": 0.08, + "sources": { + "hf": "Xenova/ms-marco-MiniLM-L-6-v2", + }, + "model_file": "onnx/model.onnx", + "description": "MiniLM-L-6-v2 model optimized for re-ranking tasks.", + "license": "apache-2.0", + } + ] + ``` + """ + return [asdict(model) for model in cls._list_supported_models()] + + @classmethod + def _list_supported_models(cls) -> list[BaseModelDescription]: + result: list[BaseModelDescription] = [] + for encoder in cls.CROSS_ENCODER_REGISTRY: + result.extend(encoder._list_supported_models()) + return result + + def __init__( + self, + model_name: str, + cache_dir: str | None = None, + threads: int | None = None, + providers: Sequence[OnnxProvider] | None = None, + cuda: bool | Device = Device.AUTO, + device_ids: list[int] | None = None, + lazy_load: bool = False, + **kwargs: Any, + ): + super().__init__(model_name, cache_dir, threads, **kwargs) + + for CROSS_ENCODER_TYPE in self.CROSS_ENCODER_REGISTRY: + supported_models = CROSS_ENCODER_TYPE._list_supported_models() + if any(model_name.lower() == model.model.lower() for model in supported_models): + self.model = CROSS_ENCODER_TYPE( + model_name=model_name, + cache_dir=cache_dir, + threads=threads, + providers=providers, + cuda=cuda, + device_ids=device_ids, + lazy_load=lazy_load, + **kwargs, + ) + return + + raise ValueError( + f"Model {model_name} is not supported in TextCrossEncoder." + "Please check the supported models using `TextCrossEncoder.list_supported_models()`" + ) + + def rerank( + self, query: str, documents: Iterable[str], batch_size: int = 64, **kwargs: Any + ) -> Iterable[float]: + """Rerank a list of documents based on a query. + + Args: + query: Query to rerank the documents against + documents: Iterator of documents to rerank + batch_size: Batch size for reranking + + Returns: + Iterable of scores for each document + """ + yield from self.model.rerank(query, documents, batch_size=batch_size, **kwargs) + + def rerank_pairs( + self, + pairs: Iterable[tuple[str, str]], + batch_size: int = 64, + parallel: int | None = None, + **kwargs: Any, + ) -> Iterable[float]: + """ + Rerank a list of query-document pairs. + + Args: + pairs (Iterable[tuple[str, str]]): An iterable of tuples, where each tuple contains a query and a document + to be scored together. + batch_size (int, optional): The number of query-document pairs to process in a single batch. Defaults to 64. + parallel (Optional[int], optional): The number of parallel processes to use for reranking. + If None, parallelization is disabled. Defaults to None. + **kwargs (Any): Additional arguments to pass to the underlying reranking model. + + Returns: + Iterable[float]: An iterable of scores corresponding to each query-document pair in the input. + Higher scores indicate a stronger match between the query and the document. + + Example: + >>> encoder = TextCrossEncoder("Xenova/ms-marco-MiniLM-L-6-v2") + >>> pairs = [("What is AI?", "Artificial intelligence is ..."), ("What is ML?", "Machine learning is ...")] + >>> scores = list(encoder.rerank_pairs(pairs)) + >>> print(list(map(lambda x: round(x, 2), scores))) + [-1.24, -10.6] + """ + yield from self.model.rerank_pairs( + pairs, batch_size=batch_size, parallel=parallel, **kwargs + ) + + @classmethod + def add_custom_model( + cls, + model: str, + sources: ModelSource, + model_file: str = "onnx/model.onnx", + description: str = "", + license: str = "", + size_in_gb: float = 0.0, + additional_files: list[str] | None = None, + ) -> None: + registered_models = cls._list_supported_models() + for registered_model in registered_models: + if model == registered_model.model: + raise ValueError( + f"Model {model} is already registered in CrossEncoderModel, if you still want to add this model, " + f"please use another model name" + ) + + CustomTextCrossEncoder.add_model( + BaseModelDescription( + model=model, + sources=sources, + model_file=model_file, + description=description, + license=license, + size_in_GB=size_in_gb, + additional_files=additional_files or [], + ) + ) + + def token_count( + self, pairs: Iterable[tuple[str, str]], batch_size: int = 1024, **kwargs: Any + ) -> int: + """Returns the number of tokens in the pairs. + + Args: + pairs: Iterable of tuples, where each tuple contains a query and a document to be tokenized + batch_size: Batch size for tokenizing + + Returns: + token count: overall number of tokens in the pairs + """ + return self.model.token_count(pairs, batch_size=batch_size, **kwargs) diff --git a/python/user_packages/Python313/site-packages/fastembed/rerank/cross_encoder/text_cross_encoder_base.py b/python/user_packages/Python313/site-packages/fastembed/rerank/cross_encoder/text_cross_encoder_base.py new file mode 100644 index 0000000000000000000000000000000000000000..6c2660b0804935b564e6e134c0ac1d490593c83b --- /dev/null +++ b/python/user_packages/Python313/site-packages/fastembed/rerank/cross_encoder/text_cross_encoder_base.py @@ -0,0 +1,63 @@ +from typing import Any, Iterable + +from fastembed.common.model_description import BaseModelDescription +from fastembed.common.model_management import ModelManagement + + +class TextCrossEncoderBase(ModelManagement[BaseModelDescription]): + def __init__( + self, + model_name: str, + cache_dir: str | None = None, + threads: int | None = None, + **kwargs: Any, + ): + self.model_name = model_name + self.cache_dir = cache_dir + self.threads = threads + self._local_files_only = kwargs.pop("local_files_only", False) + + def rerank( + self, + query: str, + documents: Iterable[str], + batch_size: int = 64, + **kwargs: Any, + ) -> Iterable[float]: + """Rerank a list of documents given a query. + + Args: + query (str): The query to rerank the documents. + documents (Iterable[str]): The list of texts to rerank. + batch_size (int): The batch size to use for reranking. + **kwargs: Additional keyword argument to pass to the rerank method. + + Yields: + Iterable[float]: The scores of the reranked the documents. + """ + raise NotImplementedError("This method should be overridden by subclasses") + + def rerank_pairs( + self, + pairs: Iterable[tuple[str, str]], + batch_size: int = 64, + parallel: int | None = None, + **kwargs: Any, + ) -> Iterable[float]: + """Rerank query-document pairs. + Args: + pairs (Iterable[tuple[str, str]]): Query-document pairs to rerank + batch_size (int): The batch size to use for reranking. + parallel: parallel: + If > 1, data-parallel encoding will be used, recommended for offline encoding of large datasets. + If 0, use all available cores. + If None, don't use data-parallel processing, use default onnxruntime threading instead. + **kwargs: Additional keyword argument to pass to the rerank method. + Yields: + Iterable[float]: Scores for each individual pair + """ + raise NotImplementedError("This method should be overridden by subclasses") + + def token_count(self, pairs: Iterable[tuple[str, str]], **kwargs: Any) -> int: + """Returns the number of tokens in the pairs.""" + raise NotImplementedError("This method should be overridden by subclasses") diff --git a/python/user_packages/Python313/site-packages/fastembed/sparse/__init__.py b/python/user_packages/Python313/site-packages/fastembed/sparse/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..93b65e217e6508bb46ba0478307c9fb99d9d855e --- /dev/null +++ b/python/user_packages/Python313/site-packages/fastembed/sparse/__init__.py @@ -0,0 +1,4 @@ +from fastembed.sparse.sparse_embedding_base import SparseEmbedding +from fastembed.sparse.sparse_text_embedding import SparseTextEmbedding + +__all__ = ["SparseEmbedding", "SparseTextEmbedding"] diff --git a/python/user_packages/Python313/site-packages/fastembed/sparse/__pycache__/__init__.cpython-313.pyc b/python/user_packages/Python313/site-packages/fastembed/sparse/__pycache__/__init__.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4d5c5a1fa351f23e62076df8cc2ed78c5ca1e8a2 Binary files /dev/null and b/python/user_packages/Python313/site-packages/fastembed/sparse/__pycache__/__init__.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/fastembed/sparse/__pycache__/bm25.cpython-313.pyc b/python/user_packages/Python313/site-packages/fastembed/sparse/__pycache__/bm25.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7e178b9a3c324378208db31fc5a5ff901372af5f Binary files /dev/null and b/python/user_packages/Python313/site-packages/fastembed/sparse/__pycache__/bm25.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/fastembed/sparse/__pycache__/bm42.cpython-313.pyc b/python/user_packages/Python313/site-packages/fastembed/sparse/__pycache__/bm42.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4b5c7956cc77427e309f76f157470465a0c5945b Binary files /dev/null and b/python/user_packages/Python313/site-packages/fastembed/sparse/__pycache__/bm42.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/fastembed/sparse/__pycache__/minicoil.cpython-313.pyc b/python/user_packages/Python313/site-packages/fastembed/sparse/__pycache__/minicoil.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f4071107cd5b2af15d0178531a165815869ddf18 Binary files /dev/null and b/python/user_packages/Python313/site-packages/fastembed/sparse/__pycache__/minicoil.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/fastembed/sparse/__pycache__/sparse_embedding_base.cpython-313.pyc b/python/user_packages/Python313/site-packages/fastembed/sparse/__pycache__/sparse_embedding_base.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e2850b7c51dbde6abbd71ad17a711d8c46e93b18 Binary files /dev/null and b/python/user_packages/Python313/site-packages/fastembed/sparse/__pycache__/sparse_embedding_base.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/fastembed/sparse/__pycache__/sparse_text_embedding.cpython-313.pyc b/python/user_packages/Python313/site-packages/fastembed/sparse/__pycache__/sparse_text_embedding.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..255eb372121ea874dcf28b6b4bbaa03b6f746565 Binary files /dev/null and b/python/user_packages/Python313/site-packages/fastembed/sparse/__pycache__/sparse_text_embedding.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/fastembed/sparse/__pycache__/splade_pp.cpython-313.pyc b/python/user_packages/Python313/site-packages/fastembed/sparse/__pycache__/splade_pp.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..128e8103db02d53733ee0e48385cca159e38b7fe Binary files /dev/null and b/python/user_packages/Python313/site-packages/fastembed/sparse/__pycache__/splade_pp.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/fastembed/sparse/bm25.py b/python/user_packages/Python313/site-packages/fastembed/sparse/bm25.py new file mode 100644 index 0000000000000000000000000000000000000000..c31acd12c67f3275ebfa78ee0cb05552fd9d2f04 --- /dev/null +++ b/python/user_packages/Python313/site-packages/fastembed/sparse/bm25.py @@ -0,0 +1,359 @@ +import os +from collections import defaultdict +from multiprocessing import get_all_start_methods +from pathlib import Path +from typing import Any, Iterable, Type + +import mmh3 +import numpy as np +from py_rust_stemmers import SnowballStemmer +from fastembed.common.utils import ( + define_cache_dir, + iter_batch, + get_all_punctuation, + remove_non_alphanumeric, +) +from fastembed.parallel_processor import ParallelWorkerPool, Worker +from fastembed.sparse.sparse_embedding_base import ( + SparseEmbedding, + SparseTextEmbeddingBase, +) +from fastembed.sparse.utils.tokenizer import SimpleTokenizer +from fastembed.common.model_description import SparseModelDescription, ModelSource + + +supported_languages = [ + "arabic", + "danish", + "dutch", + "english", + "finnish", + "french", + "german", + "greek", + "hungarian", + "italian", + "norwegian", + "portuguese", + "romanian", + "russian", + "spanish", + "swedish", + "tamil", + "turkish", +] + +supported_bm25_models: list[SparseModelDescription] = [ + SparseModelDescription( + model="Qdrant/bm25", + vocab_size=0, + description="BM25 as sparse embeddings meant to be used with Qdrant", + license="apache-2.0", + size_in_GB=0.01, + sources=ModelSource(hf="Qdrant/bm25"), + additional_files=[f"{lang}.txt" for lang in supported_languages], + requires_idf=True, + model_file="mock.file", + ), +] + + +class Bm25(SparseTextEmbeddingBase): + """Implements traditional BM25 in a form of sparse embeddings. + Uses a count of tokens in the document to evaluate the importance of the token. + + WARNING: This model is expected to be used with `modifier="idf"` in the sparse vector index of Qdrant. + + BM25 formula: + + score(q, d) = SUM[ IDF(q_i) * (f(q_i, d) * (k + 1)) / (f(q_i, d) + k * (1 - b + b * (|d| / avg_len))) ], + + where IDF is the inverse document frequency, computed on Qdrant's side + f(q_i, d) is the term frequency of the token q_i in the document d + k, b, avg_len are hyperparameters, described below. + + Args: + model_name (str): The name of the model to use. + cache_dir (str, optional): The path to the cache directory. + Can be set using the `FASTEMBED_CACHE_PATH` env variable. + Defaults to `fastembed_cache` in the system's temp directory. + k (float, optional): The k parameter in the BM25 formula. Defines the saturation of the term frequency. + I.e. defines how fast the moment when additional terms stop to increase the score. Defaults to 1.2. + b (float, optional): The b parameter in the BM25 formula. Defines the importance of the document length. + Defaults to 0.75. + avg_len (float, optional): The average length of the documents in the corpus. Defaults to 256.0. + language (str): Specifies the language for the stemmer. + disable_stemmer (bool): Disable the stemmer. + Raises: + ValueError: If the model_name is not in the format / e.g. BAAI/bge-base-en. + """ + + def __init__( + self, + model_name: str, + cache_dir: str | None = None, + k: float = 1.2, + b: float = 0.75, + avg_len: float = 256.0, + language: str = "english", + token_max_length: int = 40, + disable_stemmer: bool = False, + specific_model_path: str | None = None, + **kwargs: Any, + ): + super().__init__(model_name, cache_dir, **kwargs) + + if language not in supported_languages: + raise ValueError(f"{language} language is not supported") + else: + self.language = language + + self.k = k + self.b = b + self.avg_len = avg_len + + model_description = self._get_model_description(model_name) + self.cache_dir = str(define_cache_dir(cache_dir)) + + self._specific_model_path = specific_model_path + self._model_dir = self.download_model( + model_description, + self.cache_dir, + local_files_only=self._local_files_only, + specific_model_path=self._specific_model_path, + ) + + self.token_max_length = token_max_length + self.punctuation = set(get_all_punctuation()) + self.disable_stemmer = disable_stemmer + + if disable_stemmer: + self.stopwords: set[str] = set() + self.stemmer = None + else: + self.stopwords = set(self._load_stopwords(self._model_dir, self.language)) + self.stemmer = SnowballStemmer(language) + + self.tokenizer = SimpleTokenizer + + @classmethod + def _list_supported_models(cls) -> list[SparseModelDescription]: + """Lists the supported models. + + Returns: + list[SparseModelDescription]: A list of SparseModelDescription objects containing the model information. + """ + return supported_bm25_models + + @classmethod + def _load_stopwords(cls, model_dir: Path, language: str) -> list[str]: + stopwords_path = model_dir / f"{language}.txt" + if not stopwords_path.exists(): + return [] + + with open(stopwords_path, "r") as f: + return f.read().splitlines() + + def _embed_documents( + self, + model_name: str, + cache_dir: str, + documents: str | Iterable[str], + batch_size: int = 256, + parallel: int | None = None, + local_files_only: bool = False, + specific_model_path: str | None = None, + ) -> Iterable[SparseEmbedding]: + is_small = False + + if isinstance(documents, str): + documents = [documents] + is_small = True + + if isinstance(documents, list): + if len(documents) < batch_size: + is_small = True + + if parallel is None or is_small: + for batch in iter_batch(documents, batch_size): + yield from self.raw_embed(batch) + else: + if parallel == 0: + parallel = os.cpu_count() + + start_method = "forkserver" if "forkserver" in get_all_start_methods() else "spawn" + params = { + "model_name": model_name, + "cache_dir": cache_dir, + "k": self.k, + "b": self.b, + "avg_len": self.avg_len, + "language": self.language, + "token_max_length": self.token_max_length, + "disable_stemmer": self.disable_stemmer, + "local_files_only": local_files_only, + "specific_model_path": specific_model_path, + } + pool = ParallelWorkerPool( + num_workers=parallel or 1, + worker=self._get_worker_class(), + start_method=start_method, + ) + for batch in pool.ordered_map(iter_batch(documents, batch_size), **params): + for record in batch: + yield record # type: ignore + + def embed( + self, + documents: str | Iterable[str], + batch_size: int = 256, + parallel: int | None = None, + **kwargs: Any, + ) -> Iterable[SparseEmbedding]: + """ + Encode a list of documents into list of embeddings. + We use mean pooling with attention so that the model can handle variable-length inputs. + + Args: + documents: Iterator of documents or single document to embed + batch_size: Batch size for encoding -- higher values will use more memory, but be faster + parallel: + If > 1, data-parallel encoding will be used, recommended for offline encoding of large datasets. + If 0, use all available cores. + If None, don't use data-parallel processing, use default onnxruntime threading instead. + + Returns: + List of embeddings, one per document + """ + yield from self._embed_documents( + model_name=self.model_name, + cache_dir=str(self.cache_dir), + documents=documents, + batch_size=batch_size, + parallel=parallel, + local_files_only=self._local_files_only, + specific_model_path=self._specific_model_path, + ) + + def _stem(self, tokens: list[str]) -> list[str]: + stemmed_tokens: list[str] = [] + for token in tokens: + lower_token = token.lower() + + if token in self.punctuation: + continue + + if lower_token in self.stopwords: + continue + + if len(token) > self.token_max_length: + continue + + stemmed_token = self.stemmer.stem_word(lower_token) if self.stemmer else lower_token + + if stemmed_token: + stemmed_tokens.append(stemmed_token) + return stemmed_tokens + + def raw_embed( + self, + documents: list[str], + ) -> list[SparseEmbedding]: + embeddings: list[SparseEmbedding] = [] + for document in documents: + document = remove_non_alphanumeric(document) + tokens = self.tokenizer.tokenize(document) + stemmed_tokens = self._stem(tokens) + token_id2value = self._term_frequency(stemmed_tokens) + embeddings.append(SparseEmbedding.from_dict(token_id2value)) + return embeddings + + def token_count(self, texts: str | Iterable[str], **kwargs: Any) -> int: + token_num = 0 + texts = [texts] if isinstance(texts, str) else texts + for text in texts: + document = remove_non_alphanumeric(text) + tokens = self.tokenizer.tokenize(document) + token_num += len(tokens) + return token_num + + def _term_frequency(self, tokens: list[str]) -> dict[int, float]: + """Calculate the term frequency part of the BM25 formula. + + ( + f(q_i, d) * (k + 1) + ) / ( + f(q_i, d) + k * (1 - b + b * (|d| / avg_len)) + ) + + Args: + tokens (list[str]): The list of tokens in the document. + + Returns: + dict[int, float]: The token_id to term frequency mapping. + """ + tf_map: dict[int, float] = {} + counter: defaultdict[str, int] = defaultdict(int) + for stemmed_token in tokens: + counter[stemmed_token] += 1 + + doc_len = len(tokens) + for stemmed_token in counter: + token_id = self.compute_token_id(stemmed_token) + num_occurrences = counter[stemmed_token] + tf_map[token_id] = num_occurrences * (self.k + 1) + tf_map[token_id] /= num_occurrences + self.k * ( + 1 - self.b + self.b * doc_len / self.avg_len + ) + return tf_map + + @classmethod + def compute_token_id(cls, token: str) -> int: + return abs(mmh3.hash(token)) + + def query_embed(self, query: str | Iterable[str], **kwargs: Any) -> Iterable[SparseEmbedding]: + """To emulate BM25 behaviour, we don't need to use weights in the query, and + it's enough to just hash the tokens and assign a weight of 1.0 to them. + """ + if isinstance(query, str): + query = [query] + + for text in query: + text = remove_non_alphanumeric(text) + tokens = self.tokenizer.tokenize(text) + stemmed_tokens = self._stem(tokens) + token_ids = np.array( + list(set(self.compute_token_id(token) for token in stemmed_tokens)), + dtype=np.int32, + ) + values = np.ones_like(token_ids) + yield SparseEmbedding(indices=token_ids, values=values) + + @classmethod + def _get_worker_class(cls) -> Type["Bm25Worker"]: + return Bm25Worker + + +class Bm25Worker(Worker): + def __init__( + self, + model_name: str, + cache_dir: str, + **kwargs: Any, + ): + self.model = self.init_embedding(model_name, cache_dir, **kwargs) + + @classmethod + def start(cls, model_name: str, cache_dir: str, **kwargs: Any) -> "Bm25Worker": + return cls(model_name=model_name, cache_dir=cache_dir, **kwargs) + + def process( + self, items: Iterable[tuple[int, Any]] + ) -> Iterable[tuple[int, list[SparseEmbedding]]]: + for idx, batch in items: + onnx_output = self.model.raw_embed(batch) + yield idx, onnx_output + + @staticmethod + def init_embedding(model_name: str, cache_dir: str, **kwargs: Any) -> Bm25: + return Bm25(model_name=model_name, cache_dir=cache_dir, **kwargs) diff --git a/python/user_packages/Python313/site-packages/fastembed/sparse/bm42.py b/python/user_packages/Python313/site-packages/fastembed/sparse/bm42.py new file mode 100644 index 0000000000000000000000000000000000000000..2b090f749d44e8fc8fdcaad946d7f00606b3d4fd --- /dev/null +++ b/python/user_packages/Python313/site-packages/fastembed/sparse/bm42.py @@ -0,0 +1,369 @@ +import math +import string +from pathlib import Path +from typing import Any, Iterable, Sequence, Type + +import mmh3 +import numpy as np +from py_rust_stemmers import SnowballStemmer + +from fastembed.common import OnnxProvider +from fastembed.common.onnx_model import OnnxOutputContext +from fastembed.common.types import Device +from fastembed.common.utils import define_cache_dir +from fastembed.sparse.sparse_embedding_base import ( + SparseEmbedding, + SparseTextEmbeddingBase, +) +from fastembed.text.onnx_text_model import OnnxTextModel, TextEmbeddingWorker +from fastembed.common.model_description import SparseModelDescription, ModelSource + +supported_bm42_models: list[SparseModelDescription] = [ + SparseModelDescription( + model="Qdrant/bm42-all-minilm-l6-v2-attentions", + vocab_size=30522, + description="Light sparse embedding model, which assigns an importance score to each token in the text", + license="apache-2.0", + size_in_GB=0.09, + sources=ModelSource(hf="Qdrant/all_miniLM_L6_v2_with_attentions"), + model_file="model.onnx", + additional_files=["stopwords.txt"], + requires_idf=True, + ), +] + + +_MODEL_TO_LANGUAGE = { + "Qdrant/bm42-all-minilm-l6-v2-attentions": "english", +} +MODEL_TO_LANGUAGE = { + model_name.lower(): language for model_name, language in _MODEL_TO_LANGUAGE.items() +} + + +def get_language_by_model_name(model_name: str) -> str: + return MODEL_TO_LANGUAGE[model_name.lower()] + + +class Bm42(SparseTextEmbeddingBase, OnnxTextModel[SparseEmbedding]): + """ + Bm42 is an extension of BM25, which tries to better evaluate importance of tokens in the documents, + by extracting attention weights from the transformer model. + + Traditional BM25 uses a count of tokens in the document to evaluate the importance of the token, + but this approach doesn't work well with short documents or chunks of text, as almost all tokens + there are unique. + + BM42 addresses this issue by replacing the token count with the attention weights from the transformer model. + This allows sparse embeddings to work well with short documents, handle rare tokens and leverage traditional NLP + techniques like stemming and stopwords. + + WARNING: This model is expected to be used with `modifier="idf"` in the sparse vector index of Qdrant. + """ + + ONNX_OUTPUT_NAMES = ["attention_6"] + + def __init__( + self, + model_name: str, + cache_dir: str | None = None, + threads: int | None = None, + providers: Sequence[OnnxProvider] | None = None, + alpha: float = 0.5, + cuda: bool | Device = Device.AUTO, + device_ids: list[int] | None = None, + lazy_load: bool = False, + device_id: int | None = None, + specific_model_path: str | None = None, + **kwargs: Any, + ): + """ + Args: + model_name (str): The name of the model to use. + cache_dir (str, optional): The path to the cache directory. + Can be set using the `FASTEMBED_CACHE_PATH` env variable. + Defaults to `fastembed_cache` in the system's temp directory. + threads (int, optional): The number of threads single onnxruntime session can use. Defaults to None. + providers (Optional[Sequence[OnnxProvider]], optional): The providers to use for onnxruntime. + alpha (float, optional): Parameter, that defines the importance of the token weight in the document + versus the importance of the token frequency in the corpus. Defaults to 0.5, based on empirical testing. + It is recommended to only change this parameter based on training data for a specific dataset. + cuda (Union[bool, Device], optional): Whether to use cuda for inference. Mutually exclusive with `providers` + Defaults to Device.AUTO. + device_ids (Optional[list[int]], optional): The list of device ids to use for data parallel processing in + workers. Should be used with `cuda` equals to `True`, `Device.AUTO` or `Device.CUDA`, mutually exclusive + with `providers`. Defaults to None. + lazy_load (bool, optional): Whether to load the model during class initialization or on demand. + Should be set to True when using multiple-gpu and parallel encoding. Defaults to False. + device_id (Optional[int], optional): The device id to use for loading the model in the worker process. + specific_model_path (Optional[str], optional): The specific path to the onnx model dir if it should be imported from somewhere else + + Raises: + ValueError: If the model_name is not in the format / e.g. BAAI/bge-base-en. + """ + + super().__init__(model_name, cache_dir, threads, **kwargs) + self.providers = providers + self.lazy_load = lazy_load + self._extra_session_options = self._select_exposed_session_options(kwargs) + + # List of device ids, that can be used for data parallel processing in workers + self.device_ids = device_ids + self.cuda = cuda + + # This device_id will be used if we need to load model in current process + self.device_id: int | None = None + if device_id is not None: + self.device_id = device_id + elif self.device_ids is not None: + self.device_id = self.device_ids[0] + + self.model_description = self._get_model_description(model_name) + self.cache_dir = str(define_cache_dir(cache_dir)) + + self._specific_model_path = specific_model_path + self._model_dir = self.download_model( + self.model_description, + self.cache_dir, + local_files_only=self._local_files_only, + specific_model_path=self._specific_model_path, + ) + + self.invert_vocab: dict[int, str] = {} + + self.special_tokens: set[str] = set() + self.special_tokens_ids: set[int] = set() + self.punctuation = set(string.punctuation) + self.stopwords = set(self._load_stopwords(self._model_dir)) + self.stemmer = SnowballStemmer(get_language_by_model_name(self.model_name)) + self.alpha = alpha + + if not self.lazy_load: + self.load_onnx_model() + + def load_onnx_model(self) -> None: + self._load_onnx_model( + model_dir=self._model_dir, + model_file=self.model_description.model_file, + threads=self.threads, + providers=self.providers, + cuda=self.cuda, + device_id=self.device_id, + extra_session_options=self._extra_session_options, + ) + + for token, idx in self.tokenizer.get_vocab().items(): # type: ignore[union-attr] + self.invert_vocab[idx] = token + self.special_tokens = set(self.special_token_to_id.keys()) + self.special_tokens_ids = set(self.special_token_to_id.values()) + self.stopwords = set(self._load_stopwords(self._model_dir)) + + def _filter_pair_tokens(self, tokens: list[tuple[str, Any]]) -> list[tuple[str, Any]]: + result: list[tuple[str, Any]] = [] + for token, value in tokens: + if token in self.stopwords or token in self.punctuation: + continue + result.append((token, value)) + return result + + def _stem_pair_tokens(self, tokens: list[tuple[str, Any]]) -> list[tuple[str, Any]]: + result: list[tuple[str, Any]] = [] + for token, value in tokens: + processed_token = self.stemmer.stem_word(token) + result.append((processed_token, value)) + return result + + @classmethod + def _aggregate_weights( + cls, tokens: list[tuple[str, list[int]]], weights: list[float] + ) -> list[tuple[str, float]]: + result: list[tuple[str, float]] = [] + for token, idxs in tokens: + sum_weight = sum(weights[idx] for idx in idxs) + result.append((token, sum_weight)) + return result + + def _reconstruct_bpe( + self, bpe_tokens: Iterable[tuple[int, str]] + ) -> list[tuple[str, list[int]]]: + result: list[tuple[str, list[int]]] = [] + acc: str = "" + acc_idx: list[int] = [] + + continuing_subword_prefix = self.tokenizer.model.continuing_subword_prefix # type: ignore[union-attr] + continuing_subword_prefix_len = len(continuing_subword_prefix) + + for idx, token in bpe_tokens: + if token in self.special_tokens: + continue + + if token.startswith(continuing_subword_prefix): + acc += token[continuing_subword_prefix_len:] + acc_idx.append(idx) + else: + if acc: + result.append((acc, acc_idx)) + acc_idx = [] + acc = token + acc_idx.append(idx) + + if acc: + result.append((acc, acc_idx)) + + return result + + def _rescore_vector(self, vector: dict[str, float]) -> dict[int, float]: + """ + Orders all tokens in the vector by their importance and generates a new score based on the importance order. + So that the scoring doesn't depend on absolute values assigned by the model, but on the relative importance. + """ + + new_vector: dict[int, float] = {} + + for token, value in vector.items(): + token_id = abs(mmh3.hash(token)) + # Examples: + # Num 0: Log(1/1 + 1) = 0.6931471805599453 + # Num 1: Log(1/2 + 1) = 0.4054651081081644 + # Num 2: Log(1/3 + 1) = 0.28768207245178085 + new_vector[token_id] = math.log(1.0 + value) ** self.alpha # value + + return new_vector + + def _post_process_onnx_output( + self, output: OnnxOutputContext, **kwargs: Any + ) -> Iterable[SparseEmbedding]: + if output.input_ids is None: + raise ValueError("input_ids must be provided for document post-processing") + + token_ids_batch = output.input_ids.astype(int) + + # attention_value shape: (batch_size, num_heads, num_tokens, num_tokens) + pooled_attention = np.mean(output.model_output[:, :, 0], axis=1) * output.attention_mask + + for document_token_ids, attention_value in zip(token_ids_batch, pooled_attention): + document_tokens_with_ids = ( + (idx, self.invert_vocab[token_id]) + for idx, token_id in enumerate(document_token_ids) + ) + + reconstructed = self._reconstruct_bpe(document_tokens_with_ids) + + filtered = self._filter_pair_tokens(reconstructed) + + stemmed = self._stem_pair_tokens(filtered) + + weighted = self._aggregate_weights(stemmed, attention_value) + + max_token_weight: dict[str, float] = {} + + for token, weight in weighted: + max_token_weight[token] = max(max_token_weight.get(token, 0), weight) + + rescored = self._rescore_vector(max_token_weight) + + yield SparseEmbedding.from_dict(rescored) + + @classmethod + def _list_supported_models(cls) -> list[SparseModelDescription]: + """Lists the supported models. + + Returns: + list[SparseModelDescription]: A list of SparseModelDescription objects containing the model information. + """ + return supported_bm42_models + + @classmethod + def _load_stopwords(cls, model_dir: Path) -> list[str]: + stopwords_path = model_dir / "stopwords.txt" + if not stopwords_path.exists(): + return [] + + with open(stopwords_path, "r") as f: + return f.read().splitlines() + + def embed( + self, + documents: str | Iterable[str], + batch_size: int = 256, + parallel: int | None = None, + **kwargs: Any, + ) -> Iterable[SparseEmbedding]: + """ + Encode a list of documents into list of embeddings. + We use mean pooling with attention so that the model can handle variable-length inputs. + + Args: + documents: Iterator of documents or single document to embed + batch_size: Batch size for encoding -- higher values will use more memory, but be faster + parallel: + If > 1, data-parallel encoding will be used, recommended for offline encoding of large datasets. + If 0, use all available cores. + If None, don't use data-parallel processing, use default onnxruntime threading instead. + + Returns: + List of embeddings, one per document + """ + yield from self._embed_documents( + model_name=self.model_name, + cache_dir=str(self.cache_dir), + documents=documents, + batch_size=batch_size, + parallel=parallel, + providers=self.providers, + cuda=self.cuda, + device_ids=self.device_ids, + alpha=self.alpha, + local_files_only=self._local_files_only, + specific_model_path=self._specific_model_path, + extra_session_options=self._extra_session_options, + ) + + @classmethod + def _query_rehash(cls, tokens: Iterable[str]) -> dict[int, float]: + result: dict[int, float] = {} + for token in tokens: + token_id = abs(mmh3.hash(token)) + result[token_id] = 1.0 + return result + + def query_embed(self, query: str | Iterable[str], **kwargs: Any) -> Iterable[SparseEmbedding]: + """ + To emulate BM25 behaviour, we don't need to use smart weights in the query, and + it's enough to just hash the tokens and assign a weight of 1.0 to them. + It is also faster, as we don't need to run the model for the query. + """ + if isinstance(query, str): + query = [query] + + if not hasattr(self, "model") or self.model is None: + self.load_onnx_model() + + for text in query: + encoded = self.tokenizer.encode(text) # type: ignore[union-attr] + document_tokens_with_ids = enumerate(encoded.tokens) + reconstructed = self._reconstruct_bpe(document_tokens_with_ids) + filtered = self._filter_pair_tokens(reconstructed) + stemmed = self._stem_pair_tokens(filtered) + + yield SparseEmbedding.from_dict(self._query_rehash(token for token, _ in stemmed)) + + @classmethod + def _get_worker_class(cls) -> Type[TextEmbeddingWorker[SparseEmbedding]]: + return Bm42TextEmbeddingWorker + + def token_count( + self, texts: str | Iterable[str], batch_size: int = 1024, **kwargs: Any + ) -> int: + if not hasattr(self, "model") or self.model is None: + self.load_onnx_model() # loads the tokenizer as well + return self._token_count(texts, batch_size=batch_size, **kwargs) + + +class Bm42TextEmbeddingWorker(TextEmbeddingWorker[SparseEmbedding]): + def init_embedding(self, model_name: str, cache_dir: str, **kwargs: Any) -> Bm42: + return Bm42( + model_name=model_name, + cache_dir=cache_dir, + **kwargs, + ) diff --git a/python/user_packages/Python313/site-packages/fastembed/sparse/minicoil.py b/python/user_packages/Python313/site-packages/fastembed/sparse/minicoil.py new file mode 100644 index 0000000000000000000000000000000000000000..6f29c60fd340e975a244f59cfc50a66f25132e99 --- /dev/null +++ b/python/user_packages/Python313/site-packages/fastembed/sparse/minicoil.py @@ -0,0 +1,372 @@ +from pathlib import Path + +from typing import Any, Sequence, Iterable, Type + +import numpy as np +from numpy.typing import NDArray +from py_rust_stemmers import SnowballStemmer +from tokenizers import Tokenizer + +from fastembed.common.model_description import SparseModelDescription, ModelSource +from fastembed.common.onnx_model import OnnxOutputContext +from fastembed.common import OnnxProvider +from fastembed.common.types import Device +from fastembed.common.utils import define_cache_dir +from fastembed.sparse.sparse_embedding_base import ( + SparseEmbedding, + SparseTextEmbeddingBase, +) +from fastembed.sparse.utils.minicoil_encoder import Encoder +from fastembed.sparse.utils.sparse_vectors_converter import SparseVectorConverter, WordEmbedding +from fastembed.sparse.utils.vocab_resolver import VocabResolver, VocabTokenizer +from fastembed.text.onnx_text_model import OnnxTextModel, TextEmbeddingWorker + + +MINICOIL_MODEL_FILE = "minicoil.triplet.model.npy" +MINICOIL_VOCAB_FILE = "minicoil.triplet.model.vocab" +STOPWORDS_FILE = "stopwords.txt" + + +supported_minicoil_models: list[SparseModelDescription] = [ + SparseModelDescription( + model="Qdrant/minicoil-v1", + vocab_size=19125, + description="Sparse embedding model, that resolves semantic meaning of the words, " + "while keeping exact keyword match behavior. " + "Based on jinaai/jina-embeddings-v2-small-en-tokens", + license="apache-2.0", + size_in_GB=0.09, + sources=ModelSource(hf="Qdrant/minicoil-v1"), + model_file="onnx/model.onnx", + additional_files=[ + STOPWORDS_FILE, + MINICOIL_MODEL_FILE, + MINICOIL_VOCAB_FILE, + ], + requires_idf=True, + ), +] + +_MODEL_TO_LANGUAGE = { + "Qdrant/minicoil-v1": "english", +} +MODEL_TO_LANGUAGE = { + model_name.lower(): language for model_name, language in _MODEL_TO_LANGUAGE.items() +} + + +def get_language_by_model_name(model_name: str) -> str: + return MODEL_TO_LANGUAGE[model_name.lower()] + + +class MiniCOIL(SparseTextEmbeddingBase, OnnxTextModel[SparseEmbedding]): + """ + MiniCOIL is a sparse embedding model, that resolves semantic meaning of the words, + while keeping exact keyword match behavior. + + Each vocabulary token is converted into 4d component of a sparse vector, which is then weighted by the token frequency in the corpus. + If the token is not found in the corpus, it is treated exactly like in BM25. + ` + The model is based on `jinaai/jina-embeddings-v2-small-en-tokens` + """ + + def __init__( + self, + model_name: str, + cache_dir: str | None = None, + threads: int | None = None, + providers: Sequence[OnnxProvider] | None = None, + k: float = 1.2, + b: float = 0.75, + avg_len: float = 150.0, + cuda: bool | Device = Device.AUTO, + device_ids: list[int] | None = None, + lazy_load: bool = False, + device_id: int | None = None, + specific_model_path: str | None = None, + **kwargs: Any, + ): + """ + Args: + model_name (str): The name of the model to use. + cache_dir (str, optional): The path to the cache directory. + Can be set using the `FASTEMBED_CACHE_PATH` env variable. + Defaults to `fastembed_cache` in the system's temp directory. + threads (int, optional): The number of threads single onnxruntime session can use. Defaults to None. + providers (Optional[Sequence[OnnxProvider]], optional): The providers to use for onnxruntime. + k (float, optional): The k parameter in the BM25 formula. Defines the saturation of the term frequency. + I.e. defines how fast the moment when additional terms stop to increase the score. Defaults to 1.2. + b (float, optional): The b parameter in the BM25 formula. Defines the importance of the document length. + Defaults to 0.75. + avg_len (float, optional): The average length of the documents in the corpus. Defaults to 150.0. + cuda (Union[bool, Device], optional): Whether to use cuda for inference. Mutually exclusive with `providers` + Defaults to Device.AUTO. + device_ids (Optional[list[int]], optional): The list of device ids to use for data parallel processing in + workers. Should be used with `cuda` equals to `True`, `Device.AUTO` or `Device.CUDA`, mutually exclusive + with `providers`. Defaults to None. + lazy_load (bool, optional): Whether to load the model during class initialization or on demand. + Should be set to True when using multiple-gpu and parallel encoding. Defaults to False. + device_id (Optional[int], optional): The device id to use for loading the model in the worker process. + specific_model_path (Optional[str], optional): The specific path to the onnx model dir if it should be imported from somewhere else + + Raises: + ValueError: If the model_name is not in the format / e.g. BAAI/bge-base-en. + """ + + super().__init__(model_name, cache_dir, threads, **kwargs) + self.providers = providers + self.lazy_load = lazy_load + self.device_ids = device_ids + self.cuda = cuda + self.device_id = device_id + self._extra_session_options = self._select_exposed_session_options(kwargs) + + self.k = k + self.b = b + self.avg_len = avg_len + + # Initialize class attributes + self.tokenizer: Tokenizer | None = None + self.invert_vocab: dict[int, str] = {} + self.special_tokens: set[str] = set() + self.special_tokens_ids: set[int] = set() + self.stopwords: set[str] = set() + self.vocab_resolver: VocabResolver | None = None + self.encoder: Encoder | None = None + self.output_dim: int | None = None + self.sparse_vector_converter: SparseVectorConverter | None = None + + self.model_description = self._get_model_description(model_name) + self.cache_dir = str(define_cache_dir(cache_dir)) + self._specific_model_path = specific_model_path + self._model_dir = self.download_model( + self.model_description, + self.cache_dir, + local_files_only=self._local_files_only, + specific_model_path=self._specific_model_path, + ) + + if not self.lazy_load: + self.load_onnx_model() + + def load_onnx_model(self) -> None: + self._load_onnx_model( + model_dir=self._model_dir, + model_file=self.model_description.model_file, + threads=self.threads, + providers=self.providers, + cuda=self.cuda, + device_id=self.device_id, + extra_session_options=self._extra_session_options, + ) + + assert self.tokenizer is not None + + for token, idx in self.tokenizer.get_vocab().items(): # type: ignore[union-attr] + self.invert_vocab[idx] = token + self.special_tokens = set(self.special_token_to_id.keys()) + self.special_tokens_ids = set(self.special_token_to_id.values()) + self.stopwords = set(self._load_stopwords(self._model_dir)) + + stemmer = SnowballStemmer(get_language_by_model_name(self.model_name)) + + self.vocab_resolver = VocabResolver( + tokenizer=VocabTokenizer(self.tokenizer), + stopwords=self.stopwords, + stemmer=stemmer, + ) + self.vocab_resolver.load_json_vocab(str(self._model_dir / MINICOIL_VOCAB_FILE)) + + weights = np.load(str(self._model_dir / MINICOIL_MODEL_FILE), mmap_mode="r") + self.encoder = Encoder(weights) + self.output_dim = self.encoder.output_dim + + self.sparse_vector_converter = SparseVectorConverter( + stopwords=self.stopwords, + stemmer=stemmer, + k=self.k, + b=self.b, + avg_len=self.avg_len, + ) + + def token_count( + self, texts: str | Iterable[str], batch_size: int = 1024, **kwargs: Any + ) -> int: + return self._token_count(texts, batch_size=batch_size, **kwargs) + + def embed( + self, + documents: str | Iterable[str], + batch_size: int = 256, + parallel: int | None = None, + **kwargs: Any, + ) -> Iterable[SparseEmbedding]: + """ + Encode a list of documents into list of embeddings. + We use mean pooling with attention so that the model can handle variable-length inputs. + + Args: + documents: Iterator of documents or single document to embed + batch_size: Batch size for encoding -- higher values will use more memory, but be faster + parallel: + If > 1, data-parallel encoding will be used, recommended for offline encoding of large datasets. + If 0, use all available cores. + If None, don't use data-parallel processing, use default onnxruntime threading instead. + + Returns: + List of embeddings, one per document + """ + yield from self._embed_documents( + model_name=self.model_name, + cache_dir=str(self.cache_dir), + documents=documents, + batch_size=batch_size, + parallel=parallel, + providers=self.providers, + cuda=self.cuda, + device_ids=self.device_ids, + k=self.k, + b=self.b, + avg_len=self.avg_len, + is_query=False, + local_files_only=self._local_files_only, + specific_model_path=self._specific_model_path, + extra_session_options=self._extra_session_options, + **kwargs, + ) + + def query_embed(self, query: str | Iterable[str], **kwargs: Any) -> Iterable[SparseEmbedding]: + """ + Encode a list of queries into list of embeddings. + """ + yield from self._embed_documents( + model_name=self.model_name, + cache_dir=str(self.cache_dir), + documents=query, + providers=self.providers, + cuda=self.cuda, + device_ids=self.device_ids, + k=self.k, + b=self.b, + avg_len=self.avg_len, + is_query=True, + local_files_only=self._local_files_only, + specific_model_path=self._specific_model_path, + **kwargs, + ) + + @classmethod + def _load_stopwords(cls, model_dir: Path) -> list[str]: + stopwords_path = model_dir / STOPWORDS_FILE + if not stopwords_path.exists(): + return [] + + with open(stopwords_path, "r") as f: + return f.read().splitlines() + + @classmethod + def _list_supported_models(cls) -> list[SparseModelDescription]: + """Lists the supported models. + + Returns: + list[SparseModelDescription]: A list of SparseModelDescription objects containing the model information. + """ + return supported_minicoil_models + + def _post_process_onnx_output( + self, output: OnnxOutputContext, is_query: bool = False, **kwargs: Any + ) -> Iterable[SparseEmbedding]: + if output.input_ids is None: + raise ValueError("input_ids must be provided for document post-processing") + + assert self.vocab_resolver is not None + assert self.encoder is not None + assert self.sparse_vector_converter is not None + + # Size: (batch_size, sequence_length, hidden_size) + embeddings = output.model_output + # Size: (batch_size, sequence_length) + assert output.attention_mask is not None + masks = output.attention_mask + + vocab_size = self.vocab_resolver.vocab_size() + embedding_size = self.encoder.output_dim + + # For each document we only select those embeddings that are not masked out + + for i in range(embeddings.shape[0]): + # Size: (sequence_length, hidden_size) + token_embeddings = embeddings[i, masks[i] == 1] + + # Size: (sequence_length) + token_ids: NDArray[np.int64] = output.input_ids[i, masks[i] == 1] + + word_ids_array, counts, oov, forms = self.vocab_resolver.resolve_tokens(token_ids) + + # Size: (1, words) + word_ids_array_expanded: NDArray[np.int64] = np.expand_dims(word_ids_array, axis=0) + + # Size: (1, words, embedding_size) + token_embeddings_array: NDArray[np.float32] = np.expand_dims(token_embeddings, axis=0) + + assert word_ids_array_expanded.shape[1] == token_embeddings_array.shape[1] + + # Size of word_ids_mapping: (unique_words, 2) - [vocab_id, batch_id] + # Size of embeddings: (unique_words, embedding_size) + ids_mapping, minicoil_embeddings = self.encoder.forward( + word_ids_array_expanded, token_embeddings_array + ) + + # Size of counts: (unique_words) + words_ids: list[int] = ids_mapping[:, 0].tolist() # type: ignore[assignment] + + sentence_result: dict[str, WordEmbedding] = {} + + words = [self.vocab_resolver.lookup_word(word_id) for word_id in words_ids] + + for word, word_id, emb in zip(words, words_ids, minicoil_embeddings.tolist()): # type: ignore[arg-type] + if word_id == 0: + continue + + sentence_result[word] = WordEmbedding( + word=word, + forms=forms[word], + count=int(counts[word_id]), + word_id=int(word_id), + embedding=emb, # type: ignore[arg-type] + ) + + for oov_word, count in oov.items(): + # { + # "word": oov_word, + # "forms": [oov_word], + # "count": int(count), + # "word_id": -1, + # "embedding": [1] + # } + sentence_result[oov_word] = WordEmbedding( + word=oov_word, forms=[oov_word], count=int(count), word_id=-1, embedding=[1] + ) + + if not is_query: + yield self.sparse_vector_converter.embedding_to_vector( + sentence_result, vocab_size=vocab_size, embedding_size=embedding_size + ) + else: + yield self.sparse_vector_converter.embedding_to_vector_query( + sentence_result, vocab_size=vocab_size, embedding_size=embedding_size + ) + + @classmethod + def _get_worker_class(cls) -> Type["MiniCoilTextEmbeddingWorker"]: + return MiniCoilTextEmbeddingWorker + + +class MiniCoilTextEmbeddingWorker(TextEmbeddingWorker[SparseEmbedding]): + def init_embedding(self, model_name: str, cache_dir: str, **kwargs: Any) -> MiniCOIL: + return MiniCOIL( + model_name=model_name, + cache_dir=cache_dir, + threads=1, + **kwargs, + ) diff --git a/python/user_packages/Python313/site-packages/fastembed/sparse/sparse_embedding_base.py b/python/user_packages/Python313/site-packages/fastembed/sparse/sparse_embedding_base.py new file mode 100644 index 0000000000000000000000000000000000000000..ea9a49075b851bf19195088e55ba25ac432b5cf4 --- /dev/null +++ b/python/user_packages/Python313/site-packages/fastembed/sparse/sparse_embedding_base.py @@ -0,0 +1,90 @@ +from dataclasses import dataclass +from typing import Iterable, Any + +import numpy as np +from numpy.typing import NDArray + +from fastembed.common.model_description import SparseModelDescription +from fastembed.common.types import NumpyArray +from fastembed.common.model_management import ModelManagement + + +@dataclass +class SparseEmbedding: + values: NumpyArray + indices: NDArray[np.int64] | NDArray[np.int32] + + def as_object(self) -> dict[str, NumpyArray]: + return { + "values": self.values, + "indices": self.indices, + } + + def as_dict(self) -> dict[int, float]: + return {int(i): float(v) for i, v in zip(self.indices, self.values)} # type: ignore + + @classmethod + def from_dict(cls, data: dict[int, float]) -> "SparseEmbedding": + if len(data) == 0: + return cls(values=np.array([]), indices=np.array([])) + indices, values = zip(*data.items()) + return cls(values=np.array(values), indices=np.array(indices)) + + +class SparseTextEmbeddingBase(ModelManagement[SparseModelDescription]): + def __init__( + self, + model_name: str, + cache_dir: str | None = None, + threads: int | None = None, + **kwargs: Any, + ): + self.model_name = model_name + self.cache_dir = cache_dir + self.threads = threads + self._local_files_only = kwargs.pop("local_files_only", False) + + def embed( + self, + documents: str | Iterable[str], + batch_size: int = 256, + parallel: int | None = None, + **kwargs: Any, + ) -> Iterable[SparseEmbedding]: + raise NotImplementedError() + + def passage_embed(self, texts: Iterable[str], **kwargs: Any) -> Iterable[SparseEmbedding]: + """ + Embeds a list of text passages into a list of embeddings. + + Args: + texts (Iterable[str]): The list of texts to embed. + **kwargs: Additional keyword argument to pass to the embed method. + + Yields: + Iterable[SparseEmbedding]: The sparse embeddings. + """ + + # This is model-specific, so that different models can have specialized implementations + yield from self.embed(texts, **kwargs) + + def query_embed(self, query: str | Iterable[str], **kwargs: Any) -> Iterable[SparseEmbedding]: + """ + Embeds queries + + Args: + query (Union[str, Iterable[str]]): The query to embed, or an iterable e.g. list of queries. + + Returns: + Iterable[SparseEmbedding]: The sparse embeddings. + """ + + # This is model-specific, so that different models can have specialized implementations + if isinstance(query, str): + yield from self.embed([query], **kwargs) + else: + yield from self.embed(query, **kwargs) + + def token_count(self, texts: str | Iterable[str], **kwargs: Any) -> int: + """Returns the number of tokens in the texts.""" + raise NotImplementedError("Subclasses must implement this method") diff --git a/python/user_packages/Python313/site-packages/fastembed/sparse/sparse_text_embedding.py b/python/user_packages/Python313/site-packages/fastembed/sparse/sparse_text_embedding.py new file mode 100644 index 0000000000000000000000000000000000000000..5b5c83085520e82eb7faaeca007f7c29c69bacfe --- /dev/null +++ b/python/user_packages/Python313/site-packages/fastembed/sparse/sparse_text_embedding.py @@ -0,0 +1,143 @@ +from typing import Any, Iterable, Sequence, Type +from dataclasses import asdict + +from fastembed.common import OnnxProvider +from fastembed.common.types import Device +from fastembed.sparse.bm25 import Bm25 +from fastembed.sparse.bm42 import Bm42 +from fastembed.sparse.minicoil import MiniCOIL +from fastembed.sparse.sparse_embedding_base import ( + SparseEmbedding, + SparseTextEmbeddingBase, +) +from fastembed.sparse.splade_pp import SpladePP +import warnings +from fastembed.common.model_description import SparseModelDescription + + +class SparseTextEmbedding(SparseTextEmbeddingBase): + EMBEDDINGS_REGISTRY: list[Type[SparseTextEmbeddingBase]] = [SpladePP, Bm42, Bm25, MiniCOIL] + + @classmethod + def list_supported_models(cls) -> list[dict[str, Any]]: + """ + Lists the supported models. + + Returns: + list[dict[str, Any]]: A list of dictionaries containing the model information. + + Example: + ``` + [ + { + "model": "prithvida/SPLADE_PP_en_v1", + "vocab_size": 30522, + "description": "Independent Implementation of SPLADE++ Model for English", + "license": "apache-2.0", + "size_in_GB": 0.532, + "sources": { + "hf": "qdrant/SPLADE_PP_en_v1", + }, + } + ] + ``` + """ + return [asdict(model) for model in cls._list_supported_models()] + + @classmethod + def _list_supported_models(cls) -> list[SparseModelDescription]: + result: list[SparseModelDescription] = [] + for embedding in cls.EMBEDDINGS_REGISTRY: + result.extend(embedding._list_supported_models()) + return result + + def __init__( + self, + model_name: str, + cache_dir: str | None = None, + threads: int | None = None, + providers: Sequence[OnnxProvider] | None = None, + cuda: bool | Device = Device.AUTO, + device_ids: list[int] | None = None, + lazy_load: bool = False, + **kwargs: Any, + ): + super().__init__(model_name, cache_dir, threads, **kwargs) + if model_name.lower() == "prithvida/Splade_PP_en_v1".lower(): + warnings.warn( + "The right spelling is prithivida/Splade_PP_en_v1. " + "Support of this name will be removed soon, please fix the model_name", + DeprecationWarning, + stacklevel=2, + ) + model_name = "prithivida/Splade_PP_en_v1" + + for EMBEDDING_MODEL_TYPE in self.EMBEDDINGS_REGISTRY: + supported_models = EMBEDDING_MODEL_TYPE._list_supported_models() + if any(model_name.lower() == model.model.lower() for model in supported_models): + self.model = EMBEDDING_MODEL_TYPE( + model_name, + cache_dir, + threads=threads, + providers=providers, + cuda=cuda, + device_ids=device_ids, + lazy_load=lazy_load, + **kwargs, + ) + return + + raise ValueError( + f"Model {model_name} is not supported in SparseTextEmbedding." + "Please check the supported models using `SparseTextEmbedding.list_supported_models()`" + ) + + def embed( + self, + documents: str | Iterable[str], + batch_size: int = 256, + parallel: int | None = None, + **kwargs: Any, + ) -> Iterable[SparseEmbedding]: + """ + Encode a list of documents into list of embeddings. + We use mean pooling with attention so that the model can handle variable-length inputs. + + Args: + documents: Iterator of documents or single document to embed + batch_size: Batch size for encoding -- higher values will use more memory, but be faster + parallel: + If > 1, data-parallel encoding will be used, recommended for offline encoding of large datasets. + If 0, use all available cores. + If None, don't use data-parallel processing, use default onnxruntime threading instead. + + Returns: + List of embeddings, one per document + """ + yield from self.model.embed(documents, batch_size, parallel, **kwargs) + + def query_embed(self, query: str | Iterable[str], **kwargs: Any) -> Iterable[SparseEmbedding]: + """ + Embeds queries + + Args: + query (Union[str, Iterable[str]]): The query to embed, or an iterable e.g. list of queries. + + Returns: + Iterable[SparseEmbedding]: The sparse embeddings. + """ + yield from self.model.query_embed(query, **kwargs) + + def token_count( + self, texts: str | Iterable[str], batch_size: int = 1024, **kwargs: Any + ) -> int: + """Returns the number of tokens in the texts. + + Args: + texts (str | Iterable[str]): The list of texts to embed. + batch_size (int): Batch size for encoding + + Returns: + int: Sum of number of tokens in the texts. + """ + return self.model.token_count(texts, batch_size=batch_size, **kwargs) diff --git a/python/user_packages/Python313/site-packages/fastembed/sparse/splade_pp.py b/python/user_packages/Python313/site-packages/fastembed/sparse/splade_pp.py new file mode 100644 index 0000000000000000000000000000000000000000..562ebcd4bf9e8c069f640ae01a7a01d29d0b2035 --- /dev/null +++ b/python/user_packages/Python313/site-packages/fastembed/sparse/splade_pp.py @@ -0,0 +1,196 @@ +from typing import Any, Iterable, Sequence, Type + +import numpy as np +from fastembed.common import OnnxProvider +from fastembed.common.onnx_model import OnnxOutputContext +from fastembed.common.types import Device +from fastembed.common.utils import define_cache_dir +from fastembed.sparse.sparse_embedding_base import ( + SparseEmbedding, + SparseTextEmbeddingBase, +) +from fastembed.text.onnx_text_model import OnnxTextModel, TextEmbeddingWorker +from fastembed.common.model_description import SparseModelDescription, ModelSource + +supported_splade_models: list[SparseModelDescription] = [ + SparseModelDescription( + model="prithivida/Splade_PP_en_v1", + vocab_size=30522, + description="Independent Implementation of SPLADE++ Model for English.", + license="apache-2.0", + size_in_GB=0.532, + sources=ModelSource(hf="Qdrant/Splade_PP_en_v1"), + model_file="model.onnx", + ), + SparseModelDescription( + model="prithvida/Splade_PP_en_v1", + vocab_size=30522, + description="Independent Implementation of SPLADE++ Model for English.", + license="apache-2.0", + size_in_GB=0.532, + sources=ModelSource(hf="Qdrant/Splade_PP_en_v1"), + model_file="model.onnx", + ), +] + + +class SpladePP(SparseTextEmbeddingBase, OnnxTextModel[SparseEmbedding]): + def _post_process_onnx_output( + self, output: OnnxOutputContext, **kwargs: Any + ) -> Iterable[SparseEmbedding]: + if output.attention_mask is None: + raise ValueError("attention_mask must be provided for document post-processing") + + relu_log = np.log(1 + np.maximum(output.model_output, 0)) + + weighted_log = relu_log * np.expand_dims(output.attention_mask, axis=-1) + + scores = np.max(weighted_log, axis=1) + + # Score matrix of shape (batch_size, vocab_size) + # Most of the values are 0, only a few are non-zero + for row_scores in scores: + indices = row_scores.nonzero()[0] + scores = row_scores[indices] + yield SparseEmbedding(values=scores, indices=indices) + + def token_count( + self, texts: str | Iterable[str], batch_size: int = 1024, **kwargs: Any + ) -> int: + return self._token_count(texts, batch_size=batch_size, **kwargs) + + @classmethod + def _list_supported_models(cls) -> list[SparseModelDescription]: + """Lists the supported models. + + Returns: + list[SparseModelDescription]: A list of SparseModelDescription objects containing the model information. + """ + return supported_splade_models + + def __init__( + self, + model_name: str, + cache_dir: str | None = None, + threads: int | None = None, + providers: Sequence[OnnxProvider] | None = None, + cuda: bool | Device = Device.AUTO, + device_ids: list[int] | None = None, + lazy_load: bool = False, + device_id: int | None = None, + specific_model_path: str | None = None, + **kwargs: Any, + ): + """ + Args: + model_name (str): The name of the model to use. + cache_dir (str, optional): The path to the cache directory. + Can be set using the `FASTEMBED_CACHE_PATH` env variable. + Defaults to `fastembed_cache` in the system's temp directory. + threads (int, optional): The number of threads single onnxruntime session can use. Defaults to None. + providers (Optional[Sequence[OnnxProvider]], optional): The list of onnxruntime providers to use. + Mutually exclusive with the `cuda` and `device_ids` arguments. Defaults to None. + cuda (Union[bool, Device], optional): Whether to use cuda for inference. Mutually exclusive with `providers` + Defaults to Device. + device_ids (Optional[list[int]], optional): The list of device ids to use for data parallel processing in + workers. Should be used with `cuda` equals to `True`, `Device.AUTO` or `Device.CUDA`, mutually exclusive + with `providers`. Defaults to None. + lazy_load (bool, optional): Whether to load the model during class initialization or on demand. + Should be set to True when using multiple-gpu and parallel encoding. Defaults to False. + device_id (Optional[int], optional): The device id to use for loading the model in the worker process. + specific_model_path (Optional[str], optional): The specific path to the onnx model dir if it should be imported from somewhere else + + Raises: + ValueError: If the model_name is not in the format / e.g. BAAI/bge-base-en. + """ + super().__init__(model_name, cache_dir, threads, **kwargs) + self.providers = providers + self.lazy_load = lazy_load + self._extra_session_options = self._select_exposed_session_options(kwargs) + + # List of device ids, that can be used for data parallel processing in workers + self.device_ids = device_ids + self.cuda = cuda + + # This device_id will be used if we need to load model in current process + self.device_id: int | None = None + if device_id is not None: + self.device_id = device_id + elif self.device_ids is not None: + self.device_id = self.device_ids[0] + + self.model_description = self._get_model_description(model_name) + self.cache_dir = str(define_cache_dir(cache_dir)) + + self._specific_model_path = specific_model_path + self._model_dir = self.download_model( + self.model_description, + self.cache_dir, + local_files_only=self._local_files_only, + specific_model_path=self._specific_model_path, + ) + + if not self.lazy_load: + self.load_onnx_model() + + def load_onnx_model(self) -> None: + self._load_onnx_model( + model_dir=self._model_dir, + model_file=self.model_description.model_file, + threads=self.threads, + providers=self.providers, + cuda=self.cuda, + device_id=self.device_id, + extra_session_options=self._extra_session_options, + ) + + def embed( + self, + documents: str | Iterable[str], + batch_size: int = 256, + parallel: int | None = None, + **kwargs: Any, + ) -> Iterable[SparseEmbedding]: + """ + Encode a list of documents into list of embeddings. + We use mean pooling with attention so that the model can handle variable-length inputs. + + Args: + documents: Iterator of documents or single document to embed + batch_size: Batch size for encoding -- higher values will use more memory, but be faster + parallel: + If > 1, data-parallel encoding will be used, recommended for offline encoding of large datasets. + If 0, use all available cores. + If None, don't use data-parallel processing, use default onnxruntime threading instead. + + Returns: + List of embeddings, one per document + """ + yield from self._embed_documents( + model_name=self.model_name, + cache_dir=str(self.cache_dir), + documents=documents, + batch_size=batch_size, + parallel=parallel, + providers=self.providers, + cuda=self.cuda, + device_ids=self.device_ids, + local_files_only=self._local_files_only, + specific_model_path=self._specific_model_path, + extra_session_options=self._extra_session_options, + **kwargs, + ) + + @classmethod + def _get_worker_class(cls) -> Type[TextEmbeddingWorker[SparseEmbedding]]: + return SpladePPEmbeddingWorker + + +class SpladePPEmbeddingWorker(TextEmbeddingWorker[SparseEmbedding]): + def init_embedding(self, model_name: str, cache_dir: str, **kwargs: Any) -> SpladePP: + return SpladePP( + model_name=model_name, + cache_dir=cache_dir, + threads=1, + **kwargs, + ) diff --git a/python/user_packages/Python313/site-packages/fastembed/sparse/utils/__pycache__/minicoil_encoder.cpython-313.pyc b/python/user_packages/Python313/site-packages/fastembed/sparse/utils/__pycache__/minicoil_encoder.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4de61f98c657995ada20a93a81a4d87f69d2d8d9 Binary files /dev/null and b/python/user_packages/Python313/site-packages/fastembed/sparse/utils/__pycache__/minicoil_encoder.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/fastembed/sparse/utils/__pycache__/sparse_vectors_converter.cpython-313.pyc b/python/user_packages/Python313/site-packages/fastembed/sparse/utils/__pycache__/sparse_vectors_converter.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b373c080faecb80129adf24a0602eab972561785 Binary files /dev/null and b/python/user_packages/Python313/site-packages/fastembed/sparse/utils/__pycache__/sparse_vectors_converter.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/fastembed/sparse/utils/__pycache__/tokenizer.cpython-313.pyc b/python/user_packages/Python313/site-packages/fastembed/sparse/utils/__pycache__/tokenizer.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7e23c1bc47d6d2cb4f0d0bcf5e4bbd2a4df88ec7 Binary files /dev/null and b/python/user_packages/Python313/site-packages/fastembed/sparse/utils/__pycache__/tokenizer.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/fastembed/sparse/utils/__pycache__/vocab_resolver.cpython-313.pyc b/python/user_packages/Python313/site-packages/fastembed/sparse/utils/__pycache__/vocab_resolver.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ec9a8788986d0a43f373976c143741f20494cb8d Binary files /dev/null and b/python/user_packages/Python313/site-packages/fastembed/sparse/utils/__pycache__/vocab_resolver.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/fastembed/sparse/utils/minicoil_encoder.py b/python/user_packages/Python313/site-packages/fastembed/sparse/utils/minicoil_encoder.py new file mode 100644 index 0000000000000000000000000000000000000000..fc70acd6890772e259106852d03e64aee567be95 --- /dev/null +++ b/python/user_packages/Python313/site-packages/fastembed/sparse/utils/minicoil_encoder.py @@ -0,0 +1,146 @@ +""" +Pure numpy implementation of encoder model for a single word. + +This model is not trainable, and should only be used for inference. +""" + +import numpy as np +from fastembed.common.types import NumpyArray + + +class Encoder: + """ + Encoder(768, 4, 10000) + + Will look like this: + + + Per-word + Encoder Matrix + ┌─────────────────────┐ + │ Token Embedding(768)├──────┐ (10k, 768, 4) + └─────────────────────┘ │ ┌─────────┐ + │ │ │ + ┌─────────────────────┐ │ ┌─┴───────┐ │ + │ │ │ │ │ │ + └─────────────────────┘ │ ┌─┴───────┐ │ │ ┌─────────┐ + └────►│ │ │ ├─────►│Tanh │ + ┌─────────────────────┐ │ │ │ │ └─────────┘ + │ │ │ │ ├─┘ + └─────────────────────┘ │ ├─┘ + │ │ + ┌─────────────────────┐ └─────────┘ + │ │ + └─────────────────────┘ + + Final linear transformation is accompanied by a non-linear activation function: Tanh. + + Tanh is used to ensure that the output is in the range [-1, 1]. + It would be easier to visually interpret the output of the model, assuming that each dimension + would need to encode a type of semantic cluster. + """ + + def __init__( + self, + weights: NumpyArray, + ): + self.weights = weights + self.vocab_size, self.input_dim, self.output_dim = weights.shape + + self.encoder_weights: NumpyArray = weights + + # Activation function + self.activation = np.tanh + + @staticmethod + def convert_vocab_ids(vocab_ids: NumpyArray) -> NumpyArray: + """ + Convert vocab_ids of shape (batch_size, seq_len) into (batch_size, seq_len, 2) + by appending batch_id alongside each vocab_id. + """ + batch_size, seq_len = vocab_ids.shape + batch_ids = np.arange(batch_size, dtype=vocab_ids.dtype).reshape(batch_size, 1) + batch_ids = np.repeat(batch_ids, seq_len, axis=1) + # Stack vocab_ids and batch_ids along the last dimension + combined: NumpyArray = np.stack((vocab_ids, batch_ids), axis=2).astype(np.int32) + return combined + + @classmethod + def avg_by_vocab_ids( + cls, vocab_ids: NumpyArray, embeddings: NumpyArray + ) -> tuple[NumpyArray, NumpyArray]: + """ + Takes: + vocab_ids: (batch_size, seq_len) int array + embeddings: (batch_size, seq_len, input_dim) float array + + Returns: + unique_flattened_vocab_ids: (total_unique, 2) array of [vocab_id, batch_id] + unique_flattened_embeddings: (total_unique, input_dim) averaged embeddings + """ + input_dim = embeddings.shape[2] + + # Flatten vocab_ids and embeddings + # flattened_vocab_ids: (batch_size*seq_len, 2) + flattened_vocab_ids = cls.convert_vocab_ids(vocab_ids).reshape(-1, 2) + + # flattened_embeddings: (batch_size*seq_len, input_dim) + flattened_embeddings = embeddings.reshape(-1, input_dim) + + # Find unique (vocab_id, batch_id) pairs + unique_flattened_vocab_ids, inverse_indices = np.unique( + flattened_vocab_ids, axis=0, return_inverse=True + ) + + # Prepare arrays to accumulate sums + unique_count = unique_flattened_vocab_ids.shape[0] + unique_flattened_embeddings = np.zeros((unique_count, input_dim), dtype=np.float32) + unique_flattened_count = np.zeros(unique_count, dtype=np.int32) + + # Use np.add.at to accumulate sums based on inverse indices + np.add.at(unique_flattened_embeddings, inverse_indices, flattened_embeddings) + np.add.at(unique_flattened_count, inverse_indices, 1) + + # Compute averages + unique_flattened_embeddings /= unique_flattened_count[:, None] + + return unique_flattened_vocab_ids.astype(np.int32), unique_flattened_embeddings.astype( + np.float32 + ) + + def forward( + self, vocab_ids: NumpyArray, embeddings: NumpyArray + ) -> tuple[NumpyArray, NumpyArray]: + """ + Args: + vocab_ids: (batch_size, seq_len) int array + embeddings: (batch_size, seq_len, input_dim) float array + + Returns: + unique_flattened_vocab_ids_and_batch_ids: (total_unique, 2) + unique_flattened_encoded: (total_unique, output_dim) + """ + # Average embeddings for duplicate vocab_ids + unique_flattened_vocab_ids_and_batch_ids, unique_flattened_embeddings = ( + self.avg_by_vocab_ids(vocab_ids, embeddings) + ) + + # Select the encoder weights for each unique vocab_id + unique_flattened_vocab_ids = unique_flattened_vocab_ids_and_batch_ids[:, 0].astype( + np.int32 + ) + + # unique_encoder_weights: (total_unique, input_dim, output_dim) + unique_encoder_weights = self.encoder_weights[unique_flattened_vocab_ids] + + # Compute linear transform: (total_unique, output_dim) + # Using Einstein summation for matrix multiplication: + # 'bi,bio->bo' means: for each "b" (batch element), multiply embeddings (b,i) by weights (b,i,o) -> (b,o) + unique_flattened_encoded = np.einsum( + "bi,bio->bo", unique_flattened_embeddings, unique_encoder_weights + ) + + # Apply Tanh activation and ensure float32 type + unique_flattened_encoded = self.activation(unique_flattened_encoded).astype(np.float32) + + return unique_flattened_vocab_ids_and_batch_ids.astype(np.int32), unique_flattened_encoded diff --git a/python/user_packages/Python313/site-packages/fastembed/sparse/utils/sparse_vectors_converter.py b/python/user_packages/Python313/site-packages/fastembed/sparse/utils/sparse_vectors_converter.py new file mode 100644 index 0000000000000000000000000000000000000000..f856f0de4986fc3249961c6b451c79e040ca98c1 --- /dev/null +++ b/python/user_packages/Python313/site-packages/fastembed/sparse/utils/sparse_vectors_converter.py @@ -0,0 +1,244 @@ +import copy +from dataclasses import dataclass + +import mmh3 +import numpy as np +from py_rust_stemmers import SnowballStemmer + +from fastembed.common.utils import get_all_punctuation, remove_non_alphanumeric +from fastembed.sparse.sparse_embedding_base import SparseEmbedding + +GAP = 32000 +INT32_MAX = 2**31 - 1 + + +@dataclass +class WordEmbedding: + word: str + forms: list[str] + count: int + word_id: int + embedding: list[float] + + +class SparseVectorConverter: + def __init__( + self, + stopwords: set[str], + stemmer: SnowballStemmer, + k: float = 1.2, + b: float = 0.75, + avg_len: float = 150.0, + ): + punctuation = set(get_all_punctuation()) + special_tokens = {"[CLS]", "[SEP]", "[PAD]", "[UNK]", "[MASK]"} + + self.stemmer = stemmer + self.unwanted_tokens = punctuation | special_tokens | stopwords + + self.k = k + self.b = b + self.avg_len = avg_len + + @classmethod + def unkn_word_token_id( + cls, word: str, shift: int + ) -> int: # 2-3 words can collide in 1 index with this mapping, not considering mm3 collisions + token_hash = abs(mmh3.hash(word)) + + range_size = INT32_MAX - shift + remapped_hash = shift + (token_hash % range_size) + + return remapped_hash + + def bm25_tf(self, num_occurrences: int, sentence_len: int) -> float: + res = num_occurrences * (self.k + 1) + res /= num_occurrences + self.k * (1 - self.b + self.b * sentence_len / self.avg_len) + return res + + @classmethod + def normalize_vector(cls, vector: list[float]) -> list[float]: + norm = sum([x**2 for x in vector]) ** 0.5 + if norm < 1e-8: + return vector + return [x / norm for x in vector] + + def clean_words( + self, sentence_embedding: dict[str, WordEmbedding], token_max_length: int = 40 + ) -> dict[str, WordEmbedding]: + """ + Clean miniCOIL-produced sentence_embedding, as unknown to the miniCOIL's stemmer tokens should fully resemble + our BM25 token representation. + + sentence_embedding = {"9°": {"word": "9°", "word_id": -1, "count": 2, "embedding": [1], "forms": ["9°"]}, + "9": {"word": "9", "word_id": -1, "count": 2, "embedding": [1], "forms": ["9"]}, + "bat": {"word": "bat", "word_id": 2, "count": 3, "embedding": [0.2, 0.1, -0.2, -0.2], "forms": ["bats", "bat"]}, + "9°9": {"word": "9°9", "word_id": -1, "count": 1, "embedding": [1], "forms": ["9°9"]}, + "screech": {"word": "screech", "word_id": -1, "count": 1, "embedding": [1], "forms": ["screech"]}, + "screeched": {"word": "screeched", "word_id": -1, "count": 1, "embedding": [1], "forms": ["screeched"]} + } + cleaned_embedding_ground_truth = { + "9": {"word": "9", "word_id": -1, "count": 6, "embedding": [1], "forms": ["9°", "9", "9°9", "9°9"]}, + "bat": {"word": "bat", "word_id": 2, "count": 3, "embedding": [0.2, 0.1, -0.2, -0.2], "forms": ["bats", "bat"]}, + "screech": {"word": "screech", "word_id": -1, "count": 2, "embedding": [1], "forms": ["screech", "screeched"]} + } + """ + + new_sentence_embedding: dict[str, WordEmbedding] = {} + + for word, embedding in sentence_embedding.items(): + # embedding = { + # "word": "vector", + # "forms": ["vector", "vectors"], + # "count": 2, + # "word_id": 1231, + # "embedding": [0.1, 0.2, 0.3, 0.4] + # } + if embedding.word_id > 0: + # Known word, no need to clean + new_sentence_embedding[word] = embedding + else: + # Unknown word + if word in self.unwanted_tokens: + continue + + # Example complex word split: + # word = `word^vec` + word_cleaned = remove_non_alphanumeric(word).strip() + # word_cleaned = `word vec` + + if len(word_cleaned) > 0: + # Subwords: ['word', 'vec'] + for subword in word_cleaned.split(): + stemmed_subword: str = self.stemmer.stem_word(subword) + if ( + len(stemmed_subword) <= token_max_length + and stemmed_subword not in self.unwanted_tokens + ): + if stemmed_subword not in new_sentence_embedding: + new_sentence_embedding[stemmed_subword] = copy.deepcopy(embedding) + new_sentence_embedding[stemmed_subword].word = stemmed_subword + else: + new_sentence_embedding[stemmed_subword].count += embedding.count + new_sentence_embedding[stemmed_subword].forms += embedding.forms + + return new_sentence_embedding + + def embedding_to_vector( + self, + sentence_embedding: dict[str, WordEmbedding], + embedding_size: int, + vocab_size: int, + ) -> SparseEmbedding: + """ + Convert miniCOIL sentence embedding to Qdrant sparse vector + + Example input: + + ``` + { + "vector": WordEmbedding({ // Vocabulary word, encoded with miniCOIL normally + "word": "vector", + "forms": ["vector", "vectors"], + "count": 2, + "word_id": 1231, + "embedding": [0.1, 0.2, 0.3, 0.4] + }), + "axiotic": WordEmbedding({ // Out-of-vocabulary word, fallback to BM25 + "word": "axiotic", + "forms": ["axiotics"], + "count": 1, + "word_id": -1, + }) + } + ``` + + """ + + indices: list[int] = [] + values: list[float] = [] + + # Example: + # vocab_size = 10000 + # embedding_size = 4 + # GAP = 32000 + # + # We want to start random words section from the bucket, that is guaranteed to not + # include any vocab words. + # We need (vocab_size * embedding_size) slots for vocab words. + # Therefore we need (vocab_size * embedding_size) // GAP + 1 buckets for vocab words. + # Therefore, we can start random words from bucket (vocab_size * embedding_size) // GAP + 1 + 1 + + # ID at which the scope of OOV words starts + unknown_words_shift = ((vocab_size * embedding_size) // GAP + 2) * GAP + sentence_embedding_cleaned = self.clean_words(sentence_embedding) + + # Calculate sentence length after cleaning + sentence_len = 0 + for embedding in sentence_embedding_cleaned.values(): + sentence_len += embedding.count + + for embedding in sentence_embedding_cleaned.values(): + word_id = embedding.word_id + num_occurrences = embedding.count + tf = self.bm25_tf(num_occurrences, sentence_len) + if ( + word_id > 0 + ): # miniCOIL starts with ID 1, we generally won't have word_id == 0 (UNK), as we don't add + # these words to sentence_embedding + embedding_values = embedding.embedding + normalized_embedding = self.normalize_vector(embedding_values) + + for val_id, value in enumerate(normalized_embedding): + indices.append( + word_id * embedding_size + val_id + ) # since miniCOIL IDs start with 1 + values.append(value * tf) + else: + indices.append(self.unkn_word_token_id(embedding.word, unknown_words_shift)) + values.append(tf) + + return SparseEmbedding( + indices=np.array(indices, dtype=np.int32), + values=np.array(values, dtype=np.float32), + ) + + def embedding_to_vector_query( + self, + sentence_embedding: dict[str, WordEmbedding], + embedding_size: int, + vocab_size: int, + ) -> SparseEmbedding: + """ + Same as `embedding_to_vector`, but no TF + """ + + indices: list[int] = [] + values: list[float] = [] + + # ID at which the scope of OOV words starts + unknown_words_shift = ((vocab_size * embedding_size) // GAP + 2) * GAP + + sentence_embedding_cleaned = self.clean_words(sentence_embedding) + + for embedding in sentence_embedding_cleaned.values(): + word_id = embedding.word_id + tf = 1.0 + + if word_id >= 0: # miniCOIL starts with ID 1 + embedding_values = embedding.embedding + normalized_embedding = self.normalize_vector(embedding_values) + + for val_id, value in enumerate(normalized_embedding): + indices.append( + word_id * embedding_size + val_id + ) # since miniCOIL IDs start with 1 + values.append(value * tf) + else: + indices.append(self.unkn_word_token_id(embedding.word, unknown_words_shift)) + values.append(tf) + + return SparseEmbedding( + indices=np.array(indices, dtype=np.int32), + values=np.array(values, dtype=np.float32), + ) diff --git a/python/user_packages/Python313/site-packages/fastembed/sparse/utils/tokenizer.py b/python/user_packages/Python313/site-packages/fastembed/sparse/utils/tokenizer.py new file mode 100644 index 0000000000000000000000000000000000000000..e2129083280141fcfb7ebf297b8eaf204f057a18 --- /dev/null +++ b/python/user_packages/Python313/site-packages/fastembed/sparse/utils/tokenizer.py @@ -0,0 +1,120 @@ +# This code is a modified copy of the `NLTKWordTokenizer` class from `NLTK` library. + +import re + + +class SimpleTokenizer: + @staticmethod + def tokenize(text: str) -> list[str]: + text = re.sub(r"[^\w]", " ", text.lower()) + text = re.sub(r"\s+", " ", text) + + return text.strip().split() + + +class WordTokenizer: + """The tokenizer is "destructive" such that the regexes applied will munge the + input string to a state beyond re-construction. + """ + + # Starting quotes. + STARTING_QUOTES = [ + (re.compile("([«“‘„]|[`]+)", re.U), r" \1 "), + (re.compile(r"^\""), r"``"), + (re.compile(r"(``)"), r" \1 "), + (re.compile(r"([ \(\[{<])(\"|\'{2})"), r"\1 `` "), + (re.compile(r"(?i)(\')(?!re|ve|ll|m|t|s|d|n)(\w)\b", re.U), r"\1 \2"), + ] + + # Ending quotes. + ENDING_QUOTES = [ + (re.compile("([»”’])", re.U), r" \1 "), + (re.compile(r"''"), " '' "), + (re.compile(r'"'), " '' "), + (re.compile(r"([^' ])('[sS]|'[mM]|'[dD]|') "), r"\1 \2 "), + (re.compile(r"([^' ])('ll|'LL|'re|'RE|'ve|'VE|n't|N'T) "), r"\1 \2 "), + ] + + # Punctuation. + PUNCTUATION = [ + (re.compile(r'([^\.])(\.)([\]\)}>"\'' "»”’ " r"]*)\s*$", re.U), r"\1 \2 \3 "), + (re.compile(r"([:,])([^\d])"), r" \1 \2"), + (re.compile(r"([:,])$"), r" \1 "), + ( + re.compile(r"\.{2,}", re.U), + r" \g<0> ", + ), + (re.compile(r"[;@#$%&]"), r" \g<0> "), + ( + re.compile(r'([^\.])(\.)([\]\)}>"\']*)\s*$'), + r"\1 \2\3 ", + ), # Handles the final period. + (re.compile(r"[?!]"), r" \g<0> "), + (re.compile(r"([^'])' "), r"\1 ' "), + ( + re.compile(r"[*]", re.U), + r" \g<0> ", + ), + ] + + # Pads parentheses + PARENS_BRACKETS = (re.compile(r"[\]\[\(\)\{\}\<\>]"), r" \g<0> ") + DOUBLE_DASHES = (re.compile(r"--"), r" -- ") + + # List of contractions adapted from Robert MacIntyre's tokenizer. + CONTRACTIONS2 = [ + re.compile(pattern) + for pattern in ( + r"(?i)\b(can)(?#X)(not)\b", + r"(?i)\b(d)(?#X)('ye)\b", + r"(?i)\b(gim)(?#X)(me)\b", + r"(?i)\b(gon)(?#X)(na)\b", + r"(?i)\b(got)(?#X)(ta)\b", + r"(?i)\b(lem)(?#X)(me)\b", + r"(?i)\b(more)(?#X)('n)\b", + r"(?i)\b(wan)(?#X)(na)(?=\s)", + ) + ] + CONTRACTIONS3 = [ + re.compile(pattern) for pattern in (r"(?i) ('t)(?#X)(is)\b", r"(?i) ('t)(?#X)(was)\b") + ] + + @classmethod + def tokenize(cls, text: str) -> list[str]: + """Return a tokenized copy of `text`. + + >>> s = '''Good muffins cost $3.88 (roughly 3,36 euros)\nin New York.''' + >>> WordTokenizer().tokenize(s) + ['Good', 'muffins', 'cost', '$', '3.88', '(', 'roughly', '3,36', 'euros', ')', 'in', 'New', 'York', '.'] + + Args: + text: The text to be tokenized. + + Returns: + A list of tokens. + """ + for regexp, substitution in cls.STARTING_QUOTES: + text = regexp.sub(substitution, text) + + for regexp, substitution in cls.PUNCTUATION: + text = regexp.sub(substitution, text) + + # Handles parentheses. + regexp, substitution = cls.PARENS_BRACKETS + text = regexp.sub(substitution, text) + + # Handles double dash. + regexp, substitution = cls.DOUBLE_DASHES + text = regexp.sub(substitution, text) + + # add extra space to make things easier + text = " " + text + " " + + for regexp, substitution in cls.ENDING_QUOTES: + text = regexp.sub(substitution, text) + + for regexp in cls.CONTRACTIONS2: + text = regexp.sub(r" \1 \2 ", text) + for regexp in cls.CONTRACTIONS3: + text = regexp.sub(r" \1 \2 ", text) + return text.split() diff --git a/python/user_packages/Python313/site-packages/fastembed/sparse/utils/vocab_resolver.py b/python/user_packages/Python313/site-packages/fastembed/sparse/utils/vocab_resolver.py new file mode 100644 index 0000000000000000000000000000000000000000..1a3c52acc351adb273320553d212d373ecec1e7e --- /dev/null +++ b/python/user_packages/Python313/site-packages/fastembed/sparse/utils/vocab_resolver.py @@ -0,0 +1,202 @@ +from collections import defaultdict +from typing import Iterable + +from py_rust_stemmers import SnowballStemmer +import numpy as np +from tokenizers import Tokenizer +from numpy.typing import NDArray + +from fastembed.common.types import NumpyArray + + +class VocabTokenizerBase: + def tokenize(self, sentence: str) -> NumpyArray: + raise NotImplementedError() + + def convert_ids_to_tokens(self, token_ids: NumpyArray) -> list[str]: + raise NotImplementedError() + + +class VocabTokenizer(VocabTokenizerBase): + def __init__(self, tokenizer: Tokenizer): + self.tokenizer = tokenizer + + def tokenize(self, sentence: str) -> NumpyArray: + return np.array(self.tokenizer.encode(sentence).ids) + + def convert_ids_to_tokens(self, token_ids: NumpyArray) -> list[str]: + return [self.tokenizer.id_to_token(token_id) for token_id in token_ids] + + +class VocabResolver: + def __init__(self, tokenizer: VocabTokenizerBase, stopwords: set[str], stemmer: SnowballStemmer): + # Word to id mapping + self.vocab: dict[str, int] = {} + # Id to word mapping + self.words: list[str] = [] + # Lemma to word mapping + self.stem_mapping: dict[str, str] = {} + self.tokenizer: VocabTokenizerBase = tokenizer + self.stemmer = stemmer + self.stopwords: set[str] = stopwords + + def tokenize(self, sentence: str) -> NumpyArray: + return self.tokenizer.tokenize(sentence) + + def lookup_word(self, word_id: int) -> str: + if word_id == 0: + return "UNK" + return self.words[word_id - 1] + + def convert_ids_to_tokens(self, token_ids: NumpyArray) -> list[str]: + return self.tokenizer.convert_ids_to_tokens(token_ids) + + def vocab_size(self) -> int: + # We need +1 for UNK token + return len(self.vocab) + 1 + + def save_vocab(self, path: str) -> None: + with open(path, "w") as f: + for word in self.words: + f.write(word + "\n") + + def save_json_vocab(self, path: str) -> None: + import json + + with open(path, "w") as f: + json.dump({"vocab": self.words, "stem_mapping": self.stem_mapping}, f, indent=2) + + def load_json_vocab(self, path: str) -> None: + import json + + with open(path, "r") as f: + data = json.load(f) + self.words = data["vocab"] + self.vocab = {word: idx + 1 for idx, word in enumerate(self.words)} + self.stem_mapping = data["stem_mapping"] + + def add_word(self, word: str) -> None: + if word not in self.vocab: + self.vocab[word] = len(self.vocab) + 1 + self.words.append(word) + stem = self.stemmer.stem_word(word) + if stem not in self.stem_mapping: + self.stem_mapping[stem] = word + else: + existing_word = self.stem_mapping[stem] + if len(existing_word) > len(word): + # Prefer shorter words for the same stem + # Example: "swim" is preferred over "swimming" + self.stem_mapping[stem] = word + + def load_vocab(self, path: str) -> None: + with open(path, "r") as f: + for line in f: + self.add_word(line.strip()) + + @classmethod + def _reconstruct_bpe( + cls, bpe_tokens: Iterable[tuple[int, str]] + ) -> list[tuple[str, list[int]]]: + result: list[tuple[str, list[int]]] = [] + acc: str = "" + acc_idx: list[int] = [] + + continuing_subword_prefix = "##" + continuing_subword_prefix_len = len(continuing_subword_prefix) + + for idx, token in bpe_tokens: + if token.startswith(continuing_subword_prefix): + acc += token[continuing_subword_prefix_len:] + acc_idx.append(idx) + else: + if acc: + result.append((acc, acc_idx)) + acc_idx = [] + acc = token + acc_idx.append(idx) + + if acc: + result.append((acc, acc_idx)) + return result + + def resolve_tokens( + self, token_ids: NDArray[np.int64] + ) -> tuple[NDArray[np.int64], dict[int, int], dict[str, int], dict[str, list[str]]]: + """ + Mark known tokens (including composed tokens) with vocab ids. + + Args: + token_ids: (seq_len) - list of ids of tokens + Example: + [ + 101, 3897, 19332, 12718, 23348, + 1010, 1996, 7151, 2296, 4845, + 2359, 2005, 4234, 1010, 4332, + 2871, 3191, 2062, 102 + ] + + returns: + - token_ids with vocab ids + [ + 0, 151, 151, 0, 0, + 912, 0, 0, 0, 332, + 332, 332, 0, 7121, 191, + 0, 0, 332, 0 + ] + - counts of each token + { + 151: 1, + 332: 3, + 7121: 1, + 191: 1, + 912: 1 + } + - oov counts of each token + { + "the": 1, + "a": 1, + "[CLS]": 1, + "[SEP]": 1, + ... + } + - forms of each token + { + "hello": ["hello"], + "world": ["worlds", "world", "worlding"], + } + + """ + tokens = self.convert_ids_to_tokens(token_ids) + tokens_mapping = self._reconstruct_bpe(enumerate(tokens)) + + counts: dict[int, int] = defaultdict(int) + oov_count: dict[str, int] = defaultdict(int) + + forms: dict[str, list[str]] = defaultdict(list) + + for token, mapped_token_ids in tokens_mapping: + vocab_id = 0 + if token in self.stopwords: + vocab_id = 0 + elif token in self.vocab: + vocab_id = self.vocab[token] + forms[token].append(token) + elif token in self.stem_mapping: + vocab_id = self.vocab[self.stem_mapping[token]] + forms[self.stem_mapping[token]].append(token) + else: + stem = self.stemmer.stem_word(token) + if stem in self.stem_mapping: + vocab_id = self.vocab[self.stem_mapping[stem]] + forms[self.stem_mapping[stem]].append(token) + + for token_id in mapped_token_ids: + token_ids[token_id] = vocab_id + + if vocab_id == 0: + oov_count[token] += 1 + else: + counts[vocab_id] += 1 + return token_ids, counts, oov_count, forms + diff --git a/python/user_packages/Python313/site-packages/fastembed/text/__init__.py b/python/user_packages/Python313/site-packages/fastembed/text/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..493d0d438b4083cb08d26b6f8b1d66ecca4769f7 --- /dev/null +++ b/python/user_packages/Python313/site-packages/fastembed/text/__init__.py @@ -0,0 +1,3 @@ +from fastembed.text.text_embedding import TextEmbedding + +__all__ = ["TextEmbedding"] diff --git a/python/user_packages/Python313/site-packages/fastembed/text/__pycache__/__init__.cpython-313.pyc b/python/user_packages/Python313/site-packages/fastembed/text/__pycache__/__init__.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ee5ea7c3eb0e6f96a008f2222249113b0e756e9f Binary files /dev/null and b/python/user_packages/Python313/site-packages/fastembed/text/__pycache__/__init__.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/fastembed/text/__pycache__/clip_embedding.cpython-313.pyc b/python/user_packages/Python313/site-packages/fastembed/text/__pycache__/clip_embedding.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..34ef3102b22ed84f95edd58da827b6a27466f34f Binary files /dev/null and b/python/user_packages/Python313/site-packages/fastembed/text/__pycache__/clip_embedding.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/fastembed/text/__pycache__/custom_text_embedding.cpython-313.pyc b/python/user_packages/Python313/site-packages/fastembed/text/__pycache__/custom_text_embedding.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c0a000937e4ddfc7ae5537de3a8e9e3e688c5ea8 Binary files /dev/null and b/python/user_packages/Python313/site-packages/fastembed/text/__pycache__/custom_text_embedding.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/fastembed/text/__pycache__/multitask_embedding.cpython-313.pyc b/python/user_packages/Python313/site-packages/fastembed/text/__pycache__/multitask_embedding.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6a0c9767d3f41caaf34eab2909c93b16accb4b56 Binary files /dev/null and b/python/user_packages/Python313/site-packages/fastembed/text/__pycache__/multitask_embedding.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/fastembed/text/__pycache__/onnx_embedding.cpython-313.pyc b/python/user_packages/Python313/site-packages/fastembed/text/__pycache__/onnx_embedding.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3f7421e9e61a251fb319d345cc82d9a9e450d471 Binary files /dev/null and b/python/user_packages/Python313/site-packages/fastembed/text/__pycache__/onnx_embedding.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/fastembed/text/__pycache__/onnx_text_model.cpython-313.pyc b/python/user_packages/Python313/site-packages/fastembed/text/__pycache__/onnx_text_model.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ff208929806163c29e91f9249df689f528f7a12b Binary files /dev/null and b/python/user_packages/Python313/site-packages/fastembed/text/__pycache__/onnx_text_model.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/fastembed/text/__pycache__/pooled_embedding.cpython-313.pyc b/python/user_packages/Python313/site-packages/fastembed/text/__pycache__/pooled_embedding.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e76e9c1e9420835a52bdf09517cd1808a0959d15 Binary files /dev/null and b/python/user_packages/Python313/site-packages/fastembed/text/__pycache__/pooled_embedding.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/fastembed/text/__pycache__/pooled_normalized_embedding.cpython-313.pyc b/python/user_packages/Python313/site-packages/fastembed/text/__pycache__/pooled_normalized_embedding.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..82c09d4cf4c812a820389ef3b4f5c89a44ec1c51 Binary files /dev/null and b/python/user_packages/Python313/site-packages/fastembed/text/__pycache__/pooled_normalized_embedding.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/fastembed/text/__pycache__/text_embedding.cpython-313.pyc b/python/user_packages/Python313/site-packages/fastembed/text/__pycache__/text_embedding.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d50f923cb18d0fa49035cbaf8c8d856136204396 Binary files /dev/null and b/python/user_packages/Python313/site-packages/fastembed/text/__pycache__/text_embedding.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/fastembed/text/__pycache__/text_embedding_base.cpython-313.pyc b/python/user_packages/Python313/site-packages/fastembed/text/__pycache__/text_embedding_base.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a6b0a7de818dd8423c3229a00c134ff358c3008d Binary files /dev/null and b/python/user_packages/Python313/site-packages/fastembed/text/__pycache__/text_embedding_base.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/fastembed/text/clip_embedding.py b/python/user_packages/Python313/site-packages/fastembed/text/clip_embedding.py new file mode 100644 index 0000000000000000000000000000000000000000..b918e9f26d17fdafebd9f3dd1480bb989f38ac8d --- /dev/null +++ b/python/user_packages/Python313/site-packages/fastembed/text/clip_embedding.py @@ -0,0 +1,56 @@ +from typing import Any, Iterable, Type + +from fastembed.common.types import NumpyArray +from fastembed.common.onnx_model import OnnxOutputContext +from fastembed.text.onnx_embedding import OnnxTextEmbedding, OnnxTextEmbeddingWorker +from fastembed.common.model_description import DenseModelDescription, ModelSource + +supported_clip_models: list[DenseModelDescription] = [ + DenseModelDescription( + model="Qdrant/clip-ViT-B-32-text", + dim=512, + description=( + "Text embeddings, Multimodal (text&image), English, 77 input tokens truncation, " + "Prefixes for queries/documents: not necessary, 2021 year" + ), + license="mit", + size_in_GB=0.25, + sources=ModelSource(hf="Qdrant/clip-ViT-B-32-text"), + model_file="model.onnx", + ), +] + + +class CLIPOnnxEmbedding(OnnxTextEmbedding): + @classmethod + def _get_worker_class(cls) -> Type[OnnxTextEmbeddingWorker]: + return CLIPEmbeddingWorker + + @classmethod + def _list_supported_models(cls) -> list[DenseModelDescription]: + """Lists the supported models. + + Returns: + list[DenseModelDescription]: A list of DenseModelDescription objects containing the model information. + """ + return supported_clip_models + + def _post_process_onnx_output( + self, output: OnnxOutputContext, **kwargs: Any + ) -> Iterable[NumpyArray]: + return output.model_output + + +class CLIPEmbeddingWorker(OnnxTextEmbeddingWorker): + def init_embedding( + self, + model_name: str, + cache_dir: str, + **kwargs: Any, + ) -> OnnxTextEmbedding: + return CLIPOnnxEmbedding( + model_name=model_name, + cache_dir=cache_dir, + threads=1, + **kwargs, + ) diff --git a/python/user_packages/Python313/site-packages/fastembed/text/custom_text_embedding.py b/python/user_packages/Python313/site-packages/fastembed/text/custom_text_embedding.py new file mode 100644 index 0000000000000000000000000000000000000000..465ffd2513b62147478e692d5662e3ea9203bd5e --- /dev/null +++ b/python/user_packages/Python313/site-packages/fastembed/text/custom_text_embedding.py @@ -0,0 +1,97 @@ +from typing import Sequence, Any, Iterable +from dataclasses import dataclass + +import numpy as np +from numpy.typing import NDArray + +from fastembed.common import OnnxProvider +from fastembed.common.model_description import ( + PoolingType, + DenseModelDescription, +) +from fastembed.common.onnx_model import OnnxOutputContext +from fastembed.common.types import NumpyArray, Device +from fastembed.common.utils import normalize, mean_pooling +from fastembed.text.onnx_embedding import OnnxTextEmbedding + + +@dataclass(frozen=True) +class PostprocessingConfig: + pooling: PoolingType + normalization: bool + + +class CustomTextEmbedding(OnnxTextEmbedding): + SUPPORTED_MODELS: list[DenseModelDescription] = [] + POSTPROCESSING_MAPPING: dict[str, PostprocessingConfig] = {} + + def __init__( + self, + model_name: str, + cache_dir: str | None = None, + threads: int | None = None, + providers: Sequence[OnnxProvider] | None = None, + cuda: bool | Device = Device.AUTO, + device_ids: list[int] | None = None, + lazy_load: bool = False, + device_id: int | None = None, + specific_model_path: str | None = None, + **kwargs: Any, + ): + super().__init__( + model_name=model_name, + cache_dir=cache_dir, + threads=threads, + providers=providers, + cuda=cuda, + device_ids=device_ids, + lazy_load=lazy_load, + device_id=device_id, + specific_model_path=specific_model_path, + **kwargs, + ) + self._pooling = self.POSTPROCESSING_MAPPING[model_name].pooling + self._normalization = self.POSTPROCESSING_MAPPING[model_name].normalization + + @classmethod + def _list_supported_models(cls) -> list[DenseModelDescription]: + return cls.SUPPORTED_MODELS + + def _post_process_onnx_output( + self, output: OnnxOutputContext, **kwargs: Any + ) -> Iterable[NumpyArray]: + return self._normalize(self._pool(output.model_output, output.attention_mask)) + + def _pool( + self, embeddings: NumpyArray, attention_mask: NDArray[np.int64] | None = None + ) -> NumpyArray: + if self._pooling == PoolingType.CLS: + return embeddings[:, 0] + + if self._pooling == PoolingType.MEAN: + if attention_mask is None: + raise ValueError("attention_mask must be provided for mean pooling") + return mean_pooling(embeddings, attention_mask) + + if self._pooling == PoolingType.DISABLED: + return embeddings + + raise ValueError( + f"Unsupported pooling type {self._pooling}. " + f"Supported types are: {PoolingType.CLS}, {PoolingType.MEAN}, {PoolingType.DISABLED}." + ) + + def _normalize(self, embeddings: NumpyArray) -> NumpyArray: + return normalize(embeddings) if self._normalization else embeddings + + @classmethod + def add_model( + cls, + model_description: DenseModelDescription, + pooling: PoolingType, + normalization: bool, + ) -> None: + cls.SUPPORTED_MODELS.append(model_description) + cls.POSTPROCESSING_MAPPING[model_description.model] = PostprocessingConfig( + pooling=pooling, normalization=normalization + ) diff --git a/python/user_packages/Python313/site-packages/fastembed/text/multitask_embedding.py b/python/user_packages/Python313/site-packages/fastembed/text/multitask_embedding.py new file mode 100644 index 0000000000000000000000000000000000000000..73ce2b1bd5e00edbd3a25703c91ff27cd35b2f13 --- /dev/null +++ b/python/user_packages/Python313/site-packages/fastembed/text/multitask_embedding.py @@ -0,0 +1,109 @@ +from enum import Enum +from typing import Any, Type, Iterable + +import numpy as np + +from fastembed.common.onnx_model import OnnxOutputContext +from fastembed.common.types import NumpyArray +from fastembed.text.pooled_normalized_embedding import PooledNormalizedEmbedding +from fastembed.text.onnx_embedding import OnnxTextEmbeddingWorker +from fastembed.common.model_description import DenseModelDescription, ModelSource + +supported_multitask_models: list[DenseModelDescription] = [ + DenseModelDescription( + model="jinaai/jina-embeddings-v3", + dim=1024, + tasks={ + "retrieval.query": 0, + "retrieval.passage": 1, + "separation": 2, + "classification": 3, + "text-matching": 4, + }, + description=( + "Multi-task unimodal (text) embedding model, multi-lingual (~100), " + "1024 tokens truncation, and 8192 sequence length. Prefixes for queries/documents: not necessary, 2024 year." + ), + license="cc-by-nc-4.0", + size_in_GB=2.29, + sources=ModelSource(hf="jinaai/jina-embeddings-v3"), + model_file="onnx/model.onnx", + additional_files=["onnx/model.onnx_data"], + ), +] + + +class Task(int, Enum): + RETRIEVAL_QUERY = 0 + RETRIEVAL_PASSAGE = 1 + SEPARATION = 2 + CLASSIFICATION = 3 + TEXT_MATCHING = 4 + + +class JinaEmbeddingV3(PooledNormalizedEmbedding): + PASSAGE_TASK = Task.RETRIEVAL_PASSAGE + QUERY_TASK = Task.RETRIEVAL_QUERY + + def __init__(self, *args: Any, task_id: int | None = None, **kwargs: Any): + super().__init__(*args, **kwargs) + self.default_task_id: Task | int = task_id if task_id is not None else self.PASSAGE_TASK + + @classmethod + def _get_worker_class(cls) -> Type[OnnxTextEmbeddingWorker]: + return JinaEmbeddingV3Worker + + @classmethod + def _list_supported_models(cls) -> list[DenseModelDescription]: + return supported_multitask_models + + def _preprocess_onnx_input( + self, + onnx_input: dict[str, NumpyArray], + task_id: int | Task | None = None, + **kwargs: Any, + ) -> dict[str, NumpyArray]: + if task_id is None: + raise ValueError(f"task_id must be provided for JinaEmbeddingV3, got <{task_id}>") + onnx_input["task_id"] = np.array(task_id, dtype=np.int64) + return onnx_input + + def embed( + self, + documents: str | Iterable[str], + batch_size: int = 256, + parallel: int | None = None, + task_id: int | None = None, + **kwargs: Any, + ) -> Iterable[NumpyArray]: + task_id = ( + task_id if task_id is not None else self.default_task_id + ) # required for multiprocessing + yield from super().embed(documents, batch_size, parallel, task_id=task_id, **kwargs) + + def query_embed(self, query: str | Iterable[str], **kwargs: Any) -> Iterable[NumpyArray]: + yield from super().embed(query, task_id=self.QUERY_TASK, **kwargs) + + def passage_embed(self, texts: Iterable[str], **kwargs: Any) -> Iterable[NumpyArray]: + yield from super().embed(texts, task_id=self.PASSAGE_TASK, **kwargs) + + +class JinaEmbeddingV3Worker(OnnxTextEmbeddingWorker): + def init_embedding( + self, + model_name: str, + cache_dir: str, + **kwargs: Any, + ) -> JinaEmbeddingV3: + return JinaEmbeddingV3( + model_name=model_name, + cache_dir=cache_dir, + threads=1, + **kwargs, + ) + + def process(self, items: Iterable[tuple[int, Any]]) -> Iterable[tuple[int, OnnxOutputContext]]: + self.model: JinaEmbeddingV3 # mypy complaints `self.model` does not have `default_task_id` + for idx, batch in items: + onnx_output = self.model.onnx_embed(batch, task_id=self.model.default_task_id) + yield idx, onnx_output diff --git a/python/user_packages/Python313/site-packages/fastembed/text/onnx_embedding.py b/python/user_packages/Python313/site-packages/fastembed/text/onnx_embedding.py new file mode 100644 index 0000000000000000000000000000000000000000..1e9978f75388063d4d67232bbb7ad590c8cbeb54 --- /dev/null +++ b/python/user_packages/Python313/site-packages/fastembed/text/onnx_embedding.py @@ -0,0 +1,353 @@ +from typing import Any, Iterable, Sequence, Type + +from fastembed.common.types import NumpyArray, OnnxProvider, Device +from fastembed.common.onnx_model import OnnxOutputContext +from fastembed.common.utils import define_cache_dir, normalize +from fastembed.text.onnx_text_model import OnnxTextModel, TextEmbeddingWorker +from fastembed.text.text_embedding_base import TextEmbeddingBase +from fastembed.common.model_description import DenseModelDescription, ModelSource + +supported_onnx_models: list[DenseModelDescription] = [ + DenseModelDescription( + model="BAAI/bge-base-en", + dim=768, + description=( + "Text embeddings, Unimodal (text), English, 512 input tokens truncation, " + "Prefixes for queries/documents: necessary, 2023 year." + ), + license="mit", + size_in_GB=0.42, + sources=ModelSource( + hf="Qdrant/fast-bge-base-en", + url="https://storage.googleapis.com/qdrant-fastembed/fast-bge-base-en.tar.gz", + _deprecated_tar_struct=True, + ), + model_file="model_optimized.onnx", + ), + DenseModelDescription( + model="BAAI/bge-base-en-v1.5", + dim=768, + description=( + "Text embeddings, Unimodal (text), English, 512 input tokens truncation, " + "Prefixes for queries/documents: not so necessary, 2023 year." + ), + license="mit", + size_in_GB=0.21, + sources=ModelSource( + hf="qdrant/bge-base-en-v1.5-onnx-q", + url="https://storage.googleapis.com/qdrant-fastembed/fast-bge-base-en-v1.5.tar.gz", + _deprecated_tar_struct=True, + ), + model_file="model_optimized.onnx", + ), + DenseModelDescription( + model="BAAI/bge-large-en-v1.5", + dim=1024, + description=( + "Text embeddings, Unimodal (text), English, 512 input tokens truncation, " + "Prefixes for queries/documents: not so necessary, 2023 year." + ), + license="mit", + size_in_GB=1.20, + sources=ModelSource(hf="qdrant/bge-large-en-v1.5-onnx"), + model_file="model.onnx", + ), + DenseModelDescription( + model="BAAI/bge-small-en", + dim=384, + description=( + "Text embeddings, Unimodal (text), English, 512 input tokens truncation, " + "Prefixes for queries/documents: necessary, 2023 year." + ), + license="mit", + size_in_GB=0.13, + sources=ModelSource( + hf="Qdrant/bge-small-en", + url="https://storage.googleapis.com/qdrant-fastembed/BAAI-bge-small-en.tar.gz", + _deprecated_tar_struct=True, + ), + model_file="model_optimized.onnx", + ), + DenseModelDescription( + model="BAAI/bge-small-en-v1.5", + dim=384, + description=( + "Text embeddings, Unimodal (text), English, 512 input tokens truncation, " + "Prefixes for queries/documents: not so necessary, 2023 year." + ), + license="mit", + size_in_GB=0.067, + sources=ModelSource(hf="qdrant/bge-small-en-v1.5-onnx-q"), + model_file="model_optimized.onnx", + ), + DenseModelDescription( + model="BAAI/bge-small-zh-v1.5", + dim=512, + description=( + "Text embeddings, Unimodal (text), Chinese, 512 input tokens truncation, " + "Prefixes for queries/documents: not so necessary, 2023 year." + ), + license="mit", + size_in_GB=0.09, + sources=ModelSource( + hf="Qdrant/bge-small-zh-v1.5", + url="https://storage.googleapis.com/qdrant-fastembed/fast-bge-small-zh-v1.5.tar.gz", + _deprecated_tar_struct=True, + ), + model_file="model_optimized.onnx", + ), + DenseModelDescription( + model="mixedbread-ai/mxbai-embed-large-v1", + dim=1024, + description=( + "Text embeddings, Unimodal (text), English, 512 input tokens truncation, " + "Prefixes for queries/documents: necessary, 2024 year." + ), + license="apache-2.0", + size_in_GB=0.64, + sources=ModelSource(hf="mixedbread-ai/mxbai-embed-large-v1"), + model_file="onnx/model.onnx", + ), + DenseModelDescription( + model="snowflake/snowflake-arctic-embed-xs", + dim=384, + description=( + "Text embeddings, Unimodal (text), English, 512 input tokens truncation, " + "Prefixes for queries/documents: necessary, 2024 year." + ), + license="apache-2.0", + size_in_GB=0.09, + sources=ModelSource(hf="snowflake/snowflake-arctic-embed-xs"), + model_file="onnx/model.onnx", + ), + DenseModelDescription( + model="snowflake/snowflake-arctic-embed-s", + dim=384, + description=( + "Text embeddings, Unimodal (text), English, 512 input tokens truncation, " + "Prefixes for queries/documents: necessary, 2024 year." + ), + license="apache-2.0", + size_in_GB=0.13, + sources=ModelSource(hf="snowflake/snowflake-arctic-embed-s"), + model_file="onnx/model.onnx", + ), + DenseModelDescription( + model="snowflake/snowflake-arctic-embed-m", + dim=768, + description=( + "Text embeddings, Unimodal (text), English, 512 input tokens truncation, " + "Prefixes for queries/documents: necessary, 2024 year." + ), + license="apache-2.0", + size_in_GB=0.43, + sources=ModelSource(hf="Snowflake/snowflake-arctic-embed-m"), + model_file="onnx/model.onnx", + ), + DenseModelDescription( + model="snowflake/snowflake-arctic-embed-m-long", + dim=768, + description=( + "Text embeddings, Unimodal (text), English, 2048 input tokens truncation, " + "Prefixes for queries/documents: necessary, 2024 year." + ), + license="apache-2.0", + size_in_GB=0.54, + sources=ModelSource(hf="snowflake/snowflake-arctic-embed-m-long"), + model_file="onnx/model.onnx", + ), + DenseModelDescription( + model="snowflake/snowflake-arctic-embed-l", + dim=1024, + description=( + "Text embeddings, Unimodal (text), English, 512 input tokens truncation, " + "Prefixes for queries/documents: necessary, 2024 year." + ), + license="apache-2.0", + size_in_GB=1.02, + sources=ModelSource(hf="snowflake/snowflake-arctic-embed-l"), + model_file="onnx/model.onnx", + ), + DenseModelDescription( + model="jinaai/jina-clip-v1", + dim=768, + description=( + "Text embeddings, Multimodal (text&image), English, Prefixes for queries/documents: " + "not necessary, 2024 year" + ), + license="apache-2.0", + size_in_GB=0.55, + sources=ModelSource(hf="jinaai/jina-clip-v1"), + model_file="onnx/text_model.onnx", + ), +] + + +class OnnxTextEmbedding(TextEmbeddingBase, OnnxTextModel[NumpyArray]): + """Implementation of the Flag Embedding model.""" + + @classmethod + def _list_supported_models(cls) -> list[DenseModelDescription]: + """ + Lists the supported models. + + Returns: + list[DenseModelDescription]: A list of DenseModelDescription objects containing the model information. + """ + return supported_onnx_models + + def __init__( + self, + model_name: str = "BAAI/bge-small-en-v1.5", + cache_dir: str | None = None, + threads: int | None = None, + providers: Sequence[OnnxProvider] | None = None, + cuda: bool | Device = Device.AUTO, + device_ids: list[int] | None = None, + lazy_load: bool = False, + device_id: int | None = None, + specific_model_path: str | None = None, + **kwargs: Any, + ): + """ + Args: + model_name (str): The name of the model to use. + cache_dir (str, optional): The path to the cache directory. + Can be set using the `FASTEMBED_CACHE_PATH` env variable. + Defaults to `fastembed_cache` in the system's temp directory. + threads (int, optional): The number of threads single onnxruntime session can use. Defaults to None. + providers (Optional[Sequence[OnnxProvider]], optional): The list of onnxruntime providers to use. + Mutually exclusive with the `cuda` and `device_ids` arguments. Defaults to None. + cuda (Union[bool, Device], optional): Whether to use cuda for inference. Mutually exclusive with `providers` + Defaults to Device.AUTO. + device_ids (Optional[list[int]], optional): The list of device ids to use for data parallel processing in + workers. Should be used with `cuda` equals to `True`, `Device.AUTO` or `Device.CUDA`, mutually exclusive + with `providers`. Defaults to None. + lazy_load (bool, optional): Whether to load the model during class initialization or on demand. + Should be set to True when using multiple-gpu and parallel encoding. Defaults to False. + device_id (Optional[int], optional): The device id to use for loading the model in the worker process. + specific_model_path (Optional[str], optional): The specific path to the onnx model dir if it should be imported from somewhere else + + Raises: + ValueError: If the model_name is not in the format / e.g. BAAI/bge-base-en. + """ + super().__init__(model_name, cache_dir, threads, **kwargs) + self.providers = providers + self.lazy_load = lazy_load + self._extra_session_options = self._select_exposed_session_options(kwargs) + # List of device ids, that can be used for data parallel processing in workers + self.device_ids = device_ids + self.cuda = cuda + + # This device_id will be used if we need to load model in current process + self.device_id: int | None = None + if device_id is not None: + self.device_id = device_id + elif self.device_ids is not None: + self.device_id = self.device_ids[0] + + self.model_description = self._get_model_description(model_name) + self.cache_dir = str(define_cache_dir(cache_dir)) + self._specific_model_path = specific_model_path + self._model_dir = self.download_model( + self.model_description, + self.cache_dir, + local_files_only=self._local_files_only, + specific_model_path=self._specific_model_path, + ) + + if not self.lazy_load: + self.load_onnx_model() + + def embed( + self, + documents: str | Iterable[str], + batch_size: int = 256, + parallel: int | None = None, + **kwargs: Any, + ) -> Iterable[NumpyArray]: + """ + Encode a list of documents into list of embeddings. + We use mean pooling with attention so that the model can handle variable-length inputs. + + Args: + documents: Iterator of documents or single document to embed + batch_size: Batch size for encoding -- higher values will use more memory, but be faster + parallel: + If > 1, data-parallel encoding will be used, recommended for offline encoding of large datasets. + If 0, use all available cores. + If None, don't use data-parallel processing, use default onnxruntime threading instead. + + Returns: + List of embeddings, one per document + """ + yield from self._embed_documents( + model_name=self.model_name, + cache_dir=str(self.cache_dir), + documents=documents, + batch_size=batch_size, + parallel=parallel, + providers=self.providers, + cuda=self.cuda, + device_ids=self.device_ids, + local_files_only=self._local_files_only, + specific_model_path=self._specific_model_path, + extra_session_options=self._extra_session_options, + **kwargs, + ) + + @classmethod + def _get_worker_class(cls) -> Type["TextEmbeddingWorker[NumpyArray]"]: + return OnnxTextEmbeddingWorker + + def _preprocess_onnx_input( + self, onnx_input: dict[str, NumpyArray], **kwargs: Any + ) -> dict[str, NumpyArray]: + """ + Preprocess the onnx input. + """ + return onnx_input + + def _post_process_onnx_output( + self, output: OnnxOutputContext, **kwargs: Any + ) -> Iterable[NumpyArray]: + embeddings = output.model_output + + if embeddings.ndim == 3: # (batch_size, seq_len, embedding_dim) + processed_embeddings = embeddings[:, 0] + elif embeddings.ndim == 2: # (batch_size, embedding_dim) + processed_embeddings = embeddings + else: + raise ValueError(f"Unsupported embedding shape: {embeddings.shape}") + return normalize(processed_embeddings) + + def load_onnx_model(self) -> None: + self._load_onnx_model( + model_dir=self._model_dir, + model_file=self.model_description.model_file, + threads=self.threads, + providers=self.providers, + cuda=self.cuda, + device_id=self.device_id, + extra_session_options=self._extra_session_options, + ) + + def token_count( + self, texts: str | Iterable[str], batch_size: int = 1024, **kwargs: Any + ) -> int: + return self._token_count(texts, batch_size=batch_size, **kwargs) + + +class OnnxTextEmbeddingWorker(TextEmbeddingWorker[NumpyArray]): + def init_embedding( + self, + model_name: str, + cache_dir: str, + **kwargs: Any, + ) -> OnnxTextEmbedding: + return OnnxTextEmbedding( + model_name=model_name, + cache_dir=cache_dir, + threads=1, + **kwargs, + ) diff --git a/python/user_packages/Python313/site-packages/fastembed/text/onnx_text_model.py b/python/user_packages/Python313/site-packages/fastembed/text/onnx_text_model.py new file mode 100644 index 0000000000000000000000000000000000000000..c8001a91717ce36c3bde2d7b9c7bd8524c714ea3 --- /dev/null +++ b/python/user_packages/Python313/site-packages/fastembed/text/onnx_text_model.py @@ -0,0 +1,180 @@ +import os +from multiprocessing import get_all_start_methods +from pathlib import Path +from typing import Any, Iterable, Sequence, Type + +import numpy as np +from numpy.typing import NDArray +from tokenizers import Encoding, Tokenizer + +from fastembed.common.types import NumpyArray, OnnxProvider, Device +from fastembed.common.onnx_model import EmbeddingWorker, OnnxModel, OnnxOutputContext, T +from fastembed.common.preprocessor_utils import load_tokenizer +from fastembed.common.utils import iter_batch +from fastembed.parallel_processor import ParallelWorkerPool + + +class OnnxTextModel(OnnxModel[T]): + ONNX_OUTPUT_NAMES: list[str] | None = None + + @classmethod + def _get_worker_class(cls) -> Type["TextEmbeddingWorker[T]"]: + raise NotImplementedError("Subclasses must implement this method") + + def _post_process_onnx_output(self, output: OnnxOutputContext, **kwargs: Any) -> Iterable[T]: + """Post-process the ONNX model output to convert it into a usable format. + + Args: + output (OnnxOutputContext): The raw output from the ONNX model. + **kwargs: Additional keyword arguments that may be needed by specific implementations. + + Returns: + Iterable[T]: Post-processed output as an iterable of type T. + """ + raise NotImplementedError("Subclasses must implement this method") + + def __init__(self) -> None: + super().__init__() + self.tokenizer: Tokenizer | None = None + self.special_token_to_id: dict[str, int] = {} + + def _preprocess_onnx_input( + self, onnx_input: dict[str, NumpyArray], **kwargs: Any + ) -> dict[str, NumpyArray | NDArray[np.int64]]: + """ + Preprocess the onnx input. + """ + return onnx_input + + def _load_onnx_model( + self, + model_dir: Path, + model_file: str, + threads: int | None, + providers: Sequence[OnnxProvider] | None = None, + cuda: bool | Device = Device.AUTO, + device_id: int | None = None, + extra_session_options: dict[str, Any] | None = None, + ) -> None: + super()._load_onnx_model( + model_dir=model_dir, + model_file=model_file, + threads=threads, + providers=providers, + cuda=cuda, + device_id=device_id, + extra_session_options=extra_session_options, + ) + self.tokenizer, self.special_token_to_id = load_tokenizer(model_dir=model_dir) + + def load_onnx_model(self) -> None: + raise NotImplementedError("Subclasses must implement this method") + + def tokenize(self, documents: list[str], **kwargs: Any) -> list[Encoding]: + return self.tokenizer.encode_batch(documents) # type: ignore[union-attr] + + def onnx_embed( + self, + documents: list[str], + **kwargs: Any, + ) -> OnnxOutputContext: + encoded = self.tokenize(documents, **kwargs) + input_ids = np.array([e.ids for e in encoded]) + attention_mask = np.array([e.attention_mask for e in encoded]) + input_names = {node.name for node in self.model.get_inputs()} # type: ignore[union-attr] + onnx_input: dict[str, NumpyArray] = { + "input_ids": np.array(input_ids, dtype=np.int64), + } + if "attention_mask" in input_names: + onnx_input["attention_mask"] = np.array(attention_mask, dtype=np.int64) + if "token_type_ids" in input_names: + onnx_input["token_type_ids"] = np.array( + [np.zeros(len(e), dtype=np.int64) for e in input_ids], dtype=np.int64 + ) + onnx_input = self._preprocess_onnx_input(onnx_input, **kwargs) + + model_output = self.model.run(self.ONNX_OUTPUT_NAMES, onnx_input) # type: ignore[union-attr] + return OnnxOutputContext( + model_output=model_output[0], + attention_mask=onnx_input.get("attention_mask", attention_mask), + input_ids=onnx_input.get("input_ids", input_ids), + ) + + def _embed_documents( + self, + model_name: str, + cache_dir: str, + documents: str | Iterable[str], + batch_size: int = 256, + parallel: int | None = None, + providers: Sequence[OnnxProvider] | None = None, + cuda: bool | Device = Device.AUTO, + device_ids: list[int] | None = None, + local_files_only: bool = False, + specific_model_path: str | None = None, + extra_session_options: dict[str, Any] | None = None, + **kwargs: Any, + ) -> Iterable[T]: + is_small = False + + if isinstance(documents, str): + documents = [documents] + is_small = True + + if isinstance(documents, list): + if len(documents) < batch_size: + is_small = True + + if parallel is None or is_small: + if not hasattr(self, "model") or self.model is None: + self.load_onnx_model() + for batch in iter_batch(documents, batch_size): + yield from self._post_process_onnx_output( + self.onnx_embed(batch, **kwargs), **kwargs + ) + else: + if parallel == 0: + parallel = os.cpu_count() + + start_method = "forkserver" if "forkserver" in get_all_start_methods() else "spawn" + params = { + "model_name": model_name, + "cache_dir": cache_dir, + "providers": providers, + "local_files_only": local_files_only, + "specific_model_path": specific_model_path, + **kwargs, + } + + if extra_session_options is not None: + params.update(extra_session_options) + + pool = ParallelWorkerPool( + num_workers=parallel or 1, + worker=self._get_worker_class(), + cuda=cuda, + device_ids=device_ids, + start_method=start_method, + ) + for batch in pool.ordered_map(iter_batch(documents, batch_size), **params): + yield from self._post_process_onnx_output(batch, **kwargs) # type: ignore + + def _token_count(self, texts: str | Iterable[str], batch_size: int = 1024, **_: Any) -> int: + if not hasattr(self, "model") or self.model is None: + self.load_onnx_model() # loads the tokenizer as well + + token_num = 0 + assert self.tokenizer is not None + texts = [texts] if isinstance(texts, str) else texts + for batch in iter_batch(texts, batch_size): + for tokens in self.tokenizer.encode_batch(batch): + token_num += sum(tokens.attention_mask) + + return token_num + + +class TextEmbeddingWorker(EmbeddingWorker[T]): + def process(self, items: Iterable[tuple[int, Any]]) -> Iterable[tuple[int, OnnxOutputContext]]: + for idx, batch in items: + onnx_output = self.model.onnx_embed(batch) + yield idx, onnx_output diff --git a/python/user_packages/Python313/site-packages/fastembed/text/pooled_embedding.py b/python/user_packages/Python313/site-packages/fastembed/text/pooled_embedding.py new file mode 100644 index 0000000000000000000000000000000000000000..f3fe607e9f685b22e090a62922c611931ac4d1a9 --- /dev/null +++ b/python/user_packages/Python313/site-packages/fastembed/text/pooled_embedding.py @@ -0,0 +1,136 @@ +from typing import Any, Iterable, Type + +import numpy as np +from numpy.typing import NDArray + +from fastembed.common.types import NumpyArray +from fastembed.common.onnx_model import OnnxOutputContext +from fastembed.common.utils import mean_pooling +from fastembed.text.onnx_embedding import OnnxTextEmbedding, OnnxTextEmbeddingWorker +from fastembed.common.model_description import DenseModelDescription, ModelSource + +supported_pooled_models: list[DenseModelDescription] = [ + DenseModelDescription( + model="nomic-ai/nomic-embed-text-v1.5", + dim=768, + description=( + "Text embeddings, Multimodal (text, image), English, 8192 input tokens truncation, " + "Prefixes for queries/documents: necessary, 2024 year." + ), + license="apache-2.0", + size_in_GB=0.52, + sources=ModelSource(hf="nomic-ai/nomic-embed-text-v1.5"), + model_file="onnx/model.onnx", + ), + DenseModelDescription( + model="nomic-ai/nomic-embed-text-v1.5-Q", + dim=768, + description=( + "Text embeddings, Multimodal (text, image), English, 8192 input tokens truncation, " + "Prefixes for queries/documents: necessary, 2024 year." + ), + license="apache-2.0", + size_in_GB=0.13, + sources=ModelSource(hf="nomic-ai/nomic-embed-text-v1.5"), + model_file="onnx/model_quantized.onnx", + ), + DenseModelDescription( + model="nomic-ai/nomic-embed-text-v1", + dim=768, + description=( + "Text embeddings, Multimodal (text, image), English, 8192 input tokens truncation, " + "Prefixes for queries/documents: necessary, 2024 year." + ), + license="apache-2.0", + size_in_GB=0.52, + sources=ModelSource(hf="nomic-ai/nomic-embed-text-v1"), + model_file="onnx/model.onnx", + ), + DenseModelDescription( + model="sentence-transformers/paraphrase-multilingual-MiniLM-L12-v2", + dim=384, + description=( + "Text embeddings, Unimodal (text), Multilingual (~50 languages), 512 input tokens truncation, " + "Prefixes for queries/documents: not necessary, 2019 year." + ), + license="apache-2.0", + size_in_GB=0.22, + sources=ModelSource(hf="qdrant/paraphrase-multilingual-MiniLM-L12-v2-onnx-Q"), + model_file="model_optimized.onnx", + ), + DenseModelDescription( + model="sentence-transformers/paraphrase-multilingual-mpnet-base-v2", + dim=768, + description=( + "Text embeddings, Unimodal (text), Multilingual (~50 languages), 384 input tokens truncation, " + "Prefixes for queries/documents: not necessary, 2021 year." + ), + license="apache-2.0", + size_in_GB=1.00, + sources=ModelSource(hf="xenova/paraphrase-multilingual-mpnet-base-v2"), + model_file="onnx/model.onnx", + ), + DenseModelDescription( + model="intfloat/multilingual-e5-large", + dim=1024, + description=( + "Text embeddings, Unimodal (text), Multilingual (~100 languages), 512 input tokens truncation, " + "Prefixes for queries/documents: necessary, 2024 year." + ), + license="mit", + size_in_GB=2.24, + sources=ModelSource( + hf="qdrant/multilingual-e5-large-onnx", + url="https://storage.googleapis.com/qdrant-fastembed/fast-multilingual-e5-large.tar.gz", + _deprecated_tar_struct=True, + ), + model_file="model.onnx", + additional_files=["model.onnx_data"], + ), +] + + +class PooledEmbedding(OnnxTextEmbedding): + @classmethod + def _get_worker_class(cls) -> Type[OnnxTextEmbeddingWorker]: + return PooledEmbeddingWorker + + @classmethod + def mean_pooling( + cls, model_output: NumpyArray, attention_mask: NDArray[np.int64] + ) -> NumpyArray: + return mean_pooling(model_output, attention_mask) + + @classmethod + def _list_supported_models(cls) -> list[DenseModelDescription]: + """Lists the supported models. + + Returns: + list[DenseModelDescription]: A list of DenseModelDescription objects containing the model information. + """ + return supported_pooled_models + + def _post_process_onnx_output( + self, output: OnnxOutputContext, **kwargs: Any + ) -> Iterable[NumpyArray]: + if output.attention_mask is None: + raise ValueError("attention_mask must be provided for document post-processing") + + embeddings = output.model_output + attn_mask = output.attention_mask + return self.mean_pooling(embeddings, attn_mask) + + +class PooledEmbeddingWorker(OnnxTextEmbeddingWorker): + def init_embedding( + self, + model_name: str, + cache_dir: str, + **kwargs: Any, + ) -> OnnxTextEmbedding: + return PooledEmbedding( + model_name=model_name, + cache_dir=cache_dir, + threads=1, + **kwargs, + ) diff --git a/python/user_packages/Python313/site-packages/fastembed/text/pooled_normalized_embedding.py b/python/user_packages/Python313/site-packages/fastembed/text/pooled_normalized_embedding.py new file mode 100644 index 0000000000000000000000000000000000000000..5711da19f82abaf9efbea8011cabb631cadc952a --- /dev/null +++ b/python/user_packages/Python313/site-packages/fastembed/text/pooled_normalized_embedding.py @@ -0,0 +1,164 @@ +from typing import Any, Iterable, Type + + +from fastembed.common.types import NumpyArray +from fastembed.common.onnx_model import OnnxOutputContext +from fastembed.common.utils import normalize +from fastembed.text.onnx_embedding import OnnxTextEmbedding, OnnxTextEmbeddingWorker +from fastembed.text.pooled_embedding import PooledEmbedding +from fastembed.common.model_description import DenseModelDescription, ModelSource + +supported_pooled_normalized_models: list[DenseModelDescription] = [ + DenseModelDescription( + model="sentence-transformers/all-MiniLM-L6-v2", + dim=384, + description=( + "Text embeddings, Unimodal (text), English, 256 input tokens truncation, " + "Prefixes for queries/documents: not necessary, 2021 year." + ), + license="apache-2.0", + size_in_GB=0.09, + sources=ModelSource( + url="https://storage.googleapis.com/qdrant-fastembed/sentence-transformers-all-MiniLM-L6-v2.tar.gz", + hf="qdrant/all-MiniLM-L6-v2-onnx", + _deprecated_tar_struct=True, + ), + model_file="model.onnx", + ), + DenseModelDescription( + model="jinaai/jina-embeddings-v2-base-en", + dim=768, + description=( + "Text embeddings, Unimodal (text), English, 8192 input tokens truncation, " + "Prefixes for queries/documents: not necessary, 2023 year." + ), + license="apache-2.0", + size_in_GB=0.52, + sources=ModelSource(hf="xenova/jina-embeddings-v2-base-en"), + model_file="onnx/model.onnx", + ), + DenseModelDescription( + model="jinaai/jina-embeddings-v2-small-en", + dim=512, + description=( + "Text embeddings, Unimodal (text), English, 8192 input tokens truncation, " + "Prefixes for queries/documents: not necessary, 2023 year." + ), + license="apache-2.0", + size_in_GB=0.12, + sources=ModelSource(hf="xenova/jina-embeddings-v2-small-en"), + model_file="onnx/model.onnx", + ), + DenseModelDescription( + model="jinaai/jina-embeddings-v2-base-de", + dim=768, + description=( + "Text embeddings, Unimodal (text), Multilingual (German, English), 8192 input tokens truncation, " + "Prefixes for queries/documents: not necessary, 2024 year." + ), + license="apache-2.0", + size_in_GB=0.32, + sources=ModelSource(hf="jinaai/jina-embeddings-v2-base-de"), + model_file="onnx/model_fp16.onnx", + ), + DenseModelDescription( + model="jinaai/jina-embeddings-v2-base-code", + dim=768, + description=( + "Text embeddings, Unimodal (text), Multilingual (English, 30 programming languages), " + "8192 input tokens truncation, Prefixes for queries/documents: not necessary, 2024 year." + ), + license="apache-2.0", + size_in_GB=0.64, + sources=ModelSource(hf="jinaai/jina-embeddings-v2-base-code"), + model_file="onnx/model.onnx", + ), + DenseModelDescription( + model="jinaai/jina-embeddings-v2-base-zh", + dim=768, + description=( + "Text embeddings, Unimodal (text), supports mixed Chinese-English input text, " + "8192 input tokens truncation, Prefixes for queries/documents: not necessary, 2024 year." + ), + license="apache-2.0", + size_in_GB=0.64, + sources=ModelSource(hf="jinaai/jina-embeddings-v2-base-zh"), + model_file="onnx/model.onnx", + ), + DenseModelDescription( + model="jinaai/jina-embeddings-v2-base-es", + dim=768, + description=( + "Text embeddings, Unimodal (text), supports mixed Spanish-English input text, " + "8192 input tokens truncation, Prefixes for queries/documents: not necessary, 2024 year." + ), + license="apache-2.0", + size_in_GB=0.64, + sources=ModelSource(hf="jinaai/jina-embeddings-v2-base-es"), + model_file="onnx/model.onnx", + ), + DenseModelDescription( + model="thenlper/gte-base", + dim=768, + description=( + "General text embeddings, Unimodal (text), supports English only input text, " + "512 input tokens truncation, Prefixes for queries/documents: not necessary, 2024 year." + ), + license="mit", + size_in_GB=0.44, + sources=ModelSource(hf="thenlper/gte-base"), + model_file="onnx/model.onnx", + ), + DenseModelDescription( + model="thenlper/gte-large", + dim=1024, + description=( + "Text embeddings, Unimodal (text), English, 512 input tokens truncation, " + "Prefixes for queries/documents: not necessary, 2023 year." + ), + license="mit", + size_in_GB=1.20, + sources=ModelSource(hf="qdrant/gte-large-onnx"), + model_file="model.onnx", + ), +] + + +class PooledNormalizedEmbedding(PooledEmbedding): + @classmethod + def _get_worker_class(cls) -> Type[OnnxTextEmbeddingWorker]: + return PooledNormalizedEmbeddingWorker + + @classmethod + def _list_supported_models(cls) -> list[DenseModelDescription]: + """Lists the supported models. + + Returns: + list[DenseModelDescription]: A list of DenseModelDescription objects containing the model information. + """ + return supported_pooled_normalized_models + + def _post_process_onnx_output( + self, output: OnnxOutputContext, **kwargs: Any + ) -> Iterable[NumpyArray]: + if output.attention_mask is None: + raise ValueError("attention_mask must be provided for document post-processing") + + embeddings = output.model_output + attn_mask = output.attention_mask + return normalize(self.mean_pooling(embeddings, attn_mask)) + + +class PooledNormalizedEmbeddingWorker(OnnxTextEmbeddingWorker): + def init_embedding( + self, + model_name: str, + cache_dir: str, + **kwargs: Any, + ) -> OnnxTextEmbedding: + return PooledNormalizedEmbedding( + model_name=model_name, + cache_dir=cache_dir, + threads=1, + **kwargs, + ) diff --git a/python/user_packages/Python313/site-packages/fastembed/text/text_embedding.py b/python/user_packages/Python313/site-packages/fastembed/text/text_embedding.py new file mode 100644 index 0000000000000000000000000000000000000000..a4ae48cc5552aa62d866915c0297a6a4a0f07f3e --- /dev/null +++ b/python/user_packages/Python313/site-packages/fastembed/text/text_embedding.py @@ -0,0 +1,228 @@ +import warnings +from typing import Any, Iterable, Sequence, Type +from dataclasses import asdict + +from fastembed.common.types import NumpyArray, OnnxProvider, Device +from fastembed.text.clip_embedding import CLIPOnnxEmbedding +from fastembed.text.custom_text_embedding import CustomTextEmbedding +from fastembed.text.pooled_normalized_embedding import PooledNormalizedEmbedding +from fastembed.text.pooled_embedding import PooledEmbedding +from fastembed.text.multitask_embedding import JinaEmbeddingV3 +from fastembed.text.onnx_embedding import OnnxTextEmbedding +from fastembed.text.text_embedding_base import TextEmbeddingBase +from fastembed.common.model_description import DenseModelDescription, ModelSource, PoolingType + + +class TextEmbedding(TextEmbeddingBase): + EMBEDDINGS_REGISTRY: list[Type[TextEmbeddingBase]] = [ + OnnxTextEmbedding, + CLIPOnnxEmbedding, + PooledNormalizedEmbedding, + PooledEmbedding, + JinaEmbeddingV3, + CustomTextEmbedding, + ] + + @classmethod + def list_supported_models(cls) -> list[dict[str, Any]]: + """Lists the supported models. + + Returns: + list[dict[str, Any]]: A list of dictionaries containing the model information. + """ + return [asdict(model) for model in cls._list_supported_models()] + + @classmethod + def _list_supported_models(cls) -> list[DenseModelDescription]: + result: list[DenseModelDescription] = [] + for embedding in cls.EMBEDDINGS_REGISTRY: + result.extend(embedding._list_supported_models()) + return result + + @classmethod + def add_custom_model( + cls, + model: str, + pooling: PoolingType, + normalization: bool, + sources: ModelSource, + dim: int, + model_file: str = "onnx/model.onnx", + description: str = "", + license: str = "", + size_in_gb: float = 0.0, + additional_files: list[str] | None = None, + ) -> None: + registered_models = cls._list_supported_models() + for registered_model in registered_models: + if model.lower() == registered_model.model.lower(): + raise ValueError( + f"Model {model} is already registered in TextEmbedding, if you still want to add this model, " + f"please use another model name" + ) + + CustomTextEmbedding.add_model( + DenseModelDescription( + model=model, + sources=sources, + dim=dim, + model_file=model_file, + description=description, + license=license, + size_in_GB=size_in_gb, + additional_files=additional_files or [], + ), + pooling=pooling, + normalization=normalization, + ) + + def __init__( + self, + model_name: str = "BAAI/bge-small-en-v1.5", + cache_dir: str | None = None, + threads: int | None = None, + providers: Sequence[OnnxProvider] | None = None, + cuda: bool | Device = Device.AUTO, + device_ids: list[int] | None = None, + lazy_load: bool = False, + **kwargs: Any, + ): + super().__init__(model_name, cache_dir, threads, **kwargs) + if model_name.lower() == "nomic-ai/nomic-embed-text-v1.5-Q".lower(): + warnings.warn( + "The model 'nomic-ai/nomic-embed-text-v1.5-Q' has been updated on HuggingFace. Please review " + "the latest documentation on HF and release notes to ensure compatibility with your workflow. ", + UserWarning, + stacklevel=2, + ) + if model_name.lower() in { + "sentence-transformers/paraphrase-multilingual-MiniLM-L12-v2".lower(), + "thenlper/gte-large".lower(), + "intfloat/multilingual-e5-large".lower(), + "sentence-transformers/paraphrase-multilingual-mpnet-base-v2".lower(), + }: + warnings.warn( + f"The model {model_name} now uses mean pooling instead of CLS embedding. " + f"In order to preserve the previous behaviour, consider either pinning fastembed version to 0.5.1 or " + "using `add_custom_model` functionality.", + UserWarning, + stacklevel=2, + ) + for EMBEDDING_MODEL_TYPE in self.EMBEDDINGS_REGISTRY: + supported_models = EMBEDDING_MODEL_TYPE._list_supported_models() + if any(model_name.lower() == model.model.lower() for model in supported_models): + self.model = EMBEDDING_MODEL_TYPE( + model_name=model_name, + cache_dir=cache_dir, + threads=threads, + providers=providers, + cuda=cuda, + device_ids=device_ids, + lazy_load=lazy_load, + **kwargs, + ) + return + + raise ValueError( + f"Model {model_name} is not supported in TextEmbedding. " + "Please check the supported models using `TextEmbedding.list_supported_models()`" + ) + + @property + def embedding_size(self) -> int: + """Get the embedding size of the current model""" + if self._embedding_size is None: + self._embedding_size = self.get_embedding_size(self.model_name) + return self._embedding_size + + @classmethod + def get_embedding_size(cls, model_name: str) -> int: + """Get the embedding size of the passed model + + Args: + model_name (str): The name of the model to get embedding size for. + + Returns: + int: The size of the embedding. + + Raises: + ValueError: If the model name is not found in the supported models. + """ + descriptions = cls._list_supported_models() + embedding_size: int | None = None + for description in descriptions: + if description.model.lower() == model_name.lower(): + embedding_size = description.dim + break + if embedding_size is None: + model_names = [description.model for description in descriptions] + raise ValueError( + f"Embedding size for model {model_name} was None. " + f"Available model names: {model_names}" + ) + return embedding_size + + def embed( + self, + documents: str | Iterable[str], + batch_size: int = 256, + parallel: int | None = None, + **kwargs: Any, + ) -> Iterable[NumpyArray]: + """ + Encode a list of documents into list of embeddings. + We use mean pooling with attention so that the model can handle variable-length inputs. + + Args: + documents: Iterator of documents or single document to embed + batch_size: Batch size for encoding -- higher values will use more memory, but be faster + parallel: + If > 1, data-parallel encoding will be used, recommended for offline encoding of large datasets. + If 0, use all available cores. + If None, don't use data-parallel processing, use default onnxruntime threading instead. + + Returns: + List of embeddings, one per document + """ + yield from self.model.embed(documents, batch_size, parallel, **kwargs) + + def query_embed(self, query: str | Iterable[str], **kwargs: Any) -> Iterable[NumpyArray]: + """ + Embeds queries + + Args: + query (Union[str, Iterable[str]]): The query to embed, or an iterable e.g. list of queries. + + Returns: + Iterable[NumpyArray]: The embeddings. + """ + # This is model-specific, so that different models can have specialized implementations + yield from self.model.query_embed(query, **kwargs) + + def passage_embed(self, texts: Iterable[str], **kwargs: Any) -> Iterable[NumpyArray]: + """ + Embeds a list of text passages into a list of embeddings. + + Args: + texts (Iterable[str]): The list of texts to embed. + **kwargs: Additional keyword argument to pass to the embed method. + + Yields: + Iterable[SparseEmbedding]: The sparse embeddings. + """ + # This is model-specific, so that different models can have specialized implementations + yield from self.model.passage_embed(texts, **kwargs) + + def token_count( + self, texts: str | Iterable[str], batch_size: int = 1024, **kwargs: Any + ) -> int: + """Returns the number of tokens in the texts. + + Args: + texts (str | Iterable[str]): The list of texts to embed. + batch_size (int): Batch size for encoding + + Returns: + int: Sum of number of tokens in the texts. + """ + return self.model.token_count(texts, batch_size=batch_size, **kwargs) diff --git a/python/user_packages/Python313/site-packages/fastembed/text/text_embedding_base.py b/python/user_packages/Python313/site-packages/fastembed/text/text_embedding_base.py new file mode 100644 index 0000000000000000000000000000000000000000..13bc4f7329cf454883517f635a4ec24ad57f3e9a --- /dev/null +++ b/python/user_packages/Python313/site-packages/fastembed/text/text_embedding_base.py @@ -0,0 +1,75 @@ +from typing import Iterable, Any + +from fastembed.common.model_description import DenseModelDescription +from fastembed.common.types import NumpyArray +from fastembed.common.model_management import ModelManagement + + +class TextEmbeddingBase(ModelManagement[DenseModelDescription]): + def __init__( + self, + model_name: str, + cache_dir: str | None = None, + threads: int | None = None, + **kwargs: Any, + ): + self.model_name = model_name + self.cache_dir = cache_dir + self.threads = threads + self._local_files_only = kwargs.pop("local_files_only", False) + self._embedding_size: int | None = None + + def embed( + self, + documents: str | Iterable[str], + batch_size: int = 256, + parallel: int | None = None, + **kwargs: Any, + ) -> Iterable[NumpyArray]: + raise NotImplementedError() + + def passage_embed(self, texts: Iterable[str], **kwargs: Any) -> Iterable[NumpyArray]: + """ + Embeds a list of text passages into a list of embeddings. + + Args: + texts (Iterable[str]): The list of texts to embed. + **kwargs: Additional keyword argument to pass to the embed method. + + Yields: + Iterable[NumpyArray]: The embeddings. + """ + + # This is model-specific, so that different models can have specialized implementations + yield from self.embed(texts, **kwargs) + + def query_embed(self, query: str | Iterable[str], **kwargs: Any) -> Iterable[NumpyArray]: + """ + Embeds queries + + Args: + query (Union[str, Iterable[str]]): The query to embed, or an iterable e.g. list of queries. + + Returns: + Iterable[NumpyArray]: The embeddings. + """ + + # This is model-specific, so that different models can have specialized implementations + if isinstance(query, str): + yield from self.embed([query], **kwargs) + else: + yield from self.embed(query, **kwargs) + + @classmethod + def get_embedding_size(cls, model_name: str) -> int: + """Returns embedding size of the passed model.""" + raise NotImplementedError("Subclasses must implement this method") + + @property + def embedding_size(self) -> int: + """Returns embedding size for the current model""" + raise NotImplementedError("Subclasses must implement this method") + + def token_count(self, texts: str | Iterable[str], **kwargs: Any) -> int: + """Returns the number of tokens in the texts.""" + raise NotImplementedError("Subclasses must implement this method") diff --git a/python/user_packages/Python313/site-packages/filelock-3.29.0.dist-info/licenses/LICENSE b/python/user_packages/Python313/site-packages/filelock-3.29.0.dist-info/licenses/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..291919c0b6f41d014767f6c877af9f7595fcff99 --- /dev/null +++ b/python/user_packages/Python313/site-packages/filelock-3.29.0.dist-info/licenses/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2025 Bernát Gábor and contributors + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/python/user_packages/Python313/site-packages/filelock/__pycache__/__init__.cpython-313.pyc b/python/user_packages/Python313/site-packages/filelock/__pycache__/__init__.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..54d609a8f9ac3e0d6e3b4f411d8feb797cd7fd01 Binary files /dev/null and b/python/user_packages/Python313/site-packages/filelock/__pycache__/__init__.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/filelock/__pycache__/_api.cpython-313.pyc b/python/user_packages/Python313/site-packages/filelock/__pycache__/_api.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9895d897e5f0cc0634f51374cfef35553a0e1270 Binary files /dev/null and b/python/user_packages/Python313/site-packages/filelock/__pycache__/_api.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/filelock/__pycache__/_async_read_write.cpython-313.pyc b/python/user_packages/Python313/site-packages/filelock/__pycache__/_async_read_write.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f6949f6aba23e6d4b54058d84953226ca270a75b Binary files /dev/null and b/python/user_packages/Python313/site-packages/filelock/__pycache__/_async_read_write.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/filelock/__pycache__/_error.cpython-313.pyc b/python/user_packages/Python313/site-packages/filelock/__pycache__/_error.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1a836c473986d3be8cd37a2683f1114e7dd145d6 Binary files /dev/null and b/python/user_packages/Python313/site-packages/filelock/__pycache__/_error.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/filelock/__pycache__/_read_write.cpython-313.pyc b/python/user_packages/Python313/site-packages/filelock/__pycache__/_read_write.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..62ab8d981cd0ea2729f4bf6dd069d932bd3404fe Binary files /dev/null and b/python/user_packages/Python313/site-packages/filelock/__pycache__/_read_write.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/filelock/__pycache__/_soft.cpython-313.pyc b/python/user_packages/Python313/site-packages/filelock/__pycache__/_soft.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2e46486f35e4f565d1405167c81805298c65dbeb Binary files /dev/null and b/python/user_packages/Python313/site-packages/filelock/__pycache__/_soft.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/filelock/__pycache__/_unix.cpython-313.pyc b/python/user_packages/Python313/site-packages/filelock/__pycache__/_unix.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f333c8eb6316e51c83be2e38dff745eaf00ba075 Binary files /dev/null and b/python/user_packages/Python313/site-packages/filelock/__pycache__/_unix.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/filelock/__pycache__/_util.cpython-313.pyc b/python/user_packages/Python313/site-packages/filelock/__pycache__/_util.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c231ae56dbbc0fc8d1199fbb87bb099ac0380e29 Binary files /dev/null and b/python/user_packages/Python313/site-packages/filelock/__pycache__/_util.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/filelock/__pycache__/_windows.cpython-313.pyc b/python/user_packages/Python313/site-packages/filelock/__pycache__/_windows.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5ea9475e2b6c89722329ebc0b90ce0645b497bd9 Binary files /dev/null and b/python/user_packages/Python313/site-packages/filelock/__pycache__/_windows.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/filelock/__pycache__/asyncio.cpython-313.pyc b/python/user_packages/Python313/site-packages/filelock/__pycache__/asyncio.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8d5b96bef77dd695152d23e8330780c0233f04d6 Binary files /dev/null and b/python/user_packages/Python313/site-packages/filelock/__pycache__/asyncio.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/filelock/__pycache__/version.cpython-313.pyc b/python/user_packages/Python313/site-packages/filelock/__pycache__/version.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c3f955b83b21d226c6f8a41fca0e22b7edee0ed1 Binary files /dev/null and b/python/user_packages/Python313/site-packages/filelock/__pycache__/version.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/filelock/_soft_rw/__init__.py b/python/user_packages/Python313/site-packages/filelock/_soft_rw/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..0b737bcee9d257307ed31865e43023b967b116ab --- /dev/null +++ b/python/user_packages/Python313/site-packages/filelock/_soft_rw/__init__.py @@ -0,0 +1,12 @@ +"""Cross-process and cross-host reader/writer lock on :class:`~filelock.SoftFileLock` primitives.""" + +from __future__ import annotations + +from ._async import AsyncAcquireSoftReadWriteReturnProxy, AsyncSoftReadWriteLock +from ._sync import SoftReadWriteLock + +__all__ = [ + "AsyncAcquireSoftReadWriteReturnProxy", + "AsyncSoftReadWriteLock", + "SoftReadWriteLock", +] diff --git a/python/user_packages/Python313/site-packages/filelock/_soft_rw/__pycache__/__init__.cpython-313.pyc b/python/user_packages/Python313/site-packages/filelock/_soft_rw/__pycache__/__init__.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8ce12f782ab34459d265602d89cf51889e58b0e5 Binary files /dev/null and b/python/user_packages/Python313/site-packages/filelock/_soft_rw/__pycache__/__init__.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/filelock/_soft_rw/__pycache__/_async.cpython-313.pyc b/python/user_packages/Python313/site-packages/filelock/_soft_rw/__pycache__/_async.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2ea7876b474eb0914bb2c862b14b17aa0563092e Binary files /dev/null and b/python/user_packages/Python313/site-packages/filelock/_soft_rw/__pycache__/_async.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/filelock/_soft_rw/__pycache__/_sync.cpython-313.pyc b/python/user_packages/Python313/site-packages/filelock/_soft_rw/__pycache__/_sync.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d30783be37ac395415f1890f43f6d01ca61be24b Binary files /dev/null and b/python/user_packages/Python313/site-packages/filelock/_soft_rw/__pycache__/_sync.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/filelock/_soft_rw/_async.py b/python/user_packages/Python313/site-packages/filelock/_soft_rw/_async.py new file mode 100644 index 0000000000000000000000000000000000000000..8b5ae2ef9ba16988f9b6c49312d008ab995d7e0e --- /dev/null +++ b/python/user_packages/Python313/site-packages/filelock/_soft_rw/_async.py @@ -0,0 +1,213 @@ +"""Async wrapper around :class:`SoftReadWriteLock` for use with ``asyncio``.""" + +from __future__ import annotations + +import asyncio +import functools +from contextlib import asynccontextmanager +from typing import TYPE_CHECKING + +from ._sync import SoftReadWriteLock + +if TYPE_CHECKING: + import os + from collections.abc import AsyncGenerator, Callable + from concurrent import futures + from types import TracebackType + + +class AsyncAcquireSoftReadWriteReturnProxy: + """Async context-aware object that releases an :class:`AsyncSoftReadWriteLock` on exit.""" + + def __init__(self, lock: AsyncSoftReadWriteLock) -> None: + self.lock = lock + + async def __aenter__(self) -> AsyncSoftReadWriteLock: + return self.lock + + async def __aexit__( + self, + exc_type: type[BaseException] | None, + exc_value: BaseException | None, + traceback: TracebackType | None, + ) -> None: + await self.lock.release() + + +class AsyncSoftReadWriteLock: + """ + Async wrapper around :class:`SoftReadWriteLock` for ``asyncio`` applications. + + The sync class's blocking filesystem operations run on a thread pool via ``loop.run_in_executor()``. + Reentrancy, upgrade/downgrade rules, fork handling, heartbeat and TTL stale detection, and singleton + behavior are delegated to the underlying :class:`SoftReadWriteLock`. + + :param lock_file: path to the lock file; sidecar state/write/readers live next to it + :param timeout: maximum wait time in seconds; ``-1`` means block indefinitely + :param blocking: if ``False``, raise :class:`~filelock.Timeout` immediately on contention + :param is_singleton: if ``True``, reuse existing :class:`SoftReadWriteLock` instances per resolved path + :param heartbeat_interval: seconds between heartbeat refreshes; default 30 s + :param stale_threshold: seconds of mtime inactivity before a marker is stale; defaults to ``3 * heartbeat_interval`` + :param poll_interval: seconds between acquire retries under contention; default 0.25 s + :param loop: event loop for ``run_in_executor``; ``None`` uses the running loop + :param executor: executor for ``run_in_executor``; ``None`` uses the default executor + + .. versionadded:: 3.27.0 + + """ + + def __init__( # noqa: PLR0913 + self, + lock_file: str | os.PathLike[str], + timeout: float = -1, + *, + blocking: bool = True, + is_singleton: bool = True, + heartbeat_interval: float = 30.0, + stale_threshold: float | None = None, + poll_interval: float = 0.25, + loop: asyncio.AbstractEventLoop | None = None, + executor: futures.Executor | None = None, + ) -> None: + self._lock = SoftReadWriteLock( + lock_file, + timeout, + blocking=blocking, + is_singleton=is_singleton, + heartbeat_interval=heartbeat_interval, + stale_threshold=stale_threshold, + poll_interval=poll_interval, + ) + self._loop = loop + self._executor = executor + + @property + def lock_file(self) -> str: + """:returns: the path to the lock file passed to the constructor.""" + return self._lock.lock_file + + @property + def timeout(self) -> float: + """:returns: the default timeout applied when ``acquire_read`` / ``acquire_write`` is called without one.""" + return self._lock.timeout + + @property + def blocking(self) -> bool: + """:returns: whether ``acquire_*`` defaults to blocking; ``False`` makes contention raise immediately.""" + return self._lock.blocking + + @property + def loop(self) -> asyncio.AbstractEventLoop | None: + """:returns: the event loop used for ``run_in_executor``, or ``None`` for the running loop.""" + return self._loop + + @property + def executor(self) -> futures.Executor | None: + """:returns: the executor used for ``run_in_executor``, or ``None`` for the default executor.""" + return self._executor + + async def acquire_read( + self, timeout: float | None = None, *, blocking: bool | None = None + ) -> AsyncAcquireSoftReadWriteReturnProxy: + """ + Acquire a shared read lock. + + See :meth:`SoftReadWriteLock.acquire_read` for the full reentrancy / upgrade / fork semantics. The blocking + work runs inside ``run_in_executor`` so other coroutines on the same loop continue to progress while this + call waits. + + :param timeout: maximum wait time in seconds, or ``None`` to use the instance default + :param blocking: if ``False``, raise :class:`~filelock.Timeout` immediately; ``None`` uses the instance default + + :returns: a proxy usable as an async context manager to release the lock + + :raises RuntimeError: if a write lock is already held, if this instance was invalidated by + :func:`os.fork`, or if :meth:`close` was called + :raises Timeout: if the lock cannot be acquired within *timeout* seconds + + """ + await self._run(self._lock.acquire_read, timeout, blocking=blocking) + return AsyncAcquireSoftReadWriteReturnProxy(lock=self) + + async def acquire_write( + self, timeout: float | None = None, *, blocking: bool | None = None + ) -> AsyncAcquireSoftReadWriteReturnProxy: + """ + Acquire an exclusive write lock. + + See :meth:`SoftReadWriteLock.acquire_write` for the two-phase writer-preferring semantics. The blocking + work runs inside ``run_in_executor``. + + :param timeout: maximum wait time in seconds, or ``None`` to use the instance default + :param blocking: if ``False``, raise :class:`~filelock.Timeout` immediately; ``None`` uses the instance default + + :returns: a proxy usable as an async context manager to release the lock + + :raises RuntimeError: if a read lock is already held, if a write lock is held by a different thread, if + this instance was invalidated by :func:`os.fork`, or if :meth:`close` was called + :raises Timeout: if the lock cannot be acquired within *timeout* seconds + + """ + await self._run(self._lock.acquire_write, timeout, blocking=blocking) + return AsyncAcquireSoftReadWriteReturnProxy(lock=self) + + async def release(self, *, force: bool = False) -> None: + """ + Release one level of the current lock. + + :param force: if ``True``, release the lock completely regardless of the current lock level + + :raises RuntimeError: if no lock is currently held and *force* is ``False`` + + """ + await self._run(self._lock.release, force=force) + + @asynccontextmanager + async def read_lock(self, timeout: float | None = None, *, blocking: bool | None = None) -> AsyncGenerator[None]: + """ + Async context manager that acquires and releases a shared read lock. + + :param timeout: maximum wait time in seconds, or ``None`` to use the instance default + :param blocking: if ``False``, raise :class:`~filelock.Timeout` immediately; ``None`` uses the instance default + + :raises RuntimeError: if a write lock is already held on this instance + :raises Timeout: if the lock cannot be acquired within *timeout* seconds + + """ + await self.acquire_read(timeout, blocking=blocking) + try: + yield + finally: + await self.release() + + @asynccontextmanager + async def write_lock(self, timeout: float | None = None, *, blocking: bool | None = None) -> AsyncGenerator[None]: + """ + Async context manager that acquires and releases an exclusive write lock. + + :param timeout: maximum wait time in seconds, or ``None`` to use the instance default + :param blocking: if ``False``, raise :class:`~filelock.Timeout` immediately; ``None`` uses the instance default + + :raises RuntimeError: if a read lock is already held, or a write lock is held by a different thread + :raises Timeout: if the lock cannot be acquired within *timeout* seconds + + """ + await self.acquire_write(timeout, blocking=blocking) + try: + yield + finally: + await self.release() + + async def close(self) -> None: + """Release any held lock and release the underlying filesystem resources. Idempotent.""" + await self._run(self._lock.close) + + async def _run(self, func: Callable[..., object], *args: object, **kwargs: object) -> object: + loop = self._loop or asyncio.get_running_loop() + return await loop.run_in_executor(self._executor, functools.partial(func, *args, **kwargs)) + + +__all__ = [ + "AsyncAcquireSoftReadWriteReturnProxy", + "AsyncSoftReadWriteLock", +] diff --git a/python/user_packages/Python313/site-packages/filelock/_soft_rw/_sync.py b/python/user_packages/Python313/site-packages/filelock/_soft_rw/_sync.py new file mode 100644 index 0000000000000000000000000000000000000000..06d0c9d25524857036a129f406ae2f91785c1bd7 --- /dev/null +++ b/python/user_packages/Python313/site-packages/filelock/_soft_rw/_sync.py @@ -0,0 +1,847 @@ +"""Cross-process and cross-host reader/writer lock built on :class:`SoftFileLock` primitives.""" + +from __future__ import annotations + +import atexit +import hmac +import os +import re +import secrets +import socket +import stat +import sys +import threading +import time +import uuid +from contextlib import contextmanager, suppress +from dataclasses import dataclass +from pathlib import Path +from typing import TYPE_CHECKING, Literal +from weakref import WeakValueDictionary + +from filelock._api import AcquireReturnProxy +from filelock._error import Timeout +from filelock._soft import SoftFileLock +from filelock._util import ensure_directory_exists + +if TYPE_CHECKING: + from collections.abc import Callable, Generator + + +_Mode = Literal["read", "write"] +_BREAK_SUFFIX = ".break" +_MAX_MARKER_SIZE = 1024 +_O_NOFOLLOW = getattr(os, "O_NOFOLLOW", 0) +# dirfd-relative I/O is a Unix-only optimization; Windows cannot ``os.open()`` a directory at all, and +# its ``os`` module skips dir_fd support entirely. When disabled, callers fall back to full-path ops. +_SUPPORTS_DIR_FD = sys.platform != "win32" and os.open in os.supports_dir_fd + +_all_instances: WeakValueDictionary[Path, SoftReadWriteLock] = WeakValueDictionary() +_all_instances_lock = threading.Lock() +_atexit_registered = False +_fork_registered = False + + +@dataclass(frozen=True) +class _Paths: + state: str + write: str + readers: str + + +@dataclass +class _Locks: + internal: threading.Lock + transaction: threading.Lock + state: SoftFileLock + + +@dataclass(frozen=True) +class _MarkerInfo: + token: str + pid: int + hostname: str + + +@dataclass +class _Hold: + """Everything that exists only while a lock is held; ``None`` when the instance has no lock.""" + + level: int + mode: _Mode + write_thread_id: int | None + marker_name: str + is_reader: bool + token: str + heartbeat_thread: _HeartbeatThread + heartbeat_stop: threading.Event + + +class _SoftRWMeta(type): + _instances: WeakValueDictionary[Path, SoftReadWriteLock] + _instances_lock: threading.Lock + + def __call__( # noqa: PLR0913 + cls, + lock_file: str | os.PathLike[str], + timeout: float = -1, + *, + blocking: bool = True, + is_singleton: bool = True, + heartbeat_interval: float = 30.0, + stale_threshold: float | None = None, + poll_interval: float = 0.25, + ) -> SoftReadWriteLock: + if not is_singleton: + return super().__call__( + lock_file, + timeout, + blocking=blocking, + is_singleton=is_singleton, + heartbeat_interval=heartbeat_interval, + stale_threshold=stale_threshold, + poll_interval=poll_interval, + ) + + normalized = Path(lock_file).resolve() + with cls._instances_lock: + instance = cls._instances.get(normalized) + if instance is None: + instance = super().__call__( + lock_file, + timeout, + blocking=blocking, + is_singleton=is_singleton, + heartbeat_interval=heartbeat_interval, + stale_threshold=stale_threshold, + poll_interval=poll_interval, + ) + cls._instances[normalized] = instance + elif instance.timeout != timeout or instance.blocking != blocking: + msg = ( + f"Singleton lock created with timeout={instance.timeout}, blocking={instance.blocking}," + f" cannot be changed to timeout={timeout}, blocking={blocking}" + ) + raise ValueError(msg) + return instance + + +class SoftReadWriteLock(metaclass=_SoftRWMeta): + """ + Cross-process and cross-host reader/writer lock built on :class:`SoftFileLock` primitives. + + Use this class instead of :class:`~filelock.ReadWriteLock` when the lock file lives on a network + filesystem (NFS, Lustre with ``-o flock``, HPC cluster shared storage). ``ReadWriteLock`` is backed + by SQLite and cannot run on NFS because SQLite's ``fcntl`` locking is unreliable there. + + Layout on disk for a lock at ``foo.lock``: + + - ``foo.lock.state`` — a :class:`SoftFileLock` taken only during state transitions (microseconds). + - ``foo.lock.write`` — writer marker; its presence means a writer is claiming or holding the lock. + - ``foo.lock.readers/..`` — one file per reader. + + Each marker stores a random token (``secrets.token_hex(16)``), the holder's pid, and the holder's + hostname. A daemon heartbeat thread refreshes ``mtime`` on every held marker. A marker whose mtime + has not advanced in ``stale_threshold`` seconds may be evicted by any process on any host, giving + correct behavior when a compute node crashes with a lock held. + + Writer acquire is two-phase and writer-preferring: phase 1 claims ``.write`` (blocking any new + reader), phase 2 waits for existing readers to drain. Writer starvation is impossible. + + Reentrancy, upgrade/downgrade rules, thread pinning, and singleton caching by resolved path match + :class:`~filelock.ReadWriteLock`. + + Forking while holding a lock invalidates the inherited instance in the child so the child cannot + double-own the lock with its parent; ``release()`` on a fork-invalidated instance is a no-op, and + the child must re-acquire if it needs a lock. + + Trust boundary: protects against same-UID non-cooperating processes (one host or cross-host) and + same-host different-UID users via ``0o600`` / ``0o700`` permissions. Does not protect against root + compromise, NTP tampering on same-UID cross-host nodes, or multi-tenant mounts where hostile + co-tenants share the UID. + + :param lock_file: path to the lock file; sidecar state/write/readers live next to it + :param timeout: maximum wait time in seconds; ``-1`` means block indefinitely + :param blocking: if ``False``, raise :class:`~filelock.Timeout` immediately on contention + :param is_singleton: if ``True``, reuse existing instances for the same resolved path + :param heartbeat_interval: seconds between heartbeat refreshes; default 30 s + :param stale_threshold: seconds of ``mtime`` inactivity before a marker is stale; defaults to + ``3 * heartbeat_interval``, matching etcd's ``LeaseKeepAlive`` convention + :param poll_interval: seconds between acquire retries under contention; default 0.25 s + + .. versionadded:: 3.27.0 + + """ + + _instances: WeakValueDictionary[Path, SoftReadWriteLock] = WeakValueDictionary() + _instances_lock = threading.Lock() + + def __init__( # noqa: PLR0913 + self, + lock_file: str | os.PathLike[str], + timeout: float = -1, + *, + blocking: bool = True, + is_singleton: bool = True, # noqa: ARG002 + heartbeat_interval: float = 30.0, + stale_threshold: float | None = None, + poll_interval: float = 0.25, + ) -> None: + if heartbeat_interval <= 0: + msg = f"heartbeat_interval must be positive, got {heartbeat_interval}" + raise ValueError(msg) + if stale_threshold is None: + stale_threshold = heartbeat_interval * 3 + if stale_threshold <= heartbeat_interval: + msg = f"stale_threshold must exceed heartbeat_interval ({stale_threshold} <= {heartbeat_interval})" + raise ValueError(msg) + if poll_interval <= 0: + msg = f"poll_interval must be positive, got {poll_interval}" + raise ValueError(msg) + + self.lock_file: str = os.fspath(lock_file) + self.timeout: float = timeout + self.blocking: bool = blocking + self.heartbeat_interval: float = heartbeat_interval + self.stale_threshold: float = stale_threshold + self.poll_interval: float = poll_interval + + self._paths = _Paths( + state=f"{self.lock_file}.state", + write=f"{self.lock_file}.write", + readers=f"{self.lock_file}.readers", + ) + ensure_directory_exists(self.lock_file) + self._locks = _Locks( + internal=threading.Lock(), + transaction=threading.Lock(), + state=SoftFileLock(self._paths.state, timeout=-1), + ) + self._readers_dir_fd: int | None = None + self._hold: _Hold | None = None + self._fork_invalidated: bool = False + self._closed: bool = False + + with _all_instances_lock: + _all_instances[Path(self.lock_file).resolve()] = self + _register_hooks() + + @contextmanager + def read_lock(self, timeout: float | None = None, *, blocking: bool | None = None) -> Generator[None]: + """ + Context manager that acquires and releases a shared read lock. + + Falls back to instance defaults for *timeout* and *blocking* when ``None``. + + :param timeout: maximum wait time in seconds, or ``None`` to use the instance default + :param blocking: if ``False``, raise :class:`~filelock.Timeout` immediately; ``None`` uses the instance default + + :raises RuntimeError: if a write lock is already held on this instance + :raises Timeout: if the lock cannot be acquired within *timeout* seconds + + """ + self.acquire_read(timeout, blocking=blocking) + try: + yield + finally: + self.release() + + @contextmanager + def write_lock(self, timeout: float | None = None, *, blocking: bool | None = None) -> Generator[None]: + """ + Context manager that acquires and releases an exclusive write lock. + + Falls back to instance defaults for *timeout* and *blocking* when ``None``. + + :param timeout: maximum wait time in seconds, or ``None`` to use the instance default + :param blocking: if ``False``, raise :class:`~filelock.Timeout` immediately; ``None`` uses the instance default + + :raises RuntimeError: if a read lock is already held, or a write lock is held by a different thread + :raises Timeout: if the lock cannot be acquired within *timeout* seconds + + """ + self.acquire_write(timeout, blocking=blocking) + try: + yield + finally: + self.release() + + def acquire_read(self, timeout: float | None = None, *, blocking: bool | None = None) -> AcquireReturnProxy: + """ + Acquire a shared read lock. + + If this instance already holds a read lock, the lock level is incremented (reentrant). Attempting to acquire a + read lock while holding a write lock raises :class:`RuntimeError` (downgrade not allowed). On the 0→1 + transition a daemon heartbeat thread is started that refreshes the reader marker's ``mtime`` every + ``heartbeat_interval`` seconds so peers on other hosts do not evict the marker as stale. + + :param timeout: maximum wait time in seconds, or ``None`` to use the instance default; ``-1`` means block + indefinitely + :param blocking: if ``False``, raise :class:`~filelock.Timeout` immediately when the lock is unavailable; + ``None`` uses the instance default + + :returns: a proxy that can be used as a context manager to release the lock + + :raises RuntimeError: if a write lock is already held on this instance, if this instance was invalidated by + :func:`os.fork`, or if :meth:`close` was called + :raises Timeout: if the lock cannot be acquired within *timeout* seconds + + """ + return self._acquire("read", timeout, blocking=blocking) + + def acquire_write(self, timeout: float | None = None, *, blocking: bool | None = None) -> AcquireReturnProxy: + """ + Acquire an exclusive write lock. + + If this instance already holds a write lock from the same thread, the lock level is incremented (reentrant). + Attempting to acquire a write lock while holding a read lock raises :class:`RuntimeError` (upgrade not + allowed). Write locks are pinned to the acquiring thread: a different thread trying to re-enter also raises + :class:`RuntimeError`. + + Writer acquisition runs in two phases. Phase 1 atomically claims ``.write`` via ``O_CREAT | O_EXCL``, + which immediately blocks any new reader on any host. Phase 2 waits for existing readers to drain. Writer + starvation is impossible: new readers see ``.write`` during phase 2 and wait behind the pending writer. + + :param timeout: maximum wait time in seconds, or ``None`` to use the instance default; ``-1`` means block + indefinitely + :param blocking: if ``False``, raise :class:`~filelock.Timeout` immediately when the lock is unavailable; + ``None`` uses the instance default + + :returns: a proxy that can be used as a context manager to release the lock + + :raises RuntimeError: if a read lock is already held, if a write lock is held by a different thread, if this + instance was invalidated by :func:`os.fork`, or if :meth:`close` was called + :raises Timeout: if the lock cannot be acquired within *timeout* seconds + + """ + return self._acquire("write", timeout, blocking=blocking) + + def close(self) -> None: + """ + Release any held lock and release internal filesystem resources. + + Idempotent. After calling this method the instance can no longer acquire locks — subsequent acquires raise + :class:`RuntimeError`. A fork-invalidated instance is closed without raising. + """ + self.release(force=True) + with self._locks.internal: + if self._closed: + return + self._closed = True + if self._readers_dir_fd is not None: + with suppress(OSError): + os.close(self._readers_dir_fd) + self._readers_dir_fd = None + + def release(self, *, force: bool = False) -> None: + """ + Release one level of the current lock. + + When the lock level reaches zero the heartbeat thread is stopped and the held marker file is unlinked. On a + fork-invalidated instance (that is, the child of a :func:`os.fork` call made while the parent held a lock) + this method is a no-op so inherited ``with`` blocks can unwind cleanly in the child. + + :param force: if ``True``, release the lock completely regardless of the current lock level + + :raises RuntimeError: if no lock is currently held and *force* is ``False`` + + """ + with self._locks.internal: + if self._fork_invalidated: + # Inherited state from the parent is meaningless in the child; clear any counters and return. + self._hold = None + return + hold = self._hold + if hold is None: + if force: + return + msg = f"Cannot release a lock on {self.lock_file} (lock id: {id(self)}) that is not held" + raise RuntimeError(msg) + if force: + hold.level = 0 + else: + hold.level -= 1 + if hold.level > 0: + return + self._hold = None + + # Order matters: signal → join → unlink. A late tick on a deleted marker is harmless, and the + # token check in the heartbeat callback would catch any re-acquisition race, but joining first + # removes even that theoretical race. + hold.heartbeat_stop.set() + hold.heartbeat_thread.join(timeout=self.heartbeat_interval + 1.0) + if hold.is_reader: + _unlink(hold.marker_name, dir_fd=self._readers_dir_fd) + else: + _unlink(hold.marker_name) + + @classmethod + def get_lock( + cls, + lock_file: str | os.PathLike[str], + timeout: float = -1, + *, + blocking: bool = True, + ) -> SoftReadWriteLock: + """ + Return the singleton :class:`SoftReadWriteLock` for *lock_file*. + + :param lock_file: path to the lock file; sidecar state/write/readers live next to it + :param timeout: maximum wait time in seconds; ``-1`` means block indefinitely + :param blocking: if ``False``, raise :class:`~filelock.Timeout` immediately when the lock is unavailable + + :returns: the singleton lock instance + + :raises ValueError: if an instance already exists for this path with different *timeout* or *blocking* values + + """ + return cls(lock_file, timeout, blocking=blocking) + + def _acquire( + self, + mode: _Mode, + timeout: float | None, + *, + blocking: bool | None, + ) -> AcquireReturnProxy: + effective_timeout = self.timeout if timeout is None else timeout + effective_blocking = self.blocking if blocking is None else blocking + + with self._locks.internal: + if self._fork_invalidated: + msg = f"SoftReadWriteLock on {self.lock_file} was invalidated by fork(); construct a new instance" + raise RuntimeError(msg) + if self._closed: + msg = f"SoftReadWriteLock on {self.lock_file} has been closed" + raise RuntimeError(msg) + if self._hold is not None: + return self._validate_reentrant(mode) + + start = time.perf_counter() + if not effective_blocking: + acquired = self._locks.transaction.acquire(blocking=False) + elif effective_timeout == -1: + acquired = self._locks.transaction.acquire(blocking=True) + else: + acquired = self._locks.transaction.acquire(blocking=True, timeout=effective_timeout) + if not acquired: + raise Timeout(self.lock_file) from None + try: + with self._locks.internal: + if self._hold is not None: + return self._validate_reentrant(mode) + + deadline = None if effective_timeout == -1 else start + effective_timeout + token = secrets.token_hex(16) + if mode == "write": + marker_name, is_reader = self._acquire_writer_slot( + token, deadline=deadline, blocking=effective_blocking + ) + else: + marker_name, is_reader = self._acquire_reader_slot( + token, deadline=deadline, blocking=effective_blocking + ) + + stop_event = threading.Event() + heartbeat = _HeartbeatThread( + refresh=self._refresh_marker, + interval=self.heartbeat_interval, + stop_event=stop_event, + name=f"filelock-heartbeat-{id(self):x}", + ) + + with self._locks.internal: + self._hold = _Hold( + level=1, + mode=mode, + write_thread_id=threading.get_ident() if mode == "write" else None, + marker_name=marker_name, + is_reader=is_reader, + token=token, + heartbeat_thread=heartbeat, + heartbeat_stop=stop_event, + ) + + heartbeat.start() + return AcquireReturnProxy(lock=self) + finally: + self._locks.transaction.release() + + def _validate_reentrant(self, mode: _Mode) -> AcquireReturnProxy: + hold = self._hold + assert hold is not None # noqa: S101 + if hold.mode != mode: + opposite = "write" if mode == "read" else "read" + direction = "downgrade" if mode == "read" else "upgrade" + msg = ( + f"Cannot acquire {mode} lock on {self.lock_file} (lock id: {id(self)}): " + f"already holding a {opposite} lock ({direction} not allowed)" + ) + raise RuntimeError(msg) + if mode == "write" and (cur := threading.get_ident()) != hold.write_thread_id: + msg = ( + f"Cannot acquire write lock on {self.lock_file} (lock id: {id(self)}) " + f"from thread {cur} while it is held by thread {hold.write_thread_id}" + ) + raise RuntimeError(msg) + hold.level += 1 + return AcquireReturnProxy(lock=self) + + def _acquire_writer_slot( + self, + token: str, + *, + deadline: float | None, + blocking: bool, + ) -> tuple[str, bool]: + # Phase 2 scans readers/ via dirfd (where supported), so we need it open even though writers never + # create files inside. + self._open_readers_dir() + + def try_claim_writer() -> bool: + with self._locks.state: + _break_stale_marker(self._paths.write, stale_threshold=self.stale_threshold, now=time.time()) + if _file_exists(self._paths.write): + return False + try: + _atomic_create_marker(self._paths.write, token) + except FileExistsError: + return False + return True + + def readers_drained_touching() -> bool: + with self._locks.state: + # Refresh our writer marker on every scan iteration. Otherwise phase 2 can exceed + # ``stale_threshold`` under contention and a peer would treat us as stale and evict us. + with suppress(OSError): + _touch(self._paths.write) + self._break_stale_readers(time.time()) + return not self._any_readers() + + self._wait_for(try_claim_writer, deadline=deadline, blocking=blocking) + try: + self._wait_for(readers_drained_touching, deadline=deadline, blocking=blocking) + except Timeout: + # Give up our writer claim so readers can make progress again. + _unlink(self._paths.write) + raise + return self._paths.write, False + + def _acquire_reader_slot( + self, + token: str, + *, + deadline: float | None, + blocking: bool, + ) -> tuple[str, bool]: + self._open_readers_dir() + reader_name = f"{uuid.uuid4().hex}.{os.getpid()}" + dir_fd = self._readers_dir_fd + full_reader_path = str(Path(self._paths.readers) / reader_name) + + def try_claim_reader() -> bool: + with self._locks.state: + _break_stale_marker(self._paths.write, stale_threshold=self.stale_threshold, now=time.time()) + if _file_exists(self._paths.write): + return False + if dir_fd is not None: + _atomic_create_marker(reader_name, token, dir_fd=dir_fd) + else: # pragma: win32 cover + _atomic_create_marker(full_reader_path, token) + return True + + self._wait_for(try_claim_reader, deadline=deadline, blocking=blocking) + return (reader_name if dir_fd is not None else full_reader_path), True + + def _wait_for( + self, + predicate: Callable[[], bool], + *, + deadline: float | None, + blocking: bool, + ) -> None: + while True: + if predicate(): + return + now = time.perf_counter() + if not blocking: + raise Timeout(self.lock_file) + if deadline is not None and now >= deadline: + raise Timeout(self.lock_file) + sleep_for = self.poll_interval + if deadline is not None: + sleep_for = min(sleep_for, max(deadline - now, 0.0)) + time.sleep(sleep_for) + + def _open_readers_dir(self) -> None: + readers_path = Path(self._paths.readers) + with suppress(FileExistsError): + readers_path.mkdir(mode=0o700) + # mkdir has no O_NOFOLLOW, so verify via lstat that we did not land on an attacker-placed symlink + # or a regular file before we open or scan inside. + st = os.lstat(self._paths.readers) + if stat.S_ISLNK(st.st_mode) or not stat.S_ISDIR(st.st_mode): + msg = f"{self._paths.readers} exists but is not a directory or is a symlink; refusing to use it" + raise RuntimeError(msg) + if self._readers_dir_fd is None and _SUPPORTS_DIR_FD: + flags = os.O_RDONLY | getattr(os, "O_DIRECTORY", 0) | _O_NOFOLLOW + self._readers_dir_fd = os.open(self._paths.readers, flags) + + def _any_readers(self) -> bool: + for _ in self._iter_reader_entries(): + return True + return False + + def _iter_reader_entries(self) -> Generator[tuple[str, bool]]: + """ + Yield ``(name, dirfd_relative)`` pairs for every live reader marker. + + ``dirfd_relative`` is ``True`` when *name* should be passed to ``dir_fd=``-aware syscalls; ``False`` + when *name* is a full path because dirfd-relative I/O is unavailable on this platform. + """ + if self._readers_dir_fd is not None: + with os.scandir(self._readers_dir_fd) as it: + for entry in it: + if not _is_housekeeping_name(entry.name): + yield entry.name, True + return + readers_path = Path(self._paths.readers) # pragma: win32 cover + with os.scandir(readers_path) as it: # pragma: win32 cover + for entry in it: # pragma: win32 cover + if not _is_housekeeping_name(entry.name): # pragma: win32 cover + yield str(readers_path / entry.name), False # pragma: win32 cover + + def _break_stale_readers(self, now: float) -> None: + names: list[tuple[str, int | None]] = [] + try: + for name, dirfd_relative in self._iter_reader_entries(): + names.append((name, self._readers_dir_fd if dirfd_relative else None)) + except OSError: # pragma: no cover - transient NFS scandir hiccup + return + for name, fd in names: + _break_stale_marker(name, stale_threshold=self.stale_threshold, now=now, dir_fd=fd) + + def _refresh_marker(self) -> bool: + with self._locks.internal: + hold = self._hold + if hold is None: # pragma: no cover - race between stop_event.set and join + return False + marker_name = hold.marker_name + token = hold.token + dir_fd = self._readers_dir_fd if hold.is_reader else None + + read_result = _read_marker(marker_name, dir_fd=dir_fd) + if read_result is None: + return False + info, _mtime = read_result + # Token mismatch means another process already evicted our marker and created its own; stop the + # thread so it does not touch a stranger's file. + if info is None or not hmac.compare_digest(info.token, token): + return False + try: + _touch(marker_name, dir_fd=dir_fd) + except FileNotFoundError: # pragma: no cover - race between successful read and touch + return False + return True + + def _reset_after_fork_in_child(self) -> None: # pragma: no cover - fork child not tracked + # Replace every lock this instance owns with a fresh one; the inherited locks may still be held + # by threads that no longer exist in the child. The readers dirfd and the SoftFileLock state + # mutex both get dropped for the same reason — the child re-creates them on its next acquire. + self._locks = _Locks( + internal=threading.Lock(), + transaction=threading.Lock(), + state=SoftFileLock(self._paths.state, timeout=-1), + ) + self._hold = None + self._readers_dir_fd = None + self._fork_invalidated = True + + +class _HeartbeatThread(threading.Thread): + def __init__( + self, + refresh: Callable[[], bool], + interval: float, + stop_event: threading.Event, + name: str, + ) -> None: + super().__init__(name=name, daemon=True) + self._refresh = refresh + self._interval = interval + self._stop_event = stop_event + + def run(self) -> None: + while not self._stop_event.wait(self._interval): + if not self._refresh(): + self._stop_event.set() + return + + +def _atomic_create_marker(name: str, token: str, *, dir_fd: int | None = None) -> None: + # O_NOFOLLOW blocks the symlink-overwrite attack where an attacker pre-creates the marker path as a + # symlink pointing at a victim file. Mode 0o600 keeps the token unreadable to other users. + flags = os.O_CREAT | os.O_EXCL | os.O_WRONLY | _O_NOFOLLOW + if _SUPPORTS_DIR_FD and dir_fd is not None: + fd = os.open(name, flags, 0o600, dir_fd=dir_fd) + else: + fd = os.open(name, flags, 0o600) + try: + content = f"{token}\n{os.getpid()}\n{socket.gethostname()}\n".encode("ascii") + os.write(fd, content) + finally: + os.close(fd) + + +def _read_marker(name: str, *, dir_fd: int | None = None) -> tuple[_MarkerInfo | None, float] | None: + # O_NOFOLLOW is defense in depth: we already created this file, but a hostile replacement by symlink + # between create and read would be caught here. + flags = os.O_RDONLY | _O_NOFOLLOW + try: + fd = os.open(name, flags, dir_fd=dir_fd) if _SUPPORTS_DIR_FD and dir_fd is not None else os.open(name, flags) + except OSError: + return None + try: + try: + st = os.fstat(fd) + data = os.read(fd, _MAX_MARKER_SIZE + 1) + except OSError: # pragma: no cover - fstat/read after a successful open is hard to provoke + return None + finally: + os.close(fd) + return _parse_marker_bytes(data), st.st_mtime + + +def _parse_marker_bytes(data: bytes) -> _MarkerInfo | None: + # Trust nothing about attacker-controlled markers; any deviation returns None so callers fall through + # to stale cleanup. ``re.match`` caches compiled patterns internally, so the regex is built only once + # despite being defined inline. + if not data or len(data) > _MAX_MARKER_SIZE: + return None + try: + text = data.decode("ascii") + except UnicodeDecodeError: + return None + match = re.match( + r""" + \A # start of string + (?P [0-9a-f]{32} ) \n # 128-bit hex token + (?P [1-9][0-9]{0,9} ) \n # decimal pid: no leading zero, ≤ 10 digits + (?P [\x21-\x7e]{1,253}) # printable non-whitespace ASCII (RFC 1123 hostname limit) + \n* # tolerate sloppy writers that append extra newlines + \Z # end of string + """, + text, + re.VERBOSE, + ) + if match is None: + return None + pid = int(match["pid"], 10) + if pid > 2**31 - 1: + return None + return _MarkerInfo(token=match["token"], pid=pid, hostname=match["hostname"]) + + +def _break_stale_marker( # noqa: PLR0911 + name: str, + *, + stale_threshold: float, + now: float, + dir_fd: int | None = None, +) -> bool: + # Atomic break pattern: read → rename to unique break-name → re-verify → unlink. The rename gives us a + # private name nobody else can touch; if the re-verify sees a newer mtime or a different token, the + # legitimate holder's heartbeat fired between read and rename and we must abort (leaving the .break.* + # file behind rather than rollback-renaming, because rollback is itself racy). + read_result = _read_marker(name, dir_fd=dir_fd) + if read_result is None: + return False + info_before, mtime_before = read_result + if now - mtime_before <= stale_threshold: + return False + if info_before is None: + _unlink(name, dir_fd=dir_fd) + return True + + break_name = f"{name}{_BREAK_SUFFIX}.{os.getpid()}.{secrets.token_hex(16)}" + try: + if _SUPPORTS_DIR_FD and dir_fd is not None: + os.rename(name, break_name, src_dir_fd=dir_fd, dst_dir_fd=dir_fd) + else: + Path(name).rename(break_name) + except OSError: # pragma: no cover - race where the marker vanishes between read and rename + return False + + read_after = _read_marker(break_name, dir_fd=dir_fd) + if read_after is None: # pragma: no cover - race where a peer unlinks the break-name file + return False + info_after, mtime_after = read_after + if info_after is None: # pragma: no cover - content replaced post-rename by a racing peer + _unlink(break_name, dir_fd=dir_fd) + return True + if not hmac.compare_digest(info_before.token, info_after.token): # pragma: no cover - race only + return False + if mtime_after > mtime_before: # pragma: no cover - heartbeat raced our rename + return False + _unlink(break_name, dir_fd=dir_fd) + return True + + +def _unlink(name: str, *, dir_fd: int | None = None) -> None: + with suppress(FileNotFoundError): + if _SUPPORTS_DIR_FD and dir_fd is not None: + # Path.unlink has no dir_fd support, so we stay on os.unlink for the dirfd path. + os.unlink(name, dir_fd=dir_fd) + else: + Path(name).unlink() + + +def _touch(name: str, *, dir_fd: int | None = None) -> None: + if _SUPPORTS_DIR_FD and dir_fd is not None: + os.utime(name, None, dir_fd=dir_fd) + else: + os.utime(name, None) + + +def _file_exists(path: str) -> bool: + try: + st = os.lstat(path) + except FileNotFoundError: + return False + return stat.S_ISREG(st.st_mode) + + +def _is_housekeeping_name(name: str) -> bool: + return name.startswith(".") or _BREAK_SUFFIX in name + + +def _reset_all_after_fork() -> None: # pragma: no cover - fork child, not tracked by coverage + global _all_instances_lock # noqa: PLW0603 + # User-created threading locks do not auto-reset across fork: any lock held by a parent thread stays + # locked in the child with no owner to release it. Replace the module-level lock and every instance's + # locks with fresh ones; the child is single-threaded at this point so no synchronization is needed. + _all_instances_lock = threading.Lock() + for instance in list(_all_instances.values()): + instance._reset_after_fork_in_child() # noqa: SLF001 + + +def _cleanup_all_instances() -> None: # pragma: no cover - runs from atexit at interpreter shutdown + for instance in list(_all_instances.values()): + with suppress(Exception): + instance.release(force=True) + + +def _register_hooks() -> None: + global _atexit_registered, _fork_registered # noqa: PLW0603 + if not _atexit_registered: + atexit.register(_cleanup_all_instances) + _atexit_registered = True + # after_in_child replaces inherited state so the child cannot double-own any lock the parent held. + if not _fork_registered and hasattr(os, "register_at_fork"): + os.register_at_fork(after_in_child=_reset_all_after_fork) + _fork_registered = True + + +__all__ = [ + "SoftReadWriteLock", +] diff --git a/python/user_packages/Python313/site-packages/flask-3.1.3.dist-info/licenses/LICENSE.txt b/python/user_packages/Python313/site-packages/flask-3.1.3.dist-info/licenses/LICENSE.txt new file mode 100644 index 0000000000000000000000000000000000000000..9d227a0cc43c3268d15722b763bd94ad298645a1 --- /dev/null +++ b/python/user_packages/Python313/site-packages/flask-3.1.3.dist-info/licenses/LICENSE.txt @@ -0,0 +1,28 @@ +Copyright 2010 Pallets + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: + +1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + +2. 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. + +3. Neither the name of the copyright holder 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. diff --git a/python/user_packages/Python313/site-packages/flask/__pycache__/__init__.cpython-313.pyc b/python/user_packages/Python313/site-packages/flask/__pycache__/__init__.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..fc42ef0c81c6a4dae33295e94d7151b6652d4ed4 Binary files /dev/null and b/python/user_packages/Python313/site-packages/flask/__pycache__/__init__.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/flask/__pycache__/__main__.cpython-313.pyc b/python/user_packages/Python313/site-packages/flask/__pycache__/__main__.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2e8bbcff7dd2395b5919d22086d6dabb745cdd15 Binary files /dev/null and b/python/user_packages/Python313/site-packages/flask/__pycache__/__main__.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/flask/__pycache__/app.cpython-313.pyc b/python/user_packages/Python313/site-packages/flask/__pycache__/app.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5ae8b09236d4baadd70f3bbae078391042cffd26 Binary files /dev/null and b/python/user_packages/Python313/site-packages/flask/__pycache__/app.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/flask/__pycache__/blueprints.cpython-313.pyc b/python/user_packages/Python313/site-packages/flask/__pycache__/blueprints.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c44a17a39eb2a588b2a27fdd984a275df6c5e734 Binary files /dev/null and b/python/user_packages/Python313/site-packages/flask/__pycache__/blueprints.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/flask/__pycache__/cli.cpython-313.pyc b/python/user_packages/Python313/site-packages/flask/__pycache__/cli.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..373f36223b3edd648bb3888ca2ba1e1d97c055cf Binary files /dev/null and b/python/user_packages/Python313/site-packages/flask/__pycache__/cli.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/flask/__pycache__/config.cpython-313.pyc b/python/user_packages/Python313/site-packages/flask/__pycache__/config.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..00de856ed93567353f7433293b81889926cb1762 Binary files /dev/null and b/python/user_packages/Python313/site-packages/flask/__pycache__/config.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/flask/__pycache__/ctx.cpython-313.pyc b/python/user_packages/Python313/site-packages/flask/__pycache__/ctx.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b3bd865beac2ad0628b4158f4f6ef2da0ffd4313 Binary files /dev/null and b/python/user_packages/Python313/site-packages/flask/__pycache__/ctx.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/flask/__pycache__/debughelpers.cpython-313.pyc b/python/user_packages/Python313/site-packages/flask/__pycache__/debughelpers.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..57c3a81d593f1b512d2edd7b41e19563d1ee8184 Binary files /dev/null and b/python/user_packages/Python313/site-packages/flask/__pycache__/debughelpers.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/flask/__pycache__/globals.cpython-313.pyc b/python/user_packages/Python313/site-packages/flask/__pycache__/globals.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..07d1b9a758e0cf69f926a8b4268a3869f6a86a17 Binary files /dev/null and b/python/user_packages/Python313/site-packages/flask/__pycache__/globals.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/flask/__pycache__/helpers.cpython-313.pyc b/python/user_packages/Python313/site-packages/flask/__pycache__/helpers.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7f386f4077f2a800d0bd40b51bb60463833d1167 Binary files /dev/null and b/python/user_packages/Python313/site-packages/flask/__pycache__/helpers.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/flask/__pycache__/logging.cpython-313.pyc b/python/user_packages/Python313/site-packages/flask/__pycache__/logging.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4200201d409d406bb0f0d9c5a74427dd37ba2c68 Binary files /dev/null and b/python/user_packages/Python313/site-packages/flask/__pycache__/logging.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/flask/__pycache__/sessions.cpython-313.pyc b/python/user_packages/Python313/site-packages/flask/__pycache__/sessions.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9eb2f572d53a11583268934661cad735c2502385 Binary files /dev/null and b/python/user_packages/Python313/site-packages/flask/__pycache__/sessions.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/flask/__pycache__/signals.cpython-313.pyc b/python/user_packages/Python313/site-packages/flask/__pycache__/signals.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2b2d3c0293036c4d3990f36261a104e36f66e035 Binary files /dev/null and b/python/user_packages/Python313/site-packages/flask/__pycache__/signals.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/flask/__pycache__/templating.cpython-313.pyc b/python/user_packages/Python313/site-packages/flask/__pycache__/templating.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f5da14c1ba59f1cb87690b6e4b50fbb8fe89b133 Binary files /dev/null and b/python/user_packages/Python313/site-packages/flask/__pycache__/templating.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/flask/__pycache__/testing.cpython-313.pyc b/python/user_packages/Python313/site-packages/flask/__pycache__/testing.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..526c239e4c125d431aad6c0bc7d5bd20cadf6a23 Binary files /dev/null and b/python/user_packages/Python313/site-packages/flask/__pycache__/testing.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/flask/__pycache__/typing.cpython-313.pyc b/python/user_packages/Python313/site-packages/flask/__pycache__/typing.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8dfa0bf7b5575a37158ec7b13763c0c5bef6c49c Binary files /dev/null and b/python/user_packages/Python313/site-packages/flask/__pycache__/typing.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/flask/__pycache__/views.cpython-313.pyc b/python/user_packages/Python313/site-packages/flask/__pycache__/views.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7d25432500ced293e64a679da230db8fbe072c41 Binary files /dev/null and b/python/user_packages/Python313/site-packages/flask/__pycache__/views.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/flask/__pycache__/wrappers.cpython-313.pyc b/python/user_packages/Python313/site-packages/flask/__pycache__/wrappers.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b79f80de8e354df7a00361f0c5f380bcf9855f77 Binary files /dev/null and b/python/user_packages/Python313/site-packages/flask/__pycache__/wrappers.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/flask/json/__init__.py b/python/user_packages/Python313/site-packages/flask/json/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..c0941d049e7268345acde34667019550dadba0b8 --- /dev/null +++ b/python/user_packages/Python313/site-packages/flask/json/__init__.py @@ -0,0 +1,170 @@ +from __future__ import annotations + +import json as _json +import typing as t + +from ..globals import current_app +from .provider import _default + +if t.TYPE_CHECKING: # pragma: no cover + from ..wrappers import Response + + +def dumps(obj: t.Any, **kwargs: t.Any) -> str: + """Serialize data as JSON. + + If :data:`~flask.current_app` is available, it will use its + :meth:`app.json.dumps() ` + method, otherwise it will use :func:`json.dumps`. + + :param obj: The data to serialize. + :param kwargs: Arguments passed to the ``dumps`` implementation. + + .. versionchanged:: 2.3 + The ``app`` parameter was removed. + + .. versionchanged:: 2.2 + Calls ``current_app.json.dumps``, allowing an app to override + the behavior. + + .. versionchanged:: 2.0.2 + :class:`decimal.Decimal` is supported by converting to a string. + + .. versionchanged:: 2.0 + ``encoding`` will be removed in Flask 2.1. + + .. versionchanged:: 1.0.3 + ``app`` can be passed directly, rather than requiring an app + context for configuration. + """ + if current_app: + return current_app.json.dumps(obj, **kwargs) + + kwargs.setdefault("default", _default) + return _json.dumps(obj, **kwargs) + + +def dump(obj: t.Any, fp: t.IO[str], **kwargs: t.Any) -> None: + """Serialize data as JSON and write to a file. + + If :data:`~flask.current_app` is available, it will use its + :meth:`app.json.dump() ` + method, otherwise it will use :func:`json.dump`. + + :param obj: The data to serialize. + :param fp: A file opened for writing text. Should use the UTF-8 + encoding to be valid JSON. + :param kwargs: Arguments passed to the ``dump`` implementation. + + .. versionchanged:: 2.3 + The ``app`` parameter was removed. + + .. versionchanged:: 2.2 + Calls ``current_app.json.dump``, allowing an app to override + the behavior. + + .. versionchanged:: 2.0 + Writing to a binary file, and the ``encoding`` argument, will be + removed in Flask 2.1. + """ + if current_app: + current_app.json.dump(obj, fp, **kwargs) + else: + kwargs.setdefault("default", _default) + _json.dump(obj, fp, **kwargs) + + +def loads(s: str | bytes, **kwargs: t.Any) -> t.Any: + """Deserialize data as JSON. + + If :data:`~flask.current_app` is available, it will use its + :meth:`app.json.loads() ` + method, otherwise it will use :func:`json.loads`. + + :param s: Text or UTF-8 bytes. + :param kwargs: Arguments passed to the ``loads`` implementation. + + .. versionchanged:: 2.3 + The ``app`` parameter was removed. + + .. versionchanged:: 2.2 + Calls ``current_app.json.loads``, allowing an app to override + the behavior. + + .. versionchanged:: 2.0 + ``encoding`` will be removed in Flask 2.1. The data must be a + string or UTF-8 bytes. + + .. versionchanged:: 1.0.3 + ``app`` can be passed directly, rather than requiring an app + context for configuration. + """ + if current_app: + return current_app.json.loads(s, **kwargs) + + return _json.loads(s, **kwargs) + + +def load(fp: t.IO[t.AnyStr], **kwargs: t.Any) -> t.Any: + """Deserialize data as JSON read from a file. + + If :data:`~flask.current_app` is available, it will use its + :meth:`app.json.load() ` + method, otherwise it will use :func:`json.load`. + + :param fp: A file opened for reading text or UTF-8 bytes. + :param kwargs: Arguments passed to the ``load`` implementation. + + .. versionchanged:: 2.3 + The ``app`` parameter was removed. + + .. versionchanged:: 2.2 + Calls ``current_app.json.load``, allowing an app to override + the behavior. + + .. versionchanged:: 2.2 + The ``app`` parameter will be removed in Flask 2.3. + + .. versionchanged:: 2.0 + ``encoding`` will be removed in Flask 2.1. The file must be text + mode, or binary mode with UTF-8 bytes. + """ + if current_app: + return current_app.json.load(fp, **kwargs) + + return _json.load(fp, **kwargs) + + +def jsonify(*args: t.Any, **kwargs: t.Any) -> Response: + """Serialize the given arguments as JSON, and return a + :class:`~flask.Response` object with the ``application/json`` + mimetype. A dict or list returned from a view will be converted to a + JSON response automatically without needing to call this. + + This requires an active request or application context, and calls + :meth:`app.json.response() `. + + In debug mode, the output is formatted with indentation to make it + easier to read. This may also be controlled by the provider. + + Either positional or keyword arguments can be given, not both. + If no arguments are given, ``None`` is serialized. + + :param args: A single value to serialize, or multiple values to + treat as a list to serialize. + :param kwargs: Treat as a dict to serialize. + + .. versionchanged:: 2.2 + Calls ``current_app.json.response``, allowing an app to override + the behavior. + + .. versionchanged:: 2.0.2 + :class:`decimal.Decimal` is supported by converting to a string. + + .. versionchanged:: 0.11 + Added support for serializing top-level arrays. This was a + security risk in ancient browsers. See :ref:`security-json`. + + .. versionadded:: 0.2 + """ + return current_app.json.response(*args, **kwargs) # type: ignore[return-value] diff --git a/python/user_packages/Python313/site-packages/flask/json/__pycache__/__init__.cpython-313.pyc b/python/user_packages/Python313/site-packages/flask/json/__pycache__/__init__.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a3e0e1474d699e23900caeea364833df1230c278 Binary files /dev/null and b/python/user_packages/Python313/site-packages/flask/json/__pycache__/__init__.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/flask/json/__pycache__/provider.cpython-313.pyc b/python/user_packages/Python313/site-packages/flask/json/__pycache__/provider.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7ce1b7157cd9156b54ffe453004a88d03679af6f Binary files /dev/null and b/python/user_packages/Python313/site-packages/flask/json/__pycache__/provider.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/flask/json/__pycache__/tag.cpython-313.pyc b/python/user_packages/Python313/site-packages/flask/json/__pycache__/tag.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..fce8c67582d7123c9f6512743319c834ae69aecf Binary files /dev/null and b/python/user_packages/Python313/site-packages/flask/json/__pycache__/tag.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/flask/json/provider.py b/python/user_packages/Python313/site-packages/flask/json/provider.py new file mode 100644 index 0000000000000000000000000000000000000000..ea7e4753ffb65255ae48efa481b4d5362e476a01 --- /dev/null +++ b/python/user_packages/Python313/site-packages/flask/json/provider.py @@ -0,0 +1,215 @@ +from __future__ import annotations + +import dataclasses +import decimal +import json +import typing as t +import uuid +import weakref +from datetime import date + +from werkzeug.http import http_date + +if t.TYPE_CHECKING: # pragma: no cover + from werkzeug.sansio.response import Response + + from ..sansio.app import App + + +class JSONProvider: + """A standard set of JSON operations for an application. Subclasses + of this can be used to customize JSON behavior or use different + JSON libraries. + + To implement a provider for a specific library, subclass this base + class and implement at least :meth:`dumps` and :meth:`loads`. All + other methods have default implementations. + + To use a different provider, either subclass ``Flask`` and set + :attr:`~flask.Flask.json_provider_class` to a provider class, or set + :attr:`app.json ` to an instance of the class. + + :param app: An application instance. This will be stored as a + :class:`weakref.proxy` on the :attr:`_app` attribute. + + .. versionadded:: 2.2 + """ + + def __init__(self, app: App) -> None: + self._app: App = weakref.proxy(app) + + def dumps(self, obj: t.Any, **kwargs: t.Any) -> str: + """Serialize data as JSON. + + :param obj: The data to serialize. + :param kwargs: May be passed to the underlying JSON library. + """ + raise NotImplementedError + + def dump(self, obj: t.Any, fp: t.IO[str], **kwargs: t.Any) -> None: + """Serialize data as JSON and write to a file. + + :param obj: The data to serialize. + :param fp: A file opened for writing text. Should use the UTF-8 + encoding to be valid JSON. + :param kwargs: May be passed to the underlying JSON library. + """ + fp.write(self.dumps(obj, **kwargs)) + + def loads(self, s: str | bytes, **kwargs: t.Any) -> t.Any: + """Deserialize data as JSON. + + :param s: Text or UTF-8 bytes. + :param kwargs: May be passed to the underlying JSON library. + """ + raise NotImplementedError + + def load(self, fp: t.IO[t.AnyStr], **kwargs: t.Any) -> t.Any: + """Deserialize data as JSON read from a file. + + :param fp: A file opened for reading text or UTF-8 bytes. + :param kwargs: May be passed to the underlying JSON library. + """ + return self.loads(fp.read(), **kwargs) + + def _prepare_response_obj( + self, args: tuple[t.Any, ...], kwargs: dict[str, t.Any] + ) -> t.Any: + if args and kwargs: + raise TypeError("app.json.response() takes either args or kwargs, not both") + + if not args and not kwargs: + return None + + if len(args) == 1: + return args[0] + + return args or kwargs + + def response(self, *args: t.Any, **kwargs: t.Any) -> Response: + """Serialize the given arguments as JSON, and return a + :class:`~flask.Response` object with the ``application/json`` + mimetype. + + The :func:`~flask.json.jsonify` function calls this method for + the current application. + + Either positional or keyword arguments can be given, not both. + If no arguments are given, ``None`` is serialized. + + :param args: A single value to serialize, or multiple values to + treat as a list to serialize. + :param kwargs: Treat as a dict to serialize. + """ + obj = self._prepare_response_obj(args, kwargs) + return self._app.response_class(self.dumps(obj), mimetype="application/json") + + +def _default(o: t.Any) -> t.Any: + if isinstance(o, date): + return http_date(o) + + if isinstance(o, (decimal.Decimal, uuid.UUID)): + return str(o) + + if dataclasses and dataclasses.is_dataclass(o): + return dataclasses.asdict(o) # type: ignore[arg-type] + + if hasattr(o, "__html__"): + return str(o.__html__()) + + raise TypeError(f"Object of type {type(o).__name__} is not JSON serializable") + + +class DefaultJSONProvider(JSONProvider): + """Provide JSON operations using Python's built-in :mod:`json` + library. Serializes the following additional data types: + + - :class:`datetime.datetime` and :class:`datetime.date` are + serialized to :rfc:`822` strings. This is the same as the HTTP + date format. + - :class:`uuid.UUID` is serialized to a string. + - :class:`dataclasses.dataclass` is passed to + :func:`dataclasses.asdict`. + - :class:`~markupsafe.Markup` (or any object with a ``__html__`` + method) will call the ``__html__`` method to get a string. + """ + + default: t.Callable[[t.Any], t.Any] = staticmethod(_default) # type: ignore[assignment] + """Apply this function to any object that :meth:`json.dumps` does + not know how to serialize. It should return a valid JSON type or + raise a ``TypeError``. + """ + + ensure_ascii = True + """Replace non-ASCII characters with escape sequences. This may be + more compatible with some clients, but can be disabled for better + performance and size. + """ + + sort_keys = True + """Sort the keys in any serialized dicts. This may be useful for + some caching situations, but can be disabled for better performance. + When enabled, keys must all be strings, they are not converted + before sorting. + """ + + compact: bool | None = None + """If ``True``, or ``None`` out of debug mode, the :meth:`response` + output will not add indentation, newlines, or spaces. If ``False``, + or ``None`` in debug mode, it will use a non-compact representation. + """ + + mimetype = "application/json" + """The mimetype set in :meth:`response`.""" + + def dumps(self, obj: t.Any, **kwargs: t.Any) -> str: + """Serialize data as JSON to a string. + + Keyword arguments are passed to :func:`json.dumps`. Sets some + parameter defaults from the :attr:`default`, + :attr:`ensure_ascii`, and :attr:`sort_keys` attributes. + + :param obj: The data to serialize. + :param kwargs: Passed to :func:`json.dumps`. + """ + kwargs.setdefault("default", self.default) + kwargs.setdefault("ensure_ascii", self.ensure_ascii) + kwargs.setdefault("sort_keys", self.sort_keys) + return json.dumps(obj, **kwargs) + + def loads(self, s: str | bytes, **kwargs: t.Any) -> t.Any: + """Deserialize data as JSON from a string or bytes. + + :param s: Text or UTF-8 bytes. + :param kwargs: Passed to :func:`json.loads`. + """ + return json.loads(s, **kwargs) + + def response(self, *args: t.Any, **kwargs: t.Any) -> Response: + """Serialize the given arguments as JSON, and return a + :class:`~flask.Response` object with it. The response mimetype + will be "application/json" and can be changed with + :attr:`mimetype`. + + If :attr:`compact` is ``False`` or debug mode is enabled, the + output will be formatted to be easier to read. + + Either positional or keyword arguments can be given, not both. + If no arguments are given, ``None`` is serialized. + + :param args: A single value to serialize, or multiple values to + treat as a list to serialize. + :param kwargs: Treat as a dict to serialize. + """ + obj = self._prepare_response_obj(args, kwargs) + dump_args: dict[str, t.Any] = {} + + if (self.compact is None and self._app.debug) or self.compact is False: + dump_args.setdefault("indent", 2) + else: + dump_args.setdefault("separators", (",", ":")) + + return self._app.response_class( + f"{self.dumps(obj, **dump_args)}\n", mimetype=self.mimetype + ) diff --git a/python/user_packages/Python313/site-packages/flask/json/tag.py b/python/user_packages/Python313/site-packages/flask/json/tag.py new file mode 100644 index 0000000000000000000000000000000000000000..8dc3629bf9e5e4788e3ef69e528dfd72675cc0c6 --- /dev/null +++ b/python/user_packages/Python313/site-packages/flask/json/tag.py @@ -0,0 +1,327 @@ +""" +Tagged JSON +~~~~~~~~~~~ + +A compact representation for lossless serialization of non-standard JSON +types. :class:`~flask.sessions.SecureCookieSessionInterface` uses this +to serialize the session data, but it may be useful in other places. It +can be extended to support other types. + +.. autoclass:: TaggedJSONSerializer + :members: + +.. autoclass:: JSONTag + :members: + +Let's see an example that adds support for +:class:`~collections.OrderedDict`. Dicts don't have an order in JSON, so +to handle this we will dump the items as a list of ``[key, value]`` +pairs. Subclass :class:`JSONTag` and give it the new key ``' od'`` to +identify the type. The session serializer processes dicts first, so +insert the new tag at the front of the order since ``OrderedDict`` must +be processed before ``dict``. + +.. code-block:: python + + from flask.json.tag import JSONTag + + class TagOrderedDict(JSONTag): + __slots__ = ('serializer',) + key = ' od' + + def check(self, value): + return isinstance(value, OrderedDict) + + def to_json(self, value): + return [[k, self.serializer.tag(v)] for k, v in iteritems(value)] + + def to_python(self, value): + return OrderedDict(value) + + app.session_interface.serializer.register(TagOrderedDict, index=0) +""" + +from __future__ import annotations + +import typing as t +from base64 import b64decode +from base64 import b64encode +from datetime import datetime +from uuid import UUID + +from markupsafe import Markup +from werkzeug.http import http_date +from werkzeug.http import parse_date + +from ..json import dumps +from ..json import loads + + +class JSONTag: + """Base class for defining type tags for :class:`TaggedJSONSerializer`.""" + + __slots__ = ("serializer",) + + #: The tag to mark the serialized object with. If empty, this tag is + #: only used as an intermediate step during tagging. + key: str = "" + + def __init__(self, serializer: TaggedJSONSerializer) -> None: + """Create a tagger for the given serializer.""" + self.serializer = serializer + + def check(self, value: t.Any) -> bool: + """Check if the given value should be tagged by this tag.""" + raise NotImplementedError + + def to_json(self, value: t.Any) -> t.Any: + """Convert the Python object to an object that is a valid JSON type. + The tag will be added later.""" + raise NotImplementedError + + def to_python(self, value: t.Any) -> t.Any: + """Convert the JSON representation back to the correct type. The tag + will already be removed.""" + raise NotImplementedError + + def tag(self, value: t.Any) -> dict[str, t.Any]: + """Convert the value to a valid JSON type and add the tag structure + around it.""" + return {self.key: self.to_json(value)} + + +class TagDict(JSONTag): + """Tag for 1-item dicts whose only key matches a registered tag. + + Internally, the dict key is suffixed with `__`, and the suffix is removed + when deserializing. + """ + + __slots__ = () + key = " di" + + def check(self, value: t.Any) -> bool: + return ( + isinstance(value, dict) + and len(value) == 1 + and next(iter(value)) in self.serializer.tags + ) + + def to_json(self, value: t.Any) -> t.Any: + key = next(iter(value)) + return {f"{key}__": self.serializer.tag(value[key])} + + def to_python(self, value: t.Any) -> t.Any: + key = next(iter(value)) + return {key[:-2]: value[key]} + + +class PassDict(JSONTag): + __slots__ = () + + def check(self, value: t.Any) -> bool: + return isinstance(value, dict) + + def to_json(self, value: t.Any) -> t.Any: + # JSON objects may only have string keys, so don't bother tagging the + # key here. + return {k: self.serializer.tag(v) for k, v in value.items()} + + tag = to_json + + +class TagTuple(JSONTag): + __slots__ = () + key = " t" + + def check(self, value: t.Any) -> bool: + return isinstance(value, tuple) + + def to_json(self, value: t.Any) -> t.Any: + return [self.serializer.tag(item) for item in value] + + def to_python(self, value: t.Any) -> t.Any: + return tuple(value) + + +class PassList(JSONTag): + __slots__ = () + + def check(self, value: t.Any) -> bool: + return isinstance(value, list) + + def to_json(self, value: t.Any) -> t.Any: + return [self.serializer.tag(item) for item in value] + + tag = to_json + + +class TagBytes(JSONTag): + __slots__ = () + key = " b" + + def check(self, value: t.Any) -> bool: + return isinstance(value, bytes) + + def to_json(self, value: t.Any) -> t.Any: + return b64encode(value).decode("ascii") + + def to_python(self, value: t.Any) -> t.Any: + return b64decode(value) + + +class TagMarkup(JSONTag): + """Serialize anything matching the :class:`~markupsafe.Markup` API by + having a ``__html__`` method to the result of that method. Always + deserializes to an instance of :class:`~markupsafe.Markup`.""" + + __slots__ = () + key = " m" + + def check(self, value: t.Any) -> bool: + return callable(getattr(value, "__html__", None)) + + def to_json(self, value: t.Any) -> t.Any: + return str(value.__html__()) + + def to_python(self, value: t.Any) -> t.Any: + return Markup(value) + + +class TagUUID(JSONTag): + __slots__ = () + key = " u" + + def check(self, value: t.Any) -> bool: + return isinstance(value, UUID) + + def to_json(self, value: t.Any) -> t.Any: + return value.hex + + def to_python(self, value: t.Any) -> t.Any: + return UUID(value) + + +class TagDateTime(JSONTag): + __slots__ = () + key = " d" + + def check(self, value: t.Any) -> bool: + return isinstance(value, datetime) + + def to_json(self, value: t.Any) -> t.Any: + return http_date(value) + + def to_python(self, value: t.Any) -> t.Any: + return parse_date(value) + + +class TaggedJSONSerializer: + """Serializer that uses a tag system to compactly represent objects that + are not JSON types. Passed as the intermediate serializer to + :class:`itsdangerous.Serializer`. + + The following extra types are supported: + + * :class:`dict` + * :class:`tuple` + * :class:`bytes` + * :class:`~markupsafe.Markup` + * :class:`~uuid.UUID` + * :class:`~datetime.datetime` + """ + + __slots__ = ("tags", "order") + + #: Tag classes to bind when creating the serializer. Other tags can be + #: added later using :meth:`~register`. + default_tags = [ + TagDict, + PassDict, + TagTuple, + PassList, + TagBytes, + TagMarkup, + TagUUID, + TagDateTime, + ] + + def __init__(self) -> None: + self.tags: dict[str, JSONTag] = {} + self.order: list[JSONTag] = [] + + for cls in self.default_tags: + self.register(cls) + + def register( + self, + tag_class: type[JSONTag], + force: bool = False, + index: int | None = None, + ) -> None: + """Register a new tag with this serializer. + + :param tag_class: tag class to register. Will be instantiated with this + serializer instance. + :param force: overwrite an existing tag. If false (default), a + :exc:`KeyError` is raised. + :param index: index to insert the new tag in the tag order. Useful when + the new tag is a special case of an existing tag. If ``None`` + (default), the tag is appended to the end of the order. + + :raise KeyError: if the tag key is already registered and ``force`` is + not true. + """ + tag = tag_class(self) + key = tag.key + + if key: + if not force and key in self.tags: + raise KeyError(f"Tag '{key}' is already registered.") + + self.tags[key] = tag + + if index is None: + self.order.append(tag) + else: + self.order.insert(index, tag) + + def tag(self, value: t.Any) -> t.Any: + """Convert a value to a tagged representation if necessary.""" + for tag in self.order: + if tag.check(value): + return tag.tag(value) + + return value + + def untag(self, value: dict[str, t.Any]) -> t.Any: + """Convert a tagged representation back to the original type.""" + if len(value) != 1: + return value + + key = next(iter(value)) + + if key not in self.tags: + return value + + return self.tags[key].to_python(value[key]) + + def _untag_scan(self, value: t.Any) -> t.Any: + if isinstance(value, dict): + # untag each item recursively + value = {k: self._untag_scan(v) for k, v in value.items()} + # untag the dict itself + value = self.untag(value) + elif isinstance(value, list): + # untag each item recursively + value = [self._untag_scan(item) for item in value] + + return value + + def dumps(self, value: t.Any) -> str: + """Tag the value and dump it to a compact JSON string.""" + return dumps(self.tag(value), separators=(",", ":")) + + def loads(self, value: str) -> t.Any: + """Load data from a JSON string and deserialized any tagged objects.""" + return self._untag_scan(loads(value)) diff --git a/python/user_packages/Python313/site-packages/flask/sansio/README.md b/python/user_packages/Python313/site-packages/flask/sansio/README.md new file mode 100644 index 0000000000000000000000000000000000000000..623ac1982366d862db0a9d950fa2f50dd334d32f --- /dev/null +++ b/python/user_packages/Python313/site-packages/flask/sansio/README.md @@ -0,0 +1,6 @@ +# Sansio + +This folder contains code that can be used by alternative Flask +implementations, for example Quart. The code therefore cannot do any +IO, nor be part of a likely IO path. Finally this code cannot use the +Flask globals. diff --git a/python/user_packages/Python313/site-packages/flask/sansio/__pycache__/app.cpython-313.pyc b/python/user_packages/Python313/site-packages/flask/sansio/__pycache__/app.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e038a4eaa0c281a9f99b2a42fb9e7174b7069cca Binary files /dev/null and b/python/user_packages/Python313/site-packages/flask/sansio/__pycache__/app.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/flask/sansio/__pycache__/blueprints.cpython-313.pyc b/python/user_packages/Python313/site-packages/flask/sansio/__pycache__/blueprints.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9366a5ddf68f81ac0a6572787f502340394b57f6 Binary files /dev/null and b/python/user_packages/Python313/site-packages/flask/sansio/__pycache__/blueprints.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/flask/sansio/__pycache__/scaffold.cpython-313.pyc b/python/user_packages/Python313/site-packages/flask/sansio/__pycache__/scaffold.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1fc2d93b37c54623c4c0b8429aa74ab162c6b53b Binary files /dev/null and b/python/user_packages/Python313/site-packages/flask/sansio/__pycache__/scaffold.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/flask/sansio/app.py b/python/user_packages/Python313/site-packages/flask/sansio/app.py new file mode 100644 index 0000000000000000000000000000000000000000..58cb87306293c40ad3f6f4082ec7beb74e3885d1 --- /dev/null +++ b/python/user_packages/Python313/site-packages/flask/sansio/app.py @@ -0,0 +1,964 @@ +from __future__ import annotations + +import logging +import os +import sys +import typing as t +from datetime import timedelta +from itertools import chain + +from werkzeug.exceptions import Aborter +from werkzeug.exceptions import BadRequest +from werkzeug.exceptions import BadRequestKeyError +from werkzeug.routing import BuildError +from werkzeug.routing import Map +from werkzeug.routing import Rule +from werkzeug.sansio.response import Response +from werkzeug.utils import cached_property +from werkzeug.utils import redirect as _wz_redirect + +from .. import typing as ft +from ..config import Config +from ..config import ConfigAttribute +from ..ctx import _AppCtxGlobals +from ..helpers import _split_blueprint_path +from ..helpers import get_debug_flag +from ..json.provider import DefaultJSONProvider +from ..json.provider import JSONProvider +from ..logging import create_logger +from ..templating import DispatchingJinjaLoader +from ..templating import Environment +from .scaffold import _endpoint_from_view_func +from .scaffold import find_package +from .scaffold import Scaffold +from .scaffold import setupmethod + +if t.TYPE_CHECKING: # pragma: no cover + from werkzeug.wrappers import Response as BaseResponse + + from ..testing import FlaskClient + from ..testing import FlaskCliRunner + from .blueprints import Blueprint + +T_shell_context_processor = t.TypeVar( + "T_shell_context_processor", bound=ft.ShellContextProcessorCallable +) +T_teardown = t.TypeVar("T_teardown", bound=ft.TeardownCallable) +T_template_filter = t.TypeVar("T_template_filter", bound=ft.TemplateFilterCallable) +T_template_global = t.TypeVar("T_template_global", bound=ft.TemplateGlobalCallable) +T_template_test = t.TypeVar("T_template_test", bound=ft.TemplateTestCallable) + + +def _make_timedelta(value: timedelta | int | None) -> timedelta | None: + if value is None or isinstance(value, timedelta): + return value + + return timedelta(seconds=value) + + +class App(Scaffold): + """The flask object implements a WSGI application and acts as the central + object. It is passed the name of the module or package of the + application. Once it is created it will act as a central registry for + the view functions, the URL rules, template configuration and much more. + + The name of the package is used to resolve resources from inside the + package or the folder the module is contained in depending on if the + package parameter resolves to an actual python package (a folder with + an :file:`__init__.py` file inside) or a standard module (just a ``.py`` file). + + For more information about resource loading, see :func:`open_resource`. + + Usually you create a :class:`Flask` instance in your main module or + in the :file:`__init__.py` file of your package like this:: + + from flask import Flask + app = Flask(__name__) + + .. admonition:: About the First Parameter + + The idea of the first parameter is to give Flask an idea of what + belongs to your application. This name is used to find resources + on the filesystem, can be used by extensions to improve debugging + information and a lot more. + + So it's important what you provide there. If you are using a single + module, `__name__` is always the correct value. If you however are + using a package, it's usually recommended to hardcode the name of + your package there. + + For example if your application is defined in :file:`yourapplication/app.py` + you should create it with one of the two versions below:: + + app = Flask('yourapplication') + app = Flask(__name__.split('.')[0]) + + Why is that? The application will work even with `__name__`, thanks + to how resources are looked up. However it will make debugging more + painful. Certain extensions can make assumptions based on the + import name of your application. For example the Flask-SQLAlchemy + extension will look for the code in your application that triggered + an SQL query in debug mode. If the import name is not properly set + up, that debugging information is lost. (For example it would only + pick up SQL queries in `yourapplication.app` and not + `yourapplication.views.frontend`) + + .. versionadded:: 0.7 + The `static_url_path`, `static_folder`, and `template_folder` + parameters were added. + + .. versionadded:: 0.8 + The `instance_path` and `instance_relative_config` parameters were + added. + + .. versionadded:: 0.11 + The `root_path` parameter was added. + + .. versionadded:: 1.0 + The ``host_matching`` and ``static_host`` parameters were added. + + .. versionadded:: 1.0 + The ``subdomain_matching`` parameter was added. Subdomain + matching needs to be enabled manually now. Setting + :data:`SERVER_NAME` does not implicitly enable it. + + :param import_name: the name of the application package + :param static_url_path: can be used to specify a different path for the + static files on the web. Defaults to the name + of the `static_folder` folder. + :param static_folder: The folder with static files that is served at + ``static_url_path``. Relative to the application ``root_path`` + or an absolute path. Defaults to ``'static'``. + :param static_host: the host to use when adding the static route. + Defaults to None. Required when using ``host_matching=True`` + with a ``static_folder`` configured. + :param host_matching: set ``url_map.host_matching`` attribute. + Defaults to False. + :param subdomain_matching: consider the subdomain relative to + :data:`SERVER_NAME` when matching routes. Defaults to False. + :param template_folder: the folder that contains the templates that should + be used by the application. Defaults to + ``'templates'`` folder in the root path of the + application. + :param instance_path: An alternative instance path for the application. + By default the folder ``'instance'`` next to the + package or module is assumed to be the instance + path. + :param instance_relative_config: if set to ``True`` relative filenames + for loading the config are assumed to + be relative to the instance path instead + of the application root. + :param root_path: The path to the root of the application files. + This should only be set manually when it can't be detected + automatically, such as for namespace packages. + """ + + #: The class of the object assigned to :attr:`aborter`, created by + #: :meth:`create_aborter`. That object is called by + #: :func:`flask.abort` to raise HTTP errors, and can be + #: called directly as well. + #: + #: Defaults to :class:`werkzeug.exceptions.Aborter`. + #: + #: .. versionadded:: 2.2 + aborter_class = Aborter + + #: The class that is used for the Jinja environment. + #: + #: .. versionadded:: 0.11 + jinja_environment = Environment + + #: The class that is used for the :data:`~flask.g` instance. + #: + #: Example use cases for a custom class: + #: + #: 1. Store arbitrary attributes on flask.g. + #: 2. Add a property for lazy per-request database connectors. + #: 3. Return None instead of AttributeError on unexpected attributes. + #: 4. Raise exception if an unexpected attr is set, a "controlled" flask.g. + #: + #: In Flask 0.9 this property was called `request_globals_class` but it + #: was changed in 0.10 to :attr:`app_ctx_globals_class` because the + #: flask.g object is now application context scoped. + #: + #: .. versionadded:: 0.10 + app_ctx_globals_class = _AppCtxGlobals + + #: The class that is used for the ``config`` attribute of this app. + #: Defaults to :class:`~flask.Config`. + #: + #: Example use cases for a custom class: + #: + #: 1. Default values for certain config options. + #: 2. Access to config values through attributes in addition to keys. + #: + #: .. versionadded:: 0.11 + config_class = Config + + #: The testing flag. Set this to ``True`` to enable the test mode of + #: Flask extensions (and in the future probably also Flask itself). + #: For example this might activate test helpers that have an + #: additional runtime cost which should not be enabled by default. + #: + #: If this is enabled and PROPAGATE_EXCEPTIONS is not changed from the + #: default it's implicitly enabled. + #: + #: This attribute can also be configured from the config with the + #: ``TESTING`` configuration key. Defaults to ``False``. + testing = ConfigAttribute[bool]("TESTING") + + #: If a secret key is set, cryptographic components can use this to + #: sign cookies and other things. Set this to a complex random value + #: when you want to use the secure cookie for instance. + #: + #: This attribute can also be configured from the config with the + #: :data:`SECRET_KEY` configuration key. Defaults to ``None``. + secret_key = ConfigAttribute[t.Union[str, bytes, None]]("SECRET_KEY") + + #: A :class:`~datetime.timedelta` which is used to set the expiration + #: date of a permanent session. The default is 31 days which makes a + #: permanent session survive for roughly one month. + #: + #: This attribute can also be configured from the config with the + #: ``PERMANENT_SESSION_LIFETIME`` configuration key. Defaults to + #: ``timedelta(days=31)`` + permanent_session_lifetime = ConfigAttribute[timedelta]( + "PERMANENT_SESSION_LIFETIME", + get_converter=_make_timedelta, # type: ignore[arg-type] + ) + + json_provider_class: type[JSONProvider] = DefaultJSONProvider + """A subclass of :class:`~flask.json.provider.JSONProvider`. An + instance is created and assigned to :attr:`app.json` when creating + the app. + + The default, :class:`~flask.json.provider.DefaultJSONProvider`, uses + Python's built-in :mod:`json` library. A different provider can use + a different JSON library. + + .. versionadded:: 2.2 + """ + + #: Options that are passed to the Jinja environment in + #: :meth:`create_jinja_environment`. Changing these options after + #: the environment is created (accessing :attr:`jinja_env`) will + #: have no effect. + #: + #: .. versionchanged:: 1.1.0 + #: This is a ``dict`` instead of an ``ImmutableDict`` to allow + #: easier configuration. + #: + jinja_options: dict[str, t.Any] = {} + + #: The rule object to use for URL rules created. This is used by + #: :meth:`add_url_rule`. Defaults to :class:`werkzeug.routing.Rule`. + #: + #: .. versionadded:: 0.7 + url_rule_class = Rule + + #: The map object to use for storing the URL rules and routing + #: configuration parameters. Defaults to :class:`werkzeug.routing.Map`. + #: + #: .. versionadded:: 1.1.0 + url_map_class = Map + + #: The :meth:`test_client` method creates an instance of this test + #: client class. Defaults to :class:`~flask.testing.FlaskClient`. + #: + #: .. versionadded:: 0.7 + test_client_class: type[FlaskClient] | None = None + + #: The :class:`~click.testing.CliRunner` subclass, by default + #: :class:`~flask.testing.FlaskCliRunner` that is used by + #: :meth:`test_cli_runner`. Its ``__init__`` method should take a + #: Flask app object as the first argument. + #: + #: .. versionadded:: 1.0 + test_cli_runner_class: type[FlaskCliRunner] | None = None + + default_config: dict[str, t.Any] + response_class: type[Response] + + def __init__( + self, + import_name: str, + static_url_path: str | None = None, + static_folder: str | os.PathLike[str] | None = "static", + static_host: str | None = None, + host_matching: bool = False, + subdomain_matching: bool = False, + template_folder: str | os.PathLike[str] | None = "templates", + instance_path: str | None = None, + instance_relative_config: bool = False, + root_path: str | None = None, + ) -> None: + super().__init__( + import_name=import_name, + static_folder=static_folder, + static_url_path=static_url_path, + template_folder=template_folder, + root_path=root_path, + ) + + if instance_path is None: + instance_path = self.auto_find_instance_path() + elif not os.path.isabs(instance_path): + raise ValueError( + "If an instance path is provided it must be absolute." + " A relative path was given instead." + ) + + #: Holds the path to the instance folder. + #: + #: .. versionadded:: 0.8 + self.instance_path = instance_path + + #: The configuration dictionary as :class:`Config`. This behaves + #: exactly like a regular dictionary but supports additional methods + #: to load a config from files. + self.config = self.make_config(instance_relative_config) + + #: An instance of :attr:`aborter_class` created by + #: :meth:`make_aborter`. This is called by :func:`flask.abort` + #: to raise HTTP errors, and can be called directly as well. + #: + #: .. versionadded:: 2.2 + #: Moved from ``flask.abort``, which calls this object. + self.aborter = self.make_aborter() + + self.json: JSONProvider = self.json_provider_class(self) + """Provides access to JSON methods. Functions in ``flask.json`` + will call methods on this provider when the application context + is active. Used for handling JSON requests and responses. + + An instance of :attr:`json_provider_class`. Can be customized by + changing that attribute on a subclass, or by assigning to this + attribute afterwards. + + The default, :class:`~flask.json.provider.DefaultJSONProvider`, + uses Python's built-in :mod:`json` library. A different provider + can use a different JSON library. + + .. versionadded:: 2.2 + """ + + #: A list of functions that are called by + #: :meth:`handle_url_build_error` when :meth:`.url_for` raises a + #: :exc:`~werkzeug.routing.BuildError`. Each function is called + #: with ``error``, ``endpoint`` and ``values``. If a function + #: returns ``None`` or raises a ``BuildError``, it is skipped. + #: Otherwise, its return value is returned by ``url_for``. + #: + #: .. versionadded:: 0.9 + self.url_build_error_handlers: list[ + t.Callable[[Exception, str, dict[str, t.Any]], str] + ] = [] + + #: A list of functions that are called when the application context + #: is destroyed. Since the application context is also torn down + #: if the request ends this is the place to store code that disconnects + #: from databases. + #: + #: .. versionadded:: 0.9 + self.teardown_appcontext_funcs: list[ft.TeardownCallable] = [] + + #: A list of shell context processor functions that should be run + #: when a shell context is created. + #: + #: .. versionadded:: 0.11 + self.shell_context_processors: list[ft.ShellContextProcessorCallable] = [] + + #: Maps registered blueprint names to blueprint objects. The + #: dict retains the order the blueprints were registered in. + #: Blueprints can be registered multiple times, this dict does + #: not track how often they were attached. + #: + #: .. versionadded:: 0.7 + self.blueprints: dict[str, Blueprint] = {} + + #: a place where extensions can store application specific state. For + #: example this is where an extension could store database engines and + #: similar things. + #: + #: The key must match the name of the extension module. For example in + #: case of a "Flask-Foo" extension in `flask_foo`, the key would be + #: ``'foo'``. + #: + #: .. versionadded:: 0.7 + self.extensions: dict[str, t.Any] = {} + + #: The :class:`~werkzeug.routing.Map` for this instance. You can use + #: this to change the routing converters after the class was created + #: but before any routes are connected. Example:: + #: + #: from werkzeug.routing import BaseConverter + #: + #: class ListConverter(BaseConverter): + #: def to_python(self, value): + #: return value.split(',') + #: def to_url(self, values): + #: return ','.join(super(ListConverter, self).to_url(value) + #: for value in values) + #: + #: app = Flask(__name__) + #: app.url_map.converters['list'] = ListConverter + self.url_map = self.url_map_class(host_matching=host_matching) + + self.subdomain_matching = subdomain_matching + + # tracks internally if the application already handled at least one + # request. + self._got_first_request = False + + def _check_setup_finished(self, f_name: str) -> None: + if self._got_first_request: + raise AssertionError( + f"The setup method '{f_name}' can no longer be called" + " on the application. It has already handled its first" + " request, any changes will not be applied" + " consistently.\n" + "Make sure all imports, decorators, functions, etc." + " needed to set up the application are done before" + " running it." + ) + + @cached_property + def name(self) -> str: + """The name of the application. This is usually the import name + with the difference that it's guessed from the run file if the + import name is main. This name is used as a display name when + Flask needs the name of the application. It can be set and overridden + to change the value. + + .. versionadded:: 0.8 + """ + if self.import_name == "__main__": + fn: str | None = getattr(sys.modules["__main__"], "__file__", None) + if fn is None: + return "__main__" + return os.path.splitext(os.path.basename(fn))[0] + return self.import_name + + @cached_property + def logger(self) -> logging.Logger: + """A standard Python :class:`~logging.Logger` for the app, with + the same name as :attr:`name`. + + In debug mode, the logger's :attr:`~logging.Logger.level` will + be set to :data:`~logging.DEBUG`. + + If there are no handlers configured, a default handler will be + added. See :doc:`/logging` for more information. + + .. versionchanged:: 1.1.0 + The logger takes the same name as :attr:`name` rather than + hard-coding ``"flask.app"``. + + .. versionchanged:: 1.0.0 + Behavior was simplified. The logger is always named + ``"flask.app"``. The level is only set during configuration, + it doesn't check ``app.debug`` each time. Only one format is + used, not different ones depending on ``app.debug``. No + handlers are removed, and a handler is only added if no + handlers are already configured. + + .. versionadded:: 0.3 + """ + return create_logger(self) + + @cached_property + def jinja_env(self) -> Environment: + """The Jinja environment used to load templates. + + The environment is created the first time this property is + accessed. Changing :attr:`jinja_options` after that will have no + effect. + """ + return self.create_jinja_environment() + + def create_jinja_environment(self) -> Environment: + raise NotImplementedError() + + def make_config(self, instance_relative: bool = False) -> Config: + """Used to create the config attribute by the Flask constructor. + The `instance_relative` parameter is passed in from the constructor + of Flask (there named `instance_relative_config`) and indicates if + the config should be relative to the instance path or the root path + of the application. + + .. versionadded:: 0.8 + """ + root_path = self.root_path + if instance_relative: + root_path = self.instance_path + defaults = dict(self.default_config) + defaults["DEBUG"] = get_debug_flag() + return self.config_class(root_path, defaults) + + def make_aborter(self) -> Aborter: + """Create the object to assign to :attr:`aborter`. That object + is called by :func:`flask.abort` to raise HTTP errors, and can + be called directly as well. + + By default, this creates an instance of :attr:`aborter_class`, + which defaults to :class:`werkzeug.exceptions.Aborter`. + + .. versionadded:: 2.2 + """ + return self.aborter_class() + + def auto_find_instance_path(self) -> str: + """Tries to locate the instance path if it was not provided to the + constructor of the application class. It will basically calculate + the path to a folder named ``instance`` next to your main file or + the package. + + .. versionadded:: 0.8 + """ + prefix, package_path = find_package(self.import_name) + if prefix is None: + return os.path.join(package_path, "instance") + return os.path.join(prefix, "var", f"{self.name}-instance") + + def create_global_jinja_loader(self) -> DispatchingJinjaLoader: + """Creates the loader for the Jinja environment. Can be used to + override just the loader and keeping the rest unchanged. It's + discouraged to override this function. Instead one should override + the :meth:`jinja_loader` function instead. + + The global loader dispatches between the loaders of the application + and the individual blueprints. + + .. versionadded:: 0.7 + """ + return DispatchingJinjaLoader(self) + + def select_jinja_autoescape(self, filename: str | None) -> bool: + """Returns ``True`` if autoescaping should be active for the given + template name. If no template name is given, returns `True`. + + .. versionchanged:: 2.2 + Autoescaping is now enabled by default for ``.svg`` files. + + .. versionadded:: 0.5 + """ + if filename is None: + return True + return filename.endswith((".html", ".htm", ".xml", ".xhtml", ".svg")) + + @property + def debug(self) -> bool: + """Whether debug mode is enabled. When using ``flask run`` to start the + development server, an interactive debugger will be shown for unhandled + exceptions, and the server will be reloaded when code changes. This maps to the + :data:`DEBUG` config key. It may not behave as expected if set late. + + **Do not enable debug mode when deploying in production.** + + Default: ``False`` + """ + return self.config["DEBUG"] # type: ignore[no-any-return] + + @debug.setter + def debug(self, value: bool) -> None: + self.config["DEBUG"] = value + + if self.config["TEMPLATES_AUTO_RELOAD"] is None: + self.jinja_env.auto_reload = value + + @setupmethod + def register_blueprint(self, blueprint: Blueprint, **options: t.Any) -> None: + """Register a :class:`~flask.Blueprint` on the application. Keyword + arguments passed to this method will override the defaults set on the + blueprint. + + Calls the blueprint's :meth:`~flask.Blueprint.register` method after + recording the blueprint in the application's :attr:`blueprints`. + + :param blueprint: The blueprint to register. + :param url_prefix: Blueprint routes will be prefixed with this. + :param subdomain: Blueprint routes will match on this subdomain. + :param url_defaults: Blueprint routes will use these default values for + view arguments. + :param options: Additional keyword arguments are passed to + :class:`~flask.blueprints.BlueprintSetupState`. They can be + accessed in :meth:`~flask.Blueprint.record` callbacks. + + .. versionchanged:: 2.0.1 + The ``name`` option can be used to change the (pre-dotted) + name the blueprint is registered with. This allows the same + blueprint to be registered multiple times with unique names + for ``url_for``. + + .. versionadded:: 0.7 + """ + blueprint.register(self, options) + + def iter_blueprints(self) -> t.ValuesView[Blueprint]: + """Iterates over all blueprints by the order they were registered. + + .. versionadded:: 0.11 + """ + return self.blueprints.values() + + @setupmethod + def add_url_rule( + self, + rule: str, + endpoint: str | None = None, + view_func: ft.RouteCallable | None = None, + provide_automatic_options: bool | None = None, + **options: t.Any, + ) -> None: + if endpoint is None: + endpoint = _endpoint_from_view_func(view_func) # type: ignore + options["endpoint"] = endpoint + methods = options.pop("methods", None) + + # if the methods are not given and the view_func object knows its + # methods we can use that instead. If neither exists, we go with + # a tuple of only ``GET`` as default. + if methods is None: + methods = getattr(view_func, "methods", None) or ("GET",) + if isinstance(methods, str): + raise TypeError( + "Allowed methods must be a list of strings, for" + ' example: @app.route(..., methods=["POST"])' + ) + methods = {item.upper() for item in methods} + + # Methods that should always be added + required_methods: set[str] = set(getattr(view_func, "required_methods", ())) + + # starting with Flask 0.8 the view_func object can disable and + # force-enable the automatic options handling. + if provide_automatic_options is None: + provide_automatic_options = getattr( + view_func, "provide_automatic_options", None + ) + + if provide_automatic_options is None: + if "OPTIONS" not in methods and self.config["PROVIDE_AUTOMATIC_OPTIONS"]: + provide_automatic_options = True + required_methods.add("OPTIONS") + else: + provide_automatic_options = False + + # Add the required methods now. + methods |= required_methods + + rule_obj = self.url_rule_class(rule, methods=methods, **options) + rule_obj.provide_automatic_options = provide_automatic_options # type: ignore[attr-defined] + + self.url_map.add(rule_obj) + if view_func is not None: + old_func = self.view_functions.get(endpoint) + if old_func is not None and old_func != view_func: + raise AssertionError( + "View function mapping is overwriting an existing" + f" endpoint function: {endpoint}" + ) + self.view_functions[endpoint] = view_func + + @setupmethod + def template_filter( + self, name: str | None = None + ) -> t.Callable[[T_template_filter], T_template_filter]: + """A decorator that is used to register custom template filter. + You can specify a name for the filter, otherwise the function + name will be used. Example:: + + @app.template_filter() + def reverse(s): + return s[::-1] + + :param name: the optional name of the filter, otherwise the + function name will be used. + """ + + def decorator(f: T_template_filter) -> T_template_filter: + self.add_template_filter(f, name=name) + return f + + return decorator + + @setupmethod + def add_template_filter( + self, f: ft.TemplateFilterCallable, name: str | None = None + ) -> None: + """Register a custom template filter. Works exactly like the + :meth:`template_filter` decorator. + + :param name: the optional name of the filter, otherwise the + function name will be used. + """ + self.jinja_env.filters[name or f.__name__] = f + + @setupmethod + def template_test( + self, name: str | None = None + ) -> t.Callable[[T_template_test], T_template_test]: + """A decorator that is used to register custom template test. + You can specify a name for the test, otherwise the function + name will be used. Example:: + + @app.template_test() + def is_prime(n): + if n == 2: + return True + for i in range(2, int(math.ceil(math.sqrt(n))) + 1): + if n % i == 0: + return False + return True + + .. versionadded:: 0.10 + + :param name: the optional name of the test, otherwise the + function name will be used. + """ + + def decorator(f: T_template_test) -> T_template_test: + self.add_template_test(f, name=name) + return f + + return decorator + + @setupmethod + def add_template_test( + self, f: ft.TemplateTestCallable, name: str | None = None + ) -> None: + """Register a custom template test. Works exactly like the + :meth:`template_test` decorator. + + .. versionadded:: 0.10 + + :param name: the optional name of the test, otherwise the + function name will be used. + """ + self.jinja_env.tests[name or f.__name__] = f + + @setupmethod + def template_global( + self, name: str | None = None + ) -> t.Callable[[T_template_global], T_template_global]: + """A decorator that is used to register a custom template global function. + You can specify a name for the global function, otherwise the function + name will be used. Example:: + + @app.template_global() + def double(n): + return 2 * n + + .. versionadded:: 0.10 + + :param name: the optional name of the global function, otherwise the + function name will be used. + """ + + def decorator(f: T_template_global) -> T_template_global: + self.add_template_global(f, name=name) + return f + + return decorator + + @setupmethod + def add_template_global( + self, f: ft.TemplateGlobalCallable, name: str | None = None + ) -> None: + """Register a custom template global function. Works exactly like the + :meth:`template_global` decorator. + + .. versionadded:: 0.10 + + :param name: the optional name of the global function, otherwise the + function name will be used. + """ + self.jinja_env.globals[name or f.__name__] = f + + @setupmethod + def teardown_appcontext(self, f: T_teardown) -> T_teardown: + """Registers a function to be called when the application + context is popped. The application context is typically popped + after the request context for each request, at the end of CLI + commands, or after a manually pushed context ends. + + .. code-block:: python + + with app.app_context(): + ... + + When the ``with`` block exits (or ``ctx.pop()`` is called), the + teardown functions are called just before the app context is + made inactive. Since a request context typically also manages an + application context it would also be called when you pop a + request context. + + When a teardown function was called because of an unhandled + exception it will be passed an error object. If an + :meth:`errorhandler` is registered, it will handle the exception + and the teardown will not receive it. + + Teardown functions must avoid raising exceptions. If they + execute code that might fail they must surround that code with a + ``try``/``except`` block and log any errors. + + The return values of teardown functions are ignored. + + .. versionadded:: 0.9 + """ + self.teardown_appcontext_funcs.append(f) + return f + + @setupmethod + def shell_context_processor( + self, f: T_shell_context_processor + ) -> T_shell_context_processor: + """Registers a shell context processor function. + + .. versionadded:: 0.11 + """ + self.shell_context_processors.append(f) + return f + + def _find_error_handler( + self, e: Exception, blueprints: list[str] + ) -> ft.ErrorHandlerCallable | None: + """Return a registered error handler for an exception in this order: + blueprint handler for a specific code, app handler for a specific code, + blueprint handler for an exception class, app handler for an exception + class, or ``None`` if a suitable handler is not found. + """ + exc_class, code = self._get_exc_class_and_code(type(e)) + names = (*blueprints, None) + + for c in (code, None) if code is not None else (None,): + for name in names: + handler_map = self.error_handler_spec[name][c] + + if not handler_map: + continue + + for cls in exc_class.__mro__: + handler = handler_map.get(cls) + + if handler is not None: + return handler + return None + + def trap_http_exception(self, e: Exception) -> bool: + """Checks if an HTTP exception should be trapped or not. By default + this will return ``False`` for all exceptions except for a bad request + key error if ``TRAP_BAD_REQUEST_ERRORS`` is set to ``True``. It + also returns ``True`` if ``TRAP_HTTP_EXCEPTIONS`` is set to ``True``. + + This is called for all HTTP exceptions raised by a view function. + If it returns ``True`` for any exception the error handler for this + exception is not called and it shows up as regular exception in the + traceback. This is helpful for debugging implicitly raised HTTP + exceptions. + + .. versionchanged:: 1.0 + Bad request errors are not trapped by default in debug mode. + + .. versionadded:: 0.8 + """ + if self.config["TRAP_HTTP_EXCEPTIONS"]: + return True + + trap_bad_request = self.config["TRAP_BAD_REQUEST_ERRORS"] + + # if unset, trap key errors in debug mode + if ( + trap_bad_request is None + and self.debug + and isinstance(e, BadRequestKeyError) + ): + return True + + if trap_bad_request: + return isinstance(e, BadRequest) + + return False + + def should_ignore_error(self, error: BaseException | None) -> bool: + """This is called to figure out if an error should be ignored + or not as far as the teardown system is concerned. If this + function returns ``True`` then the teardown handlers will not be + passed the error. + + .. versionadded:: 0.10 + """ + return False + + def redirect(self, location: str, code: int = 302) -> BaseResponse: + """Create a redirect response object. + + This is called by :func:`flask.redirect`, and can be called + directly as well. + + :param location: The URL to redirect to. + :param code: The status code for the redirect. + + .. versionadded:: 2.2 + Moved from ``flask.redirect``, which calls this method. + """ + return _wz_redirect( + location, + code=code, + Response=self.response_class, # type: ignore[arg-type] + ) + + def inject_url_defaults(self, endpoint: str, values: dict[str, t.Any]) -> None: + """Injects the URL defaults for the given endpoint directly into + the values dictionary passed. This is used internally and + automatically called on URL building. + + .. versionadded:: 0.7 + """ + names: t.Iterable[str | None] = (None,) + + # url_for may be called outside a request context, parse the + # passed endpoint instead of using request.blueprints. + if "." in endpoint: + names = chain( + names, reversed(_split_blueprint_path(endpoint.rpartition(".")[0])) + ) + + for name in names: + if name in self.url_default_functions: + for func in self.url_default_functions[name]: + func(endpoint, values) + + def handle_url_build_error( + self, error: BuildError, endpoint: str, values: dict[str, t.Any] + ) -> str: + """Called by :meth:`.url_for` if a + :exc:`~werkzeug.routing.BuildError` was raised. If this returns + a value, it will be returned by ``url_for``, otherwise the error + will be re-raised. + + Each function in :attr:`url_build_error_handlers` is called with + ``error``, ``endpoint`` and ``values``. If a function returns + ``None`` or raises a ``BuildError``, it is skipped. Otherwise, + its return value is returned by ``url_for``. + + :param error: The active ``BuildError`` being handled. + :param endpoint: The endpoint being built. + :param values: The keyword arguments passed to ``url_for``. + """ + for handler in self.url_build_error_handlers: + try: + rv = handler(error, endpoint, values) + except BuildError as e: + # make error available outside except block + error = e + else: + if rv is not None: + return rv + + # Re-raise if called with an active exception, otherwise raise + # the passed in exception. + if error is sys.exc_info()[1]: + raise + + raise error diff --git a/python/user_packages/Python313/site-packages/flask/sansio/blueprints.py b/python/user_packages/Python313/site-packages/flask/sansio/blueprints.py new file mode 100644 index 0000000000000000000000000000000000000000..4f912cca0565669ac6360982716b3bc19c72a5ca --- /dev/null +++ b/python/user_packages/Python313/site-packages/flask/sansio/blueprints.py @@ -0,0 +1,632 @@ +from __future__ import annotations + +import os +import typing as t +from collections import defaultdict +from functools import update_wrapper + +from .. import typing as ft +from .scaffold import _endpoint_from_view_func +from .scaffold import _sentinel +from .scaffold import Scaffold +from .scaffold import setupmethod + +if t.TYPE_CHECKING: # pragma: no cover + from .app import App + +DeferredSetupFunction = t.Callable[["BlueprintSetupState"], None] +T_after_request = t.TypeVar("T_after_request", bound=ft.AfterRequestCallable[t.Any]) +T_before_request = t.TypeVar("T_before_request", bound=ft.BeforeRequestCallable) +T_error_handler = t.TypeVar("T_error_handler", bound=ft.ErrorHandlerCallable) +T_teardown = t.TypeVar("T_teardown", bound=ft.TeardownCallable) +T_template_context_processor = t.TypeVar( + "T_template_context_processor", bound=ft.TemplateContextProcessorCallable +) +T_template_filter = t.TypeVar("T_template_filter", bound=ft.TemplateFilterCallable) +T_template_global = t.TypeVar("T_template_global", bound=ft.TemplateGlobalCallable) +T_template_test = t.TypeVar("T_template_test", bound=ft.TemplateTestCallable) +T_url_defaults = t.TypeVar("T_url_defaults", bound=ft.URLDefaultCallable) +T_url_value_preprocessor = t.TypeVar( + "T_url_value_preprocessor", bound=ft.URLValuePreprocessorCallable +) + + +class BlueprintSetupState: + """Temporary holder object for registering a blueprint with the + application. An instance of this class is created by the + :meth:`~flask.Blueprint.make_setup_state` method and later passed + to all register callback functions. + """ + + def __init__( + self, + blueprint: Blueprint, + app: App, + options: t.Any, + first_registration: bool, + ) -> None: + #: a reference to the current application + self.app = app + + #: a reference to the blueprint that created this setup state. + self.blueprint = blueprint + + #: a dictionary with all options that were passed to the + #: :meth:`~flask.Flask.register_blueprint` method. + self.options = options + + #: as blueprints can be registered multiple times with the + #: application and not everything wants to be registered + #: multiple times on it, this attribute can be used to figure + #: out if the blueprint was registered in the past already. + self.first_registration = first_registration + + subdomain = self.options.get("subdomain") + if subdomain is None: + subdomain = self.blueprint.subdomain + + #: The subdomain that the blueprint should be active for, ``None`` + #: otherwise. + self.subdomain = subdomain + + url_prefix = self.options.get("url_prefix") + if url_prefix is None: + url_prefix = self.blueprint.url_prefix + #: The prefix that should be used for all URLs defined on the + #: blueprint. + self.url_prefix = url_prefix + + self.name = self.options.get("name", blueprint.name) + self.name_prefix = self.options.get("name_prefix", "") + + #: A dictionary with URL defaults that is added to each and every + #: URL that was defined with the blueprint. + self.url_defaults = dict(self.blueprint.url_values_defaults) + self.url_defaults.update(self.options.get("url_defaults", ())) + + def add_url_rule( + self, + rule: str, + endpoint: str | None = None, + view_func: ft.RouteCallable | None = None, + **options: t.Any, + ) -> None: + """A helper method to register a rule (and optionally a view function) + to the application. The endpoint is automatically prefixed with the + blueprint's name. + """ + if self.url_prefix is not None: + if rule: + rule = "/".join((self.url_prefix.rstrip("/"), rule.lstrip("/"))) + else: + rule = self.url_prefix + options.setdefault("subdomain", self.subdomain) + if endpoint is None: + endpoint = _endpoint_from_view_func(view_func) # type: ignore + defaults = self.url_defaults + if "defaults" in options: + defaults = dict(defaults, **options.pop("defaults")) + + self.app.add_url_rule( + rule, + f"{self.name_prefix}.{self.name}.{endpoint}".lstrip("."), + view_func, + defaults=defaults, + **options, + ) + + +class Blueprint(Scaffold): + """Represents a blueprint, a collection of routes and other + app-related functions that can be registered on a real application + later. + + A blueprint is an object that allows defining application functions + without requiring an application object ahead of time. It uses the + same decorators as :class:`~flask.Flask`, but defers the need for an + application by recording them for later registration. + + Decorating a function with a blueprint creates a deferred function + that is called with :class:`~flask.blueprints.BlueprintSetupState` + when the blueprint is registered on an application. + + See :doc:`/blueprints` for more information. + + :param name: The name of the blueprint. Will be prepended to each + endpoint name. + :param import_name: The name of the blueprint package, usually + ``__name__``. This helps locate the ``root_path`` for the + blueprint. + :param static_folder: A folder with static files that should be + served by the blueprint's static route. The path is relative to + the blueprint's root path. Blueprint static files are disabled + by default. + :param static_url_path: The url to serve static files from. + Defaults to ``static_folder``. If the blueprint does not have + a ``url_prefix``, the app's static route will take precedence, + and the blueprint's static files won't be accessible. + :param template_folder: A folder with templates that should be added + to the app's template search path. The path is relative to the + blueprint's root path. Blueprint templates are disabled by + default. Blueprint templates have a lower precedence than those + in the app's templates folder. + :param url_prefix: A path to prepend to all of the blueprint's URLs, + to make them distinct from the rest of the app's routes. + :param subdomain: A subdomain that blueprint routes will match on by + default. + :param url_defaults: A dict of default values that blueprint routes + will receive by default. + :param root_path: By default, the blueprint will automatically set + this based on ``import_name``. In certain situations this + automatic detection can fail, so the path can be specified + manually instead. + + .. versionchanged:: 1.1.0 + Blueprints have a ``cli`` group to register nested CLI commands. + The ``cli_group`` parameter controls the name of the group under + the ``flask`` command. + + .. versionadded:: 0.7 + """ + + _got_registered_once = False + + def __init__( + self, + name: str, + import_name: str, + static_folder: str | os.PathLike[str] | None = None, + static_url_path: str | None = None, + template_folder: str | os.PathLike[str] | None = None, + url_prefix: str | None = None, + subdomain: str | None = None, + url_defaults: dict[str, t.Any] | None = None, + root_path: str | None = None, + cli_group: str | None = _sentinel, # type: ignore[assignment] + ): + super().__init__( + import_name=import_name, + static_folder=static_folder, + static_url_path=static_url_path, + template_folder=template_folder, + root_path=root_path, + ) + + if not name: + raise ValueError("'name' may not be empty.") + + if "." in name: + raise ValueError("'name' may not contain a dot '.' character.") + + self.name = name + self.url_prefix = url_prefix + self.subdomain = subdomain + self.deferred_functions: list[DeferredSetupFunction] = [] + + if url_defaults is None: + url_defaults = {} + + self.url_values_defaults = url_defaults + self.cli_group = cli_group + self._blueprints: list[tuple[Blueprint, dict[str, t.Any]]] = [] + + def _check_setup_finished(self, f_name: str) -> None: + if self._got_registered_once: + raise AssertionError( + f"The setup method '{f_name}' can no longer be called on the blueprint" + f" '{self.name}'. It has already been registered at least once, any" + " changes will not be applied consistently.\n" + "Make sure all imports, decorators, functions, etc. needed to set up" + " the blueprint are done before registering it." + ) + + @setupmethod + def record(self, func: DeferredSetupFunction) -> None: + """Registers a function that is called when the blueprint is + registered on the application. This function is called with the + state as argument as returned by the :meth:`make_setup_state` + method. + """ + self.deferred_functions.append(func) + + @setupmethod + def record_once(self, func: DeferredSetupFunction) -> None: + """Works like :meth:`record` but wraps the function in another + function that will ensure the function is only called once. If the + blueprint is registered a second time on the application, the + function passed is not called. + """ + + def wrapper(state: BlueprintSetupState) -> None: + if state.first_registration: + func(state) + + self.record(update_wrapper(wrapper, func)) + + def make_setup_state( + self, app: App, options: dict[str, t.Any], first_registration: bool = False + ) -> BlueprintSetupState: + """Creates an instance of :meth:`~flask.blueprints.BlueprintSetupState` + object that is later passed to the register callback functions. + Subclasses can override this to return a subclass of the setup state. + """ + return BlueprintSetupState(self, app, options, first_registration) + + @setupmethod + def register_blueprint(self, blueprint: Blueprint, **options: t.Any) -> None: + """Register a :class:`~flask.Blueprint` on this blueprint. Keyword + arguments passed to this method will override the defaults set + on the blueprint. + + .. versionchanged:: 2.0.1 + The ``name`` option can be used to change the (pre-dotted) + name the blueprint is registered with. This allows the same + blueprint to be registered multiple times with unique names + for ``url_for``. + + .. versionadded:: 2.0 + """ + if blueprint is self: + raise ValueError("Cannot register a blueprint on itself") + self._blueprints.append((blueprint, options)) + + def register(self, app: App, options: dict[str, t.Any]) -> None: + """Called by :meth:`Flask.register_blueprint` to register all + views and callbacks registered on the blueprint with the + application. Creates a :class:`.BlueprintSetupState` and calls + each :meth:`record` callback with it. + + :param app: The application this blueprint is being registered + with. + :param options: Keyword arguments forwarded from + :meth:`~Flask.register_blueprint`. + + .. versionchanged:: 2.3 + Nested blueprints now correctly apply subdomains. + + .. versionchanged:: 2.1 + Registering the same blueprint with the same name multiple + times is an error. + + .. versionchanged:: 2.0.1 + Nested blueprints are registered with their dotted name. + This allows different blueprints with the same name to be + nested at different locations. + + .. versionchanged:: 2.0.1 + The ``name`` option can be used to change the (pre-dotted) + name the blueprint is registered with. This allows the same + blueprint to be registered multiple times with unique names + for ``url_for``. + """ + name_prefix = options.get("name_prefix", "") + self_name = options.get("name", self.name) + name = f"{name_prefix}.{self_name}".lstrip(".") + + if name in app.blueprints: + bp_desc = "this" if app.blueprints[name] is self else "a different" + existing_at = f" '{name}'" if self_name != name else "" + + raise ValueError( + f"The name '{self_name}' is already registered for" + f" {bp_desc} blueprint{existing_at}. Use 'name=' to" + f" provide a unique name." + ) + + first_bp_registration = not any(bp is self for bp in app.blueprints.values()) + first_name_registration = name not in app.blueprints + + app.blueprints[name] = self + self._got_registered_once = True + state = self.make_setup_state(app, options, first_bp_registration) + + if self.has_static_folder: + state.add_url_rule( + f"{self.static_url_path}/", + view_func=self.send_static_file, # type: ignore[attr-defined] + endpoint="static", + ) + + # Merge blueprint data into parent. + if first_bp_registration or first_name_registration: + self._merge_blueprint_funcs(app, name) + + for deferred in self.deferred_functions: + deferred(state) + + cli_resolved_group = options.get("cli_group", self.cli_group) + + if self.cli.commands: + if cli_resolved_group is None: + app.cli.commands.update(self.cli.commands) + elif cli_resolved_group is _sentinel: + self.cli.name = name + app.cli.add_command(self.cli) + else: + self.cli.name = cli_resolved_group + app.cli.add_command(self.cli) + + for blueprint, bp_options in self._blueprints: + bp_options = bp_options.copy() + bp_url_prefix = bp_options.get("url_prefix") + bp_subdomain = bp_options.get("subdomain") + + if bp_subdomain is None: + bp_subdomain = blueprint.subdomain + + if state.subdomain is not None and bp_subdomain is not None: + bp_options["subdomain"] = bp_subdomain + "." + state.subdomain + elif bp_subdomain is not None: + bp_options["subdomain"] = bp_subdomain + elif state.subdomain is not None: + bp_options["subdomain"] = state.subdomain + + if bp_url_prefix is None: + bp_url_prefix = blueprint.url_prefix + + if state.url_prefix is not None and bp_url_prefix is not None: + bp_options["url_prefix"] = ( + state.url_prefix.rstrip("/") + "/" + bp_url_prefix.lstrip("/") + ) + elif bp_url_prefix is not None: + bp_options["url_prefix"] = bp_url_prefix + elif state.url_prefix is not None: + bp_options["url_prefix"] = state.url_prefix + + bp_options["name_prefix"] = name + blueprint.register(app, bp_options) + + def _merge_blueprint_funcs(self, app: App, name: str) -> None: + def extend( + bp_dict: dict[ft.AppOrBlueprintKey, list[t.Any]], + parent_dict: dict[ft.AppOrBlueprintKey, list[t.Any]], + ) -> None: + for key, values in bp_dict.items(): + key = name if key is None else f"{name}.{key}" + parent_dict[key].extend(values) + + for key, value in self.error_handler_spec.items(): + key = name if key is None else f"{name}.{key}" + value = defaultdict( + dict, + { + code: {exc_class: func for exc_class, func in code_values.items()} + for code, code_values in value.items() + }, + ) + app.error_handler_spec[key] = value + + for endpoint, func in self.view_functions.items(): + app.view_functions[endpoint] = func + + extend(self.before_request_funcs, app.before_request_funcs) + extend(self.after_request_funcs, app.after_request_funcs) + extend( + self.teardown_request_funcs, + app.teardown_request_funcs, + ) + extend(self.url_default_functions, app.url_default_functions) + extend(self.url_value_preprocessors, app.url_value_preprocessors) + extend(self.template_context_processors, app.template_context_processors) + + @setupmethod + def add_url_rule( + self, + rule: str, + endpoint: str | None = None, + view_func: ft.RouteCallable | None = None, + provide_automatic_options: bool | None = None, + **options: t.Any, + ) -> None: + """Register a URL rule with the blueprint. See :meth:`.Flask.add_url_rule` for + full documentation. + + The URL rule is prefixed with the blueprint's URL prefix. The endpoint name, + used with :func:`url_for`, is prefixed with the blueprint's name. + """ + if endpoint and "." in endpoint: + raise ValueError("'endpoint' may not contain a dot '.' character.") + + if view_func and hasattr(view_func, "__name__") and "." in view_func.__name__: + raise ValueError("'view_func' name may not contain a dot '.' character.") + + self.record( + lambda s: s.add_url_rule( + rule, + endpoint, + view_func, + provide_automatic_options=provide_automatic_options, + **options, + ) + ) + + @setupmethod + def app_template_filter( + self, name: str | None = None + ) -> t.Callable[[T_template_filter], T_template_filter]: + """Register a template filter, available in any template rendered by the + application. Equivalent to :meth:`.Flask.template_filter`. + + :param name: the optional name of the filter, otherwise the + function name will be used. + """ + + def decorator(f: T_template_filter) -> T_template_filter: + self.add_app_template_filter(f, name=name) + return f + + return decorator + + @setupmethod + def add_app_template_filter( + self, f: ft.TemplateFilterCallable, name: str | None = None + ) -> None: + """Register a template filter, available in any template rendered by the + application. Works like the :meth:`app_template_filter` decorator. Equivalent to + :meth:`.Flask.add_template_filter`. + + :param name: the optional name of the filter, otherwise the + function name will be used. + """ + + def register_template(state: BlueprintSetupState) -> None: + state.app.jinja_env.filters[name or f.__name__] = f + + self.record_once(register_template) + + @setupmethod + def app_template_test( + self, name: str | None = None + ) -> t.Callable[[T_template_test], T_template_test]: + """Register a template test, available in any template rendered by the + application. Equivalent to :meth:`.Flask.template_test`. + + .. versionadded:: 0.10 + + :param name: the optional name of the test, otherwise the + function name will be used. + """ + + def decorator(f: T_template_test) -> T_template_test: + self.add_app_template_test(f, name=name) + return f + + return decorator + + @setupmethod + def add_app_template_test( + self, f: ft.TemplateTestCallable, name: str | None = None + ) -> None: + """Register a template test, available in any template rendered by the + application. Works like the :meth:`app_template_test` decorator. Equivalent to + :meth:`.Flask.add_template_test`. + + .. versionadded:: 0.10 + + :param name: the optional name of the test, otherwise the + function name will be used. + """ + + def register_template(state: BlueprintSetupState) -> None: + state.app.jinja_env.tests[name or f.__name__] = f + + self.record_once(register_template) + + @setupmethod + def app_template_global( + self, name: str | None = None + ) -> t.Callable[[T_template_global], T_template_global]: + """Register a template global, available in any template rendered by the + application. Equivalent to :meth:`.Flask.template_global`. + + .. versionadded:: 0.10 + + :param name: the optional name of the global, otherwise the + function name will be used. + """ + + def decorator(f: T_template_global) -> T_template_global: + self.add_app_template_global(f, name=name) + return f + + return decorator + + @setupmethod + def add_app_template_global( + self, f: ft.TemplateGlobalCallable, name: str | None = None + ) -> None: + """Register a template global, available in any template rendered by the + application. Works like the :meth:`app_template_global` decorator. Equivalent to + :meth:`.Flask.add_template_global`. + + .. versionadded:: 0.10 + + :param name: the optional name of the global, otherwise the + function name will be used. + """ + + def register_template(state: BlueprintSetupState) -> None: + state.app.jinja_env.globals[name or f.__name__] = f + + self.record_once(register_template) + + @setupmethod + def before_app_request(self, f: T_before_request) -> T_before_request: + """Like :meth:`before_request`, but before every request, not only those handled + by the blueprint. Equivalent to :meth:`.Flask.before_request`. + """ + self.record_once( + lambda s: s.app.before_request_funcs.setdefault(None, []).append(f) + ) + return f + + @setupmethod + def after_app_request(self, f: T_after_request) -> T_after_request: + """Like :meth:`after_request`, but after every request, not only those handled + by the blueprint. Equivalent to :meth:`.Flask.after_request`. + """ + self.record_once( + lambda s: s.app.after_request_funcs.setdefault(None, []).append(f) + ) + return f + + @setupmethod + def teardown_app_request(self, f: T_teardown) -> T_teardown: + """Like :meth:`teardown_request`, but after every request, not only those + handled by the blueprint. Equivalent to :meth:`.Flask.teardown_request`. + """ + self.record_once( + lambda s: s.app.teardown_request_funcs.setdefault(None, []).append(f) + ) + return f + + @setupmethod + def app_context_processor( + self, f: T_template_context_processor + ) -> T_template_context_processor: + """Like :meth:`context_processor`, but for templates rendered by every view, not + only by the blueprint. Equivalent to :meth:`.Flask.context_processor`. + """ + self.record_once( + lambda s: s.app.template_context_processors.setdefault(None, []).append(f) + ) + return f + + @setupmethod + def app_errorhandler( + self, code: type[Exception] | int + ) -> t.Callable[[T_error_handler], T_error_handler]: + """Like :meth:`errorhandler`, but for every request, not only those handled by + the blueprint. Equivalent to :meth:`.Flask.errorhandler`. + """ + + def decorator(f: T_error_handler) -> T_error_handler: + def from_blueprint(state: BlueprintSetupState) -> None: + state.app.errorhandler(code)(f) + + self.record_once(from_blueprint) + return f + + return decorator + + @setupmethod + def app_url_value_preprocessor( + self, f: T_url_value_preprocessor + ) -> T_url_value_preprocessor: + """Like :meth:`url_value_preprocessor`, but for every request, not only those + handled by the blueprint. Equivalent to :meth:`.Flask.url_value_preprocessor`. + """ + self.record_once( + lambda s: s.app.url_value_preprocessors.setdefault(None, []).append(f) + ) + return f + + @setupmethod + def app_url_defaults(self, f: T_url_defaults) -> T_url_defaults: + """Like :meth:`url_defaults`, but for every request, not only those handled by + the blueprint. Equivalent to :meth:`.Flask.url_defaults`. + """ + self.record_once( + lambda s: s.app.url_default_functions.setdefault(None, []).append(f) + ) + return f diff --git a/python/user_packages/Python313/site-packages/flask/sansio/scaffold.py b/python/user_packages/Python313/site-packages/flask/sansio/scaffold.py new file mode 100644 index 0000000000000000000000000000000000000000..0e96f15b74a4ca6096c5eaa9f041be909b5e01f1 --- /dev/null +++ b/python/user_packages/Python313/site-packages/flask/sansio/scaffold.py @@ -0,0 +1,792 @@ +from __future__ import annotations + +import importlib.util +import os +import pathlib +import sys +import typing as t +from collections import defaultdict +from functools import update_wrapper + +from jinja2 import BaseLoader +from jinja2 import FileSystemLoader +from werkzeug.exceptions import default_exceptions +from werkzeug.exceptions import HTTPException +from werkzeug.utils import cached_property + +from .. import typing as ft +from ..helpers import get_root_path +from ..templating import _default_template_ctx_processor + +if t.TYPE_CHECKING: # pragma: no cover + from click import Group + +# a singleton sentinel value for parameter defaults +_sentinel = object() + +F = t.TypeVar("F", bound=t.Callable[..., t.Any]) +T_after_request = t.TypeVar("T_after_request", bound=ft.AfterRequestCallable[t.Any]) +T_before_request = t.TypeVar("T_before_request", bound=ft.BeforeRequestCallable) +T_error_handler = t.TypeVar("T_error_handler", bound=ft.ErrorHandlerCallable) +T_teardown = t.TypeVar("T_teardown", bound=ft.TeardownCallable) +T_template_context_processor = t.TypeVar( + "T_template_context_processor", bound=ft.TemplateContextProcessorCallable +) +T_url_defaults = t.TypeVar("T_url_defaults", bound=ft.URLDefaultCallable) +T_url_value_preprocessor = t.TypeVar( + "T_url_value_preprocessor", bound=ft.URLValuePreprocessorCallable +) +T_route = t.TypeVar("T_route", bound=ft.RouteCallable) + + +def setupmethod(f: F) -> F: + f_name = f.__name__ + + def wrapper_func(self: Scaffold, *args: t.Any, **kwargs: t.Any) -> t.Any: + self._check_setup_finished(f_name) + return f(self, *args, **kwargs) + + return t.cast(F, update_wrapper(wrapper_func, f)) + + +class Scaffold: + """Common behavior shared between :class:`~flask.Flask` and + :class:`~flask.blueprints.Blueprint`. + + :param import_name: The import name of the module where this object + is defined. Usually :attr:`__name__` should be used. + :param static_folder: Path to a folder of static files to serve. + If this is set, a static route will be added. + :param static_url_path: URL prefix for the static route. + :param template_folder: Path to a folder containing template files. + for rendering. If this is set, a Jinja loader will be added. + :param root_path: The path that static, template, and resource files + are relative to. Typically not set, it is discovered based on + the ``import_name``. + + .. versionadded:: 2.0 + """ + + cli: Group + name: str + _static_folder: str | None = None + _static_url_path: str | None = None + + def __init__( + self, + import_name: str, + static_folder: str | os.PathLike[str] | None = None, + static_url_path: str | None = None, + template_folder: str | os.PathLike[str] | None = None, + root_path: str | None = None, + ): + #: The name of the package or module that this object belongs + #: to. Do not change this once it is set by the constructor. + self.import_name = import_name + + self.static_folder = static_folder + self.static_url_path = static_url_path + + #: The path to the templates folder, relative to + #: :attr:`root_path`, to add to the template loader. ``None`` if + #: templates should not be added. + self.template_folder = template_folder + + if root_path is None: + root_path = get_root_path(self.import_name) + + #: Absolute path to the package on the filesystem. Used to look + #: up resources contained in the package. + self.root_path = root_path + + #: A dictionary mapping endpoint names to view functions. + #: + #: To register a view function, use the :meth:`route` decorator. + #: + #: This data structure is internal. It should not be modified + #: directly and its format may change at any time. + self.view_functions: dict[str, ft.RouteCallable] = {} + + #: A data structure of registered error handlers, in the format + #: ``{scope: {code: {class: handler}}}``. The ``scope`` key is + #: the name of a blueprint the handlers are active for, or + #: ``None`` for all requests. The ``code`` key is the HTTP + #: status code for ``HTTPException``, or ``None`` for + #: other exceptions. The innermost dictionary maps exception + #: classes to handler functions. + #: + #: To register an error handler, use the :meth:`errorhandler` + #: decorator. + #: + #: This data structure is internal. It should not be modified + #: directly and its format may change at any time. + self.error_handler_spec: dict[ + ft.AppOrBlueprintKey, + dict[int | None, dict[type[Exception], ft.ErrorHandlerCallable]], + ] = defaultdict(lambda: defaultdict(dict)) + + #: A data structure of functions to call at the beginning of + #: each request, in the format ``{scope: [functions]}``. The + #: ``scope`` key is the name of a blueprint the functions are + #: active for, or ``None`` for all requests. + #: + #: To register a function, use the :meth:`before_request` + #: decorator. + #: + #: This data structure is internal. It should not be modified + #: directly and its format may change at any time. + self.before_request_funcs: dict[ + ft.AppOrBlueprintKey, list[ft.BeforeRequestCallable] + ] = defaultdict(list) + + #: A data structure of functions to call at the end of each + #: request, in the format ``{scope: [functions]}``. The + #: ``scope`` key is the name of a blueprint the functions are + #: active for, or ``None`` for all requests. + #: + #: To register a function, use the :meth:`after_request` + #: decorator. + #: + #: This data structure is internal. It should not be modified + #: directly and its format may change at any time. + self.after_request_funcs: dict[ + ft.AppOrBlueprintKey, list[ft.AfterRequestCallable[t.Any]] + ] = defaultdict(list) + + #: A data structure of functions to call at the end of each + #: request even if an exception is raised, in the format + #: ``{scope: [functions]}``. The ``scope`` key is the name of a + #: blueprint the functions are active for, or ``None`` for all + #: requests. + #: + #: To register a function, use the :meth:`teardown_request` + #: decorator. + #: + #: This data structure is internal. It should not be modified + #: directly and its format may change at any time. + self.teardown_request_funcs: dict[ + ft.AppOrBlueprintKey, list[ft.TeardownCallable] + ] = defaultdict(list) + + #: A data structure of functions to call to pass extra context + #: values when rendering templates, in the format + #: ``{scope: [functions]}``. The ``scope`` key is the name of a + #: blueprint the functions are active for, or ``None`` for all + #: requests. + #: + #: To register a function, use the :meth:`context_processor` + #: decorator. + #: + #: This data structure is internal. It should not be modified + #: directly and its format may change at any time. + self.template_context_processors: dict[ + ft.AppOrBlueprintKey, list[ft.TemplateContextProcessorCallable] + ] = defaultdict(list, {None: [_default_template_ctx_processor]}) + + #: A data structure of functions to call to modify the keyword + #: arguments passed to the view function, in the format + #: ``{scope: [functions]}``. The ``scope`` key is the name of a + #: blueprint the functions are active for, or ``None`` for all + #: requests. + #: + #: To register a function, use the + #: :meth:`url_value_preprocessor` decorator. + #: + #: This data structure is internal. It should not be modified + #: directly and its format may change at any time. + self.url_value_preprocessors: dict[ + ft.AppOrBlueprintKey, + list[ft.URLValuePreprocessorCallable], + ] = defaultdict(list) + + #: A data structure of functions to call to modify the keyword + #: arguments when generating URLs, in the format + #: ``{scope: [functions]}``. The ``scope`` key is the name of a + #: blueprint the functions are active for, or ``None`` for all + #: requests. + #: + #: To register a function, use the :meth:`url_defaults` + #: decorator. + #: + #: This data structure is internal. It should not be modified + #: directly and its format may change at any time. + self.url_default_functions: dict[ + ft.AppOrBlueprintKey, list[ft.URLDefaultCallable] + ] = defaultdict(list) + + def __repr__(self) -> str: + return f"<{type(self).__name__} {self.name!r}>" + + def _check_setup_finished(self, f_name: str) -> None: + raise NotImplementedError + + @property + def static_folder(self) -> str | None: + """The absolute path to the configured static folder. ``None`` + if no static folder is set. + """ + if self._static_folder is not None: + return os.path.join(self.root_path, self._static_folder) + else: + return None + + @static_folder.setter + def static_folder(self, value: str | os.PathLike[str] | None) -> None: + if value is not None: + value = os.fspath(value).rstrip(r"\/") + + self._static_folder = value + + @property + def has_static_folder(self) -> bool: + """``True`` if :attr:`static_folder` is set. + + .. versionadded:: 0.5 + """ + return self.static_folder is not None + + @property + def static_url_path(self) -> str | None: + """The URL prefix that the static route will be accessible from. + + If it was not configured during init, it is derived from + :attr:`static_folder`. + """ + if self._static_url_path is not None: + return self._static_url_path + + if self.static_folder is not None: + basename = os.path.basename(self.static_folder) + return f"/{basename}".rstrip("/") + + return None + + @static_url_path.setter + def static_url_path(self, value: str | None) -> None: + if value is not None: + value = value.rstrip("/") + + self._static_url_path = value + + @cached_property + def jinja_loader(self) -> BaseLoader | None: + """The Jinja loader for this object's templates. By default this + is a class :class:`jinja2.loaders.FileSystemLoader` to + :attr:`template_folder` if it is set. + + .. versionadded:: 0.5 + """ + if self.template_folder is not None: + return FileSystemLoader(os.path.join(self.root_path, self.template_folder)) + else: + return None + + def _method_route( + self, + method: str, + rule: str, + options: dict[str, t.Any], + ) -> t.Callable[[T_route], T_route]: + if "methods" in options: + raise TypeError("Use the 'route' decorator to use the 'methods' argument.") + + return self.route(rule, methods=[method], **options) + + @setupmethod + def get(self, rule: str, **options: t.Any) -> t.Callable[[T_route], T_route]: + """Shortcut for :meth:`route` with ``methods=["GET"]``. + + .. versionadded:: 2.0 + """ + return self._method_route("GET", rule, options) + + @setupmethod + def post(self, rule: str, **options: t.Any) -> t.Callable[[T_route], T_route]: + """Shortcut for :meth:`route` with ``methods=["POST"]``. + + .. versionadded:: 2.0 + """ + return self._method_route("POST", rule, options) + + @setupmethod + def put(self, rule: str, **options: t.Any) -> t.Callable[[T_route], T_route]: + """Shortcut for :meth:`route` with ``methods=["PUT"]``. + + .. versionadded:: 2.0 + """ + return self._method_route("PUT", rule, options) + + @setupmethod + def delete(self, rule: str, **options: t.Any) -> t.Callable[[T_route], T_route]: + """Shortcut for :meth:`route` with ``methods=["DELETE"]``. + + .. versionadded:: 2.0 + """ + return self._method_route("DELETE", rule, options) + + @setupmethod + def patch(self, rule: str, **options: t.Any) -> t.Callable[[T_route], T_route]: + """Shortcut for :meth:`route` with ``methods=["PATCH"]``. + + .. versionadded:: 2.0 + """ + return self._method_route("PATCH", rule, options) + + @setupmethod + def route(self, rule: str, **options: t.Any) -> t.Callable[[T_route], T_route]: + """Decorate a view function to register it with the given URL + rule and options. Calls :meth:`add_url_rule`, which has more + details about the implementation. + + .. code-block:: python + + @app.route("/") + def index(): + return "Hello, World!" + + See :ref:`url-route-registrations`. + + The endpoint name for the route defaults to the name of the view + function if the ``endpoint`` parameter isn't passed. + + The ``methods`` parameter defaults to ``["GET"]``. ``HEAD`` and + ``OPTIONS`` are added automatically. + + :param rule: The URL rule string. + :param options: Extra options passed to the + :class:`~werkzeug.routing.Rule` object. + """ + + def decorator(f: T_route) -> T_route: + endpoint = options.pop("endpoint", None) + self.add_url_rule(rule, endpoint, f, **options) + return f + + return decorator + + @setupmethod + def add_url_rule( + self, + rule: str, + endpoint: str | None = None, + view_func: ft.RouteCallable | None = None, + provide_automatic_options: bool | None = None, + **options: t.Any, + ) -> None: + """Register a rule for routing incoming requests and building + URLs. The :meth:`route` decorator is a shortcut to call this + with the ``view_func`` argument. These are equivalent: + + .. code-block:: python + + @app.route("/") + def index(): + ... + + .. code-block:: python + + def index(): + ... + + app.add_url_rule("/", view_func=index) + + See :ref:`url-route-registrations`. + + The endpoint name for the route defaults to the name of the view + function if the ``endpoint`` parameter isn't passed. An error + will be raised if a function has already been registered for the + endpoint. + + The ``methods`` parameter defaults to ``["GET"]``. ``HEAD`` is + always added automatically, and ``OPTIONS`` is added + automatically by default. + + ``view_func`` does not necessarily need to be passed, but if the + rule should participate in routing an endpoint name must be + associated with a view function at some point with the + :meth:`endpoint` decorator. + + .. code-block:: python + + app.add_url_rule("/", endpoint="index") + + @app.endpoint("index") + def index(): + ... + + If ``view_func`` has a ``required_methods`` attribute, those + methods are added to the passed and automatic methods. If it + has a ``provide_automatic_methods`` attribute, it is used as the + default if the parameter is not passed. + + :param rule: The URL rule string. + :param endpoint: The endpoint name to associate with the rule + and view function. Used when routing and building URLs. + Defaults to ``view_func.__name__``. + :param view_func: The view function to associate with the + endpoint name. + :param provide_automatic_options: Add the ``OPTIONS`` method and + respond to ``OPTIONS`` requests automatically. + :param options: Extra options passed to the + :class:`~werkzeug.routing.Rule` object. + """ + raise NotImplementedError + + @setupmethod + def endpoint(self, endpoint: str) -> t.Callable[[F], F]: + """Decorate a view function to register it for the given + endpoint. Used if a rule is added without a ``view_func`` with + :meth:`add_url_rule`. + + .. code-block:: python + + app.add_url_rule("/ex", endpoint="example") + + @app.endpoint("example") + def example(): + ... + + :param endpoint: The endpoint name to associate with the view + function. + """ + + def decorator(f: F) -> F: + self.view_functions[endpoint] = f + return f + + return decorator + + @setupmethod + def before_request(self, f: T_before_request) -> T_before_request: + """Register a function to run before each request. + + For example, this can be used to open a database connection, or + to load the logged in user from the session. + + .. code-block:: python + + @app.before_request + def load_user(): + if "user_id" in session: + g.user = db.session.get(session["user_id"]) + + The function will be called without any arguments. If it returns + a non-``None`` value, the value is handled as if it was the + return value from the view, and further request handling is + stopped. + + This is available on both app and blueprint objects. When used on an app, this + executes before every request. When used on a blueprint, this executes before + every request that the blueprint handles. To register with a blueprint and + execute before every request, use :meth:`.Blueprint.before_app_request`. + """ + self.before_request_funcs.setdefault(None, []).append(f) + return f + + @setupmethod + def after_request(self, f: T_after_request) -> T_after_request: + """Register a function to run after each request to this object. + + The function is called with the response object, and must return + a response object. This allows the functions to modify or + replace the response before it is sent. + + If a function raises an exception, any remaining + ``after_request`` functions will not be called. Therefore, this + should not be used for actions that must execute, such as to + close resources. Use :meth:`teardown_request` for that. + + This is available on both app and blueprint objects. When used on an app, this + executes after every request. When used on a blueprint, this executes after + every request that the blueprint handles. To register with a blueprint and + execute after every request, use :meth:`.Blueprint.after_app_request`. + """ + self.after_request_funcs.setdefault(None, []).append(f) + return f + + @setupmethod + def teardown_request(self, f: T_teardown) -> T_teardown: + """Register a function to be called when the request context is + popped. Typically this happens at the end of each request, but + contexts may be pushed manually as well during testing. + + .. code-block:: python + + with app.test_request_context(): + ... + + When the ``with`` block exits (or ``ctx.pop()`` is called), the + teardown functions are called just before the request context is + made inactive. + + When a teardown function was called because of an unhandled + exception it will be passed an error object. If an + :meth:`errorhandler` is registered, it will handle the exception + and the teardown will not receive it. + + Teardown functions must avoid raising exceptions. If they + execute code that might fail they must surround that code with a + ``try``/``except`` block and log any errors. + + The return values of teardown functions are ignored. + + This is available on both app and blueprint objects. When used on an app, this + executes after every request. When used on a blueprint, this executes after + every request that the blueprint handles. To register with a blueprint and + execute after every request, use :meth:`.Blueprint.teardown_app_request`. + """ + self.teardown_request_funcs.setdefault(None, []).append(f) + return f + + @setupmethod + def context_processor( + self, + f: T_template_context_processor, + ) -> T_template_context_processor: + """Registers a template context processor function. These functions run before + rendering a template. The keys of the returned dict are added as variables + available in the template. + + This is available on both app and blueprint objects. When used on an app, this + is called for every rendered template. When used on a blueprint, this is called + for templates rendered from the blueprint's views. To register with a blueprint + and affect every template, use :meth:`.Blueprint.app_context_processor`. + """ + self.template_context_processors[None].append(f) + return f + + @setupmethod + def url_value_preprocessor( + self, + f: T_url_value_preprocessor, + ) -> T_url_value_preprocessor: + """Register a URL value preprocessor function for all view + functions in the application. These functions will be called before the + :meth:`before_request` functions. + + The function can modify the values captured from the matched url before + they are passed to the view. For example, this can be used to pop a + common language code value and place it in ``g`` rather than pass it to + every view. + + The function is passed the endpoint name and values dict. The return + value is ignored. + + This is available on both app and blueprint objects. When used on an app, this + is called for every request. When used on a blueprint, this is called for + requests that the blueprint handles. To register with a blueprint and affect + every request, use :meth:`.Blueprint.app_url_value_preprocessor`. + """ + self.url_value_preprocessors[None].append(f) + return f + + @setupmethod + def url_defaults(self, f: T_url_defaults) -> T_url_defaults: + """Callback function for URL defaults for all view functions of the + application. It's called with the endpoint and values and should + update the values passed in place. + + This is available on both app and blueprint objects. When used on an app, this + is called for every request. When used on a blueprint, this is called for + requests that the blueprint handles. To register with a blueprint and affect + every request, use :meth:`.Blueprint.app_url_defaults`. + """ + self.url_default_functions[None].append(f) + return f + + @setupmethod + def errorhandler( + self, code_or_exception: type[Exception] | int + ) -> t.Callable[[T_error_handler], T_error_handler]: + """Register a function to handle errors by code or exception class. + + A decorator that is used to register a function given an + error code. Example:: + + @app.errorhandler(404) + def page_not_found(error): + return 'This page does not exist', 404 + + You can also register handlers for arbitrary exceptions:: + + @app.errorhandler(DatabaseError) + def special_exception_handler(error): + return 'Database connection failed', 500 + + This is available on both app and blueprint objects. When used on an app, this + can handle errors from every request. When used on a blueprint, this can handle + errors from requests that the blueprint handles. To register with a blueprint + and affect every request, use :meth:`.Blueprint.app_errorhandler`. + + .. versionadded:: 0.7 + Use :meth:`register_error_handler` instead of modifying + :attr:`error_handler_spec` directly, for application wide error + handlers. + + .. versionadded:: 0.7 + One can now additionally also register custom exception types + that do not necessarily have to be a subclass of the + :class:`~werkzeug.exceptions.HTTPException` class. + + :param code_or_exception: the code as integer for the handler, or + an arbitrary exception + """ + + def decorator(f: T_error_handler) -> T_error_handler: + self.register_error_handler(code_or_exception, f) + return f + + return decorator + + @setupmethod + def register_error_handler( + self, + code_or_exception: type[Exception] | int, + f: ft.ErrorHandlerCallable, + ) -> None: + """Alternative error attach function to the :meth:`errorhandler` + decorator that is more straightforward to use for non decorator + usage. + + .. versionadded:: 0.7 + """ + exc_class, code = self._get_exc_class_and_code(code_or_exception) + self.error_handler_spec[None][code][exc_class] = f + + @staticmethod + def _get_exc_class_and_code( + exc_class_or_code: type[Exception] | int, + ) -> tuple[type[Exception], int | None]: + """Get the exception class being handled. For HTTP status codes + or ``HTTPException`` subclasses, return both the exception and + status code. + + :param exc_class_or_code: Any exception class, or an HTTP status + code as an integer. + """ + exc_class: type[Exception] + + if isinstance(exc_class_or_code, int): + try: + exc_class = default_exceptions[exc_class_or_code] + except KeyError: + raise ValueError( + f"'{exc_class_or_code}' is not a recognized HTTP" + " error code. Use a subclass of HTTPException with" + " that code instead." + ) from None + else: + exc_class = exc_class_or_code + + if isinstance(exc_class, Exception): + raise TypeError( + f"{exc_class!r} is an instance, not a class. Handlers" + " can only be registered for Exception classes or HTTP" + " error codes." + ) + + if not issubclass(exc_class, Exception): + raise ValueError( + f"'{exc_class.__name__}' is not a subclass of Exception." + " Handlers can only be registered for Exception classes" + " or HTTP error codes." + ) + + if issubclass(exc_class, HTTPException): + return exc_class, exc_class.code + else: + return exc_class, None + + +def _endpoint_from_view_func(view_func: ft.RouteCallable) -> str: + """Internal helper that returns the default endpoint for a given + function. This always is the function name. + """ + assert view_func is not None, "expected view func if endpoint is not provided." + return view_func.__name__ + + +def _find_package_path(import_name: str) -> str: + """Find the path that contains the package or module.""" + root_mod_name, _, _ = import_name.partition(".") + + try: + root_spec = importlib.util.find_spec(root_mod_name) + + if root_spec is None: + raise ValueError("not found") + except (ImportError, ValueError): + # ImportError: the machinery told us it does not exist + # ValueError: + # - the module name was invalid + # - the module name is __main__ + # - we raised `ValueError` due to `root_spec` being `None` + return os.getcwd() + + if root_spec.submodule_search_locations: + if root_spec.origin is None or root_spec.origin == "namespace": + # namespace package + package_spec = importlib.util.find_spec(import_name) + + if package_spec is not None and package_spec.submodule_search_locations: + # Pick the path in the namespace that contains the submodule. + package_path = pathlib.Path( + os.path.commonpath(package_spec.submodule_search_locations) + ) + search_location = next( + location + for location in root_spec.submodule_search_locations + if package_path.is_relative_to(location) + ) + else: + # Pick the first path. + search_location = root_spec.submodule_search_locations[0] + + return os.path.dirname(search_location) + else: + # package with __init__.py + return os.path.dirname(os.path.dirname(root_spec.origin)) + else: + # module + return os.path.dirname(root_spec.origin) # type: ignore[type-var, return-value] + + +def find_package(import_name: str) -> tuple[str | None, str]: + """Find the prefix that a package is installed under, and the path + that it would be imported from. + + The prefix is the directory containing the standard directory + hierarchy (lib, bin, etc.). If the package is not installed to the + system (:attr:`sys.prefix`) or a virtualenv (``site-packages``), + ``None`` is returned. + + The path is the entry in :attr:`sys.path` that contains the package + for import. If the package is not installed, it's assumed that the + package was imported from the current working directory. + """ + package_path = _find_package_path(import_name) + py_prefix = os.path.abspath(sys.prefix) + + # installed to the system + if pathlib.PurePath(package_path).is_relative_to(py_prefix): + return py_prefix, package_path + + site_parent, site_folder = os.path.split(package_path) + + # installed to a virtualenv + if site_folder.lower() == "site-packages": + parent, folder = os.path.split(site_parent) + + # Windows (prefix/lib/site-packages) + if folder.lower() == "lib": + return parent, package_path + + # Unix (prefix/lib/pythonX.Y/site-packages) + if os.path.basename(parent).lower() == "lib": + return os.path.dirname(parent), package_path + + # something else (prefix/site-packages) + return site_parent, package_path + + # not installed + return None, package_path diff --git a/python/user_packages/Python313/site-packages/flatbuffers/__pycache__/__init__.cpython-313.pyc b/python/user_packages/Python313/site-packages/flatbuffers/__pycache__/__init__.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5faaaa923f2b3de69a5a0d45ee02b8c50f24e067 Binary files /dev/null and b/python/user_packages/Python313/site-packages/flatbuffers/__pycache__/__init__.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/flatbuffers/__pycache__/_version.cpython-313.pyc b/python/user_packages/Python313/site-packages/flatbuffers/__pycache__/_version.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8cf8a0b9f9fcd1945eda5906d5c965b4dd8ddb0c Binary files /dev/null and b/python/user_packages/Python313/site-packages/flatbuffers/__pycache__/_version.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/flatbuffers/__pycache__/builder.cpython-313.pyc b/python/user_packages/Python313/site-packages/flatbuffers/__pycache__/builder.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7da7a6571ff56c361cbf4764bfe3b07593b77e2b Binary files /dev/null and b/python/user_packages/Python313/site-packages/flatbuffers/__pycache__/builder.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/flatbuffers/__pycache__/compat.cpython-313.pyc b/python/user_packages/Python313/site-packages/flatbuffers/__pycache__/compat.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c1041c453994bc25352f38c5f9126dd982d31371 Binary files /dev/null and b/python/user_packages/Python313/site-packages/flatbuffers/__pycache__/compat.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/flatbuffers/__pycache__/encode.cpython-313.pyc b/python/user_packages/Python313/site-packages/flatbuffers/__pycache__/encode.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f0c3a33e61c077959a2a7d91a1532680efbe5a9e Binary files /dev/null and b/python/user_packages/Python313/site-packages/flatbuffers/__pycache__/encode.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/flatbuffers/__pycache__/flexbuffers.cpython-313.pyc b/python/user_packages/Python313/site-packages/flatbuffers/__pycache__/flexbuffers.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d3d9bbb18ebfd77cd1919ea630ac6bab800d66bd Binary files /dev/null and b/python/user_packages/Python313/site-packages/flatbuffers/__pycache__/flexbuffers.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/flatbuffers/__pycache__/number_types.cpython-313.pyc b/python/user_packages/Python313/site-packages/flatbuffers/__pycache__/number_types.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3a36fb48ab4e051e8f1e3ea12f5700a0d90f9c71 Binary files /dev/null and b/python/user_packages/Python313/site-packages/flatbuffers/__pycache__/number_types.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/flatbuffers/__pycache__/packer.cpython-313.pyc b/python/user_packages/Python313/site-packages/flatbuffers/__pycache__/packer.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..425ad83afed22371b4bac006ec61e8998befde7a Binary files /dev/null and b/python/user_packages/Python313/site-packages/flatbuffers/__pycache__/packer.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/flatbuffers/__pycache__/table.cpython-313.pyc b/python/user_packages/Python313/site-packages/flatbuffers/__pycache__/table.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..cc6c40e2c063a69ee1a587aa495ccb029b2786c0 Binary files /dev/null and b/python/user_packages/Python313/site-packages/flatbuffers/__pycache__/table.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/flatbuffers/__pycache__/util.cpython-313.pyc b/python/user_packages/Python313/site-packages/flatbuffers/__pycache__/util.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..950c296b3e5a1ca35622b3c90e5cdef282b514ff Binary files /dev/null and b/python/user_packages/Python313/site-packages/flatbuffers/__pycache__/util.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/frozenlist-1.8.0.dist-info/licenses/LICENSE b/python/user_packages/Python313/site-packages/frozenlist-1.8.0.dist-info/licenses/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..7082a2d5b9047bfc09589f387053e24ea490bc54 --- /dev/null +++ b/python/user_packages/Python313/site-packages/frozenlist-1.8.0.dist-info/licenses/LICENSE @@ -0,0 +1,201 @@ +Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "{}" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright 2013-2019 Nikolay Kim and Andrew Svetlov + + 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/python/user_packages/Python313/site-packages/frozenlist/__pycache__/__init__.cpython-313.pyc b/python/user_packages/Python313/site-packages/frozenlist/__pycache__/__init__.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1fddaf99bf6b287108bcf96fca380089e68f1087 Binary files /dev/null and b/python/user_packages/Python313/site-packages/frozenlist/__pycache__/__init__.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/fsspec-2026.4.0.dist-info/licenses/LICENSE b/python/user_packages/Python313/site-packages/fsspec-2026.4.0.dist-info/licenses/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..67590a5e5be5a5a2dde3fe53a7512e404a896c22 --- /dev/null +++ b/python/user_packages/Python313/site-packages/fsspec-2026.4.0.dist-info/licenses/LICENSE @@ -0,0 +1,29 @@ +BSD 3-Clause License + +Copyright (c) 2018, Martin Durant +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 copyright holder 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. diff --git a/python/user_packages/Python313/site-packages/fsspec/__pycache__/__init__.cpython-313.pyc b/python/user_packages/Python313/site-packages/fsspec/__pycache__/__init__.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..11dcf91c38c1108d4d72d0c2d2a55245232fdbec Binary files /dev/null and b/python/user_packages/Python313/site-packages/fsspec/__pycache__/__init__.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/fsspec/__pycache__/_version.cpython-313.pyc b/python/user_packages/Python313/site-packages/fsspec/__pycache__/_version.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e1904021cf456348c31743fe1f2cc89b03d54f8f Binary files /dev/null and b/python/user_packages/Python313/site-packages/fsspec/__pycache__/_version.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/fsspec/__pycache__/archive.cpython-313.pyc b/python/user_packages/Python313/site-packages/fsspec/__pycache__/archive.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..bec5aee1ee6dffe22df550d4b5f92c51c1ab0af1 Binary files /dev/null and b/python/user_packages/Python313/site-packages/fsspec/__pycache__/archive.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/fsspec/__pycache__/asyn.cpython-313.pyc b/python/user_packages/Python313/site-packages/fsspec/__pycache__/asyn.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..def17b9dc5d11df8604daf110b273842ad268100 Binary files /dev/null and b/python/user_packages/Python313/site-packages/fsspec/__pycache__/asyn.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/fsspec/__pycache__/caching.cpython-313.pyc b/python/user_packages/Python313/site-packages/fsspec/__pycache__/caching.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..13317ed0cde97bf649ba3be43573e98aae66ae9f Binary files /dev/null and b/python/user_packages/Python313/site-packages/fsspec/__pycache__/caching.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/fsspec/__pycache__/callbacks.cpython-313.pyc b/python/user_packages/Python313/site-packages/fsspec/__pycache__/callbacks.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..29fa38439abc825b5cbf2defef2d9cbf5119b0da Binary files /dev/null and b/python/user_packages/Python313/site-packages/fsspec/__pycache__/callbacks.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/fsspec/__pycache__/compression.cpython-313.pyc b/python/user_packages/Python313/site-packages/fsspec/__pycache__/compression.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..947540142b524a729d0f1f2009dd078cda218089 Binary files /dev/null and b/python/user_packages/Python313/site-packages/fsspec/__pycache__/compression.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/fsspec/__pycache__/config.cpython-313.pyc b/python/user_packages/Python313/site-packages/fsspec/__pycache__/config.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..117a288de2ec66f8fcdc94f5cb12e25c8dade84d Binary files /dev/null and b/python/user_packages/Python313/site-packages/fsspec/__pycache__/config.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/fsspec/__pycache__/conftest.cpython-313.pyc b/python/user_packages/Python313/site-packages/fsspec/__pycache__/conftest.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0665b4af8bac6af6a3b2f6bf23afbb1b5ef1b8ac Binary files /dev/null and b/python/user_packages/Python313/site-packages/fsspec/__pycache__/conftest.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/fsspec/__pycache__/core.cpython-313.pyc b/python/user_packages/Python313/site-packages/fsspec/__pycache__/core.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..aa77c40b6c55f153d5202703fcf2ae4d098f6766 Binary files /dev/null and b/python/user_packages/Python313/site-packages/fsspec/__pycache__/core.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/fsspec/__pycache__/dircache.cpython-313.pyc b/python/user_packages/Python313/site-packages/fsspec/__pycache__/dircache.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..78541394fee12c41a5314f83f2708d8dfa39ea54 Binary files /dev/null and b/python/user_packages/Python313/site-packages/fsspec/__pycache__/dircache.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/fsspec/__pycache__/exceptions.cpython-313.pyc b/python/user_packages/Python313/site-packages/fsspec/__pycache__/exceptions.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a6ba6c6058fc0ac9cd12cb12e2a7eb47c3c687d2 Binary files /dev/null and b/python/user_packages/Python313/site-packages/fsspec/__pycache__/exceptions.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/fsspec/__pycache__/fuse.cpython-313.pyc b/python/user_packages/Python313/site-packages/fsspec/__pycache__/fuse.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5b49a7e2c00d278edd3cc05365cfada7be1a8e54 Binary files /dev/null and b/python/user_packages/Python313/site-packages/fsspec/__pycache__/fuse.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/fsspec/__pycache__/generic.cpython-313.pyc b/python/user_packages/Python313/site-packages/fsspec/__pycache__/generic.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f8b49cf49f103856b021fe6222886663dedc8c2b Binary files /dev/null and b/python/user_packages/Python313/site-packages/fsspec/__pycache__/generic.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/fsspec/__pycache__/gui.cpython-313.pyc b/python/user_packages/Python313/site-packages/fsspec/__pycache__/gui.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..df5b16df83640e141ae5dd13402d8deaa8ca93e6 Binary files /dev/null and b/python/user_packages/Python313/site-packages/fsspec/__pycache__/gui.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/fsspec/__pycache__/json.cpython-313.pyc b/python/user_packages/Python313/site-packages/fsspec/__pycache__/json.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..997ff11f4cea238830e62635fac10966bb7324de Binary files /dev/null and b/python/user_packages/Python313/site-packages/fsspec/__pycache__/json.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/fsspec/__pycache__/mapping.cpython-313.pyc b/python/user_packages/Python313/site-packages/fsspec/__pycache__/mapping.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..90b82fb816937bc3c6838e846033d8a2d29757da Binary files /dev/null and b/python/user_packages/Python313/site-packages/fsspec/__pycache__/mapping.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/fsspec/__pycache__/parquet.cpython-313.pyc b/python/user_packages/Python313/site-packages/fsspec/__pycache__/parquet.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..57c06b05fd704df76a941f0e867b9f8717886725 Binary files /dev/null and b/python/user_packages/Python313/site-packages/fsspec/__pycache__/parquet.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/fsspec/__pycache__/registry.cpython-313.pyc b/python/user_packages/Python313/site-packages/fsspec/__pycache__/registry.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..15a6b51dd561465d57e116dd2276373a047d0fbb Binary files /dev/null and b/python/user_packages/Python313/site-packages/fsspec/__pycache__/registry.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/fsspec/__pycache__/spec.cpython-313.pyc b/python/user_packages/Python313/site-packages/fsspec/__pycache__/spec.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..439647aa0668200681908acdd7928b8c22629ea0 Binary files /dev/null and b/python/user_packages/Python313/site-packages/fsspec/__pycache__/spec.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/fsspec/__pycache__/transaction.cpython-313.pyc b/python/user_packages/Python313/site-packages/fsspec/__pycache__/transaction.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c5724d6bf02c2e12aafb8f0d0f15a29dca9fbec7 Binary files /dev/null and b/python/user_packages/Python313/site-packages/fsspec/__pycache__/transaction.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/fsspec/__pycache__/utils.cpython-313.pyc b/python/user_packages/Python313/site-packages/fsspec/__pycache__/utils.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ad8a637b9814ecc485449ade65fe5117fa3708d5 Binary files /dev/null and b/python/user_packages/Python313/site-packages/fsspec/__pycache__/utils.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/fsspec/implementations/__init__.py b/python/user_packages/Python313/site-packages/fsspec/implementations/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/python/user_packages/Python313/site-packages/fsspec/implementations/__pycache__/__init__.cpython-313.pyc b/python/user_packages/Python313/site-packages/fsspec/implementations/__pycache__/__init__.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7bcee407cb12a6a00ee046be01b9bc599a1a2dbe Binary files /dev/null and b/python/user_packages/Python313/site-packages/fsspec/implementations/__pycache__/__init__.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/fsspec/implementations/__pycache__/arrow.cpython-313.pyc b/python/user_packages/Python313/site-packages/fsspec/implementations/__pycache__/arrow.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f8eabf893000c751f8091f5d776d59f2bc300a8f Binary files /dev/null and b/python/user_packages/Python313/site-packages/fsspec/implementations/__pycache__/arrow.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/fsspec/implementations/__pycache__/asyn_wrapper.cpython-313.pyc b/python/user_packages/Python313/site-packages/fsspec/implementations/__pycache__/asyn_wrapper.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..055ad8f30aa8e5ae3bcfcf32df30c48f81ef090c Binary files /dev/null and b/python/user_packages/Python313/site-packages/fsspec/implementations/__pycache__/asyn_wrapper.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/fsspec/implementations/__pycache__/cache_mapper.cpython-313.pyc b/python/user_packages/Python313/site-packages/fsspec/implementations/__pycache__/cache_mapper.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..74f84a7df7f2b00c3f630bcb0ce19b5959baf7f9 Binary files /dev/null and b/python/user_packages/Python313/site-packages/fsspec/implementations/__pycache__/cache_mapper.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/fsspec/implementations/__pycache__/cache_metadata.cpython-313.pyc b/python/user_packages/Python313/site-packages/fsspec/implementations/__pycache__/cache_metadata.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..94ca2711ac91748f6901fc46d3de26a39c8c6adf Binary files /dev/null and b/python/user_packages/Python313/site-packages/fsspec/implementations/__pycache__/cache_metadata.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/fsspec/implementations/__pycache__/cached.cpython-313.pyc b/python/user_packages/Python313/site-packages/fsspec/implementations/__pycache__/cached.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6172c65dae17a6e7006afad8d9cffcd5d7d89ebf Binary files /dev/null and b/python/user_packages/Python313/site-packages/fsspec/implementations/__pycache__/cached.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/fsspec/implementations/__pycache__/chained.cpython-313.pyc b/python/user_packages/Python313/site-packages/fsspec/implementations/__pycache__/chained.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f1d76fd78c438b109f3caaf732258d8448983a77 Binary files /dev/null and b/python/user_packages/Python313/site-packages/fsspec/implementations/__pycache__/chained.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/fsspec/implementations/__pycache__/dask.cpython-313.pyc b/python/user_packages/Python313/site-packages/fsspec/implementations/__pycache__/dask.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e8e0d8d69241e2f2c612808de1448b610a718288 Binary files /dev/null and b/python/user_packages/Python313/site-packages/fsspec/implementations/__pycache__/dask.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/fsspec/implementations/__pycache__/data.cpython-313.pyc b/python/user_packages/Python313/site-packages/fsspec/implementations/__pycache__/data.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e194a8bf6fe0dd02e5317fb3aad7a8bf3102ddf8 Binary files /dev/null and b/python/user_packages/Python313/site-packages/fsspec/implementations/__pycache__/data.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/fsspec/implementations/__pycache__/dbfs.cpython-313.pyc b/python/user_packages/Python313/site-packages/fsspec/implementations/__pycache__/dbfs.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e9ac16aea28505d6ff60ea00d56372f081b1d711 Binary files /dev/null and b/python/user_packages/Python313/site-packages/fsspec/implementations/__pycache__/dbfs.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/fsspec/implementations/__pycache__/dirfs.cpython-313.pyc b/python/user_packages/Python313/site-packages/fsspec/implementations/__pycache__/dirfs.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e91e7f7ce2a039b01e6edbf4f600ff6b1ca2e8fc Binary files /dev/null and b/python/user_packages/Python313/site-packages/fsspec/implementations/__pycache__/dirfs.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/fsspec/implementations/__pycache__/ftp.cpython-313.pyc b/python/user_packages/Python313/site-packages/fsspec/implementations/__pycache__/ftp.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..21bd9597090b3866ab05677dedf985f36811bf03 Binary files /dev/null and b/python/user_packages/Python313/site-packages/fsspec/implementations/__pycache__/ftp.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/fsspec/implementations/__pycache__/gist.cpython-313.pyc b/python/user_packages/Python313/site-packages/fsspec/implementations/__pycache__/gist.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..04310ddb96724a87bb608fd2179ca37d4db7930e Binary files /dev/null and b/python/user_packages/Python313/site-packages/fsspec/implementations/__pycache__/gist.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/fsspec/implementations/__pycache__/git.cpython-313.pyc b/python/user_packages/Python313/site-packages/fsspec/implementations/__pycache__/git.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..66118928fda77c3416da66ed18149725581d6a50 Binary files /dev/null and b/python/user_packages/Python313/site-packages/fsspec/implementations/__pycache__/git.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/fsspec/implementations/__pycache__/github.cpython-313.pyc b/python/user_packages/Python313/site-packages/fsspec/implementations/__pycache__/github.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c1b1d2958dc9a65c67357d332e12ef57119b8031 Binary files /dev/null and b/python/user_packages/Python313/site-packages/fsspec/implementations/__pycache__/github.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/fsspec/implementations/__pycache__/http.cpython-313.pyc b/python/user_packages/Python313/site-packages/fsspec/implementations/__pycache__/http.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5d9f57110430661a504de16ab6369a91c910d1bc Binary files /dev/null and b/python/user_packages/Python313/site-packages/fsspec/implementations/__pycache__/http.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/fsspec/implementations/__pycache__/http_sync.cpython-313.pyc b/python/user_packages/Python313/site-packages/fsspec/implementations/__pycache__/http_sync.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2dc0967f52773fa118736230c638d24a8a5afac7 Binary files /dev/null and b/python/user_packages/Python313/site-packages/fsspec/implementations/__pycache__/http_sync.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/fsspec/implementations/__pycache__/jupyter.cpython-313.pyc b/python/user_packages/Python313/site-packages/fsspec/implementations/__pycache__/jupyter.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..bd08b2d4deb1f3427b52960036f9d93c8a862a6d Binary files /dev/null and b/python/user_packages/Python313/site-packages/fsspec/implementations/__pycache__/jupyter.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/fsspec/implementations/__pycache__/libarchive.cpython-313.pyc b/python/user_packages/Python313/site-packages/fsspec/implementations/__pycache__/libarchive.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0c1a04e225c4c38d85161d6a058fb2fa58e53b6d Binary files /dev/null and b/python/user_packages/Python313/site-packages/fsspec/implementations/__pycache__/libarchive.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/fsspec/implementations/__pycache__/local.cpython-313.pyc b/python/user_packages/Python313/site-packages/fsspec/implementations/__pycache__/local.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1aca3193f7b089b0b0ad0f1d2262fb4d843fbf8f Binary files /dev/null and b/python/user_packages/Python313/site-packages/fsspec/implementations/__pycache__/local.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/fsspec/implementations/__pycache__/memory.cpython-313.pyc b/python/user_packages/Python313/site-packages/fsspec/implementations/__pycache__/memory.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7aa26926662bf8850446789ca14f565cc927cd34 Binary files /dev/null and b/python/user_packages/Python313/site-packages/fsspec/implementations/__pycache__/memory.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/fsspec/implementations/__pycache__/reference.cpython-313.pyc b/python/user_packages/Python313/site-packages/fsspec/implementations/__pycache__/reference.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d2cc757b74f39ffc404237600d27864fbcfe06f5 Binary files /dev/null and b/python/user_packages/Python313/site-packages/fsspec/implementations/__pycache__/reference.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/fsspec/implementations/__pycache__/sftp.cpython-313.pyc b/python/user_packages/Python313/site-packages/fsspec/implementations/__pycache__/sftp.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9ae253f9cf984ca3809f79af95f6e08a3cbac173 Binary files /dev/null and b/python/user_packages/Python313/site-packages/fsspec/implementations/__pycache__/sftp.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/fsspec/implementations/__pycache__/smb.cpython-313.pyc b/python/user_packages/Python313/site-packages/fsspec/implementations/__pycache__/smb.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b20c2933ea99ca95a878986a2ab595540b80bed2 Binary files /dev/null and b/python/user_packages/Python313/site-packages/fsspec/implementations/__pycache__/smb.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/fsspec/implementations/__pycache__/tar.cpython-313.pyc b/python/user_packages/Python313/site-packages/fsspec/implementations/__pycache__/tar.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d858a0ff3d16624ae96d41a6813c32d70ce2471a Binary files /dev/null and b/python/user_packages/Python313/site-packages/fsspec/implementations/__pycache__/tar.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/fsspec/implementations/__pycache__/webhdfs.cpython-313.pyc b/python/user_packages/Python313/site-packages/fsspec/implementations/__pycache__/webhdfs.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d6e53ec65018e73821614d62783de95d6290abf8 Binary files /dev/null and b/python/user_packages/Python313/site-packages/fsspec/implementations/__pycache__/webhdfs.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/fsspec/implementations/__pycache__/zip.cpython-313.pyc b/python/user_packages/Python313/site-packages/fsspec/implementations/__pycache__/zip.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1ff2c88ef4b8ef0692600938aa2dfaf400922adf Binary files /dev/null and b/python/user_packages/Python313/site-packages/fsspec/implementations/__pycache__/zip.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/fsspec/implementations/arrow.py b/python/user_packages/Python313/site-packages/fsspec/implementations/arrow.py new file mode 100644 index 0000000000000000000000000000000000000000..227d50930763f56bc8c01556249eb1306347350b --- /dev/null +++ b/python/user_packages/Python313/site-packages/fsspec/implementations/arrow.py @@ -0,0 +1,312 @@ +import errno +import io +import os +import secrets +import shutil +from contextlib import suppress +from functools import cached_property, wraps +from urllib.parse import parse_qs + +from fsspec.spec import AbstractFileSystem +from fsspec.utils import ( + get_package_version_without_import, + infer_storage_options, + mirror_from, + tokenize, +) + + +def wrap_exceptions(func): + @wraps(func) + def wrapper(*args, **kwargs): + try: + return func(*args, **kwargs) + except OSError as exception: + if not exception.args: + raise + + message, *args = exception.args + if isinstance(message, str) and "does not exist" in message: + raise FileNotFoundError(errno.ENOENT, message) from exception + else: + raise + + return wrapper + + +PYARROW_VERSION = None + + +class ArrowFSWrapper(AbstractFileSystem): + """FSSpec-compatible wrapper of pyarrow.fs.FileSystem. + + Parameters + ---------- + fs : pyarrow.fs.FileSystem + + """ + + root_marker = "/" + + def __init__(self, fs, **kwargs): + global PYARROW_VERSION + PYARROW_VERSION = get_package_version_without_import("pyarrow") + self.fs = fs + super().__init__(**kwargs) + + @property + def protocol(self): + return self.fs.type_name + + @cached_property + def fsid(self): + return "hdfs_" + tokenize(self.fs.host, self.fs.port) + + @classmethod + def _strip_protocol(cls, path): + ops = infer_storage_options(path) + path = ops["path"] + if path.startswith("//"): + # special case for "hdfs://path" (without the triple slash) + path = path[1:] + return path + + def ls(self, path, detail=False, **kwargs): + path = self._strip_protocol(path) + from pyarrow.fs import FileSelector + + try: + entries = [ + self._make_entry(entry) + for entry in self.fs.get_file_info(FileSelector(path)) + ] + except (FileNotFoundError, NotADirectoryError): + entries = [self.info(path, **kwargs)] + if detail: + return entries + else: + return [entry["name"] for entry in entries] + + def info(self, path, **kwargs): + path = self._strip_protocol(path) + [info] = self.fs.get_file_info([path]) + return self._make_entry(info) + + def exists(self, path): + path = self._strip_protocol(path) + try: + self.info(path) + except FileNotFoundError: + return False + else: + return True + + def _make_entry(self, info): + from pyarrow.fs import FileType + + if info.type is FileType.Directory: + kind = "directory" + elif info.type is FileType.File: + kind = "file" + elif info.type is FileType.NotFound: + raise FileNotFoundError(errno.ENOENT, os.strerror(errno.ENOENT), info.path) + else: + kind = "other" + + return { + "name": info.path, + "size": info.size, + "type": kind, + "mtime": info.mtime, + } + + @wrap_exceptions + def cp_file(self, path1, path2, **kwargs): + path1 = self._strip_protocol(path1).rstrip("/") + path2 = self._strip_protocol(path2).rstrip("/") + + with self._open(path1, "rb") as lstream: + tmp_fname = f"{path2}.tmp.{secrets.token_hex(6)}" + try: + with self.open(tmp_fname, "wb") as rstream: + shutil.copyfileobj(lstream, rstream) + self.fs.move(tmp_fname, path2) + except BaseException: + with suppress(FileNotFoundError): + self.fs.delete_file(tmp_fname) + raise + + @wrap_exceptions + def mv(self, path1, path2, **kwargs): + path1 = self._strip_protocol(path1).rstrip("/") + path2 = self._strip_protocol(path2).rstrip("/") + self.fs.move(path1, path2) + + @wrap_exceptions + def rm_file(self, path): + path = self._strip_protocol(path) + self.fs.delete_file(path) + + @wrap_exceptions + def rm(self, path, recursive=False, maxdepth=None): + path = self._strip_protocol(path).rstrip("/") + if self.isdir(path): + if recursive: + self.fs.delete_dir(path) + else: + raise ValueError("Can't delete directories without recursive=False") + else: + self.fs.delete_file(path) + + @wrap_exceptions + def _open(self, path, mode="rb", block_size=None, seekable=True, **kwargs): + if mode == "rb": + if seekable: + method = self.fs.open_input_file + else: + method = self.fs.open_input_stream + elif mode == "wb": + method = self.fs.open_output_stream + elif mode == "ab": + method = self.fs.open_append_stream + else: + raise ValueError(f"unsupported mode for Arrow filesystem: {mode!r}") + + _kwargs = {} + if mode != "rb" or not seekable: + if int(PYARROW_VERSION.split(".")[0]) >= 4: + # disable compression auto-detection + _kwargs["compression"] = None + stream = method(path, **_kwargs) + + return ArrowFile(self, stream, path, mode, block_size, **kwargs) + + @wrap_exceptions + def mkdir(self, path, create_parents=True, **kwargs): + path = self._strip_protocol(path) + if create_parents: + self.makedirs(path, exist_ok=True) + else: + self.fs.create_dir(path, recursive=False) + + @wrap_exceptions + def makedirs(self, path, exist_ok=False): + path = self._strip_protocol(path) + self.fs.create_dir(path, recursive=True) + + @wrap_exceptions + def rmdir(self, path): + path = self._strip_protocol(path) + self.fs.delete_dir(path) + + @wrap_exceptions + def modified(self, path): + path = self._strip_protocol(path) + return self.fs.get_file_info(path).mtime + + def cat_file(self, path, start=None, end=None, **kwargs): + kwargs.setdefault("seekable", start not in [None, 0]) + return super().cat_file(path, start=None, end=None, **kwargs) + + def get_file(self, rpath, lpath, **kwargs): + kwargs.setdefault("seekable", False) + super().get_file(rpath, lpath, **kwargs) + + +@mirror_from( + "stream", + [ + "read", + "seek", + "tell", + "write", + "readable", + "writable", + "close", + "seekable", + ], +) +class ArrowFile(io.IOBase): + def __init__(self, fs, stream, path, mode, block_size=None, **kwargs): + self.path = path + self.mode = mode + + self.fs = fs + self.stream = stream + + self.blocksize = self.block_size = block_size + self.kwargs = kwargs + + def __enter__(self): + return self + + @property + def size(self): + if self.stream.seekable(): + return self.stream.size() + return None + + def __exit__(self, *args): + return self.close() + + +class HadoopFileSystem(ArrowFSWrapper): + """A wrapper on top of the pyarrow.fs.HadoopFileSystem + to connect it's interface with fsspec""" + + protocol = "hdfs" + + def __init__( + self, + host="default", + port=0, + user=None, + kerb_ticket=None, + replication=3, + extra_conf=None, + **kwargs, + ): + """ + + Parameters + ---------- + host: str + Hostname, IP or "default" to try to read from Hadoop config + port: int + Port to connect on, or default from Hadoop config if 0 + user: str or None + If given, connect as this username + kerb_ticket: str or None + If given, use this ticket for authentication + replication: int + set replication factor of file for write operations. default value is 3. + extra_conf: None or dict + Passed on to HadoopFileSystem + """ + from pyarrow.fs import HadoopFileSystem + + fs = HadoopFileSystem( + host=host, + port=port, + user=user, + kerb_ticket=kerb_ticket, + replication=replication, + extra_conf=extra_conf, + ) + super().__init__(fs=fs, **kwargs) + + @staticmethod + def _get_kwargs_from_urls(path): + ops = infer_storage_options(path) + out = {} + if ops.get("host", None): + out["host"] = ops["host"] + if ops.get("username", None): + out["user"] = ops["username"] + if ops.get("port", None): + out["port"] = ops["port"] + if ops.get("url_query", None): + queries = parse_qs(ops["url_query"]) + if queries.get("replication", None): + out["replication"] = int(queries["replication"][0]) + return out diff --git a/python/user_packages/Python313/site-packages/fsspec/implementations/asyn_wrapper.py b/python/user_packages/Python313/site-packages/fsspec/implementations/asyn_wrapper.py new file mode 100644 index 0000000000000000000000000000000000000000..91db5eb48d00e36b46d9deb49504a7d2ad76d690 --- /dev/null +++ b/python/user_packages/Python313/site-packages/fsspec/implementations/asyn_wrapper.py @@ -0,0 +1,124 @@ +import asyncio +import functools +import inspect + +import fsspec +from fsspec.asyn import AsyncFileSystem, running_async + +from .chained import ChainedFileSystem + + +def async_wrapper(func, obj=None, semaphore=None): + """ + Wraps a synchronous function to make it awaitable. + + Parameters + ---------- + func : callable + The synchronous function to wrap. + obj : object, optional + The instance to bind the function to, if applicable. + semaphore : asyncio.Semaphore, optional + A semaphore to limit concurrent calls. + + Returns + ------- + coroutine + An awaitable version of the function. + """ + + @functools.wraps(func) + async def wrapper(*args, **kwargs): + if semaphore: + async with semaphore: + return await asyncio.to_thread(func, *args, **kwargs) + return await asyncio.to_thread(func, *args, **kwargs) + + return wrapper + + +class AsyncFileSystemWrapper(AsyncFileSystem, ChainedFileSystem): + """ + A wrapper class to convert a synchronous filesystem into an asynchronous one. + + This class takes an existing synchronous filesystem implementation and wraps all + its methods to provide an asynchronous interface. + + Parameters + ---------- + sync_fs : AbstractFileSystem + The synchronous filesystem instance to wrap. + """ + + protocol = "asyncwrapper", "async_wrapper" + cachable = False + + def __init__( + self, + fs=None, + asynchronous=None, + target_protocol=None, + target_options=None, + semaphore=None, + max_concurrent_tasks=None, + **kwargs, + ): + if asynchronous is None: + asynchronous = running_async() + super().__init__(asynchronous=asynchronous, **kwargs) + if fs is not None: + self.sync_fs = fs + else: + self.sync_fs = fsspec.filesystem(target_protocol, **target_options) + self.protocol = self.sync_fs.protocol + self.semaphore = semaphore + self._wrap_all_sync_methods() + + @property + def fsid(self): + return f"async_{self.sync_fs.fsid}" + + def _wrap_all_sync_methods(self): + """ + Wrap all synchronous methods of the underlying filesystem with asynchronous versions. + """ + excluded_methods = {"open"} + for method_name in dir(self.sync_fs): + if method_name.startswith("_") or method_name in excluded_methods: + continue + + attr = inspect.getattr_static(self.sync_fs, method_name) + if isinstance(attr, property): + continue + + method = getattr(self.sync_fs, method_name) + if callable(method) and not inspect.iscoroutinefunction(method): + async_method = async_wrapper(method, obj=self, semaphore=self.semaphore) + setattr(self, f"_{method_name}", async_method) + + @classmethod + def wrap_class(cls, sync_fs_class): + """ + Create a new class that can be used to instantiate an AsyncFileSystemWrapper + with lazy instantiation of the underlying synchronous filesystem. + + Parameters + ---------- + sync_fs_class : type + The class of the synchronous filesystem to wrap. + + Returns + ------- + type + A new class that wraps the provided synchronous filesystem class. + """ + + class GeneratedAsyncFileSystemWrapper(cls): + def __init__(self, *args, **kwargs): + sync_fs = sync_fs_class(*args, **kwargs) + super().__init__(sync_fs) + + GeneratedAsyncFileSystemWrapper.__name__ = ( + f"Async{sync_fs_class.__name__}Wrapper" + ) + return GeneratedAsyncFileSystemWrapper diff --git a/python/user_packages/Python313/site-packages/fsspec/implementations/cache_mapper.py b/python/user_packages/Python313/site-packages/fsspec/implementations/cache_mapper.py new file mode 100644 index 0000000000000000000000000000000000000000..6e7c7d88afdddf12f77b26bb635bd8bf1e2bd7f1 --- /dev/null +++ b/python/user_packages/Python313/site-packages/fsspec/implementations/cache_mapper.py @@ -0,0 +1,75 @@ +from __future__ import annotations + +import abc +import hashlib + +from fsspec.implementations.local import make_path_posix + + +class AbstractCacheMapper(abc.ABC): + """Abstract super-class for mappers from remote URLs to local cached + basenames. + """ + + @abc.abstractmethod + def __call__(self, path: str) -> str: ... + + def __eq__(self, other: object) -> bool: + # Identity only depends on class. When derived classes have attributes + # they will need to be included. + return isinstance(other, type(self)) + + def __hash__(self) -> int: + # Identity only depends on class. When derived classes have attributes + # they will need to be included. + return hash(type(self)) + + +class BasenameCacheMapper(AbstractCacheMapper): + """Cache mapper that uses the basename of the remote URL and a fixed number + of directory levels above this. + + The default is zero directory levels, meaning different paths with the same + basename will have the same cached basename. + """ + + def __init__(self, directory_levels: int = 0): + if directory_levels < 0: + raise ValueError( + "BasenameCacheMapper requires zero or positive directory_levels" + ) + self.directory_levels = directory_levels + + # Separator for directories when encoded as strings. + self._separator = "_@_" + + def __call__(self, path: str) -> str: + path = make_path_posix(path) + prefix, *bits = path.rsplit("/", self.directory_levels + 1) + if bits: + return self._separator.join(bits) + else: + return prefix # No separator found, simple filename + + def __eq__(self, other: object) -> bool: + return super().__eq__(other) and self.directory_levels == other.directory_levels + + def __hash__(self) -> int: + return super().__hash__() ^ hash(self.directory_levels) + + +class HashCacheMapper(AbstractCacheMapper): + """Cache mapper that uses a hash of the remote URL.""" + + def __call__(self, path: str) -> str: + return hashlib.sha256(path.encode()).hexdigest() + + +def create_cache_mapper(same_names: bool) -> AbstractCacheMapper: + """Factory method to create cache mapper for backward compatibility with + ``CachingFileSystem`` constructor using ``same_names`` kwarg. + """ + if same_names: + return BasenameCacheMapper() + else: + return HashCacheMapper() diff --git a/python/user_packages/Python313/site-packages/fsspec/implementations/cache_metadata.py b/python/user_packages/Python313/site-packages/fsspec/implementations/cache_metadata.py new file mode 100644 index 0000000000000000000000000000000000000000..7690ff17228a9d489bef4ca937060c4f5855b0ce --- /dev/null +++ b/python/user_packages/Python313/site-packages/fsspec/implementations/cache_metadata.py @@ -0,0 +1,231 @@ +from __future__ import annotations + +import os +import pickle +import time +from typing import TYPE_CHECKING + +from fsspec.utils import atomic_write + +try: + import ujson as json +except ImportError: + if not TYPE_CHECKING: + import json + +if TYPE_CHECKING: + from collections.abc import Iterator + from typing import Any, Literal, TypeAlias + + from .cached import CachingFileSystem + + Detail: TypeAlias = dict[str, Any] + + +class CacheMetadata: + """Cache metadata. + + All reading and writing of cache metadata is performed by this class, + accessing the cached files and blocks is not. + + Metadata is stored in a single file per storage directory in JSON format. + For backward compatibility, also reads metadata stored in pickle format + which is converted to JSON when next saved. + """ + + def __init__(self, storage: list[str]): + """ + + Parameters + ---------- + storage: list[str] + Directories containing cached files, must be at least one. Metadata + is stored in the last of these directories by convention. + """ + if not storage: + raise ValueError("CacheMetadata expects at least one storage location") + + self._storage = storage + self.cached_files: list[Detail] = [{}] + + # Private attribute to force saving of metadata in pickle format rather than + # JSON for use in tests to confirm can read both pickle and JSON formats. + self._force_save_pickle = False + + def _load(self, fn: str) -> Detail: + """Low-level function to load metadata from specific file""" + try: + with open(fn, "r") as f: + loaded = json.load(f) + except ValueError: + with open(fn, "rb") as f: + loaded = pickle.load(f) + for c in loaded.values(): + if isinstance(c.get("blocks"), list): + c["blocks"] = set(c["blocks"]) + return loaded + + def _save(self, metadata_to_save: Detail, fn: str) -> None: + """Low-level function to save metadata to specific file""" + if self._force_save_pickle: + with atomic_write(fn) as f: + pickle.dump(metadata_to_save, f) + else: + with atomic_write(fn, mode="w") as f: + json.dump(metadata_to_save, f) + + def _scan_locations( + self, writable_only: bool = False + ) -> Iterator[tuple[str, str, bool]]: + """Yield locations (filenames) where metadata is stored, and whether + writable or not. + + Parameters + ---------- + writable: bool + Set to True to only yield writable locations. + + Returns + ------- + Yields (str, str, bool) + """ + n = len(self._storage) + for i, storage in enumerate(self._storage): + writable = i == n - 1 + if writable_only and not writable: + continue + yield os.path.join(storage, "cache"), storage, writable + + def check_file( + self, path: str, cfs: CachingFileSystem | None + ) -> Literal[False] | tuple[Detail, str]: + """If path is in cache return its details, otherwise return ``False``. + + If the optional CachingFileSystem is specified then it is used to + perform extra checks to reject possible matches, such as if they are + too old. + """ + for (fn, base, _), cache in zip(self._scan_locations(), self.cached_files): + if path not in cache: + continue + detail = cache[path].copy() + + if cfs is not None: + if cfs.check_files and detail["uid"] != cfs.fs.ukey(path): + # Wrong file as determined by hash of file properties + continue + if cfs.expiry and time.time() - detail["time"] > cfs.expiry: + # Cached file has expired + continue + + fn = os.path.join(base, detail["fn"]) + if os.path.exists(fn): + return detail, fn + return False + + def clear_expired(self, expiry_time: int) -> tuple[list[str], bool]: + """Remove expired metadata from the cache. + + Returns names of files corresponding to expired metadata and a boolean + flag indicating whether the writable cache is empty. Caller is + responsible for deleting the expired files. + """ + expired_files = [] + for path, detail in self.cached_files[-1].copy().items(): + if time.time() - detail["time"] > expiry_time: + fn = detail.get("fn", "") + if not fn: + raise RuntimeError( + f"Cache metadata does not contain 'fn' for {path}" + ) + fn = os.path.join(self._storage[-1], fn) + expired_files.append(fn) + self.cached_files[-1].pop(path) + + if self.cached_files[-1]: + cache_path = os.path.join(self._storage[-1], "cache") + self._save(self.cached_files[-1], cache_path) + + writable_cache_empty = not self.cached_files[-1] + return expired_files, writable_cache_empty + + def load(self) -> None: + """Load all metadata from disk and store in ``self.cached_files``""" + cached_files = [] + for fn, _, _ in self._scan_locations(): + if os.path.exists(fn): + # TODO: consolidate blocks here + cached_files.append(self._load(fn)) + else: + cached_files.append({}) + self.cached_files = cached_files or [{}] + + def on_close_cached_file(self, f: Any, path: str) -> None: + """Perform side-effect actions on closing a cached file. + + The actual closing of the file is the responsibility of the caller. + """ + # File must be writable, so in self.cached_files[-1] + c = self.cached_files[-1][path] + if c["blocks"] is not True and len(c["blocks"]) * f.blocksize >= f.size: + c["blocks"] = True + + def pop_file(self, path: str) -> str | None: + """Remove metadata of cached file. + + If path is in the cache, return the filename of the cached file, + otherwise return ``None``. Caller is responsible for deleting the + cached file. + """ + details = self.check_file(path, None) + if not details: + return None + _, fn = details + if fn.startswith(self._storage[-1]): + self.cached_files[-1].pop(path) + self.save() + else: + raise PermissionError( + "Can only delete cached file in last, writable cache location" + ) + return fn + + def save(self) -> None: + """Save metadata to disk""" + for (fn, _, writable), cache in zip(self._scan_locations(), self.cached_files): + if not writable: + continue + + if os.path.exists(fn): + cached_files = self._load(fn) + for k, c in cached_files.items(): + if k in cache: + if c["blocks"] is True or cache[k]["blocks"] is True: + c["blocks"] = True + else: + # self.cached_files[*][*]["blocks"] must continue to + # point to the same set object so that updates + # performed by MMapCache are propagated back to + # self.cached_files. + blocks = cache[k]["blocks"] + blocks.update(c["blocks"]) + c["blocks"] = blocks + c["time"] = max(c["time"], cache[k]["time"]) + c["uid"] = cache[k]["uid"] + + # Files can be added to cache after it was written once + for k, c in cache.items(): + if k not in cached_files: + cached_files[k] = c + else: + cached_files = cache + cache = {k: v.copy() for k, v in cached_files.items()} + for c in cache.values(): + if isinstance(c["blocks"], set): + c["blocks"] = list(c["blocks"]) + self._save(cache, fn) + self.cached_files[-1] = cached_files + + def update_file(self, path: str, detail: Detail) -> None: + """Update metadata for specific file in memory, do not save""" + self.cached_files[-1][path] = detail diff --git a/python/user_packages/Python313/site-packages/fsspec/implementations/cached.py b/python/user_packages/Python313/site-packages/fsspec/implementations/cached.py new file mode 100644 index 0000000000000000000000000000000000000000..c140f8d617d7cfe5781b01344ab3fb77e0fe3775 --- /dev/null +++ b/python/user_packages/Python313/site-packages/fsspec/implementations/cached.py @@ -0,0 +1,1024 @@ +from __future__ import annotations + +import inspect +import logging +import os +import tempfile +import time +import weakref +from collections.abc import Callable +from shutil import rmtree +from typing import TYPE_CHECKING, Any, ClassVar + +from fsspec import filesystem +from fsspec.callbacks import DEFAULT_CALLBACK +from fsspec.compression import compr +from fsspec.core import BaseCache, MMapCache +from fsspec.exceptions import BlocksizeMismatchError +from fsspec.implementations.cache_mapper import create_cache_mapper +from fsspec.implementations.cache_metadata import CacheMetadata +from fsspec.implementations.chained import ChainedFileSystem +from fsspec.implementations.local import LocalFileSystem +from fsspec.spec import AbstractBufferedFile +from fsspec.transaction import Transaction +from fsspec.utils import infer_compression + +if TYPE_CHECKING: + from fsspec.implementations.cache_mapper import AbstractCacheMapper + +logger = logging.getLogger("fsspec.cached") + + +class WriteCachedTransaction(Transaction): + def complete(self, commit=True): + rpaths = [f.path for f in self.files] + lpaths = [f.fn for f in self.files] + if commit: + self.fs.put(lpaths, rpaths) + self.files.clear() + self.fs._intrans = False + self.fs._transaction = None + self.fs = None # break cycle + + +class CachingFileSystem(ChainedFileSystem): + """Locally caching filesystem, layer over any other FS + + This class implements chunk-wise local storage of remote files, for quick + access after the initial download. The files are stored in a given + directory with hashes of URLs for the filenames. If no directory is given, + a temporary one is used, which should be cleaned up by the OS after the + process ends. The files themselves are sparse (as implemented in + :class:`~fsspec.caching.MMapCache`), so only the data which is accessed + takes up space. + + Restrictions: + + - the block-size must be the same for each access of a given file, unless + all blocks of the file have already been read + - caching can only be applied to file-systems which produce files + derived from fsspec.spec.AbstractBufferedFile ; LocalFileSystem is also + allowed, for testing + """ + + protocol: ClassVar[str | tuple[str, ...]] = ("blockcache", "cached") + _strip_tokenize_options = ("fo",) + + def __init__( + self, + target_protocol=None, + cache_storage="TMP", + cache_check=10, + check_files=False, + expiry_time=604800, + target_options=None, + fs=None, + same_names: bool | None = None, + compression=None, + cache_mapper: AbstractCacheMapper | None = None, + **kwargs, + ): + """ + + Parameters + ---------- + target_protocol: str (optional) + Target filesystem protocol. Provide either this or ``fs``. + cache_storage: str or list(str) + Location to store files. If "TMP", this is a temporary directory, + and will be cleaned up by the OS when this process ends (or later). + If a list, each location will be tried in the order given, but + only the last will be considered writable. + cache_check: int + Number of seconds between reload of cache metadata + check_files: bool + Whether to explicitly see if the UID of the remote file matches + the stored one before using. Warning: some file systems such as + HTTP cannot reliably give a unique hash of the contents of some + path, so be sure to set this option to False. + expiry_time: int + The time in seconds after which a local copy is considered useless. + Set to falsy to prevent expiry. The default is equivalent to one + week. + target_options: dict or None + Passed to the instantiation of the FS, if fs is None. + fs: filesystem instance + The target filesystem to run against. Provide this or ``protocol``. + same_names: bool (optional) + By default, target URLs are hashed using a ``HashCacheMapper`` so + that files from different backends with the same basename do not + conflict. If this argument is ``true``, a ``BasenameCacheMapper`` + is used instead. Other cache mapper options are available by using + the ``cache_mapper`` keyword argument. Only one of this and + ``cache_mapper`` should be specified. + compression: str (optional) + To decompress on download. Can be 'infer' (guess from the URL name), + one of the entries in ``fsspec.compression.compr``, or None for no + decompression. + cache_mapper: AbstractCacheMapper (optional) + The object use to map from original filenames to cached filenames. + Only one of this and ``same_names`` should be specified. + """ + super().__init__(**kwargs) + if fs is None and target_protocol is None: + raise ValueError( + "Please provide filesystem instance(fs) or target_protocol" + ) + if not (fs is None) ^ (target_protocol is None): + raise ValueError( + "Both filesystems (fs) and target_protocol may not be both given." + ) + if cache_storage == "TMP": + tempdir = tempfile.mkdtemp() + storage = [tempdir] + weakref.finalize(self, self._remove_tempdir, tempdir) + else: + if isinstance(cache_storage, str): + storage = [cache_storage] + else: + storage = cache_storage + os.makedirs(storage[-1], exist_ok=True) + self.storage = storage + self.kwargs = target_options or {} + self.cache_check = cache_check + self.check_files = check_files + self.expiry = expiry_time + self.compression = compression + + # Size of cache in bytes. If None then the size is unknown and will be + # recalculated the next time cache_size() is called. On writes to the + # cache this is reset to None. + self._cache_size = None + + if same_names is not None and cache_mapper is not None: + raise ValueError( + "Cannot specify both same_names and cache_mapper in " + "CachingFileSystem.__init__" + ) + if cache_mapper is not None: + self._mapper = cache_mapper + else: + self._mapper = create_cache_mapper( + same_names if same_names is not None else False + ) + + self.target_protocol = ( + target_protocol + if isinstance(target_protocol, str) + else (fs.protocol if isinstance(fs.protocol, str) else fs.protocol[0]) + ) + self._metadata = CacheMetadata(self.storage) + self.load_cache() + self.fs = fs if fs is not None else filesystem(target_protocol, **self.kwargs) + + def _strip_protocol(path): + # acts as a method, since each instance has a difference target + return self.fs._strip_protocol(type(self)._strip_protocol(path)) + + self._strip_protocol: Callable = _strip_protocol + + @staticmethod + def _remove_tempdir(tempdir): + try: + rmtree(tempdir) + except Exception: + pass + + def _mkcache(self): + os.makedirs(self.storage[-1], exist_ok=True) + + def cache_size(self): + """Return size of cache in bytes. + + If more than one cache directory is in use, only the size of the last + one (the writable cache directory) is returned. + """ + if self._cache_size is None: + cache_dir = self.storage[-1] + self._cache_size = filesystem("file").du(cache_dir, withdirs=True) + return self._cache_size + + def load_cache(self): + """Read set of stored blocks from file""" + self._metadata.load() + self._mkcache() + self.last_cache = time.time() + + def save_cache(self): + """Save set of stored blocks from file""" + self._mkcache() + self._metadata.save() + self.last_cache = time.time() + self._cache_size = None + + def _check_cache(self): + """Reload caches if time elapsed or any disappeared""" + self._mkcache() + if not self.cache_check: + # explicitly told not to bother checking + return + timecond = time.time() - self.last_cache > self.cache_check + existcond = all(os.path.exists(storage) for storage in self.storage) + if timecond or not existcond: + self.load_cache() + + def _check_file(self, path): + """Is path in cache and still valid""" + path = self._strip_protocol(path) + self._check_cache() + return self._metadata.check_file(path, self) + + def clear_cache(self): + """Remove all files and metadata from the cache + + In the case of multiple cache locations, this clears only the last one, + which is assumed to be the read/write one. + """ + rmtree(self.storage[-1]) + self.load_cache() + self._cache_size = None + + def clear_expired_cache(self, expiry_time=None): + """Remove all expired files and metadata from the cache + + In the case of multiple cache locations, this clears only the last one, + which is assumed to be the read/write one. + + Parameters + ---------- + expiry_time: int + The time in seconds after which a local copy is considered useless. + If not defined the default is equivalent to the attribute from the + file caching instantiation. + """ + + if not expiry_time: + expiry_time = self.expiry + + self._check_cache() + + expired_files, writable_cache_empty = self._metadata.clear_expired(expiry_time) + for fn in expired_files: + if os.path.exists(fn): + os.remove(fn) + + if writable_cache_empty: + rmtree(self.storage[-1]) + self.load_cache() + + self._cache_size = None + + def pop_from_cache(self, path): + """Remove cached version of given file + + Deletes local copy of the given (remote) path. If it is found in a cache + location which is not the last, it is assumed to be read-only, and + raises PermissionError + """ + path = self._strip_protocol(path) + fn = self._metadata.pop_file(path) + if fn is not None: + os.remove(fn) + self._cache_size = None + + def _open( + self, + path, + mode="rb", + block_size=None, + autocommit=True, + cache_options=None, + **kwargs, + ): + """Wrap the target _open + + If the whole file exists in the cache, just open it locally and + return that. + + Otherwise, open the file on the target FS, and make it have a mmap + cache pointing to the location which we determine, in our cache. + The ``blocks`` instance is shared, so as the mmap cache instance + updates, so does the entry in our ``cached_files`` attribute. + We monkey-patch this file, so that when it closes, we call + ``close_and_update`` to save the state of the blocks. + """ + path = self._strip_protocol(path) + + path = self.fs._strip_protocol(path) + if "r" not in mode: + return self.fs._open( + path, + mode=mode, + block_size=block_size, + autocommit=autocommit, + cache_options=cache_options, + **kwargs, + ) + detail = self._check_file(path) + if detail: + # file is in cache + detail, fn = detail + hash, blocks = detail["fn"], detail["blocks"] + if blocks is True: + # stored file is complete + logger.debug("Opening local copy of %s", path) + return open(fn, mode) + # TODO: action where partial file exists in read-only cache + logger.debug("Opening partially cached copy of %s", path) + else: + hash = self._mapper(path) + fn = os.path.join(self.storage[-1], hash) + blocks = set() + detail = { + "original": path, + "fn": hash, + "blocks": blocks, + "time": time.time(), + "uid": self.fs.ukey(path), + } + self._metadata.update_file(path, detail) + logger.debug("Creating local sparse file for %s", path) + + # explicitly submitting the size to the open call will avoid extra + # operations when opening. This is particularly relevant + # for any file that is read over a network, e.g. S3. + size = detail.get("size") + + # call target filesystems open + self._mkcache() + f = self.fs._open( + path, + mode=mode, + block_size=block_size, + autocommit=autocommit, + cache_options=cache_options, + cache_type="none", + size=size, + **kwargs, + ) + + # set size if not already set + if size is None: + detail["size"] = f.size + self._metadata.update_file(path, detail) + + if self.compression: + comp = ( + infer_compression(path) + if self.compression == "infer" + else self.compression + ) + f = compr[comp](f, mode="rb") + if "blocksize" in detail: + if detail["blocksize"] != f.blocksize: + raise BlocksizeMismatchError( + f"Cached file must be reopened with same block" + f" size as original (old: {detail['blocksize']}," + f" new {f.blocksize})" + ) + else: + detail["blocksize"] = f.blocksize + + def _fetch_ranges(ranges): + return self.fs.cat_ranges( + [path] * len(ranges), + [r[0] for r in ranges], + [r[1] for r in ranges], + **kwargs, + ) + + multi_fetcher = None if self.compression else _fetch_ranges + f.cache = MMapCache( + f.blocksize, f._fetch_range, f.size, fn, blocks, multi_fetcher=multi_fetcher + ) + close = f.close + f.close = lambda: self.close_and_update(f, close) + self.save_cache() + return f + + def _parent(self, path): + return self.fs._parent(path) + + def hash_name(self, path: str, *args: Any) -> str: + # Kept for backward compatibility with downstream libraries. + # Ignores extra arguments, previously same_name boolean. + return self._mapper(path) + + def close_and_update(self, f, close): + """Called when a file is closing, so store the set of blocks""" + if f.closed: + return + path = self._strip_protocol(f.path) + self._metadata.on_close_cached_file(f, path) + try: + logger.debug("going to save") + self.save_cache() + logger.debug("saved") + except OSError: + logger.debug("Cache saving failed while closing file") + except NameError: + logger.debug("Cache save failed due to interpreter shutdown") + close() + f.closed = True + + def ls(self, path, detail=True): + return self.fs.ls(path, detail) + + def __getattribute__(self, item): + if item in { + "load_cache", + "_get_cached_file_before_open", + "_open", + "save_cache", + "close_and_update", + "__init__", + "__getattribute__", + "__reduce__", + "_make_local_details", + "open", + "cat", + "cat_file", + "_cat_file", + "cat_ranges", + "_cat_ranges", + "get", + "read_block", + "tail", + "head", + "info", + "ls", + "exists", + "isfile", + "isdir", + "_check_file", + "_check_cache", + "_mkcache", + "clear_cache", + "clear_expired_cache", + "pop_from_cache", + "local_file", + "_paths_from_path", + "get_mapper", + "open_many", + "commit_many", + "hash_name", + "__hash__", + "__eq__", + "to_json", + "to_dict", + "cache_size", + "pipe_file", + "pipe", + "start_transaction", + "end_transaction", + }: + # all the methods defined in this class. Note `open` here, since + # it calls `_open`, but is actually in superclass + if hasattr(type(self), item): + return lambda *args, **kw: getattr(type(self), item).__get__(self)( + *args, **kw + ) + # method is in the whitelist but not defined on this subclass; + # fall through to delegate to the wrapped filesystem below + if item in ["__reduce_ex__"]: + raise AttributeError + if item in ["transaction"]: + # property + return type(self).transaction.__get__(self) + if item in {"_cache", "transaction_type", "protocol"}: + # class attributes + return getattr(type(self), item) + if item == "__class__": + return type(self) + d = object.__getattribute__(self, "__dict__") + fs = d.get("fs", None) # fs is not immediately defined + if item in d: + return d[item] + elif fs is not None: + if item in fs.__dict__: + # attribute of instance + return fs.__dict__[item] + # attributed belonging to the target filesystem + cls = type(fs) + m = getattr(cls, item) + if (inspect.isfunction(m) or inspect.isdatadescriptor(m)) and ( + not hasattr(m, "__self__") or m.__self__ is None + ): + # instance method + return m.__get__(fs, cls) + return m # class method or attribute + else: + # attributes of the superclass, while target is being set up + return super().__getattribute__(item) + + def __eq__(self, other): + """Test for equality.""" + if self is other: + return True + if not isinstance(other, type(self)): + return False + return ( + self.storage == other.storage + and self.kwargs == other.kwargs + and self.cache_check == other.cache_check + and self.check_files == other.check_files + and self.expiry == other.expiry + and self.compression == other.compression + and self._mapper == other._mapper + and self.target_protocol == other.target_protocol + ) + + def __hash__(self): + """Calculate hash.""" + return ( + hash(tuple(self.storage)) + ^ hash(str(self.kwargs)) + ^ hash(self.cache_check) + ^ hash(self.check_files) + ^ hash(self.expiry) + ^ hash(self.compression) + ^ hash(self._mapper) + ^ hash(self.target_protocol) + ) + + +class WholeFileCacheFileSystem(CachingFileSystem): + """Caches whole remote files on first access + + This class is intended as a layer over any other file system, and + will make a local copy of each file accessed, so that all subsequent + reads are local. This is similar to ``CachingFileSystem``, but without + the block-wise functionality and so can work even when sparse files + are not allowed. See its docstring for definition of the init + arguments. + + The class still needs access to the remote store for listing files, + and may refresh cached files. + """ + + protocol = "filecache" + local_file = True + + def open_many(self, open_files, **kwargs): + paths = [of.path for of in open_files] + if "r" in open_files.mode: + self._mkcache() + else: + return [ + LocalTempFile( + self.fs, + path, + mode=open_files.mode, + fn=os.path.join(self.storage[-1], self._mapper(path)), + **kwargs, + ) + for path in paths + ] + + if self.compression: + raise NotImplementedError + details = [self._check_file(sp) for sp in paths] + downpath = [p for p, d in zip(paths, details) if not d] + downfn0 = [ + os.path.join(self.storage[-1], self._mapper(p)) + for p, d in zip(paths, details) + ] # keep these path names for opening later + downfn = [fn for fn, d in zip(downfn0, details) if not d] + if downpath: + # skip if all files are already cached and up to date + self.fs.get(downpath, downfn) + + # update metadata - only happens when downloads are successful + newdetail = [ + { + "original": path, + "fn": self._mapper(path), + "blocks": True, + "time": time.time(), + "uid": self.fs.ukey(path), + } + for path in downpath + ] + for path, detail in zip(downpath, newdetail): + self._metadata.update_file(path, detail) + self.save_cache() + + def firstpart(fn): + # helper to adapt both whole-file and simple-cache + return fn[1] if isinstance(fn, tuple) else fn + + return [ + open(firstpart(fn0) if fn0 else fn1, mode=open_files.mode) + for fn0, fn1 in zip(details, downfn0) + ] + + def commit_many(self, open_files): + self.fs.put([f.fn for f in open_files], [f.path for f in open_files]) + [f.close() for f in open_files] + for f in open_files: + # in case autocommit is off, and so close did not already delete + try: + os.remove(f.name) + except FileNotFoundError: + pass + self._cache_size = None + + def _make_local_details(self, path): + hash = self._mapper(path) + fn = os.path.join(self.storage[-1], hash) + detail = { + "original": path, + "fn": hash, + "blocks": True, + "time": time.time(), + "uid": self.fs.ukey(path), + } + self._metadata.update_file(path, detail) + logger.debug("Copying %s to local cache", path) + return fn + + def cat( + self, + path, + recursive=False, + on_error="raise", + callback=DEFAULT_CALLBACK, + **kwargs, + ): + paths = self.expand_path( + path, recursive=recursive, maxdepth=kwargs.get("maxdepth") + ) + getpaths = [] + storepaths = [] + fns = [] + out = {} + for p in paths.copy(): + try: + detail = self._check_file(p) + if not detail: + fn = self._make_local_details(p) + getpaths.append(p) + storepaths.append(fn) + else: + detail, fn = detail if isinstance(detail, tuple) else (None, detail) + fns.append(fn) + except Exception as e: + if on_error == "raise": + raise + if on_error == "return": + out[p] = e + paths.remove(p) + + if getpaths: + self.fs.get(getpaths, storepaths) + self.save_cache() + + callback.set_size(len(paths)) + for p, fn in zip(paths, fns): + with open(fn, "rb") as f: + out[p] = f.read() + callback.relative_update(1) + if isinstance(path, str) and len(paths) == 1 and recursive is False: + out = out[paths[0]] + return out + + def _get_cached_file_before_open(self, path, **kwargs): + fn = self._make_local_details(path) + # call target filesystems open + self._mkcache() + if self.compression: + with self.fs._open(path, mode="rb", **kwargs) as f, open(fn, "wb") as f2: + if isinstance(f, AbstractBufferedFile): + # want no type of caching if just downloading whole thing + f.cache = BaseCache(0, f.cache.fetcher, f.size) + comp = ( + infer_compression(path) + if self.compression == "infer" + else self.compression + ) + f = compr[comp](f, mode="rb") + data = True + while data: + block = getattr(f, "blocksize", 5 * 2**20) + data = f.read(block) + f2.write(data) + else: + self.fs.get_file(path, fn) + self.save_cache() + + def _open(self, path, mode="rb", **kwargs): + path = self._strip_protocol(path) + # For read (or append), (try) download from remote + if "r" in mode or "a" in mode: + if not self._check_file(path): + if self.fs.exists(path): + self._get_cached_file_before_open(path, **kwargs) + elif "r" in mode: + raise FileNotFoundError(path) + + detail, fn = self._check_file(path) + _, blocks = detail["fn"], detail["blocks"] + if blocks is True: + logger.debug("Opening local copy of %s", path) + else: + raise ValueError( + f"Attempt to open partially cached file {path}" + f" as a wholly cached file" + ) + + # Just reading does not need special file handling + if "r" in mode and "+" not in mode: + # In order to support downstream filesystems to be able to + # infer the compression from the original filename, like + # the `TarFileSystem`, let's extend the `io.BufferedReader` + # fileobject protocol by adding a dedicated attribute + # `original`. + f = open(fn, mode) + f.original = detail.get("original") + return f + + hash = self._mapper(path) + fn = os.path.join(self.storage[-1], hash) + user_specified_kwargs = { + k: v + for k, v in kwargs.items() + # those kwargs were added by open(), we don't want them + if k not in ["autocommit", "block_size", "cache_options"] + } + return LocalTempFile(self, path, mode=mode, fn=fn, **user_specified_kwargs) + + async def _cat_file(self, path, start=None, end=None, **kwargs): + logger.debug("async cat_file %s", path) + path = self._strip_protocol(path) + sha = self._mapper(path) + fn = self._check_file(path) + + if not fn: + fn = os.path.join(self.storage[-1], sha) + await self.fs._get_file(path, fn, **kwargs) + + with open(fn, "rb") as f: # noqa ASYNC230 + if start: + f.seek(start) + size = -1 if end is None else end - f.tell() + return f.read(size) + + async def _cat_ranges( + self, paths, starts, ends, max_gap=None, on_error="return", **kwargs + ): + logger.debug("async cat ranges %s", paths) + lpaths = [] + rset = set() + download = [] + rpaths = [] + for p in paths: + fn = self._check_file(p) + if fn is None and p not in rset: + sha = self._mapper(p) + fn = os.path.join(self.storage[-1], sha) + download.append(fn) + rset.add(p) + rpaths.append(p) + lpaths.append(fn) + if download: + await self.fs._get(rpaths, download, on_error=on_error) + + return LocalFileSystem().cat_ranges( + lpaths, starts, ends, max_gap=max_gap, on_error=on_error, **kwargs + ) + + +class SimpleCacheFileSystem(WholeFileCacheFileSystem): + """Caches whole remote files on first access + + This class is intended as a layer over any other file system, and + will make a local copy of each file accessed, so that all subsequent + reads are local. This implementation only copies whole files, and + does not keep any metadata about the download time or file details. + It is therefore safer to use in multi-threaded/concurrent situations. + + This is the only of the caching filesystems that supports write: you will + be given a real local open file, and upon close and commit, it will be + uploaded to the target filesystem; the writability or the target URL is + not checked until that time. + + """ + + protocol = "simplecache" + local_file = True + transaction_type = WriteCachedTransaction + + def __init__(self, **kwargs): + kw = kwargs.copy() + for key in ["cache_check", "expiry_time", "check_files"]: + kw[key] = False + super().__init__(**kw) + for storage in self.storage: + if not os.path.exists(storage): + os.makedirs(storage, exist_ok=True) + + def _check_file(self, path): + self._check_cache() + sha = self._mapper(path) + for storage in self.storage: + fn = os.path.join(storage, sha) + if os.path.exists(fn): + return fn + + def save_cache(self): + pass + + def load_cache(self): + pass + + def pipe_file(self, path, value=None, **kwargs): + if self._intrans: + with self.open(path, "wb") as f: + f.write(value) + else: + super().pipe_file(path, value) + + def ls(self, path, detail=True, **kwargs): + path = self._strip_protocol(path) + details = [] + try: + details = self.fs.ls( + path, detail=True, **kwargs + ).copy() # don't edit original! + except FileNotFoundError as e: + ex = e + else: + ex = None + if self._intrans: + path1 = path.rstrip("/") + "/" + for f in self.transaction.files: + if f.path == path: + details.append( + {"name": path, "size": f.size or f.tell(), "type": "file"} + ) + elif f.path.startswith(path1): + if f.path.count("/") == path1.count("/"): + details.append( + {"name": f.path, "size": f.size or f.tell(), "type": "file"} + ) + else: + dname = "/".join(f.path.split("/")[: path1.count("/") + 1]) + details.append({"name": dname, "size": 0, "type": "directory"}) + if ex is not None and not details: + raise ex + if detail: + return details + return sorted(_["name"] for _ in details) + + def info(self, path, **kwargs): + path = self._strip_protocol(path) + if self._intrans: + f = [_ for _ in self.transaction.files if _.path == path] + if f: + size = os.path.getsize(f[0].fn) if f[0].closed else f[0].tell() + return {"name": path, "size": size, "type": "file"} + f = any(_.path.startswith(path + "/") for _ in self.transaction.files) + if f: + return {"name": path, "size": 0, "type": "directory"} + return self.fs.info(path, **kwargs) + + def pipe(self, path, value=None, **kwargs): + if isinstance(path, str): + self.pipe_file(self._strip_protocol(path), value, **kwargs) + elif isinstance(path, dict): + for k, v in path.items(): + self.pipe_file(self._strip_protocol(k), v, **kwargs) + else: + raise ValueError("path must be str or dict") + + def cat_ranges( + self, paths, starts, ends, max_gap=None, on_error="return", **kwargs + ): + logger.debug("cat ranges %s", paths) + lpaths = [self._check_file(p) for p in paths] + rpaths = [p for l, p in zip(lpaths, paths) if l is False] + lpaths = [l for l, p in zip(lpaths, paths) if l is False] + self.fs.get(rpaths, lpaths) + paths = [self._check_file(p) for p in paths] + return LocalFileSystem().cat_ranges( + paths, starts, ends, max_gap=max_gap, on_error=on_error, **kwargs + ) + + def _get_cached_file_before_open(self, path, **kwargs): + sha = self._mapper(path) + fn = os.path.join(self.storage[-1], sha) + logger.debug("Copying %s to local cache", path) + + self._mkcache() + self._cache_size = None + + if self.compression: + with self.fs._open(path, mode="rb", **kwargs) as f, open(fn, "wb") as f2: + if isinstance(f, AbstractBufferedFile): + # want no type of caching if just downloading whole thing + f.cache = BaseCache(0, f.cache.fetcher, f.size) + comp = ( + infer_compression(path) + if self.compression == "infer" + else self.compression + ) + f = compr[comp](f, mode="rb") + data = True + while data: + block = getattr(f, "blocksize", 5 * 2**20) + data = f.read(block) + f2.write(data) + else: + self.fs.get_file(path, fn) + + def _open(self, path, mode="rb", **kwargs): + path = self._strip_protocol(path) + sha = self._mapper(path) + + # For read (or append), (try) download from remote + if "r" in mode or "a" in mode: + if not self._check_file(path): + # append does not require an existing file but read does + if self.fs.exists(path): + self._get_cached_file_before_open(path, **kwargs) + elif "r" in mode: + raise FileNotFoundError(path) + + fn = self._check_file(path) + # Just reading does not need special file handling + if "r" in mode and "+" not in mode: + return open(fn, mode) + + fn = os.path.join(self.storage[-1], sha) + user_specified_kwargs = { + k: v + for k, v in kwargs.items() + if k not in ["autocommit", "block_size", "cache_options"] + } # those were added by open() + return LocalTempFile( + self, + path, + mode=mode, + autocommit=not self._intrans, + fn=fn, + **user_specified_kwargs, + ) + + +class LocalTempFile: + """A temporary local file, which will be uploaded on commit""" + + def __init__(self, fs, path, fn, mode="wb", autocommit=True, seek=0, **kwargs): + self.fn = fn + self.fh = open(fn, mode) + self.mode = mode + if seek: + self.fh.seek(seek) + self.path = path + self.size = None + self.fs = fs + self.closed = False + self.autocommit = autocommit + self.kwargs = kwargs + + def __reduce__(self): + # always open in r+b to allow continuing writing at a location + return ( + LocalTempFile, + (self.fs, self.path, self.fn, "r+b", self.autocommit, self.tell()), + ) + + def __enter__(self): + return self.fh + + def __exit__(self, exc_type, exc_val, exc_tb): + self.close() + + def close(self): + # self.size = self.fh.tell() + if self.closed: + return + self.fh.close() + self.closed = True + if self.autocommit: + self.commit() + + def discard(self): + self.fh.close() + os.remove(self.fn) + + def commit(self): + # calling put() with list arguments avoids path expansion and additional operations + # like isdir() + self.fs.put([self.fn], [self.path], **self.kwargs) + # we do not delete the local copy, it's still in the cache. + + @property + def name(self): + return self.fn + + def __repr__(self) -> str: + return f"LocalTempFile: {self.path}" + + def __getattr__(self, item): + return getattr(self.fh, item) diff --git a/python/user_packages/Python313/site-packages/fsspec/implementations/chained.py b/python/user_packages/Python313/site-packages/fsspec/implementations/chained.py new file mode 100644 index 0000000000000000000000000000000000000000..bfce64334e8db0272eefa96b4428b23524b059f0 --- /dev/null +++ b/python/user_packages/Python313/site-packages/fsspec/implementations/chained.py @@ -0,0 +1,23 @@ +from typing import ClassVar + +from fsspec import AbstractFileSystem + +__all__ = ("ChainedFileSystem",) + + +class ChainedFileSystem(AbstractFileSystem): + """Chained filesystem base class. + + A chained filesystem is designed to be layered over another FS. + This is useful to implement things like caching. + + This base class does very little on its own, but is used as a marker + that the class is designed for chaining. + + Right now this is only used in `url_to_fs` to provide the path argument + (`fo`) to the chained filesystem from the underlying filesystem. + + Additional functionality may be added in the future. + """ + + protocol: ClassVar[str] = "chained" diff --git a/python/user_packages/Python313/site-packages/fsspec/implementations/dask.py b/python/user_packages/Python313/site-packages/fsspec/implementations/dask.py new file mode 100644 index 0000000000000000000000000000000000000000..3e1276463db6866665e6a0fe114efc247971b57e --- /dev/null +++ b/python/user_packages/Python313/site-packages/fsspec/implementations/dask.py @@ -0,0 +1,152 @@ +import dask +from distributed.client import Client, _get_global_client +from distributed.worker import Worker + +from fsspec import filesystem +from fsspec.spec import AbstractBufferedFile, AbstractFileSystem +from fsspec.utils import infer_storage_options + + +def _get_client(client): + if client is None: + return _get_global_client() + elif isinstance(client, Client): + return client + else: + # e.g., connection string + return Client(client) + + +def _in_worker(): + return bool(Worker._instances) + + +class DaskWorkerFileSystem(AbstractFileSystem): + """View files accessible to a worker as any other remote file-system + + When instances are run on the worker, uses the real filesystem. When + run on the client, they call the worker to provide information or data. + + **Warning** this implementation is experimental, and read-only for now. + """ + + def __init__( + self, target_protocol=None, target_options=None, fs=None, client=None, **kwargs + ): + super().__init__(**kwargs) + if not (fs is None) ^ (target_protocol is None): + raise ValueError( + "Please provide one of filesystem instance (fs) or" + " target_protocol, not both" + ) + self.target_protocol = target_protocol + self.target_options = target_options + self.worker = None + self.client = client + self.fs = fs + self._determine_worker() + + @staticmethod + def _get_kwargs_from_urls(path): + so = infer_storage_options(path) + if "host" in so and "port" in so: + return {"client": f"{so['host']}:{so['port']}"} + else: + return {} + + def _determine_worker(self): + if _in_worker(): + self.worker = True + if self.fs is None: + self.fs = filesystem( + self.target_protocol, **(self.target_options or {}) + ) + else: + self.worker = False + self.client = _get_client(self.client) + self.rfs = dask.delayed(self) + + def mkdir(self, *args, **kwargs): + if self.worker: + self.fs.mkdir(*args, **kwargs) + else: + self.rfs.mkdir(*args, **kwargs).compute() + + def rm(self, *args, **kwargs): + if self.worker: + self.fs.rm(*args, **kwargs) + else: + self.rfs.rm(*args, **kwargs).compute() + + def copy(self, *args, **kwargs): + if self.worker: + self.fs.copy(*args, **kwargs) + else: + self.rfs.copy(*args, **kwargs).compute() + + def mv(self, *args, **kwargs): + if self.worker: + self.fs.mv(*args, **kwargs) + else: + self.rfs.mv(*args, **kwargs).compute() + + def ls(self, *args, **kwargs): + if self.worker: + return self.fs.ls(*args, **kwargs) + else: + return self.rfs.ls(*args, **kwargs).compute() + + def _open( + self, + path, + mode="rb", + block_size=None, + autocommit=True, + cache_options=None, + **kwargs, + ): + if self.worker: + return self.fs._open( + path, + mode=mode, + block_size=block_size, + autocommit=autocommit, + cache_options=cache_options, + **kwargs, + ) + else: + return DaskFile( + fs=self, + path=path, + mode=mode, + block_size=block_size, + autocommit=autocommit, + cache_options=cache_options, + **kwargs, + ) + + def fetch_range(self, path, mode, start, end): + if self.worker: + with self._open(path, mode) as f: + f.seek(start) + return f.read(end - start) + else: + return self.rfs.fetch_range(path, mode, start, end).compute() + + +class DaskFile(AbstractBufferedFile): + def __init__(self, mode="rb", **kwargs): + if mode != "rb": + raise ValueError('Remote dask files can only be opened in "rb" mode') + super().__init__(**kwargs) + + def _upload_chunk(self, final=False): + pass + + def _initiate_upload(self): + """Create remote file/upload""" + pass + + def _fetch_range(self, start, end): + """Get the specified set of bytes from remote""" + return self.fs.fetch_range(self.path, self.mode, start, end) diff --git a/python/user_packages/Python313/site-packages/fsspec/implementations/data.py b/python/user_packages/Python313/site-packages/fsspec/implementations/data.py new file mode 100644 index 0000000000000000000000000000000000000000..f11542b48c98fd53fc367ade7425a00b38487619 --- /dev/null +++ b/python/user_packages/Python313/site-packages/fsspec/implementations/data.py @@ -0,0 +1,57 @@ +import base64 +import io +from urllib.parse import unquote + +from fsspec import AbstractFileSystem + + +class DataFileSystem(AbstractFileSystem): + """A handy decoder for data-URLs + + Example + ------- + >>> with fsspec.open("data:,Hello%2C%20World%21") as f: + ... print(f.read()) + b"Hello, World!" + + See https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/Data_URLs + """ + + protocol = "data" + + def __init__(self, **kwargs): + """No parameters for this filesystem""" + super().__init__(**kwargs) + + def cat_file(self, path, start=None, end=None, **kwargs): + pref, data = path.split(",", 1) + if pref.endswith("base64"): + return base64.b64decode(data)[start:end] + return unquote(data).encode()[start:end] + + def info(self, path, **kwargs): + pref, name = path.split(",", 1) + data = self.cat_file(path) + mime = pref.split(":", 1)[1].split(";", 1)[0] + return {"name": name, "size": len(data), "type": "file", "mimetype": mime} + + def _open( + self, + path, + mode="rb", + block_size=None, + autocommit=True, + cache_options=None, + **kwargs, + ): + if "r" not in mode: + raise ValueError("Read only filesystem") + return io.BytesIO(self.cat_file(path)) + + @staticmethod + def encode(data: bytes, mime: str | None = None): + """Format the given data into data-URL syntax + + This version always base64 encodes, even when the data is ascii/url-safe. + """ + return f"data:{mime or ''};base64,{base64.b64encode(data).decode()}" diff --git a/python/user_packages/Python313/site-packages/fsspec/implementations/dbfs.py b/python/user_packages/Python313/site-packages/fsspec/implementations/dbfs.py new file mode 100644 index 0000000000000000000000000000000000000000..1a7fc93d7389c894ecb5fc6267ce20abe4087068 --- /dev/null +++ b/python/user_packages/Python313/site-packages/fsspec/implementations/dbfs.py @@ -0,0 +1,496 @@ +from __future__ import annotations + +import base64 +import urllib + +import requests +from requests.adapters import HTTPAdapter, Retry +from typing_extensions import override + +from fsspec import AbstractFileSystem +from fsspec.spec import AbstractBufferedFile + + +class DatabricksException(Exception): + """ + Helper class for exceptions raised in this module. + """ + + def __init__(self, error_code, message, details=None): + """Create a new DatabricksException""" + super().__init__(message) + + self.error_code = error_code + self.message = message + self.details = details + + +class DatabricksFileSystem(AbstractFileSystem): + """ + Get access to the Databricks filesystem implementation over HTTP. + Can be used inside and outside of a databricks cluster. + """ + + def __init__(self, instance, token, **kwargs): + """ + Create a new DatabricksFileSystem. + + Parameters + ---------- + instance: str + The instance URL of the databricks cluster. + For example for an Azure databricks cluster, this + has the form adb-..azuredatabricks.net. + token: str + Your personal token. Find out more + here: https://docs.databricks.com/dev-tools/api/latest/authentication.html + """ + self.instance = instance + self.token = token + self.session = requests.Session() + self.retries = Retry( + total=10, + backoff_factor=0.05, + status_forcelist=[408, 429, 500, 502, 503, 504], + ) + + self.session.mount("https://", HTTPAdapter(max_retries=self.retries)) + self.session.headers.update({"Authorization": f"Bearer {self.token}"}) + + super().__init__(**kwargs) + + @override + def _ls_from_cache(self, path) -> list[dict[str, str | int]] | None: + """Check cache for listing + + Returns listing, if found (may be empty list for a directory that + exists but contains nothing), None if not in cache. + """ + self.dircache.pop(path.rstrip("/"), None) + + parent = self._parent(path) + if parent in self.dircache: + for entry in self.dircache[parent]: + if entry["name"] == path.rstrip("/"): + if entry["type"] != "directory": + return [entry] + return [] + raise FileNotFoundError(path) + + def ls(self, path, detail=True, **kwargs): + """ + List the contents of the given path. + + Parameters + ---------- + path: str + Absolute path + detail: bool + Return not only the list of filenames, + but also additional information on file sizes + and types. + """ + try: + out = self._ls_from_cache(path) + except FileNotFoundError: + # This happens if the `path`'s parent was cached, but `path` is not + # there. This suggests that `path` is new since the parent was + # cached. Attempt to invalidate parent's cache before continuing. + self.dircache.pop(self._parent(path), None) + out = None + + if not out: + try: + r = self._send_to_api( + method="get", endpoint="list", json={"path": path} + ) + except DatabricksException as e: + if e.error_code == "RESOURCE_DOES_NOT_EXIST": + raise FileNotFoundError(e.message) from e + + raise + files = r.get("files", []) + out = [ + { + "name": o["path"], + "type": "directory" if o["is_dir"] else "file", + "size": o["file_size"], + } + for o in files + ] + self.dircache[path] = out + + if detail: + return out + return [o["name"] for o in out] + + def makedirs(self, path, exist_ok=True): + """ + Create a given absolute path and all of its parents. + + Parameters + ---------- + path: str + Absolute path to create + exist_ok: bool + If false, checks if the folder + exists before creating it (and raises an + Exception if this is the case) + """ + if not exist_ok: + try: + # If the following succeeds, the path is already present + self._send_to_api( + method="get", endpoint="get-status", json={"path": path} + ) + raise FileExistsError(f"Path {path} already exists") + except DatabricksException as e: + if e.error_code == "RESOURCE_DOES_NOT_EXIST": + pass + + try: + self._send_to_api(method="post", endpoint="mkdirs", json={"path": path}) + except DatabricksException as e: + if e.error_code == "RESOURCE_ALREADY_EXISTS": + raise FileExistsError(e.message) from e + + raise + self.invalidate_cache(self._parent(path)) + + def mkdir(self, path, create_parents=True, **kwargs): + """ + Create a given absolute path and all of its parents. + + Parameters + ---------- + path: str + Absolute path to create + create_parents: bool + Whether to create all parents or not. + "False" is not implemented so far. + """ + if not create_parents: + raise NotImplementedError + + self.mkdirs(path, **kwargs) + + def rm(self, path, recursive=False, **kwargs): + """ + Remove the file or folder at the given absolute path. + + Parameters + ---------- + path: str + Absolute path what to remove + recursive: bool + Recursively delete all files in a folder. + """ + try: + self._send_to_api( + method="post", + endpoint="delete", + json={"path": path, "recursive": recursive}, + ) + except DatabricksException as e: + # This is not really an exception, it just means + # not everything was deleted so far + if e.error_code == "PARTIAL_DELETE": + self.rm(path=path, recursive=recursive) + elif e.error_code == "IO_ERROR": + # Using the same exception as the os module would use here + raise OSError(e.message) from e + + raise + self.invalidate_cache(self._parent(path)) + + def mv( + self, source_path, destination_path, recursive=False, maxdepth=None, **kwargs + ): + """ + Move a source to a destination path. + + A note from the original [databricks API manual] + (https://docs.databricks.com/dev-tools/api/latest/dbfs.html#move). + + When moving a large number of files the API call will time out after + approximately 60s, potentially resulting in partially moved data. + Therefore, for operations that move more than 10k files, we strongly + discourage using the DBFS REST API. + + Parameters + ---------- + source_path: str + From where to move (absolute path) + destination_path: str + To where to move (absolute path) + recursive: bool + Not implemented to far. + maxdepth: + Not implemented to far. + """ + if recursive: + raise NotImplementedError + if maxdepth: + raise NotImplementedError + + try: + self._send_to_api( + method="post", + endpoint="move", + json={"source_path": source_path, "destination_path": destination_path}, + ) + except DatabricksException as e: + if e.error_code == "RESOURCE_DOES_NOT_EXIST": + raise FileNotFoundError(e.message) from e + elif e.error_code == "RESOURCE_ALREADY_EXISTS": + raise FileExistsError(e.message) from e + + raise + self.invalidate_cache(self._parent(source_path)) + self.invalidate_cache(self._parent(destination_path)) + + def _open(self, path, mode="rb", block_size="default", **kwargs): + """ + Overwrite the base class method to make sure to create a DBFile. + All arguments are copied from the base method. + + Only the default blocksize is allowed. + """ + return DatabricksFile(self, path, mode=mode, block_size=block_size, **kwargs) + + def _send_to_api(self, method, endpoint, json): + """ + Send the given json to the DBFS API + using a get or post request (specified by the argument `method`). + + Parameters + ---------- + method: str + Which http method to use for communication; "get" or "post". + endpoint: str + Where to send the request to (last part of the API URL) + json: dict + Dictionary of information to send + """ + if method == "post": + session_call = self.session.post + elif method == "get": + session_call = self.session.get + else: + raise ValueError(f"Do not understand method {method}") + + url = urllib.parse.urljoin(f"https://{self.instance}/api/2.0/dbfs/", endpoint) + + r = session_call(url, json=json) + + # The DBFS API will return a json, also in case of an exception. + # We want to preserve this information as good as possible. + try: + r.raise_for_status() + except requests.HTTPError as e: + # try to extract json error message + # if that fails, fall back to the original exception + try: + exception_json = e.response.json() + except Exception: + raise e from None + + raise DatabricksException(**exception_json) from e + + return r.json() + + def _create_handle(self, path, overwrite=True): + """ + Internal function to create a handle, which can be used to + write blocks of a file to DBFS. + A handle has a unique identifier which needs to be passed + whenever written during this transaction. + The handle is active for 10 minutes - after that a new + write transaction needs to be created. + Make sure to close the handle after you are finished. + + Parameters + ---------- + path: str + Absolute path for this file. + overwrite: bool + If a file already exist at this location, either overwrite + it or raise an exception. + """ + try: + r = self._send_to_api( + method="post", + endpoint="create", + json={"path": path, "overwrite": overwrite}, + ) + return r["handle"] + except DatabricksException as e: + if e.error_code == "RESOURCE_ALREADY_EXISTS": + raise FileExistsError(e.message) from e + + raise + + def _close_handle(self, handle): + """ + Close a handle, which was opened by :func:`_create_handle`. + + Parameters + ---------- + handle: str + Which handle to close. + """ + try: + self._send_to_api(method="post", endpoint="close", json={"handle": handle}) + except DatabricksException as e: + if e.error_code == "RESOURCE_DOES_NOT_EXIST": + raise FileNotFoundError(e.message) from e + + raise + + def _add_data(self, handle, data): + """ + Upload data to an already opened file handle + (opened by :func:`_create_handle`). + The maximal allowed data size is 1MB after + conversion to base64. + Remember to close the handle when you are finished. + + Parameters + ---------- + handle: str + Which handle to upload data to. + data: bytes + Block of data to add to the handle. + """ + data = base64.b64encode(data).decode() + try: + self._send_to_api( + method="post", + endpoint="add-block", + json={"handle": handle, "data": data}, + ) + except DatabricksException as e: + if e.error_code == "RESOURCE_DOES_NOT_EXIST": + raise FileNotFoundError(e.message) from e + elif e.error_code == "MAX_BLOCK_SIZE_EXCEEDED": + raise ValueError(e.message) from e + + raise + + def _get_data(self, path, start, end): + """ + Download data in bytes from a given absolute path in a block + from [start, start+length]. + The maximum number of allowed bytes to read is 1MB. + + Parameters + ---------- + path: str + Absolute path to download data from + start: int + Start position of the block + end: int + End position of the block + """ + try: + r = self._send_to_api( + method="get", + endpoint="read", + json={"path": path, "offset": start, "length": end - start}, + ) + return base64.b64decode(r["data"]) + except DatabricksException as e: + if e.error_code == "RESOURCE_DOES_NOT_EXIST": + raise FileNotFoundError(e.message) from e + elif e.error_code in ["INVALID_PARAMETER_VALUE", "MAX_READ_SIZE_EXCEEDED"]: + raise ValueError(e.message) from e + + raise + + def invalidate_cache(self, path=None): + if path is None: + self.dircache.clear() + else: + self.dircache.pop(path, None) + super().invalidate_cache(path) + + +class DatabricksFile(AbstractBufferedFile): + """ + Helper class for files referenced in the DatabricksFileSystem. + """ + + DEFAULT_BLOCK_SIZE = 1 * 2**20 # only allowed block size + + def __init__( + self, + fs, + path, + mode="rb", + block_size="default", + autocommit=True, + cache_type="readahead", + cache_options=None, + **kwargs, + ): + """ + Create a new instance of the DatabricksFile. + + The blocksize needs to be the default one. + """ + if block_size is None or block_size == "default": + block_size = self.DEFAULT_BLOCK_SIZE + + assert block_size == self.DEFAULT_BLOCK_SIZE, ( + f"Only the default block size is allowed, not {block_size}" + ) + + super().__init__( + fs, + path, + mode=mode, + block_size=block_size, + autocommit=autocommit, + cache_type=cache_type, + cache_options=cache_options or {}, + **kwargs, + ) + + def _initiate_upload(self): + """Internal function to start a file upload""" + self.handle = self.fs._create_handle(self.path) + + def _upload_chunk(self, final=False): + """Internal function to add a chunk of data to a started upload""" + self.buffer.seek(0) + data = self.buffer.getvalue() + + data_chunks = [ + data[start:end] for start, end in self._to_sized_blocks(len(data)) + ] + + for data_chunk in data_chunks: + self.fs._add_data(handle=self.handle, data=data_chunk) + + if final: + self.fs._close_handle(handle=self.handle) + return True + + def _fetch_range(self, start, end): + """Internal function to download a block of data""" + return_buffer = b"" + length = end - start + for chunk_start, chunk_end in self._to_sized_blocks(length, start): + return_buffer += self.fs._get_data( + path=self.path, start=chunk_start, end=chunk_end + ) + + return return_buffer + + def _to_sized_blocks(self, length, start=0): + """Helper function to split a range from 0 to total_length into blocksizes""" + end = start + length + for data_chunk in range(start, end, self.blocksize): + data_start = data_chunk + data_end = min(end, data_chunk + self.blocksize) + yield data_start, data_end diff --git a/python/user_packages/Python313/site-packages/fsspec/implementations/dirfs.py b/python/user_packages/Python313/site-packages/fsspec/implementations/dirfs.py new file mode 100644 index 0000000000000000000000000000000000000000..65b9b5da1219eb3a2e642c6dfb7f508f629d4e37 --- /dev/null +++ b/python/user_packages/Python313/site-packages/fsspec/implementations/dirfs.py @@ -0,0 +1,404 @@ +from .. import filesystem +from ..asyn import AsyncFileSystem +from .chained import ChainedFileSystem + + +class DirFileSystem(AsyncFileSystem, ChainedFileSystem): + """Directory prefix filesystem + + The DirFileSystem is a filesystem-wrapper. It assumes every path it is dealing with + is relative to the `path`. After performing the necessary paths operation it + delegates everything to the wrapped filesystem. + """ + + protocol = "dir" + + def __init__( + self, + path=None, + fs=None, + fo=None, + target_protocol=None, + target_options=None, + **storage_options, + ): + """ + Parameters + ---------- + path: str + Path to the directory. + fs: AbstractFileSystem + An instantiated filesystem to wrap. + target_protocol, target_options: + if fs is none, construct it from these + fo: str + Alternate for path; do not provide both + """ + super().__init__(**storage_options) + if fs is None: + fs = filesystem(protocol=target_protocol, **(target_options or {})) + path = path or fo + + if self.asynchronous and not fs.async_impl: + raise ValueError("can't use asynchronous with non-async fs") + + if fs.async_impl and self.asynchronous != fs.asynchronous: + raise ValueError("both dirfs and fs should be in the same sync/async mode") + + self.path = fs._strip_protocol(path) + self.fs = fs + + def _join(self, path): + if isinstance(path, str): + if not self.path: + return path + if not path: + return self.path + return self.fs.sep.join((self.path, self._strip_protocol(path))) + if isinstance(path, dict): + return {self._join(_path): value for _path, value in path.items()} + return [self._join(_path) for _path in path] + + def _relpath(self, path): + if isinstance(path, str): + if not self.path: + return path + # We need to account for S3FileSystem returning paths that do not + # start with a '/' + if path == self.path or ( + self.path.startswith(self.fs.sep) and path == self.path[1:] + ): + return "" + prefix = self.path + self.fs.sep + if self.path.startswith(self.fs.sep) and not path.startswith(self.fs.sep): + prefix = prefix[1:] + assert path.startswith(prefix) + return path[len(prefix) :] + return [self._relpath(_path) for _path in path] + + # Wrappers below + + @property + def sep(self): + return self.fs.sep + + async def set_session(self, *args, **kwargs): + return await self.fs.set_session(*args, **kwargs) + + async def _rm_file(self, path, **kwargs): + return await self.fs._rm_file(self._join(path), **kwargs) + + def rm_file(self, path, **kwargs): + return self.fs.rm_file(self._join(path), **kwargs) + + async def _rm(self, path, *args, **kwargs): + return await self.fs._rm(self._join(path), *args, **kwargs) + + def rm(self, path, *args, **kwargs): + return self.fs.rm(self._join(path), *args, **kwargs) + + def delete(self, path, recursive=False, maxdepth=None): + return self.fs.delete(self._join(path), recursive=recursive, maxdepth=maxdepth) + + async def _cp_file(self, path1, path2, **kwargs): + return await self.fs._cp_file(self._join(path1), self._join(path2), **kwargs) + + def cp_file(self, path1, path2, **kwargs): + return self.fs.cp_file(self._join(path1), self._join(path2), **kwargs) + + async def _copy( + self, + path1, + path2, + *args, + **kwargs, + ): + return await self.fs._copy( + self._join(path1), + self._join(path2), + *args, + **kwargs, + ) + + def copy(self, path1, path2, *args, **kwargs): + return self.fs.copy( + self._join(path1), + self._join(path2), + *args, + **kwargs, + ) + + async def _pipe(self, path, *args, **kwargs): + return await self.fs._pipe(self._join(path), *args, **kwargs) + + def pipe(self, path, *args, **kwargs): + return self.fs.pipe(self._join(path), *args, **kwargs) + + async def _pipe_file(self, path, *args, **kwargs): + return await self.fs._pipe_file(self._join(path), *args, **kwargs) + + def pipe_file(self, path, *args, **kwargs): + return self.fs.pipe_file(self._join(path), *args, **kwargs) + + def write_text( + self, path, value, encoding=None, errors=None, newline=None, **kwargs + ): + return self.fs.write_text( + self._join(path), + value, + encoding=encoding, + errors=errors, + newline=newline, + **kwargs, + ) + + async def _cat_file(self, path, *args, **kwargs): + return await self.fs._cat_file(self._join(path), *args, **kwargs) + + def cat_file(self, path, *args, **kwargs): + return self.fs.cat_file(self._join(path), *args, **kwargs) + + async def _cat(self, path, *args, **kwargs): + ret = await self.fs._cat( + self._join(path), + *args, + **kwargs, + ) + + if isinstance(ret, dict): + return {self._relpath(key): value for key, value in ret.items()} + + return ret + + def cat(self, path, *args, **kwargs): + ret = self.fs.cat( + self._join(path), + *args, + **kwargs, + ) + + if isinstance(ret, dict): + return {self._relpath(key): value for key, value in ret.items()} + + return ret + + async def _put_file(self, lpath, rpath, **kwargs): + return await self.fs._put_file(lpath, self._join(rpath), **kwargs) + + def put_file(self, lpath, rpath, **kwargs): + return self.fs.put_file(lpath, self._join(rpath), **kwargs) + + async def _put( + self, + lpath, + rpath, + *args, + **kwargs, + ): + return await self.fs._put( + lpath, + self._join(rpath), + *args, + **kwargs, + ) + + def put(self, lpath, rpath, *args, **kwargs): + return self.fs.put( + lpath, + self._join(rpath), + *args, + **kwargs, + ) + + async def _get_file(self, rpath, lpath, **kwargs): + return await self.fs._get_file(self._join(rpath), lpath, **kwargs) + + def get_file(self, rpath, lpath, **kwargs): + return self.fs.get_file(self._join(rpath), lpath, **kwargs) + + async def _get(self, rpath, *args, **kwargs): + return await self.fs._get(self._join(rpath), *args, **kwargs) + + def get(self, rpath, *args, **kwargs): + return self.fs.get(self._join(rpath), *args, **kwargs) + + async def _isfile(self, path): + return await self.fs._isfile(self._join(path)) + + def isfile(self, path): + return self.fs.isfile(self._join(path)) + + async def _isdir(self, path): + return await self.fs._isdir(self._join(path)) + + def isdir(self, path): + return self.fs.isdir(self._join(path)) + + async def _size(self, path): + return await self.fs._size(self._join(path)) + + def size(self, path): + return self.fs.size(self._join(path)) + + async def _exists(self, path): + return await self.fs._exists(self._join(path)) + + def exists(self, path): + return self.fs.exists(self._join(path)) + + async def _info(self, path, **kwargs): + info = await self.fs._info(self._join(path), **kwargs) + info = info.copy() + info["name"] = self._relpath(info["name"]) + return info + + def info(self, path, **kwargs): + info = self.fs.info(self._join(path), **kwargs) + info = info.copy() + info["name"] = self._relpath(info["name"]) + return info + + async def _ls(self, path, detail=True, **kwargs): + ret = (await self.fs._ls(self._join(path), detail=detail, **kwargs)).copy() + if detail: + out = [] + for entry in ret: + entry = entry.copy() + entry["name"] = self._relpath(entry["name"]) + out.append(entry) + return out + + return self._relpath(ret) + + def ls(self, path, detail=True, **kwargs): + ret = self.fs.ls(self._join(path), detail=detail, **kwargs).copy() + if detail: + out = [] + for entry in ret: + entry = entry.copy() + entry["name"] = self._relpath(entry["name"]) + out.append(entry) + return out + + return self._relpath(ret) + + async def _walk(self, path, *args, **kwargs): + async for root, dirs, files in self.fs._walk(self._join(path), *args, **kwargs): + yield self._relpath(root), dirs, files + + def walk(self, path, *args, **kwargs): + for root, dirs, files in self.fs.walk(self._join(path), *args, **kwargs): + yield self._relpath(root), dirs, files + + async def _glob(self, path, **kwargs): + detail = kwargs.get("detail", False) + ret = await self.fs._glob(self._join(path), **kwargs) + if detail: + return {self._relpath(path): info for path, info in ret.items()} + return self._relpath(ret) + + def glob(self, path, **kwargs): + detail = kwargs.get("detail", False) + ret = self.fs.glob(self._join(path), **kwargs) + if detail: + return {self._relpath(path): info for path, info in ret.items()} + return self._relpath(ret) + + async def _du(self, path, *args, **kwargs): + total = kwargs.get("total", True) + ret = await self.fs._du(self._join(path), *args, **kwargs) + if total: + return ret + + return {self._relpath(path): size for path, size in ret.items()} + + def du(self, path, *args, **kwargs): + total = kwargs.get("total", True) + ret = self.fs.du(self._join(path), *args, **kwargs) + if total: + return ret + + return {self._relpath(path): size for path, size in ret.items()} + + async def _find(self, path, *args, **kwargs): + detail = kwargs.get("detail", False) + ret = await self.fs._find(self._join(path), *args, **kwargs) + if detail: + return {self._relpath(path): info for path, info in ret.items()} + return self._relpath(ret) + + def find(self, path, *args, **kwargs): + detail = kwargs.get("detail", False) + ret = self.fs.find(self._join(path), *args, **kwargs) + if detail: + return {self._relpath(path): info for path, info in ret.items()} + return self._relpath(ret) + + async def _expand_path(self, path, *args, **kwargs): + return self._relpath( + await self.fs._expand_path(self._join(path), *args, **kwargs) + ) + + def expand_path(self, path, *args, **kwargs): + return self._relpath(self.fs.expand_path(self._join(path), *args, **kwargs)) + + async def _mkdir(self, path, *args, **kwargs): + return await self.fs._mkdir(self._join(path), *args, **kwargs) + + def mkdir(self, path, *args, **kwargs): + return self.fs.mkdir(self._join(path), *args, **kwargs) + + async def _makedirs(self, path, *args, **kwargs): + return await self.fs._makedirs(self._join(path), *args, **kwargs) + + def makedirs(self, path, *args, **kwargs): + return self.fs.makedirs(self._join(path), *args, **kwargs) + + def rmdir(self, path): + return self.fs.rmdir(self._join(path)) + + def mv(self, path1, path2, **kwargs): + return self.fs.mv( + self._join(path1), + self._join(path2), + **kwargs, + ) + + def touch(self, path, **kwargs): + return self.fs.touch(self._join(path), **kwargs) + + def created(self, path): + return self.fs.created(self._join(path)) + + def modified(self, path): + return self.fs.modified(self._join(path)) + + def sign(self, path, *args, **kwargs): + return self.fs.sign(self._join(path), *args, **kwargs) + + def __repr__(self): + return f"{self.__class__.__qualname__}(path='{self.path}', fs={self.fs})" + + def open( + self, + path, + *args, + **kwargs, + ): + return self.fs.open( + self._join(path), + *args, + **kwargs, + ) + + async def open_async( + self, + path, + *args, + **kwargs, + ): + return await self.fs.open_async( + self._join(path), + *args, + **kwargs, + ) diff --git a/python/user_packages/Python313/site-packages/fsspec/implementations/ftp.py b/python/user_packages/Python313/site-packages/fsspec/implementations/ftp.py new file mode 100644 index 0000000000000000000000000000000000000000..ca151c6ea3cc2bb514701cd95fd5258bed3c9899 --- /dev/null +++ b/python/user_packages/Python313/site-packages/fsspec/implementations/ftp.py @@ -0,0 +1,437 @@ +import os +import ssl +import uuid +from ftplib import FTP, FTP_TLS, Error, error_perm +from typing import Any + +from ..spec import AbstractBufferedFile, AbstractFileSystem +from ..utils import infer_storage_options, isfilelike + +SECURITY_PROTOCOL_MAP = { + "tls": ssl.PROTOCOL_TLS, + "tlsv1": ssl.PROTOCOL_TLSv1, + "tlsv1_1": ssl.PROTOCOL_TLSv1_1, + "tlsv1_2": ssl.PROTOCOL_TLSv1_2, + "sslv23": ssl.PROTOCOL_SSLv23, +} + + +class ImplicitFTPTLS(FTP_TLS): + """ + FTP_TLS subclass that automatically wraps sockets in SSL + to support implicit FTPS. + """ + + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + self._sock = None + + @property + def sock(self): + """Return the socket.""" + return self._sock + + @sock.setter + def sock(self, value): + """When modifying the socket, ensure that it is ssl wrapped.""" + if value is not None and not isinstance(value, ssl.SSLSocket): + value = self.context.wrap_socket(value) + self._sock = value + + +class FTPFileSystem(AbstractFileSystem): + """A filesystem over classic FTP""" + + root_marker = "/" + cachable = False + protocol = "ftp" + + def __init__( + self, + host, + port=21, + username=None, + password=None, + acct=None, + block_size=None, + tempdir=None, + timeout=30, + encoding="utf-8", + tls=False, + **kwargs, + ): + """ + You can use _get_kwargs_from_urls to get some kwargs from + a reasonable FTP url. + + Authentication will be anonymous if username/password are not + given. + + Parameters + ---------- + host: str + The remote server name/ip to connect to + port: int + Port to connect with + username: str or None + If authenticating, the user's identifier + password: str of None + User's password on the server, if using + acct: str or None + Some servers also need an "account" string for auth + block_size: int or None + If given, the read-ahead or write buffer size. + tempdir: str + Directory on remote to put temporary files when in a transaction + timeout: int + Timeout of the ftp connection in seconds + encoding: str + Encoding to use for directories and filenames in FTP connection + tls: bool or str + Enable FTP-TLS for secure connections: + - False: Plain FTP (default) + - True: Explicit TLS (FTPS with AUTH TLS command) + - "tls": Auto-negotiate highest protocol + - "tlsv1": TLS v1.0 + - "tlsv1_1": TLS v1.1 + - "tlsv1_2": TLS v1.2 + """ + super().__init__(**kwargs) + self.host = host + self.port = port + self.tempdir = tempdir or "/tmp" + self.cred = username or "", password or "", acct or "" + self.timeout = timeout + self.encoding = encoding + if block_size is not None: + self.blocksize = block_size + else: + self.blocksize = 2**16 + self.tls = tls + self._connect() + if isinstance(self.tls, bool) and self.tls: + self.ftp.prot_p() + + def _connect(self): + security = None + if self.tls: + if isinstance(self.tls, str): + ftp_cls = ImplicitFTPTLS + security = SECURITY_PROTOCOL_MAP.get( + self.tls, + f"Not supported {self.tls} protocol", + ) + if isinstance(security, str): + raise ValueError(security) + else: + ftp_cls = FTP_TLS + else: + ftp_cls = FTP + self.ftp = ftp_cls(timeout=self.timeout, encoding=self.encoding) + if security: + self.ftp.ssl_version = security + self.ftp.connect(self.host, self.port) + self.ftp.login(*self.cred) + + @classmethod + def _strip_protocol(cls, path): + return "/" + infer_storage_options(path)["path"].lstrip("/").rstrip("/") + + @staticmethod + def _get_kwargs_from_urls(urlpath): + out = infer_storage_options(urlpath) + out.pop("path", None) + out.pop("protocol", None) + return out + + def ls(self, path, detail=True, **kwargs): + path = self._strip_protocol(path) + out = [] + if path not in self.dircache: + try: + try: + out = [ + (fn, details) + for (fn, details) in self.ftp.mlsd(path) + if fn not in [".", ".."] + and details["type"] not in ["pdir", "cdir"] + ] + except error_perm: + out = _mlsd2(self.ftp, path) # Not platform independent + for fn, details in out: + details["name"] = "/".join( + ["" if path == "/" else path, fn.lstrip("/")] + ) + if details["type"] == "file": + details["size"] = int(details["size"]) + else: + details["size"] = 0 + if details["type"] == "dir": + details["type"] = "directory" + self.dircache[path] = out + except Error: + try: + info = self.info(path) + if info["type"] == "file": + out = [(path, info)] + except (Error, IndexError) as exc: + raise FileNotFoundError(path) from exc + files = self.dircache.get(path, out) + if not detail: + return sorted([fn for fn, details in files]) + return [details for fn, details in files] + + def info(self, path, **kwargs): + # implement with direct method + path = self._strip_protocol(path) + if path == "/": + # special case, since this dir has no real entry + return {"name": "/", "size": 0, "type": "directory"} + files = self.ls(self._parent(path).lstrip("/"), True) + try: + out = next(f for f in files if f["name"] == path) + except StopIteration as exc: + raise FileNotFoundError(path) from exc + return out + + def get_file(self, rpath, lpath, **kwargs): + if self.isdir(rpath): + if not os.path.exists(lpath): + os.mkdir(lpath) + return + if isfilelike(lpath): + outfile = lpath + else: + outfile = open(lpath, "wb") + + def cb(x): + outfile.write(x) + + self.ftp.retrbinary( + f"RETR {rpath}", + blocksize=self.blocksize, + callback=cb, + ) + if not isfilelike(lpath): + outfile.close() + + def cat_file(self, path, start=None, end=None, **kwargs): + if end is not None: + return super().cat_file(path, start, end, **kwargs) + out = [] + + def cb(x): + out.append(x) + + try: + self.ftp.retrbinary( + f"RETR {path}", + blocksize=self.blocksize, + rest=start, + callback=cb, + ) + except (Error, error_perm) as orig_exc: + raise FileNotFoundError(path) from orig_exc + return b"".join(out) + + def _open( + self, + path, + mode="rb", + block_size=None, + cache_options=None, + autocommit=True, + **kwargs, + ): + path = self._strip_protocol(path) + block_size = block_size or self.blocksize + return FTPFile( + self, + path, + mode=mode, + block_size=block_size, + tempdir=self.tempdir, + autocommit=autocommit, + cache_options=cache_options, + ) + + def _rm(self, path): + path = self._strip_protocol(path) + self.ftp.delete(path) + self.invalidate_cache(self._parent(path)) + + def rm(self, path, recursive=False, maxdepth=None): + paths = self.expand_path(path, recursive=recursive, maxdepth=maxdepth) + for p in reversed(paths): + if self.isfile(p): + self.rm_file(p) + else: + self.rmdir(p) + + def mkdir(self, path: str, create_parents: bool = True, **kwargs: Any) -> None: + path = self._strip_protocol(path) + parent = self._parent(path) + if parent != self.root_marker and not self.exists(parent) and create_parents: + self.mkdir(parent, create_parents=create_parents) + + self.ftp.mkd(path) + self.invalidate_cache(self._parent(path)) + + def makedirs(self, path: str, exist_ok: bool = False) -> None: + path = self._strip_protocol(path) + if self.exists(path): + # NB: "/" does not "exist" as it has no directory entry + if not exist_ok: + raise FileExistsError(f"{path} exists without `exist_ok`") + # exists_ok=True -> no-op + else: + self.mkdir(path, create_parents=True) + + def rmdir(self, path): + path = self._strip_protocol(path) + self.ftp.rmd(path) + self.invalidate_cache(self._parent(path)) + + def mv(self, path1, path2, **kwargs): + path1 = self._strip_protocol(path1) + path2 = self._strip_protocol(path2) + self.ftp.rename(path1, path2) + self.invalidate_cache(self._parent(path1)) + self.invalidate_cache(self._parent(path2)) + + def __del__(self): + self.ftp.close() + + def invalidate_cache(self, path=None): + if path is None: + self.dircache.clear() + else: + self.dircache.pop(path, None) + super().invalidate_cache(path) + + +class TransferDone(Exception): + """Internal exception to break out of transfer""" + + pass + + +class FTPFile(AbstractBufferedFile): + """Interact with a remote FTP file with read/write buffering""" + + def __init__( + self, + fs, + path, + mode="rb", + block_size="default", + autocommit=True, + cache_type="readahead", + cache_options=None, + **kwargs, + ): + super().__init__( + fs, + path, + mode=mode, + block_size=block_size, + autocommit=autocommit, + cache_type=cache_type, + cache_options=cache_options, + **kwargs, + ) + if not autocommit: + self.target = self.path + self.path = "/".join([kwargs["tempdir"], str(uuid.uuid4())]) + + def commit(self): + self.fs.mv(self.path, self.target) + + def discard(self): + self.fs.rm(self.path) + + def _fetch_range(self, start, end): + """Get bytes between given byte limits + + Implemented by raising an exception in the fetch callback when the + number of bytes received reaches the requested amount. + + Will fail if the server does not respect the REST command on + retrieve requests. + """ + out = [] + total = [0] + + def callback(x): + total[0] += len(x) + if total[0] > end - start: + out.append(x[: (end - start) - total[0]]) + if end < self.size: + raise TransferDone + else: + out.append(x) + + if total[0] == end - start and end < self.size: + raise TransferDone + + try: + self.fs.ftp.retrbinary( + f"RETR {self.path}", + blocksize=self.blocksize, + rest=start, + callback=callback, + ) + except TransferDone: + try: + # stop transfer, we got enough bytes for this block + self.fs.ftp.abort() + self.fs.ftp.getmultiline() + except Error: + self.fs._connect() + + return b"".join(out) + + def _upload_chunk(self, final=False): + self.buffer.seek(0) + self.fs.ftp.storbinary( + f"STOR {self.path}", self.buffer, blocksize=self.blocksize, rest=self.offset + ) + return True + + +def _mlsd2(ftp, path="."): + """ + Fall back to using `dir` instead of `mlsd` if not supported. + + This parses a Linux style `ls -l` response to `dir`, but the response may + be platform dependent. + + Parameters + ---------- + ftp: ftplib.FTP + path: str + Expects to be given path, but defaults to ".". + """ + lines = [] + minfo = [] + ftp.dir(path, lines.append) + for line in lines: + split_line = line.split() + if len(split_line) < 9: + continue + this = ( + split_line[-1], + { + "modify": " ".join(split_line[5:8]), + "unix.owner": split_line[2], + "unix.group": split_line[3], + "unix.mode": split_line[0], + "size": split_line[4], + }, + ) + if this[1]["unix.mode"][0] == "d": + this[1]["type"] = "dir" + else: + this[1]["type"] = "file" + minfo.append(this) + return minfo diff --git a/python/user_packages/Python313/site-packages/fsspec/implementations/gist.py b/python/user_packages/Python313/site-packages/fsspec/implementations/gist.py new file mode 100644 index 0000000000000000000000000000000000000000..ad9ac0b6a1cdbcfba6188e2cdeab2350bb9aad0a --- /dev/null +++ b/python/user_packages/Python313/site-packages/fsspec/implementations/gist.py @@ -0,0 +1,241 @@ +import requests + +from ..spec import AbstractFileSystem +from ..utils import infer_storage_options +from .memory import MemoryFile + + +class GistFileSystem(AbstractFileSystem): + """ + Interface to files in a single GitHub Gist. + + Provides read-only access to a gist's files. Gists do not contain + subdirectories, so file listing is straightforward. + + Parameters + ---------- + gist_id: str + The ID of the gist you want to access (the long hex value from the URL). + filenames: list[str] (optional) + If provided, only make a file system representing these files, and do not fetch + the list of all files for this gist. + sha: str (optional) + If provided, fetch a particular revision of the gist. If omitted, + the latest revision is used. + username: str (optional) + GitHub username for authentication. + token: str (optional) + GitHub personal access token (required if username is given), or. + timeout: (float, float) or float, optional + Connect and read timeouts for requests (default 60s each). + kwargs: dict + Stored on `self.request_kw` and passed to `requests.get` when fetching Gist + metadata or reading ("opening") a file. + """ + + protocol = "gist" + gist_url = "https://api.github.com/gists/{gist_id}" + gist_rev_url = "https://api.github.com/gists/{gist_id}/{sha}" + + def __init__( + self, + gist_id, + filenames=None, + sha=None, + username=None, + token=None, + timeout=None, + **kwargs, + ): + super().__init__() + self.gist_id = gist_id + self.filenames = filenames + self.sha = sha # revision of the gist (optional) + if username is not None and token is None: + raise ValueError("User auth requires a token") + self.username = username + self.token = token + self.request_kw = kwargs + # Default timeouts to 60s connect/read if none provided + self.timeout = timeout if timeout is not None else (60, 60) + + # We use a single-level "directory" cache, because a gist is essentially flat + self.dircache[""] = self._fetch_file_list() + + @property + def kw(self): + """Auth parameters passed to 'requests' if we have username/token.""" + kw = { + "headers": { + "Accept": "application/vnd.github+json", + "X-GitHub-Api-Version": "2022-11-28", + } + } + kw.update(self.request_kw) + if self.username and self.token: + kw["auth"] = (self.username, self.token) + elif self.token: + kw["headers"]["Authorization"] = f"Bearer {self.token}" + return kw + + def _fetch_gist_metadata(self): + """ + Fetch the JSON metadata for this gist (possibly for a specific revision). + """ + if self.sha: + url = self.gist_rev_url.format(gist_id=self.gist_id, sha=self.sha) + else: + url = self.gist_url.format(gist_id=self.gist_id) + + r = requests.get(url, timeout=self.timeout, **self.kw) + if r.status_code == 404: + raise FileNotFoundError( + f"Gist not found: {self.gist_id}@{self.sha or 'latest'}" + ) + r.raise_for_status() + return r.json() + + def _fetch_file_list(self): + """ + Returns a list of dicts describing each file in the gist. These get stored + in self.dircache[""]. + """ + meta = self._fetch_gist_metadata() + if self.filenames: + available_files = meta.get("files", {}) + files = {} + for fn in self.filenames: + if fn not in available_files: + raise FileNotFoundError(fn) + files[fn] = available_files[fn] + else: + files = meta.get("files", {}) + + out = [] + for fname, finfo in files.items(): + if finfo is None: + # Occasionally GitHub returns a file entry with null if it was deleted + continue + # Build a directory entry + out.append( + { + "name": fname, # file's name + "type": "file", # gists have no subdirectories + "size": finfo.get("size", 0), # file size in bytes + "raw_url": finfo.get("raw_url"), + } + ) + return out + + @classmethod + def _strip_protocol(cls, path): + """ + Remove 'gist://' from the path, if present. + """ + # The default infer_storage_options can handle gist://username:token@id/file + # or gist://id/file, but let's ensure we handle a normal usage too. + # We'll just strip the protocol prefix if it exists. + path = infer_storage_options(path).get("path", path) + return path.lstrip("/") + + @staticmethod + def _get_kwargs_from_urls(path): + """ + Parse 'gist://' style URLs into GistFileSystem constructor kwargs. + For example: + gist://:TOKEN@/file.txt + gist://username:TOKEN@/file.txt + """ + so = infer_storage_options(path) + out = {} + if "username" in so and so["username"]: + out["username"] = so["username"] + if "password" in so and so["password"]: + out["token"] = so["password"] + if "host" in so and so["host"]: + # We interpret 'host' as the gist ID + out["gist_id"] = so["host"] + + # Extract SHA and filename from path + if "path" in so and so["path"]: + path_parts = so["path"].rsplit("/", 2)[-2:] + if len(path_parts) == 2: + if path_parts[0]: # SHA present + out["sha"] = path_parts[0] + if path_parts[1]: # filename also present + out["filenames"] = [path_parts[1]] + + return out + + def ls(self, path="", detail=False, **kwargs): + """ + List files in the gist. Gists are single-level, so any 'path' is basically + the filename, or empty for all files. + + Parameters + ---------- + path : str, optional + The filename to list. If empty, returns all files in the gist. + detail : bool, default False + If True, return a list of dicts; if False, return a list of filenames. + """ + path = self._strip_protocol(path or "") + # If path is empty, return all + if path == "": + results = self.dircache[""] + else: + # We want just the single file with this name + all_files = self.dircache[""] + results = [f for f in all_files if f["name"] == path] + if not results: + raise FileNotFoundError(path) + if detail: + return results + else: + return sorted(f["name"] for f in results) + + def _open(self, path, mode="rb", block_size=None, **kwargs): + """ + Read a single file from the gist. + """ + if mode != "rb": + raise NotImplementedError("GitHub Gist FS is read-only (no write).") + + path = self._strip_protocol(path) + # Find the file entry in our dircache + matches = [f for f in self.dircache[""] if f["name"] == path] + if not matches: + raise FileNotFoundError(path) + finfo = matches[0] + + raw_url = finfo.get("raw_url") + if not raw_url: + raise FileNotFoundError(f"No raw_url for file: {path}") + + r = requests.get(raw_url, timeout=self.timeout, **self.kw) + if r.status_code == 404: + raise FileNotFoundError(path) + r.raise_for_status() + return MemoryFile(path, None, r.content) + + def cat(self, path, recursive=False, on_error="raise", **kwargs): + """ + Return {path: contents} for the given file or files. If 'recursive' is True, + and path is empty, returns all files in the gist. + """ + paths = self.expand_path(path, recursive=recursive) + out = {} + for p in paths: + try: + with self.open(p, "rb") as f: + out[p] = f.read() + except FileNotFoundError as e: + if on_error == "raise": + raise e + elif on_error == "omit": + pass # skip + else: + out[p] = e + if len(paths) == 1 and paths[0] == path: + return out[path] + return out diff --git a/python/user_packages/Python313/site-packages/fsspec/implementations/git.py b/python/user_packages/Python313/site-packages/fsspec/implementations/git.py new file mode 100644 index 0000000000000000000000000000000000000000..808d293a1c991ea87d19a2129f3e56d9b813daaa --- /dev/null +++ b/python/user_packages/Python313/site-packages/fsspec/implementations/git.py @@ -0,0 +1,114 @@ +import os + +import pygit2 + +from fsspec.spec import AbstractFileSystem + +from .memory import MemoryFile + + +class GitFileSystem(AbstractFileSystem): + """Browse the files of a local git repo at any hash/tag/branch + + (experimental backend) + """ + + root_marker = "" + cachable = True + + def __init__(self, path=None, fo=None, ref=None, **kwargs): + """ + + Parameters + ---------- + path: str (optional) + Local location of the repo (uses current directory if not given). + May be deprecated in favour of ``fo``. When used with a higher + level function such as fsspec.open(), may be of the form + "git://[path-to-repo[:]][ref@]path/to/file" (but the actual + file path should not contain "@" or ":"). + fo: str (optional) + Same as ``path``, but passed as part of a chained URL. This one + takes precedence if both are given. + ref: str (optional) + Reference to work with, could be a hash, tag or branch name. Defaults + to current working tree. Note that ``ls`` and ``open`` also take hash, + so this becomes the default for those operations + kwargs + """ + super().__init__(**kwargs) + self.repo = pygit2.Repository(fo or path or os.getcwd()) + self.ref = ref or "master" + + @classmethod + def _strip_protocol(cls, path): + path = super()._strip_protocol(path).lstrip("/") + if ":" in path: + path = path.split(":", 1)[1] + if "@" in path: + path = path.split("@", 1)[1] + return path.lstrip("/") + + def _path_to_object(self, path, ref): + comm, ref = self.repo.resolve_refish(ref or self.ref) + parts = path.split("/") + tree = comm.tree + for part in parts: + if part and isinstance(tree, pygit2.Tree): + if part not in tree: + raise FileNotFoundError(path) + tree = tree[part] + return tree + + @staticmethod + def _get_kwargs_from_urls(path): + path = path.removeprefix("git://") + out = {} + if ":" in path: + out["path"], path = path.split(":", 1) + if "@" in path: + out["ref"], path = path.split("@", 1) + return out + + @staticmethod + def _object_to_info(obj, path=None): + # obj.name and obj.filemode are None for the root tree! + is_dir = isinstance(obj, pygit2.Tree) + return { + "type": "directory" if is_dir else "file", + "name": ( + "/".join([path, obj.name or ""]).lstrip("/") if path else obj.name + ), + "hex": str(obj.id), + "mode": "100644" if obj.filemode is None else f"{obj.filemode:o}", + "size": 0 if is_dir else obj.size, + } + + def ls(self, path, detail=True, ref=None, **kwargs): + tree = self._path_to_object(self._strip_protocol(path), ref) + return [ + GitFileSystem._object_to_info(obj, path) + if detail + else GitFileSystem._object_to_info(obj, path)["name"] + for obj in (tree if isinstance(tree, pygit2.Tree) else [tree]) + ] + + def info(self, path, ref=None, **kwargs): + tree = self._path_to_object(self._strip_protocol(path), ref) + return GitFileSystem._object_to_info(tree, path) + + def ukey(self, path, ref=None): + return self.info(path, ref=ref)["hex"] + + def _open( + self, + path, + mode="rb", + block_size=None, + autocommit=True, + cache_options=None, + ref=None, + **kwargs, + ): + obj = self._path_to_object(path, ref or self.ref) + return MemoryFile(data=obj.data) diff --git a/python/user_packages/Python313/site-packages/fsspec/implementations/github.py b/python/user_packages/Python313/site-packages/fsspec/implementations/github.py new file mode 100644 index 0000000000000000000000000000000000000000..3630f6db54413e2c396f6cc1b6b10cd379200043 --- /dev/null +++ b/python/user_packages/Python313/site-packages/fsspec/implementations/github.py @@ -0,0 +1,333 @@ +import base64 +import re + +import requests + +from ..spec import AbstractFileSystem +from ..utils import infer_storage_options +from .memory import MemoryFile + + +class GithubFileSystem(AbstractFileSystem): + """Interface to files in github + + An instance of this class provides the files residing within a remote github + repository. You may specify a point in the repos history, by SHA, branch + or tag (default is current master). + + For files less than 1 MB in size, file content is returned directly in a + MemoryFile. For larger files, or for files tracked by git-lfs, file content + is returned as an HTTPFile wrapping the ``download_url`` provided by the + GitHub API. + + When using fsspec.open, allows URIs of the form: + + - "github://path/file", in which case you must specify org, repo and + may specify sha in the extra args + - 'github://org:repo@/precip/catalog.yml', where the org and repo are + part of the URI + - 'github://org:repo@sha/precip/catalog.yml', where the sha is also included + + ``sha`` can be the full or abbreviated hex of the commit you want to fetch + from, or a branch or tag name (so long as it doesn't contain special characters + like "/", "?", which would have to be HTTP-encoded). + + For authorised access, you must provide username and token, which can be made + at https://github.com/settings/tokens + """ + + url = "https://api.github.com/repos/{org}/{repo}/git/trees/{sha}" + content_url = "https://api.github.com/repos/{org}/{repo}/contents/{path}?ref={sha}" + protocol = "github" + timeout = (60, 60) # connect, read timeouts + + def __init__( + self, org, repo, sha=None, username=None, token=None, timeout=None, **kwargs + ): + super().__init__(**kwargs) + self.org = org + self.repo = repo + if (username is None) ^ (token is None): + raise ValueError("Auth required both username and token") + self.username = username + self.token = token + if timeout is not None: + self.timeout = timeout + if sha is None: + # look up default branch (not necessarily "master") + u = "https://api.github.com/repos/{org}/{repo}" + r = requests.get( + u.format(org=org, repo=repo), timeout=self.timeout, **self.kw + ) + r.raise_for_status() + sha = r.json()["default_branch"] + + self.root = sha + self.ls("") + try: + from .http import HTTPFileSystem + + self.http_fs = HTTPFileSystem(**kwargs) + except ImportError: + self.http_fs = None + + @property + def kw(self): + if self.username: + return {"auth": (self.username, self.token)} + return {} + + @classmethod + def repos(cls, org_or_user, is_org=True): + """List repo names for given org or user + + This may become the top level of the FS + + Parameters + ---------- + org_or_user: str + Name of the github org or user to query + is_org: bool (default True) + Whether the name is an organisation (True) or user (False) + + Returns + ------- + List of string + """ + r = requests.get( + f"https://api.github.com/{['users', 'orgs'][is_org]}/{org_or_user}/repos", + timeout=cls.timeout, + ) + r.raise_for_status() + return [repo["name"] for repo in r.json()] + + @property + def tags(self): + """Names of tags in the repo""" + r = requests.get( + f"https://api.github.com/repos/{self.org}/{self.repo}/tags", + timeout=self.timeout, + **self.kw, + ) + r.raise_for_status() + return [t["name"] for t in r.json()] + + @property + def branches(self): + """Names of branches in the repo""" + r = requests.get( + f"https://api.github.com/repos/{self.org}/{self.repo}/branches", + timeout=self.timeout, + **self.kw, + ) + r.raise_for_status() + return [t["name"] for t in r.json()] + + @property + def refs(self): + """Named references, tags and branches""" + return {"tags": self.tags, "branches": self.branches} + + def ls(self, path, detail=False, sha=None, _sha=None, **kwargs): + """List files at given path + + Parameters + ---------- + path: str + Location to list, relative to repo root + detail: bool + If True, returns list of dicts, one per file; if False, returns + list of full filenames only + sha: str (optional) + List at the given point in the repo history, branch or tag name or commit + SHA + _sha: str (optional) + List this specific tree object (used internally to descend into trees) + """ + path = self._strip_protocol(path) + if path == "": + _sha = sha or self.root + if _sha is None: + parts = path.rstrip("/").split("/") + so_far = "" + _sha = sha or self.root + for part in parts: + out = self.ls(so_far, True, sha=sha, _sha=_sha) + so_far += "/" + part if so_far else part + out = [o for o in out if o["name"] == so_far] + if not out: + raise FileNotFoundError(path) + out = out[0] + if out["type"] == "file": + if detail: + return [out] + else: + return path + _sha = out["sha"] + if path not in self.dircache or sha not in [self.root, None]: + r = requests.get( + self.url.format(org=self.org, repo=self.repo, sha=_sha), + timeout=self.timeout, + **self.kw, + ) + if r.status_code == 404: + raise FileNotFoundError(path) + r.raise_for_status() + types = {"blob": "file", "tree": "directory"} + out = [ + { + "name": path + "/" + f["path"] if path else f["path"], + "mode": f["mode"], + "type": types[f["type"]], + "size": f.get("size", 0), + "sha": f["sha"], + } + for f in r.json()["tree"] + if f["type"] in types + ] + if sha in [self.root, None]: + self.dircache[path] = out + else: + out = self.dircache[path] + if detail: + return out + else: + return sorted([f["name"] for f in out]) + + def invalidate_cache(self, path=None): + self.dircache.clear() + + @classmethod + def _strip_protocol(cls, path): + opts = infer_storage_options(path) + if "username" not in opts: + return super()._strip_protocol(path) + return opts["path"].lstrip("/") + + @staticmethod + def _get_kwargs_from_urls(path): + opts = infer_storage_options(path) + if "username" not in opts: + return {} + out = {"org": opts["username"], "repo": opts["password"]} + if opts["host"]: + out["sha"] = opts["host"] + return out + + def _open( + self, + path, + mode="rb", + block_size=None, + cache_options=None, + sha=None, + **kwargs, + ): + if mode != "rb": + raise NotImplementedError + + # construct a url to hit the GitHub API's repo contents API + url = self.content_url.format( + org=self.org, repo=self.repo, path=path, sha=sha or self.root + ) + + # make a request to this API, and parse the response as JSON + r = requests.get(url, timeout=self.timeout, **self.kw) + if r.status_code == 404: + raise FileNotFoundError(path) + r.raise_for_status() + content_json = r.json() + + # if the response's content key is not empty, try to parse it as base64 + if content_json["content"]: + content = base64.b64decode(content_json["content"]) + + # as long as the content does not start with the string + # "version https://git-lfs.github.com/" + # then it is probably not a git-lfs pointer and we can just return + # the content directly + if not content.startswith(b"version https://git-lfs.github.com/"): + return MemoryFile(None, None, content) + + # we land here if the content was not present in the first response + # (regular file over 1MB or git-lfs tracked file) + # in this case, we get let the HTTPFileSystem handle the download + if self.http_fs is None: + raise ImportError( + "Please install fsspec[http] to access github files >1 MB " + "or git-lfs tracked files." + ) + return self.http_fs.open( + content_json["download_url"], + mode=mode, + block_size=block_size, + cache_options=cache_options, + **kwargs, + ) + + def rm(self, path, recursive=False, maxdepth=None, message=None): + path = self.expand_path(path, recursive=recursive, maxdepth=maxdepth) + for p in reversed(path): + self.rm_file(p, message=message) + + def rm_file(self, path, message=None, **kwargs): + """ + Remove a file from a specified branch using a given commit message. + + Since Github DELETE operation requires a branch name, and we can't reliably + determine whether the provided SHA refers to a branch, tag, or commit, we + assume it's a branch. If it's not, the user will encounter an error when + attempting to retrieve the file SHA or delete the file. + + Parameters + ---------- + path: str + The file's location relative to the repository root. + message: str, optional + The commit message for the deletion. + """ + + if not self.username: + raise ValueError("Authentication required") + + path = self._strip_protocol(path) + + # Attempt to get SHA from cache or Github API + sha = self._get_sha_from_cache(path) + if not sha: + url = self.content_url.format( + org=self.org, repo=self.repo, path=path.lstrip("/"), sha=self.root + ) + r = requests.get(url, timeout=self.timeout, **self.kw) + if r.status_code == 404: + raise FileNotFoundError(path) + r.raise_for_status() + sha = r.json()["sha"] + + # Delete the file + delete_url = self.content_url.format( + org=self.org, repo=self.repo, path=path, sha=self.root + ) + branch = self.root + data = { + "message": message or f"Delete {path}", + "sha": sha, + **({"branch": branch} if branch else {}), + } + + r = requests.delete(delete_url, json=data, timeout=self.timeout, **self.kw) + error_message = r.json().get("message", "") + if re.search(r"Branch .+ not found", error_message): + error = "Remove only works when the filesystem is initialised from a branch or default (None)" + raise ValueError(error) + r.raise_for_status() + + self.invalidate_cache(path) + + def _get_sha_from_cache(self, path): + for entries in self.dircache.values(): + for entry in entries: + entry_path = entry.get("name") + if entry_path and entry_path == path and "sha" in entry: + return entry["sha"] + return None diff --git a/python/user_packages/Python313/site-packages/fsspec/implementations/http.py b/python/user_packages/Python313/site-packages/fsspec/implementations/http.py new file mode 100644 index 0000000000000000000000000000000000000000..aff1a955c27091229513b988627de9e806dca8c5 --- /dev/null +++ b/python/user_packages/Python313/site-packages/fsspec/implementations/http.py @@ -0,0 +1,902 @@ +import asyncio +import io +import logging +import re +import weakref +from copy import copy +from urllib.parse import urlparse + +import aiohttp +import yarl + +from fsspec.asyn import AbstractAsyncStreamedFile, AsyncFileSystem, sync, sync_wrapper +from fsspec.callbacks import DEFAULT_CALLBACK +from fsspec.exceptions import FSTimeoutError +from fsspec.spec import AbstractBufferedFile +from fsspec.utils import ( + DEFAULT_BLOCK_SIZE, + glob_translate, + isfilelike, + nullcontext, + tokenize, +) + +from ..caching import AllBytes + +# https://stackoverflow.com/a/15926317/3821154 +ex = re.compile(r"""<(a|A)\s+(?:[^>]*?\s+)?(href|HREF)=["'](?P[^"']+)""") +ex2 = re.compile(r"""(?Phttp[s]?://[-a-zA-Z0-9@:%_+.~#?&/=]+)""") +logger = logging.getLogger("fsspec.http") + + +async def get_client(**kwargs): + return aiohttp.ClientSession(**kwargs) + + +class HTTPFileSystem(AsyncFileSystem): + """ + Simple File-System for fetching data via HTTP(S) + + ``ls()`` is implemented by loading the parent page and doing a regex + match on the result. If simple_link=True, anything of the form + "http(s)://server.com/stuff?thing=other"; otherwise only links within + HTML href tags will be used. + + URLs are passed unfiltered to aiohttp, so all addresses are accessible. Where URLs are + supplied by a user, the calling application may wish to filter to prevent scanning. + """ + + protocol = ("http", "https") + sep = "/" + + def __init__( + self, + simple_links=True, + block_size=None, + same_scheme=True, + size_policy=None, + cache_type="bytes", + cache_options=None, + asynchronous=False, + loop=None, + client_kwargs=None, + get_client=get_client, + encoded=False, + **storage_options, + ): + """ + NB: if this is called async, you must await set_client + + Parameters + ---------- + block_size: int + Blocks to read bytes; if 0, will default to raw requests file-like + objects instead of HTTPFile instances + simple_links: bool + If True, will consider both HTML tags and anything that looks + like a URL; if False, will consider only the former. + same_scheme: True + When doing ls/glob, if this is True, only consider paths that have + http/https matching the input URLs. + size_policy: this argument is deprecated + client_kwargs: dict + Passed to aiohttp.ClientSession, see + https://docs.aiohttp.org/en/stable/client_reference.html + For example, ``{'auth': aiohttp.BasicAuth('user', 'pass')}`` + get_client: Callable[..., aiohttp.ClientSession] + A callable, which takes keyword arguments and constructs + an aiohttp.ClientSession. Its state will be managed by + the HTTPFileSystem class. + storage_options: key-value + Any other parameters passed on to requests + cache_type, cache_options: defaults used in open() + """ + super().__init__(self, asynchronous=asynchronous, loop=loop, **storage_options) + self.block_size = block_size if block_size is not None else DEFAULT_BLOCK_SIZE + self.simple_links = simple_links + self.same_schema = same_scheme + self.cache_type = cache_type + self.cache_options = cache_options + self.client_kwargs = client_kwargs or {} + self.get_client = get_client + self.encoded = encoded + self.kwargs = storage_options + self._session = None + + # Clean caching-related parameters from `storage_options` + # before propagating them as `request_options` through `self.kwargs`. + # TODO: Maybe rename `self.kwargs` to `self.request_options` to make + # it clearer. + request_options = copy(storage_options) + self.use_listings_cache = request_options.pop("use_listings_cache", False) + request_options.pop("listings_expiry_time", None) + request_options.pop("max_paths", None) + request_options.pop("skip_instance_cache", None) + self.kwargs = request_options + + @property + def fsid(self): + return "http" + + def encode_url(self, url): + return yarl.URL(url, encoded=self.encoded) + + @staticmethod + def close_session(loop, session): + if loop is not None and loop.is_running(): + try: + sync(loop, session.close, timeout=0.1) + return + except (TimeoutError, FSTimeoutError, NotImplementedError): + pass + connector = getattr(session, "_connector", None) + if connector is not None: + # close after loop is dead + connector._close() + + async def set_session(self): + if self._session is None: + self._session = await self.get_client(loop=self.loop, **self.client_kwargs) + if not self.asynchronous: + weakref.finalize(self, self.close_session, self.loop, self._session) + return self._session + + @classmethod + def _strip_protocol(cls, path): + """For HTTP, we always want to keep the full URL""" + return path + + @classmethod + def _parent(cls, path): + # override, since _strip_protocol is different for URLs + par = super()._parent(path) + if len(par) > 7: # "http://..." + return par + return "" + + async def _ls_real(self, url, detail=True, **kwargs): + # ignoring URL-encoded arguments + kw = self.kwargs.copy() + kw.update(kwargs) + logger.debug(url) + session = await self.set_session() + async with session.get(self.encode_url(url), **self.kwargs) as r: + self._raise_not_found_for_status(r, url) + + if "Content-Type" in r.headers: + mimetype = r.headers["Content-Type"].partition(";")[0] + else: + mimetype = None + + if mimetype in ("text/html", None): + try: + text = await r.text(errors="ignore") + if self.simple_links: + links = ex2.findall(text) + [u[2] for u in ex.findall(text)] + else: + links = [u[2] for u in ex.findall(text)] + except UnicodeDecodeError: + links = [] # binary, not HTML + else: + links = [] + + out = set() + parts = urlparse(url) + for l in links: + if isinstance(l, tuple): + l = l[1] + if l.startswith("/") and len(l) > 1: + # absolute URL on this server + l = f"{parts.scheme}://{parts.netloc}{l}" + if l.startswith("http"): + if self.same_schema and l.startswith(url.rstrip("/") + "/"): + out.add(l) + elif l.replace("https", "http").startswith( + url.replace("https", "http").rstrip("/") + "/" + ): + # allowed to cross http <-> https + out.add(l) + else: + if l not in ["..", "../"]: + # Ignore FTP-like "parent" + out.add("/".join([url.rstrip("/"), l.lstrip("/")])) + if not out and url.endswith("/"): + out = await self._ls_real(url.rstrip("/"), detail=False) + if detail: + return [ + { + "name": u, + "size": None, + "type": "directory" if u.endswith("/") else "file", + } + for u in out + ] + else: + return sorted(out) + + async def _ls(self, url, detail=True, **kwargs): + if self.use_listings_cache and url in self.dircache: + out = self.dircache[url] + else: + out = await self._ls_real(url, detail=detail, **kwargs) + self.dircache[url] = out + return out + + ls = sync_wrapper(_ls) + + def _raise_not_found_for_status(self, response, url): + """ + Raises FileNotFoundError for 404s, otherwise uses raise_for_status. + """ + if response.status == 404: + raise FileNotFoundError(url) + response.raise_for_status() + + async def _cat_file(self, url, start=None, end=None, **kwargs): + kw = self.kwargs.copy() + kw.update(kwargs) + logger.debug(url) + + if start is not None or end is not None: + if start == end: + return b"" + headers = kw.pop("headers", {}).copy() + + headers["Range"] = await self._process_limits(url, start, end) + kw["headers"] = headers + session = await self.set_session() + async with session.get(self.encode_url(url), **kw) as r: + out = await r.read() + self._raise_not_found_for_status(r, url) + return out + + async def _get_file( + self, rpath, lpath, chunk_size=5 * 2**20, callback=DEFAULT_CALLBACK, **kwargs + ): + kw = self.kwargs.copy() + kw.update(kwargs) + logger.debug(rpath) + session = await self.set_session() + async with session.get(self.encode_url(rpath), **kw) as r: + try: + size = int(r.headers["content-length"]) + except (ValueError, KeyError): + size = None + + callback.set_size(size) + self._raise_not_found_for_status(r, rpath) + if isfilelike(lpath): + outfile = lpath + else: + outfile = open(lpath, "wb") # noqa: ASYNC230 + + try: + chunk = True + while chunk: + chunk = await r.content.read(chunk_size) + outfile.write(chunk) + callback.relative_update(len(chunk)) + finally: + if not isfilelike(lpath): + outfile.close() + + async def _put_file( + self, + lpath, + rpath, + chunk_size=5 * 2**20, + callback=DEFAULT_CALLBACK, + method="post", + mode="overwrite", + **kwargs, + ): + if mode != "overwrite": + raise NotImplementedError("Exclusive write") + + async def gen_chunks(): + # Support passing arbitrary file-like objects + # and use them instead of streams. + if isinstance(lpath, io.IOBase): + context = nullcontext(lpath) + use_seek = False # might not support seeking + else: + context = open(lpath, "rb") # noqa: ASYNC230 + use_seek = True + + with context as f: + if use_seek: + callback.set_size(f.seek(0, 2)) + f.seek(0) + else: + callback.set_size(getattr(f, "size", None)) + + chunk = f.read(chunk_size) + while chunk: + yield chunk + callback.relative_update(len(chunk)) + chunk = f.read(chunk_size) + + kw = self.kwargs.copy() + kw.update(kwargs) + session = await self.set_session() + + method = method.lower() + if method not in ("post", "put"): + raise ValueError( + f"method has to be either 'post' or 'put', not: {method!r}" + ) + + meth = getattr(session, method) + async with meth(self.encode_url(rpath), data=gen_chunks(), **kw) as resp: + self._raise_not_found_for_status(resp, rpath) + + async def _exists(self, path, strict=False, **kwargs): + kw = self.kwargs.copy() + kw.update(kwargs) + try: + logger.debug(path) + session = await self.set_session() + r = await session.get(self.encode_url(path), **kw) + async with r: + if strict: + self._raise_not_found_for_status(r, path) + return r.status < 400 + except FileNotFoundError: + return False + except aiohttp.ClientError: + if strict: + raise + return False + + async def _isfile(self, path, **kwargs): + return await self._exists(path, **kwargs) + + def _open( + self, + path, + mode="rb", + block_size=None, + autocommit=None, # XXX: This differs from the base class. + cache_type=None, + cache_options=None, + size=None, + **kwargs, + ): + """Make a file-like object + + Parameters + ---------- + path: str + Full URL with protocol + mode: string + must be "rb" + block_size: int or None + Bytes to download in one request; use instance value if None. If + zero, will return a streaming Requests file-like instance. + kwargs: key-value + Any other parameters, passed to requests calls + """ + if mode != "rb": + raise NotImplementedError + block_size = block_size if block_size is not None else self.block_size + kw = self.kwargs.copy() + kw["asynchronous"] = self.asynchronous + kw.update(kwargs) + info = {} + size = size or info.update(self.info(path, **kwargs)) or info["size"] + session = sync(self.loop, self.set_session) + if block_size and size and info.get("partial", True): + return HTTPFile( + self, + path, + session=session, + block_size=block_size, + mode=mode, + size=size, + cache_type=cache_type or self.cache_type, + cache_options=cache_options or self.cache_options, + loop=self.loop, + **kw, + ) + else: + return HTTPStreamFile( + self, + path, + mode=mode, + loop=self.loop, + session=session, + **kw, + ) + + async def open_async(self, path, mode="rb", size=None, **kwargs): + session = await self.set_session() + if size is None: + try: + size = (await self._info(path, **kwargs))["size"] + except FileNotFoundError: + pass + return AsyncStreamFile( + self, + path, + loop=self.loop, + session=session, + size=size, + **kwargs, + ) + + def ukey(self, url): + """Unique identifier; assume HTTP files are static, unchanging""" + return tokenize(url, self.kwargs, self.protocol) + + async def _info(self, url, **kwargs): + """Get info of URL + + Tries to access location via HEAD, and then GET methods, but does + not fetch the data. + + It is possible that the server does not supply any size information, in + which case size will be given as None (and certain operations on the + corresponding file will not work). + """ + info = {} + session = await self.set_session() + + for policy in ["head", "get"]: + try: + info.update( + await _file_info( + self.encode_url(url), + size_policy=policy, + session=session, + **self.kwargs, + **kwargs, + ) + ) + if info.get("size") is not None: + break + except Exception as exc: + if policy == "get": + # If get failed, then raise a FileNotFoundError + raise FileNotFoundError(url) from exc + logger.debug("", exc_info=exc) + + return {"name": url, "size": None, **info, "type": "file"} + + async def _glob(self, path, maxdepth=None, **kwargs): + """ + Find files by glob-matching. + + This implementation is idntical to the one in AbstractFileSystem, + but "?" is not considered as a character for globbing, because it is + so common in URLs, often identifying the "query" part. + """ + if maxdepth is not None and maxdepth < 1: + raise ValueError("maxdepth must be at least 1") + import re + + ends_with_slash = path.endswith("/") # _strip_protocol strips trailing slash + path = self._strip_protocol(path) + append_slash_to_dirname = ends_with_slash or path.endswith(("/**", "/*")) + idx_star = path.find("*") if path.find("*") >= 0 else len(path) + idx_brace = path.find("[") if path.find("[") >= 0 else len(path) + + min_idx = min(idx_star, idx_brace) + + detail = kwargs.pop("detail", False) + + if not has_magic(path): + if await self._exists(path, **kwargs): + if not detail: + return [path] + else: + return {path: await self._info(path, **kwargs)} + else: + if not detail: + return [] # glob of non-existent returns empty + else: + return {} + elif "/" in path[:min_idx]: + min_idx = path[:min_idx].rindex("/") + root = path[: min_idx + 1] + depth = path[min_idx + 1 :].count("/") + 1 + else: + root = "" + depth = path[min_idx + 1 :].count("/") + 1 + + if "**" in path: + if maxdepth is not None: + idx_double_stars = path.find("**") + depth_double_stars = path[idx_double_stars:].count("/") + 1 + depth = depth - depth_double_stars + maxdepth + else: + depth = None + + allpaths = await self._find( + root, maxdepth=depth, withdirs=True, detail=True, **kwargs + ) + + pattern = glob_translate(path + ("/" if ends_with_slash else "")) + pattern = re.compile(pattern) + + out = { + ( + p.rstrip("/") + if not append_slash_to_dirname + and info["type"] == "directory" + and p.endswith("/") + else p + ): info + for p, info in sorted(allpaths.items()) + if pattern.match(p.rstrip("/")) + } + + if detail: + return out + else: + return list(out) + + async def _isdir(self, path): + # override, since all URLs are (also) files + try: + return bool(await self._ls(path)) + except (FileNotFoundError, ValueError): + return False + + async def _pipe_file(self, path, value, mode="overwrite", **kwargs): + """ + Write bytes to a remote file over HTTP. + + Parameters + ---------- + path : str + Target URL where the data should be written + value : bytes + Data to be written + mode : str + How to write to the file - 'overwrite' or 'append' + **kwargs : dict + Additional parameters to pass to the HTTP request + """ + url = self._strip_protocol(path) + headers = kwargs.pop("headers", {}) + headers["Content-Length"] = str(len(value)) + + session = await self.set_session() + + async with session.put( + self.encode_url(url), data=value, headers=headers, **kwargs + ) as r: + r.raise_for_status() + + +class HTTPFile(AbstractBufferedFile): + """ + A file-like object pointing to a remote HTTP(S) resource + + Supports only reading, with read-ahead of a predetermined block-size. + + In the case that the server does not supply the filesize, only reading of + the complete file in one go is supported. + + Parameters + ---------- + url: str + Full URL of the remote resource, including the protocol + session: aiohttp.ClientSession or None + All calls will be made within this session, to avoid restarting + connections where the server allows this + block_size: int or None + The amount of read-ahead to do, in bytes. Default is 5MB, or the value + configured for the FileSystem creating this file + size: None or int + If given, this is the size of the file in bytes, and we don't attempt + to call the server to find the value. + kwargs: all other key-values are passed to requests calls. + """ + + def __init__( + self, + fs, + url, + session=None, + block_size=None, + mode="rb", + cache_type="bytes", + cache_options=None, + size=None, + loop=None, + asynchronous=False, + **kwargs, + ): + if mode != "rb": + raise NotImplementedError("File mode not supported") + self.asynchronous = asynchronous + self.loop = loop + self.url = url + self.session = session + self.details = {"name": url, "size": size, "type": "file"} + super().__init__( + fs=fs, + path=url, + mode=mode, + block_size=block_size, + cache_type=cache_type, + cache_options=cache_options, + **kwargs, + ) + + def read(self, length=-1): + """Read bytes from file + + Parameters + ---------- + length: int + Read up to this many bytes. If negative, read all content to end of + file. If the server has not supplied the filesize, attempting to + read only part of the data will raise a ValueError. + """ + if ( + (length < 0 and self.loc == 0) # explicit read all + # but not when the size is known and fits into a block anyways + and not (self.size is not None and self.size <= self.blocksize) + ): + self._fetch_all() + if self.size is None: + if length < 0: + self._fetch_all() + else: + length = min(self.size - self.loc, length) + return super().read(length) + + async def async_fetch_all(self): + """Read whole file in one shot, without caching + + This is only called when position is still at zero, + and read() is called without a byte-count. + """ + logger.debug(f"Fetch all for {self}") + if not isinstance(self.cache, AllBytes): + r = await self.session.get(self.fs.encode_url(self.url), **self.kwargs) + async with r: + r.raise_for_status() + out = await r.read() + self.cache = AllBytes( + size=len(out), fetcher=None, blocksize=None, data=out + ) + self.size = len(out) + + _fetch_all = sync_wrapper(async_fetch_all) + + def _parse_content_range(self, headers): + """Parse the Content-Range header""" + s = headers.get("Content-Range", "") + m = re.match(r"bytes (\d+-\d+|\*)/(\d+|\*)", s) + if not m: + return None, None, None + + if m[1] == "*": + start = end = None + else: + start, end = [int(x) for x in m[1].split("-")] + total = None if m[2] == "*" else int(m[2]) + return start, end, total + + async def async_fetch_range(self, start, end): + """Download a block of data + + The expectation is that the server returns only the requested bytes, + with HTTP code 206. If this is not the case, we first check the headers, + and then stream the output - if the data size is bigger than we + requested, an exception is raised. + """ + logger.debug(f"Fetch range for {self}: {start}-{end}") + kwargs = self.kwargs.copy() + headers = kwargs.pop("headers", {}).copy() + headers["Range"] = f"bytes={start}-{end - 1}" + logger.debug(f"{self.url} : {headers['Range']}") + r = await self.session.get( + self.fs.encode_url(self.url), headers=headers, **kwargs + ) + async with r: + if r.status == 416: + # range request outside file + return b"" + r.raise_for_status() + + # If the server has handled the range request, it should reply + # with status 206 (partial content). But we'll guess that a suitable + # Content-Range header or a Content-Length no more than the + # requested range also mean we have got the desired range. + response_is_range = ( + r.status == 206 + or self._parse_content_range(r.headers)[0] == start + or int(r.headers.get("Content-Length", end + 1)) <= end - start + ) + + if response_is_range: + # partial content, as expected + out = await r.read() + elif start > 0: + raise ValueError( + "The HTTP server doesn't appear to support range requests. " + "Only reading this file from the beginning is supported. " + "Open with block_size=0 for a streaming file interface." + ) + else: + # Response is not a range, but we want the start of the file, + # so we can read the required amount anyway. + cl = 0 + out = [] + while True: + chunk = await r.content.read(2**20) + # data size unknown, let's read until we have enough + if chunk: + out.append(chunk) + cl += len(chunk) + if cl > end - start: + break + else: + break + out = b"".join(out)[: end - start] + return out + + _fetch_range = sync_wrapper(async_fetch_range) + + +magic_check = re.compile("([*[])") + + +def has_magic(s): + match = magic_check.search(s) + return match is not None + + +class HTTPStreamFile(AbstractBufferedFile): + def __init__(self, fs, url, mode="rb", loop=None, session=None, **kwargs): + self.asynchronous = kwargs.pop("asynchronous", False) + self.url = url + self.loop = loop + self.session = session + if mode != "rb": + raise ValueError + self.details = {"name": url, "size": None} + super().__init__(fs=fs, path=url, mode=mode, cache_type="none", **kwargs) + + async def cor(): + r = await self.session.get(self.fs.encode_url(url), **kwargs).__aenter__() + self.fs._raise_not_found_for_status(r, url) + return r + + self.r = sync(self.loop, cor) + self.loop = fs.loop + + def seek(self, loc, whence=0): + if loc == 0 and whence == 1: + return + if loc == self.loc and whence == 0: + return + raise ValueError("Cannot seek streaming HTTP file") + + async def _read(self, num=-1): + out = await self.r.content.read(num) + self.loc += len(out) + return out + + read = sync_wrapper(_read) + + async def _close(self): + self.r.close() + + def close(self): + asyncio.run_coroutine_threadsafe(self._close(), self.loop) + super().close() + + +class AsyncStreamFile(AbstractAsyncStreamedFile): + def __init__( + self, fs, url, mode="rb", loop=None, session=None, size=None, **kwargs + ): + self.url = url + self.session = session + self.r = None + if mode != "rb": + raise ValueError + self.details = {"name": url, "size": None} + self.kwargs = kwargs + super().__init__(fs=fs, path=url, mode=mode, cache_type="none") + self.size = size + + async def read(self, num=-1): + if self.r is None: + r = await self.session.get( + self.fs.encode_url(self.url), **self.kwargs + ).__aenter__() + self.fs._raise_not_found_for_status(r, self.url) + self.r = r + out = await self.r.content.read(num) + self.loc += len(out) + return out + + async def close(self): + if self.r is not None: + self.r.close() + self.r = None + await super().close() + + +async def get_range(session, url, start, end, file=None, **kwargs): + # explicit get a range when we know it must be safe + kwargs = kwargs.copy() + headers = kwargs.pop("headers", {}).copy() + headers["Range"] = f"bytes={start}-{end - 1}" + r = await session.get(url, headers=headers, **kwargs) + r.raise_for_status() + async with r: + out = await r.read() + if file: + with open(file, "r+b") as f: # noqa: ASYNC230 + f.seek(start) + f.write(out) + else: + return out + + +async def _file_info(url, session, size_policy="head", **kwargs): + """Call HEAD on the server to get details about the file (size/checksum etc.) + + Default operation is to explicitly allow redirects and use encoding + 'identity' (no compression) to get the true size of the target. + """ + logger.debug("Retrieve file size for %s", url) + kwargs = kwargs.copy() + ar = kwargs.pop("allow_redirects", True) + head = kwargs.get("headers", {}).copy() + head["Accept-Encoding"] = "identity" + kwargs["headers"] = head + + info = {} + if size_policy == "head": + r = await session.head(url, allow_redirects=ar, **kwargs) + elif size_policy == "get": + r = await session.get(url, allow_redirects=ar, **kwargs) + else: + raise TypeError(f'size_policy must be "head" or "get", got {size_policy}') + async with r: + r.raise_for_status() + + if "Content-Length" in r.headers: + # Some servers may choose to ignore Accept-Encoding and return + # compressed content, in which case the returned size is unreliable. + if "Content-Encoding" not in r.headers or r.headers["Content-Encoding"] in [ + "identity", + "", + ]: + info["size"] = int(r.headers["Content-Length"]) + elif "Content-Range" in r.headers: + info["size"] = int(r.headers["Content-Range"].split("/")[1]) + + if "Content-Type" in r.headers: + info["mimetype"] = r.headers["Content-Type"].partition(";")[0] + + if r.headers.get("Accept-Ranges") == "none": + # Some servers may explicitly discourage partial content requests, but + # the lack of "Accept-Ranges" does not always indicate they would fail + info["partial"] = False + + info["url"] = str(r.url) + + for checksum_field in ["ETag", "Content-MD5", "Digest", "Last-Modified"]: + if r.headers.get(checksum_field): + info[checksum_field] = r.headers[checksum_field] + + return info + + +async def _file_size(url, session=None, *args, **kwargs): + if session is None: + session = await get_client() + info = await _file_info(url, session=session, *args, **kwargs) + return info.get("size") + + +file_size = sync_wrapper(_file_size) diff --git a/python/user_packages/Python313/site-packages/fsspec/implementations/http_sync.py b/python/user_packages/Python313/site-packages/fsspec/implementations/http_sync.py new file mode 100644 index 0000000000000000000000000000000000000000..a67ea3ea5fee9e6b51f7f3f66773e8cf65735e52 --- /dev/null +++ b/python/user_packages/Python313/site-packages/fsspec/implementations/http_sync.py @@ -0,0 +1,937 @@ +"""This file is largely copied from http.py""" + +import io +import logging +import re +import urllib.error +import urllib.parse +from copy import copy +from json import dumps, loads +from urllib.parse import urlparse + +try: + import yarl +except (ImportError, ModuleNotFoundError, OSError): + yarl = False + +from fsspec.callbacks import _DEFAULT_CALLBACK +from fsspec.registry import register_implementation +from fsspec.spec import AbstractBufferedFile, AbstractFileSystem +from fsspec.utils import DEFAULT_BLOCK_SIZE, isfilelike, nullcontext, tokenize + +from ..caching import AllBytes + +# https://stackoverflow.com/a/15926317/3821154 +ex = re.compile(r"""<(a|A)\s+(?:[^>]*?\s+)?(href|HREF)=["'](?P[^"']+)""") +ex2 = re.compile(r"""(?Phttp[s]?://[-a-zA-Z0-9@:%_+.~#?&/=]+)""") +logger = logging.getLogger("fsspec.http") + + +class JsHttpException(urllib.error.HTTPError): ... + + +class StreamIO(io.BytesIO): + # fake class, so you can set attributes on it + # will eventually actually stream + ... + + +class ResponseProxy: + """Looks like a requests response""" + + def __init__(self, req, stream=False): + self.request = req + self.stream = stream + self._data = None + self._headers = None + + @property + def raw(self): + if self._data is None: + b = self.request.response.to_bytes() + if self.stream: + self._data = StreamIO(b) + else: + self._data = b + return self._data + + def close(self): + if hasattr(self, "_data"): + del self._data + + @property + def headers(self): + if self._headers is None: + self._headers = dict( + [ + _.split(": ") + for _ in self.request.getAllResponseHeaders().strip().split("\r\n") + ] + ) + return self._headers + + @property + def status_code(self): + return int(self.request.status) + + def raise_for_status(self): + if not self.ok: + raise JsHttpException( + self.url, self.status_code, self.reason, self.headers, None + ) + + def iter_content(self, chunksize, *_, **__): + while True: + out = self.raw.read(chunksize) + if out: + yield out + else: + break + + @property + def reason(self): + return self.request.statusText + + @property + def ok(self): + return self.status_code < 400 + + @property + def url(self): + return self.request.response.responseURL + + @property + def text(self): + # TODO: encoding from headers + return self.content.decode() + + @property + def content(self): + self.stream = False + return self.raw + + def json(self): + return loads(self.text) + + +class RequestsSessionShim: + def __init__(self): + self.headers = {} + + def request( + self, + method, + url, + params=None, + data=None, + headers=None, + cookies=None, + files=None, + auth=None, + timeout=None, + allow_redirects=None, + proxies=None, + hooks=None, + stream=None, + verify=None, + cert=None, + json=None, + ): + from js import Blob, XMLHttpRequest + + logger.debug("JS request: %s %s", method, url) + + if cert or verify or proxies or files or cookies or hooks: + raise NotImplementedError + if data and json: + raise ValueError("Use json= or data=, not both") + req = XMLHttpRequest.new() + extra = auth if auth else () + if params: + url = f"{url}?{urllib.parse.urlencode(params)}" + req.open(method, url, False, *extra) + if timeout: + req.timeout = timeout + if headers: + for k, v in headers.items(): + req.setRequestHeader(k, v) + + req.setRequestHeader("Accept", "application/octet-stream") + req.responseType = "arraybuffer" + if json: + blob = Blob.new([dumps(data)], {type: "application/json"}) + req.send(blob) + elif data: + if isinstance(data, io.IOBase): + data = data.read() + blob = Blob.new([data], {type: "application/octet-stream"}) + req.send(blob) + else: + req.send(None) + return ResponseProxy(req, stream=stream) + + def get(self, url, **kwargs): + return self.request("GET", url, **kwargs) + + def head(self, url, **kwargs): + return self.request("HEAD", url, **kwargs) + + def post(self, url, **kwargs): + return self.request("POST}", url, **kwargs) + + def put(self, url, **kwargs): + return self.request("PUT", url, **kwargs) + + def patch(self, url, **kwargs): + return self.request("PATCH", url, **kwargs) + + def delete(self, url, **kwargs): + return self.request("DELETE", url, **kwargs) + + +class HTTPFileSystem(AbstractFileSystem): + """ + Simple File-System for fetching data via HTTP(S) + + This is the BLOCKING version of the normal HTTPFileSystem. It uses + requests in normal python and the JS runtime in pyodide. + + ***This implementation is extremely experimental, do not use unless + you are testing pyodide/pyscript integration*** + """ + + protocol = ("http", "https", "sync-http", "sync-https") + sep = "/" + + def __init__( + self, + simple_links=True, + block_size=None, + same_scheme=True, + cache_type="readahead", + cache_options=None, + client_kwargs=None, + encoded=False, + **storage_options, + ): + """ + + Parameters + ---------- + block_size: int + Blocks to read bytes; if 0, will default to raw requests file-like + objects instead of HTTPFile instances + simple_links: bool + If True, will consider both HTML tags and anything that looks + like a URL; if False, will consider only the former. + same_scheme: True + When doing ls/glob, if this is True, only consider paths that have + http/https matching the input URLs. + size_policy: this argument is deprecated + client_kwargs: dict + Passed to aiohttp.ClientSession, see + https://docs.aiohttp.org/en/stable/client_reference.html + For example, ``{'auth': aiohttp.BasicAuth('user', 'pass')}`` + storage_options: key-value + Any other parameters passed on to requests + cache_type, cache_options: defaults used in open + """ + super().__init__(self, **storage_options) + self.block_size = block_size if block_size is not None else DEFAULT_BLOCK_SIZE + self.simple_links = simple_links + self.same_schema = same_scheme + self.cache_type = cache_type + self.cache_options = cache_options + self.client_kwargs = client_kwargs or {} + self.encoded = encoded + self.kwargs = storage_options + + try: + import js # noqa: F401 + + logger.debug("Starting JS session") + self.session = RequestsSessionShim() + self.js = True + except Exception as e: + import requests + + logger.debug("Starting cpython session because of: %s", e) + self.session = requests.Session(**(client_kwargs or {})) + self.js = False + + request_options = copy(storage_options) + self.use_listings_cache = request_options.pop("use_listings_cache", False) + request_options.pop("listings_expiry_time", None) + request_options.pop("max_paths", None) + request_options.pop("skip_instance_cache", None) + self.kwargs = request_options + + @property + def fsid(self): + return "sync-http" + + def encode_url(self, url): + if yarl: + return yarl.URL(url, encoded=self.encoded) + return url + + @classmethod + def _strip_protocol(cls, path: str) -> str: + """For HTTP, we always want to keep the full URL""" + path = path.replace("sync-http://", "http://").replace( + "sync-https://", "https://" + ) + return path + + @classmethod + def _parent(cls, path): + # override, since _strip_protocol is different for URLs + par = super()._parent(path) + if len(par) > 7: # "http://..." + return par + return "" + + def _ls_real(self, url, detail=True, **kwargs): + # ignoring URL-encoded arguments + kw = self.kwargs.copy() + kw.update(kwargs) + logger.debug(url) + r = self.session.get(self.encode_url(url), **self.kwargs) + self._raise_not_found_for_status(r, url) + text = r.text + if self.simple_links: + links = ex2.findall(text) + [u[2] for u in ex.findall(text)] + else: + links = [u[2] for u in ex.findall(text)] + out = set() + parts = urlparse(url) + for l in links: + if isinstance(l, tuple): + l = l[1] + if l.startswith("/") and len(l) > 1: + # absolute URL on this server + l = parts.scheme + "://" + parts.netloc + l + if l.startswith("http"): + if self.same_schema and l.startswith(url.rstrip("/") + "/"): + out.add(l) + elif l.replace("https", "http").startswith( + url.replace("https", "http").rstrip("/") + "/" + ): + # allowed to cross http <-> https + out.add(l) + else: + if l not in ["..", "../"]: + # Ignore FTP-like "parent" + out.add("/".join([url.rstrip("/"), l.lstrip("/")])) + if not out and url.endswith("/"): + out = self._ls_real(url.rstrip("/"), detail=False) + if detail: + return [ + { + "name": u, + "size": None, + "type": "directory" if u.endswith("/") else "file", + } + for u in out + ] + else: + return sorted(out) + + def ls(self, url, detail=True, **kwargs): + if self.use_listings_cache and url in self.dircache: + out = self.dircache[url] + else: + out = self._ls_real(url, detail=detail, **kwargs) + self.dircache[url] = out + return out + + def _raise_not_found_for_status(self, response, url): + """ + Raises FileNotFoundError for 404s, otherwise uses raise_for_status. + """ + if response.status_code == 404: + raise FileNotFoundError(url) + response.raise_for_status() + + def cat_file(self, url, start=None, end=None, **kwargs): + kw = self.kwargs.copy() + kw.update(kwargs) + logger.debug(url) + + if start is not None or end is not None: + if start == end: + return b"" + headers = kw.pop("headers", {}).copy() + + headers["Range"] = self._process_limits(url, start, end) + kw["headers"] = headers + r = self.session.get(self.encode_url(url), **kw) + self._raise_not_found_for_status(r, url) + return r.content + + def get_file( + self, rpath, lpath, chunk_size=5 * 2**20, callback=_DEFAULT_CALLBACK, **kwargs + ): + kw = self.kwargs.copy() + kw.update(kwargs) + logger.debug(rpath) + r = self.session.get(self.encode_url(rpath), **kw) + try: + size = int( + r.headers.get("content-length", None) + or r.headers.get("Content-Length", None) + ) + except (ValueError, KeyError, TypeError): + size = None + + callback.set_size(size) + self._raise_not_found_for_status(r, rpath) + if not isfilelike(lpath): + lpath = open(lpath, "wb") + for chunk in r.iter_content(chunk_size, decode_unicode=False): + lpath.write(chunk) + callback.relative_update(len(chunk)) + + def put_file( + self, + lpath, + rpath, + chunk_size=5 * 2**20, + callback=_DEFAULT_CALLBACK, + method="post", + **kwargs, + ): + def gen_chunks(): + # Support passing arbitrary file-like objects + # and use them instead of streams. + if isinstance(lpath, io.IOBase): + context = nullcontext(lpath) + use_seek = False # might not support seeking + else: + context = open(lpath, "rb") + use_seek = True + + with context as f: + if use_seek: + callback.set_size(f.seek(0, 2)) + f.seek(0) + else: + callback.set_size(getattr(f, "size", None)) + + chunk = f.read(chunk_size) + while chunk: + yield chunk + callback.relative_update(len(chunk)) + chunk = f.read(chunk_size) + + kw = self.kwargs.copy() + kw.update(kwargs) + + method = method.lower() + if method not in ("post", "put"): + raise ValueError( + f"method has to be either 'post' or 'put', not: {method!r}" + ) + + meth = getattr(self.session, method) + resp = meth(rpath, data=gen_chunks(), **kw) + self._raise_not_found_for_status(resp, rpath) + + def _process_limits(self, url, start, end): + """Helper for "Range"-based _cat_file""" + size = None + suff = False + if start is not None and start < 0: + # if start is negative and end None, end is the "suffix length" + if end is None: + end = -start + start = "" + suff = True + else: + size = size or self.info(url)["size"] + start = size + start + elif start is None: + start = 0 + if not suff: + if end is not None and end < 0: + if start is not None: + size = size or self.info(url)["size"] + end = size + end + elif end is None: + end = "" + if isinstance(end, int): + end -= 1 # bytes range is inclusive + return f"bytes={start}-{end}" + + def exists(self, path, strict=False, **kwargs): + kw = self.kwargs.copy() + kw.update(kwargs) + try: + logger.debug(path) + r = self.session.get(self.encode_url(path), **kw) + if strict: + self._raise_not_found_for_status(r, path) + return r.status_code < 400 + except FileNotFoundError: + return False + except Exception: + if strict: + raise + return False + + def isfile(self, path, **kwargs): + return self.exists(path, **kwargs) + + def _open( + self, + path, + mode="rb", + block_size=None, + autocommit=None, # XXX: This differs from the base class. + cache_type=None, + cache_options=None, + size=None, + **kwargs, + ): + """Make a file-like object + + Parameters + ---------- + path: str + Full URL with protocol + mode: string + must be "rb" + block_size: int or None + Bytes to download in one request; use instance value if None. If + zero, will return a streaming Requests file-like instance. + kwargs: key-value + Any other parameters, passed to requests calls + """ + if mode != "rb": + raise NotImplementedError + block_size = block_size if block_size is not None else self.block_size + kw = self.kwargs.copy() + kw.update(kwargs) + size = size or self.info(path, **kwargs)["size"] + if block_size and size: + return HTTPFile( + self, + path, + session=self.session, + block_size=block_size, + mode=mode, + size=size, + cache_type=cache_type or self.cache_type, + cache_options=cache_options or self.cache_options, + **kw, + ) + else: + return HTTPStreamFile( + self, + path, + mode=mode, + session=self.session, + **kw, + ) + + def ukey(self, url): + """Unique identifier; assume HTTP files are static, unchanging""" + return tokenize(url, self.kwargs, self.protocol) + + def info(self, url, **kwargs): + """Get info of URL + + Tries to access location via HEAD, and then GET methods, but does + not fetch the data. + + It is possible that the server does not supply any size information, in + which case size will be given as None (and certain operations on the + corresponding file will not work). + """ + info = {} + for policy in ["head", "get"]: + try: + info.update( + _file_info( + self.encode_url(url), + size_policy=policy, + session=self.session, + **self.kwargs, + **kwargs, + ) + ) + if info.get("size") is not None: + break + except Exception as exc: + if policy == "get": + # If get failed, then raise a FileNotFoundError + raise FileNotFoundError(url) from exc + logger.debug(str(exc)) + + return {"name": url, "size": None, **info, "type": "file"} + + def glob(self, path, maxdepth=None, **kwargs): + """ + Find files by glob-matching. + + This implementation is idntical to the one in AbstractFileSystem, + but "?" is not considered as a character for globbing, because it is + so common in URLs, often identifying the "query" part. + """ + import re + + ends = path.endswith("/") + path = self._strip_protocol(path) + indstar = path.find("*") if path.find("*") >= 0 else len(path) + indbrace = path.find("[") if path.find("[") >= 0 else len(path) + + ind = min(indstar, indbrace) + + detail = kwargs.pop("detail", False) + + if not has_magic(path): + root = path + depth = 1 + if ends: + path += "/*" + elif self.exists(path): + if not detail: + return [path] + else: + return {path: self.info(path)} + else: + if not detail: + return [] # glob of non-existent returns empty + else: + return {} + elif "/" in path[:ind]: + ind2 = path[:ind].rindex("/") + root = path[: ind2 + 1] + depth = None if "**" in path else path[ind2 + 1 :].count("/") + 1 + else: + root = "" + depth = None if "**" in path else path[ind + 1 :].count("/") + 1 + + allpaths = self.find( + root, maxdepth=maxdepth or depth, withdirs=True, detail=True, **kwargs + ) + # Escape characters special to python regex, leaving our supported + # special characters in place. + # See https://www.gnu.org/software/bash/manual/html_node/Pattern-Matching.html + # for shell globbing details. + pattern = ( + "^" + + ( + path.replace("\\", r"\\") + .replace(".", r"\.") + .replace("+", r"\+") + .replace("//", "/") + .replace("(", r"\(") + .replace(")", r"\)") + .replace("|", r"\|") + .replace("^", r"\^") + .replace("$", r"\$") + .replace("{", r"\{") + .replace("}", r"\}") + .rstrip("/") + ) + + "$" + ) + pattern = re.sub("[*]{2}", "=PLACEHOLDER=", pattern) + pattern = re.sub("[*]", "[^/]*", pattern) + pattern = re.compile(pattern.replace("=PLACEHOLDER=", ".*")) + out = { + p: allpaths[p] + for p in sorted(allpaths) + if pattern.match(p.replace("//", "/").rstrip("/")) + } + if detail: + return out + else: + return list(out) + + def isdir(self, path): + # override, since all URLs are (also) files + try: + return bool(self.ls(path)) + except (FileNotFoundError, ValueError): + return False + + +class HTTPFile(AbstractBufferedFile): + """ + A file-like object pointing to a remove HTTP(S) resource + + Supports only reading, with read-ahead of a predermined block-size. + + In the case that the server does not supply the filesize, only reading of + the complete file in one go is supported. + + Parameters + ---------- + url: str + Full URL of the remote resource, including the protocol + session: requests.Session or None + All calls will be made within this session, to avoid restarting + connections where the server allows this + block_size: int or None + The amount of read-ahead to do, in bytes. Default is 5MB, or the value + configured for the FileSystem creating this file + size: None or int + If given, this is the size of the file in bytes, and we don't attempt + to call the server to find the value. + kwargs: all other key-values are passed to requests calls. + """ + + def __init__( + self, + fs, + url, + session=None, + block_size=None, + mode="rb", + cache_type="bytes", + cache_options=None, + size=None, + **kwargs, + ): + if mode != "rb": + raise NotImplementedError("File mode not supported") + self.url = url + self.session = session + self.details = {"name": url, "size": size, "type": "file"} + super().__init__( + fs=fs, + path=url, + mode=mode, + block_size=block_size, + cache_type=cache_type, + cache_options=cache_options, + **kwargs, + ) + + def read(self, length=-1): + """Read bytes from file + + Parameters + ---------- + length: int + Read up to this many bytes. If negative, read all content to end of + file. If the server has not supplied the filesize, attempting to + read only part of the data will raise a ValueError. + """ + if ( + (length < 0 and self.loc == 0) # explicit read all + # but not when the size is known and fits into a block anyways + and not (self.size is not None and self.size <= self.blocksize) + ): + self._fetch_all() + if self.size is None: + if length < 0: + self._fetch_all() + else: + length = min(self.size - self.loc, length) + return super().read(length) + + def _fetch_all(self): + """Read whole file in one shot, without caching + + This is only called when position is still at zero, + and read() is called without a byte-count. + """ + logger.debug(f"Fetch all for {self}") + if not isinstance(self.cache, AllBytes): + r = self.session.get(self.fs.encode_url(self.url), **self.kwargs) + r.raise_for_status() + out = r.content + self.cache = AllBytes(size=len(out), fetcher=None, blocksize=None, data=out) + self.size = len(out) + + def _parse_content_range(self, headers): + """Parse the Content-Range header""" + s = headers.get("Content-Range", "") + m = re.match(r"bytes (\d+-\d+|\*)/(\d+|\*)", s) + if not m: + return None, None, None + + if m[1] == "*": + start = end = None + else: + start, end = [int(x) for x in m[1].split("-")] + total = None if m[2] == "*" else int(m[2]) + return start, end, total + + def _fetch_range(self, start, end): + """Download a block of data + + The expectation is that the server returns only the requested bytes, + with HTTP code 206. If this is not the case, we first check the headers, + and then stream the output - if the data size is bigger than we + requested, an exception is raised. + """ + logger.debug(f"Fetch range for {self}: {start}-{end}") + kwargs = self.kwargs.copy() + headers = kwargs.pop("headers", {}).copy() + headers["Range"] = f"bytes={start}-{end - 1}" + logger.debug("%s : %s", self.url, headers["Range"]) + r = self.session.get(self.fs.encode_url(self.url), headers=headers, **kwargs) + if r.status_code == 416: + # range request outside file + return b"" + r.raise_for_status() + + # If the server has handled the range request, it should reply + # with status 206 (partial content). But we'll guess that a suitable + # Content-Range header or a Content-Length no more than the + # requested range also mean we have got the desired range. + cl = r.headers.get("Content-Length", r.headers.get("content-length", end + 1)) + response_is_range = ( + r.status_code == 206 + or self._parse_content_range(r.headers)[0] == start + or int(cl) <= end - start + ) + + if response_is_range: + # partial content, as expected + out = r.content + elif start > 0: + raise ValueError( + "The HTTP server doesn't appear to support range requests. " + "Only reading this file from the beginning is supported. " + "Open with block_size=0 for a streaming file interface." + ) + else: + # Response is not a range, but we want the start of the file, + # so we can read the required amount anyway. + cl = 0 + out = [] + for chunk in r.iter_content(2**20, False): + out.append(chunk) + cl += len(chunk) + out = b"".join(out)[: end - start] + return out + + +magic_check = re.compile("([*[])") + + +def has_magic(s): + match = magic_check.search(s) + return match is not None + + +class HTTPStreamFile(AbstractBufferedFile): + def __init__(self, fs, url, mode="rb", session=None, **kwargs): + self.url = url + self.session = session + if mode != "rb": + raise ValueError + self.details = {"name": url, "size": None} + super().__init__(fs=fs, path=url, mode=mode, cache_type="readahead", **kwargs) + + r = self.session.get(self.fs.encode_url(url), stream=True, **kwargs) + self.fs._raise_not_found_for_status(r, url) + self.it = r.iter_content(1024, False) + self.leftover = b"" + + self.r = r + + def seek(self, *args, **kwargs): + raise ValueError("Cannot seek streaming HTTP file") + + def read(self, num=-1): + bufs = [self.leftover] + leng = len(self.leftover) + while leng < num or num < 0: + try: + out = self.it.__next__() + except StopIteration: + break + if out: + bufs.append(out) + else: + break + leng += len(out) + out = b"".join(bufs) + if num >= 0: + self.leftover = out[num:] + out = out[:num] + else: + self.leftover = b"" + self.loc += len(out) + return out + + def close(self): + self.r.close() + self.closed = True + + +def get_range(session, url, start, end, **kwargs): + # explicit get a range when we know it must be safe + kwargs = kwargs.copy() + headers = kwargs.pop("headers", {}).copy() + headers["Range"] = f"bytes={start}-{end - 1}" + r = session.get(url, headers=headers, **kwargs) + r.raise_for_status() + return r.content + + +def _file_info(url, session, size_policy="head", **kwargs): + """Call HEAD on the server to get details about the file (size/checksum etc.) + + Default operation is to explicitly allow redirects and use encoding + 'identity' (no compression) to get the true size of the target. + """ + logger.debug("Retrieve file size for %s", url) + kwargs = kwargs.copy() + ar = kwargs.pop("allow_redirects", True) + head = kwargs.get("headers", {}).copy() + # TODO: not allowed in JS + # head["Accept-Encoding"] = "identity" + kwargs["headers"] = head + + info = {} + if size_policy == "head": + r = session.head(url, allow_redirects=ar, **kwargs) + elif size_policy == "get": + r = session.get(url, allow_redirects=ar, **kwargs) + else: + raise TypeError(f'size_policy must be "head" or "get", got {size_policy}') + r.raise_for_status() + + # TODO: + # recognise lack of 'Accept-Ranges', + # or 'Accept-Ranges': 'none' (not 'bytes') + # to mean streaming only, no random access => return None + if "Content-Length" in r.headers: + info["size"] = int(r.headers["Content-Length"]) + elif "Content-Range" in r.headers: + info["size"] = int(r.headers["Content-Range"].split("/")[1]) + elif "content-length" in r.headers: + info["size"] = int(r.headers["content-length"]) + elif "content-range" in r.headers: + info["size"] = int(r.headers["content-range"].split("/")[1]) + + for checksum_field in ["ETag", "Content-MD5", "Digest"]: + if r.headers.get(checksum_field): + info[checksum_field] = r.headers[checksum_field] + + return info + + +# importing this is enough to register it +def register(): + register_implementation("http", HTTPFileSystem, clobber=True) + register_implementation("https", HTTPFileSystem, clobber=True) + register_implementation("sync-http", HTTPFileSystem, clobber=True) + register_implementation("sync-https", HTTPFileSystem, clobber=True) + + +register() + + +def unregister(): + from fsspec.implementations.http import HTTPFileSystem + + register_implementation("http", HTTPFileSystem, clobber=True) + register_implementation("https", HTTPFileSystem, clobber=True) diff --git a/python/user_packages/Python313/site-packages/fsspec/implementations/jupyter.py b/python/user_packages/Python313/site-packages/fsspec/implementations/jupyter.py new file mode 100644 index 0000000000000000000000000000000000000000..e5571ed56582170051f3b7cd903093eed4c65244 --- /dev/null +++ b/python/user_packages/Python313/site-packages/fsspec/implementations/jupyter.py @@ -0,0 +1,129 @@ +import base64 +import io +import re + +import requests + +import fsspec + + +class JupyterFileSystem(fsspec.AbstractFileSystem): + """View of the files as seen by a Jupyter server (notebook or lab)""" + + protocol = ("jupyter", "jlab") + + def __init__(self, url, tok=None, **kwargs): + """ + + Parameters + ---------- + url : str + Base URL of the server, like "http://127.0.0.1:8888". May include + token in the string, which is given by the process when starting up + tok : str + If the token is obtained separately, can be given here + kwargs + """ + if "?" in url: + if tok is None: + try: + tok = re.findall("token=([a-z0-9]+)", url)[0] + except IndexError as e: + raise ValueError("Could not determine token") from e + url = url.split("?", 1)[0] + self.url = url.rstrip("/") + "/api/contents" + self.session = requests.Session() + if tok: + self.session.headers["Authorization"] = f"token {tok}" + + super().__init__(**kwargs) + + def ls(self, path, detail=True, **kwargs): + path = self._strip_protocol(path) + r = self.session.get(f"{self.url}/{path}") + if r.status_code == 404: + raise FileNotFoundError(path) + r.raise_for_status() + out = r.json() + + if out["type"] == "directory": + out = out["content"] + else: + out = [out] + for o in out: + o["name"] = o.pop("path") + o.pop("content") + if o["type"] == "notebook": + o["type"] = "file" + if detail: + return out + return [o["name"] for o in out] + + def cat_file(self, path, start=None, end=None, **kwargs): + path = self._strip_protocol(path) + r = self.session.get(f"{self.url}/{path}") + if r.status_code == 404: + raise FileNotFoundError(path) + r.raise_for_status() + out = r.json() + if out["format"] == "text": + # data should be binary + b = out["content"].encode() + else: + b = base64.b64decode(out["content"]) + return b[start:end] + + def pipe_file(self, path, value, **_): + path = self._strip_protocol(path) + json = { + "name": path.rsplit("/", 1)[-1], + "path": path, + "size": len(value), + "content": base64.b64encode(value).decode(), + "format": "base64", + "type": "file", + } + self.session.put(f"{self.url}/{path}", json=json) + + def mkdir(self, path, create_parents=True, **kwargs): + path = self._strip_protocol(path) + if create_parents and "/" in path: + self.mkdir(path.rsplit("/", 1)[0], True) + json = { + "name": path.rsplit("/", 1)[-1], + "path": path, + "size": None, + "content": None, + "type": "directory", + } + self.session.put(f"{self.url}/{path}", json=json) + + def mv(self, path1, path2, recursive=False, maxdepth=None, **kwargs): + if path1 == path2: + return + self.session.patch(f"{self.url}/{path1}", json={"path": path2}) + + def _rm(self, path): + path = self._strip_protocol(path) + self.session.delete(f"{self.url}/{path}") + + def _open(self, path, mode="rb", **kwargs): + path = self._strip_protocol(path) + if mode == "rb": + data = self.cat_file(path) + return io.BytesIO(data) + else: + return SimpleFileWriter(self, path, mode="wb") + + +class SimpleFileWriter(fsspec.spec.AbstractBufferedFile): + def _upload_chunk(self, final=False): + """Never uploads a chunk until file is done + + Not suitable for large files + """ + if final is False: + return False + self.buffer.seek(0) + data = self.buffer.read() + self.fs.pipe_file(self.path, data) diff --git a/python/user_packages/Python313/site-packages/fsspec/implementations/libarchive.py b/python/user_packages/Python313/site-packages/fsspec/implementations/libarchive.py new file mode 100644 index 0000000000000000000000000000000000000000..6f8e750002df72865d611b48022e6634f9572614 --- /dev/null +++ b/python/user_packages/Python313/site-packages/fsspec/implementations/libarchive.py @@ -0,0 +1,213 @@ +from contextlib import contextmanager +from ctypes import ( + CFUNCTYPE, + POINTER, + c_int, + c_longlong, + c_void_p, + cast, + create_string_buffer, +) + +import libarchive +import libarchive.ffi as ffi + +from fsspec import open_files +from fsspec.archive import AbstractArchiveFileSystem +from fsspec.implementations.memory import MemoryFile +from fsspec.utils import DEFAULT_BLOCK_SIZE + +# Libarchive requires seekable files or memory only for certain archive +# types. However, since we read the directory first to cache the contents +# and also allow random access to any file, the file-like object needs +# to be seekable no matter what. + +# Seek call-backs (not provided in the libarchive python wrapper) +SEEK_CALLBACK = CFUNCTYPE(c_longlong, c_int, c_void_p, c_longlong, c_int) +read_set_seek_callback = ffi.ffi( + "read_set_seek_callback", [ffi.c_archive_p, SEEK_CALLBACK], c_int, ffi.check_int +) +new_api = hasattr(ffi, "NO_OPEN_CB") + + +@contextmanager +def custom_reader(file, format_name="all", filter_name="all", block_size=ffi.page_size): + """Read an archive from a seekable file-like object. + + The `file` object must support the standard `readinto` and 'seek' methods. + """ + buf = create_string_buffer(block_size) + buf_p = cast(buf, c_void_p) + + def read_func(archive_p, context, ptrptr): + # readinto the buffer, returns number of bytes read + length = file.readinto(buf) + # write the address of the buffer into the pointer + ptrptr = cast(ptrptr, POINTER(c_void_p)) + ptrptr[0] = buf_p + # tell libarchive how much data was written into the buffer + return length + + def seek_func(archive_p, context, offset, whence): + file.seek(offset, whence) + # tell libarchvie the current position + return file.tell() + + read_cb = ffi.READ_CALLBACK(read_func) + seek_cb = SEEK_CALLBACK(seek_func) + + if new_api: + open_cb = ffi.NO_OPEN_CB + close_cb = ffi.NO_CLOSE_CB + else: + open_cb = libarchive.read.OPEN_CALLBACK(ffi.VOID_CB) + close_cb = libarchive.read.CLOSE_CALLBACK(ffi.VOID_CB) + + with libarchive.read.new_archive_read(format_name, filter_name) as archive_p: + read_set_seek_callback(archive_p, seek_cb) + ffi.read_open(archive_p, None, open_cb, read_cb, close_cb) + yield libarchive.read.ArchiveRead(archive_p) + + +class LibArchiveFileSystem(AbstractArchiveFileSystem): + """Compressed archives as a file-system (read-only) + + Supports the following formats: + tar, pax , cpio, ISO9660, zip, mtree, shar, ar, raw, xar, lha/lzh, rar + Microsoft CAB, 7-Zip, WARC + + See the libarchive documentation for further restrictions. + https://www.libarchive.org/ + + Keeps file object open while instance lives. It only works in seekable + file-like objects. In case the filesystem does not support this kind of + file object, it is recommended to cache locally. + + This class is pickleable, but not necessarily thread-safe (depends on the + platform). See libarchive documentation for details. + """ + + root_marker = "" + protocol = "libarchive" + cachable = False + + def __init__( + self, + fo="", + mode="r", + target_protocol=None, + target_options=None, + block_size=DEFAULT_BLOCK_SIZE, + **kwargs, + ): + """ + Parameters + ---------- + fo: str or file-like + Contains ZIP, and must exist. If a str, will fetch file using + :meth:`~fsspec.open_files`, which must return one file exactly. + mode: str + Currently, only 'r' accepted + target_protocol: str (optional) + If ``fo`` is a string, this value can be used to override the + FS protocol inferred from a URL + target_options: dict (optional) + Kwargs passed when instantiating the target FS, if ``fo`` is + a string. + """ + super().__init__(self, **kwargs) + if mode != "r": + raise ValueError("Only read from archive files accepted") + if isinstance(fo, str): + files = open_files(fo, protocol=target_protocol, **(target_options or {})) + if len(files) != 1: + raise ValueError( + f'Path "{fo}" did not resolve to exactly one file: "{files}"' + ) + fo = files[0] + self.of = fo + self.fo = fo.__enter__() # the whole instance is a context + self.block_size = block_size + self.dir_cache = None + + @contextmanager + def _open_archive(self): + self.fo.seek(0) + with custom_reader(self.fo, block_size=self.block_size) as arc: + yield arc + + @classmethod + def _strip_protocol(cls, path): + # file paths are always relative to the archive root + return super()._strip_protocol(path).lstrip("/") + + def _get_dirs(self): + fields = { + "name": "pathname", + "size": "size", + "created": "ctime", + "mode": "mode", + "uid": "uid", + "gid": "gid", + "mtime": "mtime", + } + + if self.dir_cache is not None: + return + + self.dir_cache = {} + list_names = [] + with self._open_archive() as arc: + for entry in arc: + if not entry.isdir and not entry.isfile: + # Skip symbolic links, fifo entries, etc. + continue + self.dir_cache.update( + { + dirname: {"name": dirname, "size": 0, "type": "directory"} + for dirname in self._all_dirnames(set(entry.name)) + } + ) + f = {key: getattr(entry, fields[key]) for key in fields} + f["type"] = "directory" if entry.isdir else "file" + list_names.append(entry.name) + + self.dir_cache[f["name"]] = f + # libarchive does not seem to return an entry for the directories (at least + # not in all formats), so get the directories names from the files names + self.dir_cache.update( + { + dirname: {"name": dirname, "size": 0, "type": "directory"} + for dirname in self._all_dirnames(list_names) + } + ) + + def _open( + self, + path, + mode="rb", + block_size=None, + autocommit=True, + cache_options=None, + **kwargs, + ): + path = self._strip_protocol(path) + if mode != "rb": + raise NotImplementedError + + data = b"" + with self._open_archive() as arc: + for entry in arc: + if entry.pathname != path: + continue + + if entry.size == 0: + # empty file, so there are no blocks + break + + for block in entry.get_blocks(entry.size): + data = block + break + else: + raise ValueError + return MemoryFile(fs=self, path=path, data=data) diff --git a/python/user_packages/Python313/site-packages/fsspec/implementations/local.py b/python/user_packages/Python313/site-packages/fsspec/implementations/local.py new file mode 100644 index 0000000000000000000000000000000000000000..b549b93e22c56fc67c00a3a87718999d2039d4c2 --- /dev/null +++ b/python/user_packages/Python313/site-packages/fsspec/implementations/local.py @@ -0,0 +1,517 @@ +import datetime +import io +import logging +import os +import os.path as osp +import shutil +import stat +import tempfile +from functools import lru_cache + +from fsspec import AbstractFileSystem +from fsspec.compression import compr +from fsspec.core import get_compression +from fsspec.utils import isfilelike, stringify_path + +logger = logging.getLogger("fsspec.local") + + +class LocalFileSystem(AbstractFileSystem): + """Interface to files on local storage + + Parameters + ---------- + auto_mkdir: bool + Whether, when opening a file, the directory containing it should + be created (if it doesn't already exist). This is assumed by pyarrow + code. + """ + + root_marker = "/" + protocol = "file", "local" + local_file = True + + def __init__(self, auto_mkdir=False, **kwargs): + super().__init__(**kwargs) + self.auto_mkdir = auto_mkdir + + @property + def fsid(self): + return "local" + + def mkdir(self, path, create_parents=True, **kwargs): + path = self._strip_protocol(path) + if self.exists(path): + raise FileExistsError(path) + if create_parents: + self.makedirs(path, exist_ok=True) + else: + os.mkdir(path, **kwargs) + + def makedirs(self, path, exist_ok=False): + path = self._strip_protocol(path) + os.makedirs(path, exist_ok=exist_ok) + + def rmdir(self, path): + path = self._strip_protocol(path) + os.rmdir(path) + + def ls(self, path, detail=False, **kwargs): + path = self._strip_protocol(path) + path_info = self.info(path) + infos = [] + if path_info["type"] == "directory": + with os.scandir(path) as it: + for f in it: + try: + # Only get the info if requested since it is a bit expensive (the stat call inside) + # The strip_protocol is also used in info() and calls make_path_posix to always return posix paths + info = self.info(f) if detail else self._strip_protocol(f.path) + infos.append(info) + except FileNotFoundError: + pass + else: + infos = [path_info] if detail else [path_info["name"]] + + return infos + + def info(self, path, **kwargs): + if isinstance(path, os.DirEntry): + # scandir DirEntry + out = path.stat(follow_symlinks=False) + link = path.is_symlink() + if path.is_dir(follow_symlinks=False): + t = "directory" + elif path.is_file(follow_symlinks=False): + t = "file" + else: + t = "other" + + size = out.st_size + if link: + try: + out2 = path.stat(follow_symlinks=True) + size = out2.st_size + except OSError: + size = 0 + path = self._strip_protocol(path.path) + else: + # str or path-like + path = self._strip_protocol(path) + out = os.stat(path, follow_symlinks=False) + link = stat.S_ISLNK(out.st_mode) + if link: + out = os.stat(path, follow_symlinks=True) + size = out.st_size + if stat.S_ISDIR(out.st_mode): + t = "directory" + elif stat.S_ISREG(out.st_mode): + t = "file" + else: + t = "other" + + # Check for the 'st_birthtime' attribute, which is not always present; fallback to st_ctime + created_time = getattr(out, "st_birthtime", out.st_ctime) + + result = { + "name": path, + "size": size, + "type": t, + "created": created_time, + "islink": link, + } + for field in ["mode", "uid", "gid", "mtime", "ino", "nlink"]: + result[field] = getattr(out, f"st_{field}") + if link: + result["destination"] = os.readlink(path) + return result + + def lexists(self, path, **kwargs): + return osp.lexists(path) + + def cp_file(self, path1, path2, **kwargs): + path1 = self._strip_protocol(path1) + path2 = self._strip_protocol(path2) + if self.auto_mkdir: + self.makedirs(self._parent(path2), exist_ok=True) + if self.isfile(path1): + shutil.copyfile(path1, path2) + elif self.isdir(path1): + self.mkdirs(path2, exist_ok=True) + else: + raise FileNotFoundError(path1) + + def isfile(self, path): + path = self._strip_protocol(path) + return os.path.isfile(path) + + def isdir(self, path): + path = self._strip_protocol(path) + return os.path.isdir(path) + + def get_file(self, path1, path2, callback=None, **kwargs): + if isfilelike(path2): + with open(path1, "rb") as f: + shutil.copyfileobj(f, path2) + else: + return self.cp_file(path1, path2, **kwargs) + + def put_file(self, path1, path2, callback=None, **kwargs): + return self.cp_file(path1, path2, **kwargs) + + def mv(self, path1, path2, recursive: bool = True, **kwargs): + """Move files/directories + For the specific case of local, all ops on directories are recursive and + the recursive= kwarg is ignored. + """ + path1 = self._strip_protocol(path1) + path2 = self._strip_protocol(path2) + + if self.auto_mkdir: + self.makedirs(self._parent(path2), exist_ok=True) + + shutil.move(path1, path2) + + def link(self, src, dst, **kwargs): + src = self._strip_protocol(src) + dst = self._strip_protocol(dst) + os.link(src, dst, **kwargs) + + def symlink(self, src, dst, **kwargs): + src = self._strip_protocol(src) + dst = self._strip_protocol(dst) + os.symlink(src, dst, **kwargs) + + def islink(self, path) -> bool: + return os.path.islink(self._strip_protocol(path)) + + def rm_file(self, path): + os.remove(self._strip_protocol(path)) + + def rm(self, path, recursive=False, maxdepth=None): + if not isinstance(path, list): + path = [path] + + for p in path: + p = self._strip_protocol(p) + if self.isdir(p): + if not recursive: + raise ValueError("Cannot delete directory, set recursive=True") + if osp.abspath(p) == os.getcwd(): + raise ValueError("Cannot delete current working directory") + shutil.rmtree(p) + else: + os.remove(p) + + def unstrip_protocol(self, name): + protocol = self.protocol if isinstance(self.protocol, str) else self.protocol[0] + name = self._strip_protocol(name) # normalise for local/win/... + return f"{protocol}://{name}" + + def _open(self, path, mode="rb", block_size=None, **kwargs): + path = self._strip_protocol(path) + if self.auto_mkdir and "w" in mode: + self.makedirs(self._parent(path), exist_ok=True) + return LocalFileOpener(path, mode, fs=self, **kwargs) + + def touch(self, path, truncate=True, **kwargs): + path = self._strip_protocol(path) + if self.auto_mkdir: + self.makedirs(self._parent(path), exist_ok=True) + if self.exists(path): + os.utime(path, None) + else: + open(path, "a").close() + if truncate: + os.truncate(path, 0) + + def created(self, path): + info = self.info(path=path) + return datetime.datetime.fromtimestamp( + info["created"], tz=datetime.timezone.utc + ) + + def modified(self, path): + info = self.info(path=path) + return datetime.datetime.fromtimestamp(info["mtime"], tz=datetime.timezone.utc) + + @classmethod + def _parent(cls, path): + path = cls._strip_protocol(path) + if os.sep == "/": + # posix native + return path.rsplit("/", 1)[0] or "/" + else: + # NT + path_ = path.rsplit("/", 1)[0] + if len(path_) <= 3: + if path_[1:2] == ":": + # nt root (something like c:/) + return path_[0] + ":/" + # More cases may be required here + return path_ + + @classmethod + def _strip_protocol(cls, path): + path = stringify_path(path) + protos = (cls.protocol,) if isinstance(cls.protocol, str) else cls.protocol + prefixes = (protocol + sep for protocol in protos for sep in ("://", ":")) + for prefix in prefixes: + if path.startswith(prefix): + path = path.removeprefix(prefix) + break + + path = make_path_posix(path) + if os.sep != "/": + # This code-path is a stripped down version of + # > drive, path = ntpath.splitdrive(path) + if path[1:2] == ":": + # Absolute drive-letter path, e.g. X:\Windows + # Relative path with drive, e.g. X:Windows + drive, path = path[:2], path[2:] + elif path[:2] == "//": + # UNC drives, e.g. \\server\share or \\?\UNC\server\share + # Device drives, e.g. \\.\device or \\?\device + if (index1 := path.find("/", 2)) == -1 or ( + index2 := path.find("/", index1 + 1) + ) == -1: + drive, path = path, "" + else: + drive, path = path[:index2], path[index2:] + else: + # Relative path, e.g. Windows + drive = "" + + path = path.rstrip("/") or cls.root_marker + return drive + path + + else: + return path.rstrip("/") or cls.root_marker + + def _isfilestore(self): + # Inheriting from DaskFileSystem makes this False (S3, etc. were) + # the original motivation. But we are a posix-like file system. + # See https://github.com/dask/dask/issues/5526 + return True + + def chmod(self, path, mode): + path = stringify_path(path) + return os.chmod(path, mode) + + +def make_path_posix(path): + """Make path generic and absolute for current OS""" + if not isinstance(path, str): + if isinstance(path, (list, set, tuple)): + return type(path)(make_path_posix(p) for p in path) + else: + path = stringify_path(path) + if not isinstance(path, str): + raise TypeError(f"could not convert {path!r} to string") + if os.sep == "/": + # Native posix + if path.startswith("/"): + # most common fast case for posix + return path + elif path.startswith("~"): + return osp.expanduser(path) + elif path.startswith("./"): + path = path[2:] + elif path == ".": + path = "" + return f"{os.getcwd()}/{path}" + else: + # NT handling + if path[0:1] == "/" and path[2:3] == ":": + # path is like "/c:/local/path" + path = path[1:] + if path[1:2] == ":": + # windows full path like "C:\\local\\path" + if len(path) <= 3: + # nt root (something like c:/) + return path[0] + ":/" + path = path.replace("\\", "/") + return path + elif path[0:1] == "~": + return make_path_posix(osp.expanduser(path)) + elif path.startswith(("\\\\", "//")): + # windows UNC/DFS-style paths + return "//" + path[2:].replace("\\", "/") + elif path.startswith(("\\", "/")): + # windows relative path with root + path = path.replace("\\", "/") + return f"{osp.splitdrive(os.getcwd())[0]}{path}" + else: + path = path.replace("\\", "/") + if path.startswith("./"): + path = path[2:] + elif path == ".": + path = "" + return f"{make_path_posix(os.getcwd())}/{path}" + + +def trailing_sep(path): + """Return True if the path ends with a path separator. + + A forward slash is always considered a path separator, even on Operating + Systems that normally use a backslash. + """ + # TODO: if all incoming paths were posix-compliant then separator would + # always be a forward slash, simplifying this function. + # See https://github.com/fsspec/filesystem_spec/pull/1250 + return path.endswith(os.sep) or (os.altsep is not None and path.endswith(os.altsep)) + + +@lru_cache(maxsize=1) +def get_umask(mask: int = 0o666) -> int: + """Get the current umask. + + Follows https://stackoverflow.com/a/44130549 to get the umask. + Temporarily sets the umask to the given value, and then resets it to the + original value. + """ + value = os.umask(mask) + os.umask(value) + return value + + +class LocalFileOpener(io.IOBase): + def __init__( + self, path, mode, autocommit=True, fs=None, compression=None, **kwargs + ): + logger.debug("open file: %s", path) + self.path = path + self.mode = mode + self.fs = fs + self.f = None + self.autocommit = autocommit + self.compression = get_compression(path, compression) + self.blocksize = io.DEFAULT_BUFFER_SIZE + self._open() + + def _open(self): + if self.f is None or self.f.closed: + if self.autocommit or "w" not in self.mode: + self.f = open(self.path, mode=self.mode) + if self.compression: + compress = compr[self.compression] + self.f = compress(self.f, mode=self.mode) + else: + # TODO: check if path is writable? + i, name = tempfile.mkstemp() + os.close(i) # we want normal open and normal buffered file + self.temp = name + self.f = open(name, mode=self.mode) + if "w" not in self.mode: + self.size = self.f.seek(0, 2) + self.f.seek(0) + self.f.size = self.size + + def _fetch_range(self, start, end): + # probably only used by cached FS + if "r" not in self.mode: + raise ValueError + self._open() + self.f.seek(start) + return self.f.read(end - start) + + def __setstate__(self, state): + self.f = None + loc = state.pop("loc", None) + self.__dict__.update(state) + if "r" in state["mode"]: + self.f = None + self._open() + self.f.seek(loc) + + def __getstate__(self): + d = self.__dict__.copy() + d.pop("f") + if "r" in self.mode: + d["loc"] = self.f.tell() + else: + if not self.f.closed: + raise ValueError("Cannot serialise open write-mode local file") + return d + + def commit(self): + if self.autocommit: + raise RuntimeError("Can only commit if not already set to autocommit") + try: + shutil.move(self.temp, self.path) + except PermissionError as e: + # shutil.move raises PermissionError if os.rename + # and the default copy2 fallback with shutil.copystats fail. + # The file should be there nonetheless, but without copied permissions. + # If it doesn't exist, there was no permission to create the file. + if not os.path.exists(self.path): + raise e + else: + # If PermissionError is not raised, permissions can be set. + try: + mask = 0o666 + os.chmod(self.path, mask & ~get_umask(mask)) + except RuntimeError: + pass + + def discard(self): + if self.autocommit: + raise RuntimeError("Cannot discard if set to autocommit") + os.remove(self.temp) + + def readable(self) -> bool: + return True + + def writable(self) -> bool: + return "r" not in self.mode + + def read(self, *args, **kwargs): + return self.f.read(*args, **kwargs) + + def write(self, *args, **kwargs): + return self.f.write(*args, **kwargs) + + def tell(self, *args, **kwargs): + return self.f.tell(*args, **kwargs) + + def seek(self, *args, **kwargs): + return self.f.seek(*args, **kwargs) + + def seekable(self, *args, **kwargs): + return self.f.seekable(*args, **kwargs) + + def readline(self, *args, **kwargs): + return self.f.readline(*args, **kwargs) + + def readlines(self, *args, **kwargs): + return self.f.readlines(*args, **kwargs) + + def close(self): + return self.f.close() + + def truncate(self, size=None) -> int: + return self.f.truncate(size) + + @property + def closed(self): + return self.f.closed + + def fileno(self): + return self.raw.fileno() + + def flush(self) -> None: + self.f.flush() + + def __iter__(self): + return self.f.__iter__() + + def __getattr__(self, item): + return getattr(self.f, item) + + def __enter__(self): + self._incontext = True + return self + + def __exit__(self, exc_type, exc_value, traceback): + self._incontext = False + self.f.__exit__(exc_type, exc_value, traceback) diff --git a/python/user_packages/Python313/site-packages/fsspec/implementations/memory.py b/python/user_packages/Python313/site-packages/fsspec/implementations/memory.py new file mode 100644 index 0000000000000000000000000000000000000000..f6b67bbc84e7aa625eee5609c20f6a893ddd349e --- /dev/null +++ b/python/user_packages/Python313/site-packages/fsspec/implementations/memory.py @@ -0,0 +1,311 @@ +from __future__ import annotations + +import logging +from datetime import datetime, timezone +from errno import ENOTEMPTY +from io import BytesIO +from pathlib import PurePath, PureWindowsPath +from typing import Any, ClassVar + +from fsspec import AbstractFileSystem +from fsspec.implementations.local import LocalFileSystem +from fsspec.utils import stringify_path + +logger = logging.getLogger("fsspec.memoryfs") + + +class MemoryFileSystem(AbstractFileSystem): + """A filesystem based on a dict of BytesIO objects + + This is a global filesystem so instances of this class all point to the same + in memory filesystem. + """ + + store: ClassVar[dict[str, Any]] = {} # global, do not overwrite! + pseudo_dirs = [""] # global, do not overwrite! + protocol = "memory" + root_marker = "/" + + @classmethod + def _strip_protocol(cls, path): + if isinstance(path, PurePath): + if isinstance(path, PureWindowsPath): + return LocalFileSystem._strip_protocol(path) + else: + path = stringify_path(path) + + path = path.removeprefix("memory://") + if "::" in path or "://" in path: + return path.rstrip("/") + path = path.lstrip("/").rstrip("/") + return "/" + path if path else "" + + def ls(self, path, detail=True, **kwargs): + path = self._strip_protocol(path) + if path in self.store: + # there is a key with this exact name + if not detail: + return [path] + return [ + { + "name": path, + "size": self.store[path].size, + "type": "file", + "created": self.store[path].created.timestamp(), + } + ] + paths = set() + starter = path + "/" + out = [] + for p2 in tuple(self.store): + if p2.startswith(starter): + if "/" not in p2[len(starter) :]: + # exact child + out.append( + { + "name": p2, + "size": self.store[p2].size, + "type": "file", + "created": self.store[p2].created.timestamp(), + } + ) + elif len(p2) > len(starter): + # implied child directory + ppath = starter + p2[len(starter) :].split("/", 1)[0] + if ppath not in paths: + out = out or [] + out.append( + { + "name": ppath, + "size": 0, + "type": "directory", + } + ) + paths.add(ppath) + for p2 in self.pseudo_dirs: + if p2.startswith(starter): + if "/" not in p2[len(starter) :]: + # exact child pdir + if p2 not in paths: + out.append({"name": p2, "size": 0, "type": "directory"}) + paths.add(p2) + else: + # directory implied by deeper pdir + ppath = starter + p2[len(starter) :].split("/", 1)[0] + if ppath not in paths: + out.append({"name": ppath, "size": 0, "type": "directory"}) + paths.add(ppath) + if not out: + if path in self.pseudo_dirs: + # empty dir + return [] + raise FileNotFoundError(path) + if detail: + return out + return sorted([f["name"] for f in out]) + + def mkdir(self, path, create_parents=True, **kwargs): + path = self._strip_protocol(path) + if path in self.store or path in self.pseudo_dirs: + raise FileExistsError(path) + if self._parent(path).strip("/") and self.isfile(self._parent(path)): + raise NotADirectoryError(self._parent(path)) + if create_parents and self._parent(path).strip("/"): + try: + self.mkdir(self._parent(path), create_parents, **kwargs) + except FileExistsError: + pass + if path and path not in self.pseudo_dirs: + self.pseudo_dirs.append(path) + + def makedirs(self, path, exist_ok=False): + try: + self.mkdir(path, create_parents=True) + except FileExistsError: + if not exist_ok: + raise + + def pipe_file(self, path, value, mode="overwrite", **kwargs): + """Set the bytes of given file + + Avoids copies of the data if possible + """ + mode = "xb" if mode == "create" else "wb" + self.open(path, mode=mode, data=value) + + def rmdir(self, path): + path = self._strip_protocol(path) + if path == "": + # silently avoid deleting FS root + return + if path in self.pseudo_dirs: + if not self.ls(path): + self.pseudo_dirs.remove(path) + else: + raise OSError(ENOTEMPTY, "Directory not empty", path) + else: + raise FileNotFoundError(path) + + def info(self, path, **kwargs): + logger.debug("info: %s", path) + path = self._strip_protocol(path) + if path in self.pseudo_dirs or any( + p.startswith(path + "/") for p in list(self.store) + self.pseudo_dirs + ): + return { + "name": path, + "size": 0, + "type": "directory", + } + elif path in self.store: + filelike = self.store[path] + return { + "name": path, + "size": filelike.size, + "type": "file", + "created": getattr(filelike, "created", None), + } + else: + raise FileNotFoundError(path) + + def _open( + self, + path, + mode="rb", + block_size=None, + autocommit=True, + cache_options=None, + **kwargs, + ): + path = self._strip_protocol(path) + if "x" in mode and self.exists(path): + raise FileExistsError + if path in self.pseudo_dirs: + raise IsADirectoryError(path) + parent = path + while len(parent) > 1: + parent = self._parent(parent) + if self.isfile(parent): + raise FileExistsError(parent) + if mode in ["rb", "ab", "r+b", "a+b"]: + if path in self.store: + f = self.store[path] + if "a" in mode: + # position at the end of file + f.seek(0, 2) + else: + # position at the beginning of file + f.seek(0) + return f + else: + raise FileNotFoundError(path) + elif mode in {"wb", "w+b", "xb", "x+b"}: + if "x" in mode and self.exists(path): + raise FileExistsError + m = MemoryFile(self, path, kwargs.get("data")) + if not self._intrans: + m.commit() + return m + else: + name = self.__class__.__name__ + raise ValueError(f"unsupported file mode for {name}: {mode!r}") + + def cp_file(self, path1, path2, **kwargs): + path1 = self._strip_protocol(path1) + path2 = self._strip_protocol(path2) + if self.isfile(path1): + self.store[path2] = MemoryFile( + self, path2, self.store[path1].getvalue() + ) # implicit copy + elif self.isdir(path1): + if path2 not in self.pseudo_dirs: + self.pseudo_dirs.append(path2) + else: + raise FileNotFoundError(path1) + + def cat_file(self, path, start=None, end=None, **kwargs): + logger.debug("cat: %s", path) + path = self._strip_protocol(path) + try: + return bytes(self.store[path].getbuffer()[start:end]) + except KeyError as e: + raise FileNotFoundError(path) from e + + def _rm(self, path): + path = self._strip_protocol(path) + try: + del self.store[path] + except KeyError as e: + raise FileNotFoundError(path) from e + + def modified(self, path): + path = self._strip_protocol(path) + try: + return self.store[path].modified + except KeyError as e: + raise FileNotFoundError(path) from e + + def created(self, path): + path = self._strip_protocol(path) + try: + return self.store[path].created + except KeyError as e: + raise FileNotFoundError(path) from e + + def isfile(self, path): + path = self._strip_protocol(path) + return path in self.store + + def rm(self, path, recursive=False, maxdepth=None): + if isinstance(path, str): + path = self._strip_protocol(path) + else: + path = [self._strip_protocol(p) for p in path] + paths = self.expand_path(path, recursive=recursive, maxdepth=maxdepth) + for p in reversed(paths): + if self.isfile(p): + self.rm_file(p) + # If the expanded path doesn't exist, it is only because the expanded + # path was a directory that does not exist in self.pseudo_dirs. This + # is possible if you directly create files without making the + # directories first. + elif not self.exists(p): + continue + else: + self.rmdir(p) + + +class MemoryFile(BytesIO): + """A BytesIO which can't close and works as a context manager + + Can initialise with data. Each path should only be active once at any moment. + + No need to provide fs, path if auto-committing (default) + """ + + def __init__(self, fs=None, path=None, data=None): + logger.debug("open file %s", path) + self.fs = fs + self.path = path + self.created = datetime.now(tz=timezone.utc) + self.modified = datetime.now(tz=timezone.utc) + if data: + super().__init__(data) + self.seek(0) + + @property + def size(self): + return self.getbuffer().nbytes + + def __enter__(self): + return self + + def close(self): + pass + + def discard(self): + pass + + def commit(self): + self.fs.store[self.path] = self + self.modified = datetime.now(tz=timezone.utc) diff --git a/python/user_packages/Python313/site-packages/fsspec/implementations/reference.py b/python/user_packages/Python313/site-packages/fsspec/implementations/reference.py new file mode 100644 index 0000000000000000000000000000000000000000..562e76160dbf8b65b8bd9d38d6ffe082514e96bc --- /dev/null +++ b/python/user_packages/Python313/site-packages/fsspec/implementations/reference.py @@ -0,0 +1,1316 @@ +import base64 +import collections +import io +import itertools +import logging +import math +import os +from functools import lru_cache +from itertools import chain +from typing import TYPE_CHECKING, Literal + +import fsspec.core +from fsspec.spec import AbstractBufferedFile + +try: + import ujson as json +except ImportError: + if not TYPE_CHECKING: + import json + +from fsspec.asyn import AsyncFileSystem +from fsspec.callbacks import DEFAULT_CALLBACK +from fsspec.core import filesystem, open, split_protocol +from fsspec.implementations.asyn_wrapper import AsyncFileSystemWrapper +from fsspec.utils import ( + isfilelike, + merge_offset_ranges, + other_paths, +) + +logger = logging.getLogger("fsspec.reference") + + +class ReferenceNotReachable(RuntimeError): + def __init__(self, reference, target, *args): + super().__init__(*args) + self.reference = reference + self.target = target + + def __str__(self): + return f'Reference "{self.reference}" failed to fetch target {self.target}' + + +def _first(d): + return next(iter(d.values())) + + +def _prot_in_references(path, references): + ref = references.get(path) + if isinstance(ref, (list, tuple)) and isinstance(ref[0], str): + return split_protocol(ref[0])[0] if ref[0] else ref[0] + + +def _protocol_groups(paths, references): + if isinstance(paths, str): + return {_prot_in_references(paths, references): [paths]} + out = {} + for path in paths: + protocol = _prot_in_references(path, references) + out.setdefault(protocol, []).append(path) + return out + + +class RefsValuesView(collections.abc.ValuesView): + def __iter__(self): + for val in self._mapping.zmetadata.values(): + yield json.dumps(val).encode() + yield from self._mapping._items.values() + for field in self._mapping.listdir(): + chunk_sizes = self._mapping._get_chunk_sizes(field) + if len(chunk_sizes) == 0: + yield self._mapping[field + "/0"] + continue + yield from self._mapping._generate_all_records(field) + + +class RefsItemsView(collections.abc.ItemsView): + def __iter__(self): + return zip(self._mapping.keys(), self._mapping.values()) + + +def ravel_multi_index(idx, sizes): + val = 0 + mult = 1 + for i, s in zip(idx[::-1], sizes[::-1]): + val += i * mult + mult *= s + return val + + +class LazyReferenceMapper(collections.abc.MutableMapping): + """This interface can be used to read/write references from Parquet stores. + It is not intended for other types of references. + It can be used with Kerchunk's MultiZarrToZarr method to combine + references into a parquet store. + Examples of this use-case can be found here: + https://fsspec.github.io/kerchunk/advanced.html?highlight=parquet#parquet-storage""" + + # import is class level to prevent numpy dep requirement for fsspec + @property + def np(self): + import numpy as np + + return np + + @property + def pd(self): + import pandas as pd + + return pd + + def __init__( + self, + root, + fs=None, + out_root=None, + cache_size=128, + categorical_threshold=10, + engine: Literal["fastparquet", "pyarrow"] = "fastparquet", + ): + """ + + This instance will be writable, storing changes in memory until full partitions + are accumulated or .flush() is called. + + To create an empty lazy store, use .create() + + Parameters + ---------- + root : str + Root of parquet store + fs : fsspec.AbstractFileSystem + fsspec filesystem object, default is local filesystem. + cache_size : int, default=128 + Maximum size of LRU cache, where cache_size*record_size denotes + the total number of references that can be loaded in memory at once. + categorical_threshold : int + Encode urls as pandas.Categorical to reduce memory footprint if the ratio + of the number of unique urls to total number of refs for each variable + is greater than or equal to this number. (default 10) + engine: Literal["fastparquet","pyarrow"] + Engine choice for reading parquet files. (default is "fastparquet") + """ + + self.root = root + self.chunk_sizes = {} + self.cat_thresh = categorical_threshold + self.engine = engine + self.cache_size = cache_size + self.url = self.root + "/{field}/refs.{record}.parq" + # TODO: derive fs from `root` + self.fs = fsspec.filesystem("file") if fs is None else fs + self.out_root = self.fs.unstrip_protocol(out_root or self.root) + + from importlib.util import find_spec + + if self.engine == "pyarrow" and find_spec("pyarrow") is None: + raise ImportError("engine choice `pyarrow` is not installed.") + + # Apply `lru_cache` decorator manually per instance. + # This way `self` reference is not held on class level. + # WARNING: However, this means that self and its members are not reflected + # in the cache key, so we expect they won't be mutated once a value is cached. + self.listdir = lru_cache()(self.listdir) + self._key_to_record = lru_cache(maxsize=4096)(self._key_to_record) + + def __getattr__(self, item): + if item in ("_items", "record_size", "zmetadata"): + self.setup() + # avoid possible recursion if setup fails somehow + return self.__dict__[item] + raise AttributeError(item) + + def setup(self): + self._items = {} + self._items[".zmetadata"] = self.fs.cat_file( + "/".join([self.root, ".zmetadata"]) + ) + met = json.loads(self._items[".zmetadata"]) + self.record_size = met["record_size"] + self.zmetadata = met["metadata"] + + # Define function to open and decompress refs + @lru_cache(maxsize=self.cache_size) + def open_refs(field, record): + """cached parquet file loader""" + path = self.url.format(field=field, record=record) + data = io.BytesIO(self.fs.cat_file(path)) + try: + df = self.pd.read_parquet(data, engine=self.engine) + refs = {c: df[c].to_numpy() for c in df.columns} + except OSError: + refs = None + return refs + + self.open_refs = open_refs + + @staticmethod + def create(root, storage_options=None, fs=None, record_size=10000, **kwargs): + """Make empty parquet reference set + + First deletes the contents of the given directory, if it exists. + + Parameters + ---------- + root: str + Directory to contain the output; will be created + storage_options: dict | None + For making the filesystem to use for writing is fs is None + fs: FileSystem | None + Filesystem for writing + record_size: int + Number of references per parquet file + kwargs: passed to __init__ + + Returns + ------- + LazyReferenceMapper instance + """ + met = {"metadata": {}, "record_size": record_size} + if fs is None: + fs, root = fsspec.core.url_to_fs(root, **(storage_options or {})) + if fs.exists(root): + fs.rm(root, recursive=True) + fs.makedirs(root, exist_ok=True) + fs.pipe("/".join([root, ".zmetadata"]), json.dumps(met).encode()) + return LazyReferenceMapper(root, fs, **kwargs) + + def listdir(self): + """List top-level directories""" + dirs = (p.rsplit("/", 1)[0] for p in self.zmetadata if not p.startswith(".z")) + return set(dirs) + + def ls(self, path="", detail=True): + """Shortcut file listings""" + path = path.rstrip("/") + pathdash = path + "/" if path else "" + dirnames = self.listdir() + dirs = [ + d + for d in dirnames + if d.startswith(pathdash) and "/" not in d.lstrip(pathdash) + ] + if dirs: + others = { + f + for f in chain( + [".zmetadata"], + (name for name in self.zmetadata), + (name for name in self._items), + ) + if f.startswith(pathdash) and "/" not in f.lstrip(pathdash) + } + if detail is False: + others.update(dirs) + return sorted(others) + dirinfo = [{"name": name, "type": "directory", "size": 0} for name in dirs] + fileinfo = [ + { + "name": name, + "type": "file", + "size": len( + json.dumps(self.zmetadata[name]) + if name in self.zmetadata + else self._items[name] + ), + } + for name in others + ] + return sorted(dirinfo + fileinfo, key=lambda s: s["name"]) + field = path + others = set( + [name for name in self.zmetadata if name.startswith(f"{path}/")] + + [name for name in self._items if name.startswith(f"{path}/")] + ) + fileinfo = [ + { + "name": name, + "type": "file", + "size": len( + json.dumps(self.zmetadata[name]) + if name in self.zmetadata + else self._items[name] + ), + } + for name in others + ] + keys = self._keys_in_field(field) + + if detail is False: + return list(others) + list(keys) + recs = self._generate_all_records(field) + recinfo = [ + {"name": name, "type": "file", "size": rec[-1]} + for name, rec in zip(keys, recs) + if rec[0] # filters out path==None, deleted/missing + ] + return fileinfo + recinfo + + def _load_one_key(self, key): + """Get the reference for one key + + Returns bytes, one-element list or three-element list. + """ + if key in self._items: + return self._items[key] + elif key in self.zmetadata: + return json.dumps(self.zmetadata[key]).encode() + elif "/" not in key or self._is_meta(key): + raise KeyError(key) + field, _ = key.rsplit("/", 1) + record, ri, chunk_size = self._key_to_record(key) + maybe = self._items.get((field, record), {}).get(ri, False) + if maybe is None: + # explicitly deleted + raise KeyError + elif maybe: + return maybe + elif chunk_size == 0: + return b"" + + # Chunk keys can be loaded from row group and cached in LRU cache + try: + refs = self.open_refs(field, record) + except (ValueError, TypeError, FileNotFoundError) as exc: + raise KeyError(key) from exc + columns = ["path", "offset", "size", "raw"] + selection = [refs[c][ri] if c in refs else None for c in columns] + raw = selection[-1] + if raw is not None: + return raw + if selection[0] is None: + raise KeyError("This reference does not exist or has been deleted") + if selection[1:3] == [0, 0]: + # URL only + return selection[:1] + # URL, offset, size + return selection[:3] + + def _key_to_record(self, key): + """Details needed to construct a reference for one key""" + field, chunk = key.rsplit("/", 1) + chunk_sizes = self._get_chunk_sizes(field) + if len(chunk_sizes) == 0: + return 0, 0, 0 + chunk_idx = [int(c) for c in chunk.split(".")] + chunk_number = ravel_multi_index(chunk_idx, chunk_sizes) + record = chunk_number // self.record_size + ri = chunk_number % self.record_size + return record, ri, len(chunk_sizes) + + def _get_chunk_sizes(self, field): + """The number of chunks along each axis for a given field""" + if field not in self.chunk_sizes: + zarray = self.zmetadata[f"{field}/.zarray"] + size_ratio = [ + math.ceil(s / c) for s, c in zip(zarray["shape"], zarray["chunks"]) + ] + self.chunk_sizes[field] = size_ratio or [1] + return self.chunk_sizes[field] + + def _generate_record(self, field, record): + """The references for a given parquet file of a given field""" + refs = self.open_refs(field, record) + it = iter(zip(*refs.values())) + if len(refs) == 3: + # All urls + return (list(t) for t in it) + elif len(refs) == 1: + # All raws + return refs["raw"] + else: + # Mix of urls and raws + return (list(t[:3]) if not t[3] else t[3] for t in it) + + def _generate_all_records(self, field): + """Load all the references within a field by iterating over the parquet files""" + nrec = 1 + for ch in self._get_chunk_sizes(field): + nrec *= ch + nrec = math.ceil(nrec / self.record_size) + for record in range(nrec): + yield from self._generate_record(field, record) + + def values(self): + return RefsValuesView(self) + + def items(self): + return RefsItemsView(self) + + def __hash__(self): + return id(self) + + def __getitem__(self, key): + return self._load_one_key(key) + + def __setitem__(self, key, value): + if "/" in key and not self._is_meta(key): + field, chunk = key.rsplit("/", 1) + record, i, _ = self._key_to_record(key) + subdict = self._items.setdefault((field, record), {}) + subdict[i] = value + if len(subdict) == self.record_size: + self.write(field, record) + else: + # metadata or top-level + if hasattr(value, "to_bytes"): + val = value.to_bytes().decode() + elif isinstance(value, bytes): + val = value.decode() + else: + val = value + self._items[key] = val + new_value = json.loads(val) + self.zmetadata[key] = {**self.zmetadata.get(key, {}), **new_value} + + @staticmethod + def _is_meta(key): + return key.startswith(".z") or "/.z" in key + + def __delitem__(self, key): + if key in self._items: + del self._items[key] + elif key in self.zmetadata: + del self.zmetadata[key] + else: + if "/" in key and not self._is_meta(key): + field, _ = key.rsplit("/", 1) + record, i, _ = self._key_to_record(key) + subdict = self._items.setdefault((field, record), {}) + subdict[i] = None + if len(subdict) == self.record_size: + self.write(field, record) + else: + # metadata or top-level + self._items[key] = None + + def write(self, field, record, base_url=None, storage_options=None): + # extra requirements if writing + import kerchunk.df + import numpy as np + import pandas as pd + + partition = self._items[(field, record)] + original = False + if len(partition) < self.record_size: + try: + original = self.open_refs(field, record) + except OSError: + pass + + if original: + paths = original["path"] + offsets = original["offset"] + sizes = original["size"] + raws = original["raw"] + else: + paths = np.full(self.record_size, np.nan, dtype="O") + offsets = np.zeros(self.record_size, dtype="int64") + sizes = np.zeros(self.record_size, dtype="int64") + raws = np.full(self.record_size, np.nan, dtype="O") + for j, data in partition.items(): + if isinstance(data, list): + if ( + str(paths.dtype) == "category" + and data[0] not in paths.dtype.categories + ): + paths = paths.add_categories(data[0]) + paths[j] = data[0] + if len(data) > 1: + offsets[j] = data[1] + sizes[j] = data[2] + elif data is None: + # delete + paths[j] = None + offsets[j] = 0 + sizes[j] = 0 + raws[j] = None + else: + # this is the only call into kerchunk, could remove + raws[j] = kerchunk.df._proc_raw(data) + # TODO: only save needed columns + df = pd.DataFrame( + { + "path": paths, + "offset": offsets, + "size": sizes, + "raw": raws, + }, + copy=False, + ) + if df.path.count() / (df.path.nunique() or 1) > self.cat_thresh: + df["path"] = df["path"].astype("category") + object_encoding = {"raw": "bytes", "path": "utf8"} + has_nulls = ["path", "raw"] + + fn = f"{base_url or self.out_root}/{field}/refs.{record}.parq" + self.fs.mkdirs(f"{base_url or self.out_root}/{field}", exist_ok=True) + + if self.engine == "pyarrow": + df_backend_kwargs = {"write_statistics": False} + elif self.engine == "fastparquet": + df_backend_kwargs = { + "stats": False, + "object_encoding": object_encoding, + "has_nulls": has_nulls, + } + else: + raise NotImplementedError(f"{self.engine} not supported") + df.to_parquet( + fn, + engine=self.engine, + storage_options=storage_options + or getattr(self.fs, "storage_options", None), + compression="zstd", + index=False, + **df_backend_kwargs, + ) + + partition.clear() + self._items.pop((field, record)) + + def flush(self, base_url=None, storage_options=None): + """Output any modified or deleted keys + + Parameters + ---------- + base_url: str + Location of the output + """ + + # write what we have so far and clear sub chunks + for thing in list(self._items): + if isinstance(thing, tuple): + field, record = thing + self.write( + field, + record, + base_url=base_url, + storage_options=storage_options, + ) + + # gather .zmetadata from self._items and write that too + for k in list(self._items): + if k != ".zmetadata" and ".z" in k: + self.zmetadata[k] = json.loads(self._items.pop(k)) + met = {"metadata": self.zmetadata, "record_size": self.record_size} + self._items.clear() + self._items[".zmetadata"] = json.dumps(met).encode() + self.fs.pipe( + "/".join([base_url or self.out_root, ".zmetadata"]), + self._items[".zmetadata"], + ) + + # TODO: only clear those that we wrote to? + self.open_refs.cache_clear() + + def __len__(self): + # Caveat: This counts expected references, not actual - but is fast + count = 0 + for field in self.listdir(): + if field.startswith("."): + count += 1 + else: + count += math.prod(self._get_chunk_sizes(field)) + count += len(self.zmetadata) # all metadata keys + # any other files not in reference partitions + count += sum(1 for _ in self._items if not isinstance(_, tuple)) + return count + + def __iter__(self): + # Caveat: returns only existing keys, so the number of these does not + # match len(self) + metas = set(self.zmetadata) + metas.update(self._items) + for bit in metas: + if isinstance(bit, str): + yield bit + for field in self.listdir(): + for k in self._keys_in_field(field): + if k in self: + yield k + + def __contains__(self, item): + try: + self._load_one_key(item) + return True + except KeyError: + return False + + def _keys_in_field(self, field): + """List key names in given field + + Produces strings like "field/x.y" appropriate from the chunking of the array + """ + chunk_sizes = self._get_chunk_sizes(field) + if len(chunk_sizes) == 0: + yield field + "/0" + return + inds = itertools.product(*(range(i) for i in chunk_sizes)) + for ind in inds: + yield field + "/" + ".".join([str(c) for c in ind]) + + +class ReferenceFileSystem(AsyncFileSystem): + """View byte ranges of some other file as a file system + Initial version: single file system target, which must support + async, and must allow start and end args in _cat_file. Later versions + may allow multiple arbitrary URLs for the targets. + This FileSystem is read-only. It is designed to be used with async + targets (for now). We do not get original file details from the target FS. + Configuration is by passing a dict of references at init, or a URL to + a JSON file containing the same; this dict + can also contain concrete data for some set of paths. + Reference dict format: + {path0: bytes_data, path1: (target_url, offset, size)} + https://github.com/fsspec/kerchunk/blob/main/README.md + """ + + protocol = "reference" + cachable = False + + def __init__( + self, + fo, + target=None, + ref_storage_args=None, + target_protocol=None, + target_options=None, + remote_protocol=None, + remote_options=None, + fs=None, + template_overrides=None, + simple_templates=True, + max_gap=64_000, + max_block=256_000_000, + cache_size=128, + **kwargs, + ): + """ + Parameters + ---------- + fo : dict or str + The set of references to use for this instance, with a structure as above. + If str referencing a JSON file, will use fsspec.open, in conjunction + with target_options and target_protocol to open and parse JSON at this + location. If a directory, then assume references are a set of parquet + files to be loaded lazily. + target : str + For any references having target_url as None, this is the default file + target to use + ref_storage_args : dict + If references is a str, use these kwargs for loading the JSON file. + Deprecated: use target_options instead. + target_protocol : str + Used for loading the reference file, if it is a path. If None, protocol + will be derived from the given path + target_options : dict + Extra FS options for loading the reference file ``fo``, if given as a path + remote_protocol : str + The protocol of the filesystem on which the references will be evaluated + (unless fs is provided). If not given, will be derived from the first + URL that has a protocol in the templates or in the references, in that + order. + remote_options : dict + kwargs to go with remote_protocol + fs : AbstractFileSystem | dict(str, (AbstractFileSystem | dict)) + Directly provide a file system(s): + - a single filesystem instance + - a dict of protocol:filesystem, where each value is either a filesystem + instance, or a dict of kwargs that can be used to create in + instance for the given protocol + + If this is given, remote_options and remote_protocol are ignored. + template_overrides : dict + Swap out any templates in the references file with these - useful for + testing. + simple_templates: bool + Whether templates can be processed with simple replace (True) or if + jinja is needed (False, much slower). All reference sets produced by + ``kerchunk`` are simple in this sense, but the spec allows for complex. + max_gap, max_block: int + For merging multiple concurrent requests to the same remote file. + Neighboring byte ranges will only be merged when their + inter-range gap is <= ``max_gap``. Default is 64KB. Set to 0 + to only merge when it requires no extra bytes. Pass a negative + number to disable merging, appropriate for local target files. + Neighboring byte ranges will only be merged when the size of + the aggregated range is <= ``max_block``. Default is 256MB. + cache_size : int + Maximum size of LRU cache, where cache_size*record_size denotes + the total number of references that can be loaded in memory at once. + Only used for lazily loaded references. + kwargs : passed to parent class + """ + super().__init__(**kwargs) + self.target = target + self.template_overrides = template_overrides + self.simple_templates = simple_templates + self.templates = {} + self.fss = {} + self._dircache = {} + self.max_gap = max_gap + self.max_block = max_block + if isinstance(fo, str): + dic = dict( + **(ref_storage_args or target_options or {}), protocol=target_protocol + ) + ref_fs, fo2 = fsspec.core.url_to_fs(fo, **dic) + if ".json" not in fo2 and ( + fo.endswith(("parq", "parquet", "/")) or ref_fs.isdir(fo2) + ): + # Lazy parquet refs + logger.info("Open lazy reference dict from URL %s", fo) + self.references = LazyReferenceMapper( + fo2, + fs=ref_fs, + cache_size=cache_size, + ) + else: + # text JSON + with fsspec.open(fo, "rb", **dic) as f: + logger.info("Read reference from URL %s", fo) + text = json.load(f) + self._process_references(text, template_overrides) + else: + # dictionaries + self._process_references(fo, template_overrides) + if isinstance(fs, dict): + self.fss = { + k: ( + fsspec.filesystem(k.split(":", 1)[0], **opts) + if isinstance(opts, dict) + else opts + ) + for k, opts in fs.items() + } + if None not in self.fss: + self.fss[None] = filesystem("file") + return + if fs is not None: + # single remote FS + remote_protocol = ( + fs.protocol[0] if isinstance(fs.protocol, tuple) else fs.protocol + ) + self.fss[remote_protocol] = fs + + if remote_protocol is None: + # get single protocol from any templates + for ref in self.templates.values(): + if callable(ref): + ref = ref() + protocol, _ = fsspec.core.split_protocol(ref) + if protocol and protocol not in self.fss: + fs = filesystem(protocol, **(remote_options or {})) + self.fss[protocol] = fs + if remote_protocol is None: + # get single protocol from references + # TODO: warning here, since this can be very expensive? + for ref in self.references.values(): + if callable(ref): + ref = ref() + if isinstance(ref, list) and ref[0]: + protocol, _ = fsspec.core.split_protocol(ref[0]) + if protocol not in self.fss: + fs = filesystem(protocol, **(remote_options or {})) + self.fss[protocol] = fs + # only use first remote URL + break + + if remote_protocol and remote_protocol not in self.fss: + fs = filesystem(remote_protocol, **(remote_options or {})) + self.fss[remote_protocol] = fs + + self.fss[None] = fs or filesystem("file") # default one + # Wrap any non-async filesystems to ensure async methods are available below + for k, f in self.fss.items(): + if not f.async_impl: + self.fss[k] = AsyncFileSystemWrapper(f, asynchronous=self.asynchronous) + elif self.asynchronous ^ f.asynchronous: + raise ValueError( + "Reference-FS's target filesystem must have same value " + "of asynchronous" + ) + + def _cat_common(self, path, start=None, end=None): + path = self._strip_protocol(path) + logger.debug(f"cat: {path}") + try: + part = self.references[path] + except KeyError as exc: + raise FileNotFoundError(path) from exc + if isinstance(part, str): + part = part.encode() + if hasattr(part, "to_bytes"): + part = part.to_bytes() + if isinstance(part, bytes): + logger.debug(f"Reference: {path}, type bytes") + if part.startswith(b"base64:"): + part = base64.b64decode(part[7:]) + return part, None, None + + if len(part) == 1: + logger.debug(f"Reference: {path}, whole file => {part}") + url = part[0] + start1, end1 = start, end + else: + url, start0, size = part + logger.debug(f"Reference: {path} => {url}, offset {start0}, size {size}") + end0 = start0 + size + + if start is not None: + if start >= 0: + start1 = start0 + start + else: + start1 = end0 + start + else: + start1 = start0 + if end is not None: + if end >= 0: + end1 = start0 + end + else: + end1 = end0 + end + else: + end1 = end0 + if url is None: + url = self.target + return url, start1, end1 + + async def _cat_file(self, path, start=None, end=None, **kwargs): + part_or_url, start0, end0 = self._cat_common(path, start=start, end=end) + if isinstance(part_or_url, bytes): + return part_or_url[start:end] + protocol, _ = split_protocol(part_or_url) + try: + return await self.fss[protocol]._cat_file( + part_or_url, start=start0, end=end0 + ) + except Exception as e: + raise ReferenceNotReachable(path, part_or_url) from e + + def cat_file(self, path, start=None, end=None, **kwargs): + part_or_url, start0, end0 = self._cat_common(path, start=start, end=end) + if isinstance(part_or_url, bytes): + return part_or_url[start:end] + protocol, _ = split_protocol(part_or_url) + try: + return self.fss[protocol].cat_file(part_or_url, start=start0, end=end0) + except Exception as e: + raise ReferenceNotReachable(path, part_or_url) from e + + def pipe_file(self, path, value, **_): + """Temporarily add binary data or reference as a file""" + self.references[path] = value + + async def _get_file(self, rpath, lpath, **kwargs): + if self.isdir(rpath): + return os.makedirs(lpath, exist_ok=True) + data = await self._cat_file(rpath) + with open(lpath, "wb") as f: + f.write(data) + + def get_file(self, rpath, lpath, callback=DEFAULT_CALLBACK, **kwargs): + if self.isdir(rpath): + return os.makedirs(lpath, exist_ok=True) + data = self.cat_file(rpath, **kwargs) + callback.set_size(len(data)) + if isfilelike(lpath): + lpath.write(data) + else: + with open(lpath, "wb") as f: + f.write(data) + callback.absolute_update(len(data)) + + def get(self, rpath, lpath, recursive=False, **kwargs): + if recursive: + # trigger directory build + self.ls("") + rpath = self.expand_path(rpath, recursive=recursive) + fs = fsspec.filesystem("file", auto_mkdir=True) + targets = other_paths(rpath, lpath) + if recursive: + data = self.cat([r for r in rpath if not self.isdir(r)]) + else: + data = self.cat(rpath) + for remote, local in zip(rpath, targets): + if remote in data: + fs.pipe_file(local, data[remote]) + + def cat(self, path, recursive=False, on_error="raise", **kwargs): + if isinstance(path, str) and recursive: + raise NotImplementedError + if isinstance(path, list) and (recursive or any("*" in p for p in path)): + raise NotImplementedError + # TODO: if references is lazy, pre-fetch all paths in batch before access + proto_dict = _protocol_groups(path, self.references) + out = {} + for proto, paths in proto_dict.items(): + fs = self.fss[proto] + urls, starts, ends, valid_paths = [], [], [], [] + for p in paths: + # find references or label not-found. Early exit if any not + # found and on_error is "raise" + try: + u, s, e = self._cat_common(p) + if not isinstance(u, (bytes, str)): + # nan/None from parquet + continue + except FileNotFoundError as err: + if on_error == "raise": + raise + if on_error != "omit": + out[p] = err + else: + urls.append(u) + starts.append(s) + ends.append(e) + valid_paths.append(p) + + # process references into form for merging + urls2 = [] + starts2 = [] + ends2 = [] + paths2 = [] + whole_files = set() + for u, s, e, p in zip(urls, starts, ends, valid_paths): + if isinstance(u, bytes): + # data + out[p] = u + elif s is None: + # whole file - limits are None, None, but no further + # entries take for this file + whole_files.add(u) + urls2.append(u) + starts2.append(s) + ends2.append(e) + paths2.append(p) + for u, s, e, p in zip(urls, starts, ends, valid_paths): + # second run to account for files that are to be loaded whole + if s is not None and u not in whole_files: + urls2.append(u) + starts2.append(s) + ends2.append(e) + paths2.append(p) + + # merge and fetch consolidated ranges + new_paths, new_starts, new_ends = merge_offset_ranges( + list(urls2), + list(starts2), + list(ends2), + sort=True, + max_gap=self.max_gap, + max_block=self.max_block, + ) + bytes_out = fs.cat_ranges(new_paths, new_starts, new_ends) + + # unbundle from merged bytes - simple approach + for u, s, e, p in zip(urls, starts, ends, valid_paths): + if p in out: + continue # was bytes, already handled + for np, ns, ne, b in zip(new_paths, new_starts, new_ends, bytes_out): + if np == u and (ns is None or ne is None): + if isinstance(b, Exception): + out[p] = b + else: + out[p] = b[s:e] + elif np == u and s >= ns and e <= ne: + if isinstance(b, Exception): + out[p] = b + else: + out[p] = b[s - ns : (e - ne) or None] + + for k, v in out.copy().items(): + # these were valid references, but fetch failed, so transform exc + if isinstance(v, Exception) and k in self.references: + ex = out[k] + new_ex = ReferenceNotReachable(k, self.references[k]) + new_ex.__cause__ = ex + if on_error == "raise": + raise new_ex + elif on_error != "omit": + out[k] = new_ex + + if len(out) == 1 and isinstance(path, str) and "*" not in path: + return _first(out) + return out + + def _process_references(self, references, template_overrides=None): + vers = references.get("version", None) + if vers is None: + self._process_references0(references) + elif vers == 1: + self._process_references1(references, template_overrides=template_overrides) + else: + raise ValueError(f"Unknown reference spec version: {vers}") + # TODO: we make dircache by iterating over all entries, but for Spec >= 1, + # can replace with programmatic. Is it even needed for mapper interface? + + def _process_references0(self, references): + """Make reference dict for Spec Version 0""" + if isinstance(references, dict): + # do not do this for lazy/parquet backend, which will not make dicts, + # but must remain writable in the original object + references = { + key: json.dumps(val) if isinstance(val, dict) else val + for key, val in references.items() + } + self.references = references + + def _process_references1(self, references, template_overrides=None): + if not self.simple_templates or self.templates: + import jinja2 + self.references = {} + self._process_templates(references.get("templates", {})) + + @lru_cache(1000) + def _render_jinja(u): + return jinja2.Template(u).render(**self.templates) + + for k, v in references.get("refs", {}).items(): + if isinstance(v, str): + if v.startswith("base64:"): + self.references[k] = base64.b64decode(v[7:]) + self.references[k] = v + elif isinstance(v, dict): + self.references[k] = json.dumps(v) + elif self.templates: + u = v[0] + if "{{" in u: + if self.simple_templates: + u = ( + u.replace("{{", "{") + .replace("}}", "}") + .format(**self.templates) + ) + else: + u = _render_jinja(u) + self.references[k] = [u] if len(v) == 1 else [u, v[1], v[2]] + else: + self.references[k] = v + self.references.update(self._process_gen(references.get("gen", []))) + + def _process_templates(self, tmp): + self.templates = {} + if self.template_overrides is not None: + tmp.update(self.template_overrides) + for k, v in tmp.items(): + if "{{" in v: + import jinja2 + + self.templates[k] = lambda temp=v, **kwargs: jinja2.Template( + temp + ).render(**kwargs) + else: + self.templates[k] = v + + def _process_gen(self, gens): + out = {} + for gen in gens: + dimension = { + k: ( + v + if isinstance(v, list) + else range(v.get("start", 0), v["stop"], v.get("step", 1)) + ) + for k, v in gen["dimensions"].items() + } + products = ( + dict(zip(dimension.keys(), values)) + for values in itertools.product(*dimension.values()) + ) + for pr in products: + import jinja2 + + key = jinja2.Template(gen["key"]).render(**pr, **self.templates) + url = jinja2.Template(gen["url"]).render(**pr, **self.templates) + if ("offset" in gen) and ("length" in gen): + offset = int( + jinja2.Template(gen["offset"]).render(**pr, **self.templates) + ) + length = int( + jinja2.Template(gen["length"]).render(**pr, **self.templates) + ) + out[key] = [url, offset, length] + elif ("offset" in gen) ^ ("length" in gen): + raise ValueError( + "Both 'offset' and 'length' are required for a " + "reference generator entry if either is provided." + ) + else: + out[key] = [url] + return out + + def _dircache_from_items(self): + self.dircache = {"": []} + it = self.references.items() + for path, part in it: + if isinstance(part, (bytes, str)) or hasattr(part, "to_bytes"): + size = len(part) + elif len(part) == 1: + size = None + else: + _, _, size = part + par = path.rsplit("/", 1)[0] if "/" in path else "" + par0 = par + subdirs = [par0] + while par0 and par0 not in self.dircache: + # collect parent directories + par0 = self._parent(par0) + subdirs.append(par0) + + subdirs.reverse() + for parent, child in zip(subdirs, subdirs[1:]): + # register newly discovered directories + assert child not in self.dircache + assert parent in self.dircache + self.dircache[parent].append( + {"name": child, "type": "directory", "size": 0} + ) + self.dircache[child] = [] + + self.dircache[par].append({"name": path, "type": "file", "size": size}) + + def _open(self, path, mode="rb", block_size=None, cache_options=None, **kwargs): + part_or_url, start0, end0 = self._cat_common(path) + # This logic is kept outside `ReferenceFile` to avoid unnecessary redirection. + # That does mean `_cat_common` gets called twice if it eventually reaches `ReferenceFile`. + if isinstance(part_or_url, bytes): + return io.BytesIO(part_or_url[start0:end0]) + + protocol, _ = split_protocol(part_or_url) + if start0 is None and end0 is None: + return self.fss[protocol]._open( + part_or_url, + mode, + block_size=block_size, + cache_options=cache_options, + **kwargs, + ) + + return ReferenceFile( + self, + path, + mode, + block_size=block_size, + cache_options=cache_options, + **kwargs, + ) + + def ls(self, path, detail=True, **kwargs): + logger.debug("list %s", path) + path = self._strip_protocol(path) + if isinstance(self.references, LazyReferenceMapper): + try: + return self.references.ls(path, detail) + except KeyError: + pass + raise FileNotFoundError(f"'{path}' is not a known key") + if not self.dircache: + self._dircache_from_items() + out = self._ls_from_cache(path) + if out is None: + raise FileNotFoundError(path) + if detail: + return out + return [o["name"] for o in out] + + def exists(self, path, **kwargs): # overwrite auto-sync version + return self.isdir(path) or self.isfile(path) + + def isdir(self, path): # overwrite auto-sync version + if self.dircache: + return path in self.dircache + elif isinstance(self.references, LazyReferenceMapper): + return path in self.references.listdir() + else: + # this may be faster than building dircache for single calls, but + # by looping will be slow for many calls; could cache it? + return any(_.startswith(f"{path}/") for _ in self.references) + + def isfile(self, path): # overwrite auto-sync version + return path in self.references + + async def _ls(self, path, detail=True, **kwargs): # calls fast sync code + return self.ls(path, detail, **kwargs) + + def find(self, path, maxdepth=None, withdirs=False, detail=False, **kwargs): + if withdirs: + return super().find( + path, maxdepth=maxdepth, withdirs=withdirs, detail=detail, **kwargs + ) + if path: + path = self._strip_protocol(path) + r = sorted(k for k in self.references if k.startswith(path)) + else: + r = sorted(self.references) + if detail: + if not self.dircache: + self._dircache_from_items() + return {k: self._ls_from_cache(k)[0] for k in r} + else: + return r + + def info(self, path, **kwargs): + out = self.references.get(path) + if out is not None: + if isinstance(out, (str, bytes)): + # decode base64 here + return {"name": path, "type": "file", "size": len(out)} + elif len(out) > 1: + return {"name": path, "type": "file", "size": out[2]} + else: + out0 = [{"name": path, "type": "file", "size": None}] + else: + out = self.ls(path, True) + out0 = [o for o in out if o["name"] == path] + if not out0: + return {"name": path, "type": "directory", "size": 0} + if out0[0]["size"] is None: + # if this is a whole remote file, update size using remote FS + prot, _ = split_protocol(self.references[path][0]) + out0[0]["size"] = self.fss[prot].size(self.references[path][0]) + return out0[0] + + async def _info(self, path, **kwargs): # calls fast sync code + return self.info(path) + + async def _rm_file(self, path, **kwargs): + self.references.pop( + path, None + ) # ignores FileNotFound, just as well for directories + self.dircache.clear() # this is a bit heavy handed + + async def _pipe_file(self, path, data, mode="overwrite", **kwargs): + if mode == "create" and self.exists(path): + raise FileExistsError + # can be str or bytes + self.references[path] = data + self.dircache.clear() # this is a bit heavy handed + + async def _put_file(self, lpath, rpath, mode="overwrite", **kwargs): + # puts binary + if mode == "create" and self.exists(rpath): + raise FileExistsError + with open(lpath, "rb") as f: + self.references[rpath] = f.read() + self.dircache.clear() # this is a bit heavy handed + + def save_json(self, url, **storage_options): + """Write modified references into new location""" + out = {} + for k, v in self.references.items(): + if isinstance(v, bytes): + try: + out[k] = v.decode("ascii") + except UnicodeDecodeError: + out[k] = (b"base64:" + base64.b64encode(v)).decode() + else: + out[k] = v + with fsspec.open(url, "wb", **storage_options) as f: + f.write(json.dumps({"version": 1, "refs": out}).encode()) + + +class ReferenceFile(AbstractBufferedFile): + def __init__( + self, + fs, + path, + mode="rb", + block_size="default", + autocommit=True, + cache_type="readahead", + cache_options=None, + size=None, + **kwargs, + ): + super().__init__( + fs, + path, + mode=mode, + block_size=block_size, + autocommit=autocommit, + size=size, + cache_type=cache_type, + cache_options=cache_options, + **kwargs, + ) + part_or_url, self.start, self.end = self.fs._cat_common(self.path) + protocol, _ = split_protocol(part_or_url) + self.src_fs = self.fs.fss[protocol] + self.src_path = part_or_url + self._f = None + + @property + def f(self): + if self._f is None or self._f.closed: + self._f = self.src_fs._open( + self.src_path, + mode=self.mode, + block_size=self.blocksize, + autocommit=self.autocommit, + cache_type="none", + **self.kwargs, + ) + return self._f + + def close(self): + if self._f is not None: + self._f.close() + return super().close() + + def _fetch_range(self, start, end): + start = start + self.start + end = min(end + self.start, self.end) + self.f.seek(start) + return self.f.read(end - start) diff --git a/python/user_packages/Python313/site-packages/fsspec/implementations/sftp.py b/python/user_packages/Python313/site-packages/fsspec/implementations/sftp.py new file mode 100644 index 0000000000000000000000000000000000000000..7c347963d692d50390b131225a56477b328f7a3c --- /dev/null +++ b/python/user_packages/Python313/site-packages/fsspec/implementations/sftp.py @@ -0,0 +1,187 @@ +import datetime +import logging +import os +import types +import uuid +from stat import S_ISDIR, S_ISLNK + +import paramiko + +from .. import AbstractFileSystem +from ..utils import infer_storage_options + +logger = logging.getLogger("fsspec.sftp") + + +class SFTPFileSystem(AbstractFileSystem): + """Files over SFTP/SSH + + Peer-to-peer filesystem over SSH using paramiko. + + Note: if using this with the ``open`` or ``open_files``, with full URLs, + there is no way to tell if a path is relative, so all paths are assumed + to be absolute. + """ + + protocol = "sftp", "ssh" + + def __init__(self, host, **ssh_kwargs): + """ + + Parameters + ---------- + host: str + Hostname or IP as a string + temppath: str + Location on the server to put files, when within a transaction + ssh_kwargs: dict + Parameters passed on to connection. See details in + https://docs.paramiko.org/en/3.3/api/client.html#paramiko.client.SSHClient.connect + May include port, username, password... + """ + if self._cached: + return + super().__init__(**ssh_kwargs) + self.temppath = ssh_kwargs.pop("temppath", "/tmp") # remote temp directory + self.host = host + self.ssh_kwargs = ssh_kwargs + self._connect() + + def _connect(self): + logger.debug("Connecting to SFTP server %s", self.host) + self.client = paramiko.SSHClient() + self.client.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + self.client.connect(self.host, **self.ssh_kwargs) + self.ftp = self.client.open_sftp() + + @classmethod + def _strip_protocol(cls, path): + return infer_storage_options(path)["path"] + + @staticmethod + def _get_kwargs_from_urls(urlpath): + out = infer_storage_options(urlpath) + out.pop("path", None) + out.pop("protocol", None) + return out + + def mkdir(self, path, create_parents=True, mode=511): + path = self._strip_protocol(path) + logger.debug("Creating folder %s", path) + if self.exists(path): + raise FileExistsError(f"File exists: {path}") + + if create_parents: + self.makedirs(path) + else: + self.ftp.mkdir(path, mode) + + def makedirs(self, path, exist_ok=False, mode=511): + if self.exists(path) and not exist_ok: + raise FileExistsError(f"File exists: {path}") + + parts = path.split("/") + new_path = "/" if path[:1] == "/" else "" + + for part in parts: + if part: + new_path = f"{new_path}/{part}" if new_path else part + if not self.exists(new_path): + self.ftp.mkdir(new_path, mode) + + def rmdir(self, path): + path = self._strip_protocol(path) + logger.debug("Removing folder %s", path) + self.ftp.rmdir(path) + + def info(self, path): + path = self._strip_protocol(path) + stat = self._decode_stat(self.ftp.stat(path)) + stat["name"] = path + return stat + + @staticmethod + def _decode_stat(stat, parent_path=None): + if S_ISDIR(stat.st_mode): + t = "directory" + elif S_ISLNK(stat.st_mode): + t = "link" + else: + t = "file" + out = { + "name": "", + "size": stat.st_size, + "type": t, + "uid": stat.st_uid, + "gid": stat.st_gid, + "time": datetime.datetime.fromtimestamp( + stat.st_atime, tz=datetime.timezone.utc + ), + "mtime": datetime.datetime.fromtimestamp( + stat.st_mtime, tz=datetime.timezone.utc + ), + } + if parent_path: + out["name"] = "/".join([parent_path.rstrip("/"), stat.filename]) + return out + + def ls(self, path, detail=False): + path = self._strip_protocol(path) + logger.debug("Listing folder %s", path) + stats = [self._decode_stat(stat, path) for stat in self.ftp.listdir_iter(path)] + if detail: + return stats + else: + paths = [stat["name"] for stat in stats] + return sorted(paths) + + def put_file(self, lpath, rpath, callback=None, **kwargs): + self.mkdirs(self._parent(os.fspath(rpath)), exist_ok=True) + logger.debug("Put file %s into %s", lpath, rpath) + self.ftp.put(lpath, rpath) + + def get_file(self, rpath, lpath, **kwargs): + if self.isdir(rpath): + os.makedirs(lpath, exist_ok=True) + else: + self.ftp.get(self._strip_protocol(rpath), lpath) + + def _open(self, path, mode="rb", block_size=None, **kwargs): + """ + block_size: int or None + If 0, no buffering, if 1, line buffering, if >1, buffer that many + bytes, if None use default from paramiko. + """ + logger.debug("Opening file %s", path) + if kwargs.get("autocommit", True) is False: + # writes to temporary file, move on commit + path2 = "/".join([self.temppath, str(uuid.uuid4())]) + f = self.ftp.open(path2, mode, bufsize=block_size if block_size else -1) + f.temppath = path2 + f.targetpath = path + f.fs = self + f.commit = types.MethodType(commit_a_file, f) + f.discard = types.MethodType(discard_a_file, f) + else: + f = self.ftp.open(path, mode, bufsize=block_size if block_size else -1) + return f + + def _rm(self, path): + if self.isdir(path): + self.ftp.rmdir(path) + else: + self.ftp.remove(path) + + def mv(self, old, new): + new = self._strip_protocol(new) + old = self._strip_protocol(old) + logger.debug("Renaming %s into %s", old, new) + self.ftp.posix_rename(old, new) + + +def commit_a_file(self): + self.fs.mv(self.temppath, self.targetpath) + + +def discard_a_file(self): + self.fs._rm(self.temppath) diff --git a/python/user_packages/Python313/site-packages/fsspec/implementations/smb.py b/python/user_packages/Python313/site-packages/fsspec/implementations/smb.py new file mode 100644 index 0000000000000000000000000000000000000000..db6b3f5c3702de90cf121ccca49f3ca2b580df9f --- /dev/null +++ b/python/user_packages/Python313/site-packages/fsspec/implementations/smb.py @@ -0,0 +1,416 @@ +""" +This module contains SMBFileSystem class responsible for handling access to +Windows Samba network shares by using package smbprotocol +""" + +import datetime +import re +import uuid +from stat import S_ISDIR, S_ISLNK + +import smbclient +import smbprotocol.exceptions + +from .. import AbstractFileSystem +from ..utils import infer_storage_options + +# ! pylint: disable=bad-continuation + + +class SMBFileSystem(AbstractFileSystem): + """Allow reading and writing to Windows and Samba network shares. + + When using `fsspec.open()` for getting a file-like object the URI + should be specified as this format: + ``smb://workgroup;user:password@server:port/share/folder/file.csv``. + + Example:: + + >>> import fsspec + >>> with fsspec.open( + ... 'smb://myuser:mypassword@myserver.com/' 'share/folder/file.csv' + ... ) as smbfile: + ... df = pd.read_csv(smbfile, sep='|', header=None) + + Note that you need to pass in a valid hostname or IP address for the host + component of the URL. Do not use the Windows/NetBIOS machine name for the + host component. + + The first component of the path in the URL points to the name of the shared + folder. Subsequent path components will point to the directory/folder/file. + + The URL components ``workgroup`` , ``user``, ``password`` and ``port`` may be + optional. + + .. note:: + + For working this source require `smbprotocol`_ to be installed, e.g.:: + + $ pip install smbprotocol + # or + # pip install smbprotocol[kerberos] + + .. _smbprotocol: https://github.com/jborean93/smbprotocol#requirements + + Note: if using this with the ``open`` or ``open_files``, with full URLs, + there is no way to tell if a path is relative, so all paths are assumed + to be absolute. + """ + + protocol = "smb" + + # pylint: disable=too-many-arguments + def __init__( + self, + host, + port=None, + username=None, + password=None, + timeout=60, + encrypt=None, + share_access=None, + register_session_retries=4, + register_session_retry_wait=1, + register_session_retry_factor=10, + auto_mkdir=False, + **kwargs, + ): + """ + You can use _get_kwargs_from_urls to get some kwargs from + a reasonable SMB url. + + Authentication will be anonymous or integrated if username/password are not + given. + + Parameters + ---------- + host: str + The remote server name/ip to connect to + port: int or None + Port to connect with. Usually 445, sometimes 139. + username: str or None + Username to connect with. Required if Kerberos auth is not being used. + password: str or None + User's password on the server, if using username + timeout: int + Connection timeout in seconds + encrypt: bool + Whether to force encryption or not, once this has been set to True + the session cannot be changed back to False. + share_access: str or None + Specifies the default access applied to file open operations + performed with this file system object. + This affects whether other processes can concurrently open a handle + to the same file. + + - None (the default): exclusively locks the file until closed. + - 'r': Allow other handles to be opened with read access. + - 'w': Allow other handles to be opened with write access. + - 'd': Allow other handles to be opened with delete access. + register_session_retries: int + Number of retries to register a session with the server. Retries are not performed + for authentication errors, as they are considered as invalid credentials and not network + issues. If set to negative value, no register attempts will be performed. + register_session_retry_wait: int + Time in seconds to wait between each retry. Number must be non-negative. + register_session_retry_factor: int + Base factor for the wait time between each retry. The wait time + is calculated using exponential function. For factor=1 all wait times + will be equal to `register_session_retry_wait`. For any number of retries, + the last wait time will be equal to `register_session_retry_wait` and for retries>1 + the first wait time will be equal to `register_session_retry_wait / factor`. + Number must be equal to or greater than 1. Optimal factor is 10. + auto_mkdir: bool + Whether, when opening a file, the directory containing it should + be created (if it doesn't already exist). This is assumed by pyarrow + and zarr-python code. + """ + super().__init__(**kwargs) + self.host = host + self.port = port + self.username = username + self.password = password + self.timeout = timeout + self.encrypt = encrypt + self.temppath = kwargs.pop("temppath", "") + self.share_access = share_access + self.register_session_retries = register_session_retries + if register_session_retry_wait < 0: + raise ValueError( + "register_session_retry_wait must be a non-negative integer" + ) + self.register_session_retry_wait = register_session_retry_wait + if register_session_retry_factor < 1: + raise ValueError( + "register_session_retry_factor must be a positive " + "integer equal to or greater than 1" + ) + self.register_session_retry_factor = register_session_retry_factor + self.auto_mkdir = auto_mkdir + self._connect() + + @property + def _port(self): + return 445 if self.port is None else self.port + + def _connect(self): + import time + + if self.register_session_retries <= -1: + return + + retried_errors = [] + + wait_time = self.register_session_retry_wait + n_waits = ( + self.register_session_retries - 1 + ) # -1 = No wait time after the last retry + factor = self.register_session_retry_factor + + # Generate wait times for each retry attempt. + # Wait times are calculated using exponential function. For factor=1 all wait times + # will be equal to `wait`. For any number of retries the last wait time will be + # equal to `wait` and for retries>2 the first wait time will be equal to `wait / factor`. + wait_times = iter( + factor ** (n / n_waits - 1) * wait_time for n in range(0, n_waits + 1) + ) + + for attempt in range(self.register_session_retries + 1): + try: + smbclient.register_session( + self.host, + username=self.username, + password=self.password, + port=self._port, + encrypt=self.encrypt, + connection_timeout=self.timeout, + ) + return + except ( + smbprotocol.exceptions.SMBAuthenticationError, + smbprotocol.exceptions.LogonFailure, + ): + # These exceptions should not be repeated, as they clearly indicate + # that the credentials are invalid and not a network issue. + raise + except ValueError as exc: + if re.findall(r"\[Errno -\d+]", str(exc)): + # This exception is raised by the smbprotocol.transport:Tcp.connect + # and originates from socket.gaierror (OSError). These exceptions might + # be raised due to network instability. We will retry to connect. + retried_errors.append(exc) + else: + # All another ValueError exceptions should be raised, as they are not + # related to network issues. + raise + except Exception as exc: + # Save the exception and retry to connect. This except might be dropped + # in the future, once all exceptions suited for retry are identified. + retried_errors.append(exc) + + if attempt < self.register_session_retries: + time.sleep(next(wait_times)) + + # Raise last exception to inform user about the connection issues. + # Note: Should we use ExceptionGroup to raise all exceptions? + raise retried_errors[-1] + + @classmethod + def _strip_protocol(cls, path): + return infer_storage_options(path)["path"] + + @staticmethod + def _get_kwargs_from_urls(path): + # smb://workgroup;user:password@host:port/share/folder/file.csv + out = infer_storage_options(path) + out.pop("path", None) + out.pop("protocol", None) + return out + + def mkdir(self, path, create_parents=True, **kwargs): + wpath = _as_unc_path(self.host, path) + if create_parents: + smbclient.makedirs(wpath, exist_ok=False, port=self._port, **kwargs) + else: + smbclient.mkdir(wpath, port=self._port, **kwargs) + + def makedirs(self, path, exist_ok=False): + if _share_has_path(path): + wpath = _as_unc_path(self.host, path) + smbclient.makedirs(wpath, exist_ok=exist_ok, port=self._port) + + def rmdir(self, path): + if _share_has_path(path): + wpath = _as_unc_path(self.host, path) + smbclient.rmdir(wpath, port=self._port) + + def info(self, path, **kwargs): + wpath = _as_unc_path(self.host, path) + stats = smbclient.stat(wpath, port=self._port, **kwargs) + if S_ISDIR(stats.st_mode): + stype = "directory" + elif S_ISLNK(stats.st_mode): + stype = "link" + else: + stype = "file" + res = { + "name": path + "/" if stype == "directory" else path, + "size": stats.st_size, + "type": stype, + "uid": stats.st_uid, + "gid": stats.st_gid, + "time": stats.st_atime, + "mtime": stats.st_mtime, + } + return res + + def created(self, path): + """Return the created timestamp of a file as a datetime.datetime""" + wpath = _as_unc_path(self.host, path) + stats = smbclient.stat(wpath, port=self._port) + return datetime.datetime.fromtimestamp(stats.st_ctime, tz=datetime.timezone.utc) + + def modified(self, path): + """Return the modified timestamp of a file as a datetime.datetime""" + wpath = _as_unc_path(self.host, path) + stats = smbclient.stat(wpath, port=self._port) + return datetime.datetime.fromtimestamp(stats.st_mtime, tz=datetime.timezone.utc) + + def ls(self, path, detail=True, **kwargs): + unc = _as_unc_path(self.host, path) + listed = smbclient.listdir(unc, port=self._port, **kwargs) + dirs = ["/".join([path.rstrip("/"), p]) for p in listed] + if detail: + dirs = [self.info(d) for d in dirs] + return dirs + + # pylint: disable=too-many-arguments + def _open( + self, + path, + mode="rb", + block_size=-1, + autocommit=True, + cache_options=None, + **kwargs, + ): + """ + block_size: int or None + If 0, no buffering, 1, line buffering, >1, buffer that many bytes + + Notes + ----- + By specifying 'share_access' in 'kwargs' it is possible to override the + default shared access setting applied in the constructor of this object. + """ + if self.auto_mkdir and "w" in mode: + self.makedirs(self._parent(path), exist_ok=True) + bls = block_size if block_size is not None and block_size >= 0 else -1 + wpath = _as_unc_path(self.host, path) + share_access = kwargs.pop("share_access", self.share_access) + if "w" in mode and autocommit is False: + temp = _as_temp_path(self.host, path, self.temppath) + return SMBFileOpener( + wpath, temp, mode, port=self._port, block_size=bls, **kwargs + ) + return smbclient.open_file( + wpath, + mode, + buffering=bls, + share_access=share_access, + port=self._port, + **kwargs, + ) + + def copy(self, path1, path2, **kwargs): + """Copy within two locations in the same filesystem""" + wpath1 = _as_unc_path(self.host, path1) + wpath2 = _as_unc_path(self.host, path2) + if self.auto_mkdir: + self.makedirs(self._parent(path2), exist_ok=True) + smbclient.copyfile(wpath1, wpath2, port=self._port, **kwargs) + + def _rm(self, path): + if _share_has_path(path): + wpath = _as_unc_path(self.host, path) + stats = smbclient.stat(wpath, port=self._port) + if S_ISDIR(stats.st_mode): + smbclient.rmdir(wpath, port=self._port) + else: + smbclient.remove(wpath, port=self._port) + + def mv(self, path1, path2, recursive=None, maxdepth=None, **kwargs): + wpath1 = _as_unc_path(self.host, path1) + wpath2 = _as_unc_path(self.host, path2) + smbclient.rename(wpath1, wpath2, port=self._port, **kwargs) + + +def _as_unc_path(host, path): + rpath = path.replace("/", "\\") + unc = f"\\\\{host}{rpath}" + return unc + + +def _as_temp_path(host, path, temppath): + share = path.split("/")[1] + temp_file = f"/{share}{temppath}/{uuid.uuid4()}" + unc = _as_unc_path(host, temp_file) + return unc + + +def _share_has_path(path): + parts = path.count("/") + if path.endswith("/"): + return parts > 2 + return parts > 1 + + +class SMBFileOpener: + """writes to remote temporary file, move on commit""" + + def __init__(self, path, temp, mode, port=445, block_size=-1, **kwargs): + self.path = path + self.temp = temp + self.mode = mode + self.block_size = block_size + self.kwargs = kwargs + self.smbfile = None + self._incontext = False + self.port = port + self._open() + + def _open(self): + if self.smbfile is None or self.smbfile.closed: + self.smbfile = smbclient.open_file( + self.temp, + self.mode, + port=self.port, + buffering=self.block_size, + **self.kwargs, + ) + + def commit(self): + """Move temp file to definitive on success.""" + # TODO: use transaction support in SMB protocol + smbclient.replace(self.temp, self.path, port=self.port) + + def discard(self): + """Remove the temp file on failure.""" + smbclient.remove(self.temp, port=self.port) + + def __fspath__(self): + return self.path + + def __iter__(self): + return self.smbfile.__iter__() + + def __getattr__(self, item): + return getattr(self.smbfile, item) + + def __enter__(self): + self._incontext = True + return self.smbfile.__enter__() + + def __exit__(self, exc_type, exc_value, traceback): + self._incontext = False + self.smbfile.__exit__(exc_type, exc_value, traceback) diff --git a/python/user_packages/Python313/site-packages/fsspec/implementations/tar.py b/python/user_packages/Python313/site-packages/fsspec/implementations/tar.py new file mode 100644 index 0000000000000000000000000000000000000000..41bd894a4e3f1b3b2318f9b28d690dada72d670a --- /dev/null +++ b/python/user_packages/Python313/site-packages/fsspec/implementations/tar.py @@ -0,0 +1,135 @@ +import logging +import tarfile + +import fsspec +from fsspec.archive import AbstractArchiveFileSystem +from fsspec.compression import compr +from fsspec.utils import infer_compression + +typemap = {b"0": "file", b"5": "directory"} + +logger = logging.getLogger("tar") + + +class TarFileSystem(AbstractArchiveFileSystem): + """Compressed Tar archives as a file-system (read-only) + + Supports the following formats: + tar.gz, tar.bz2, tar.xz + """ + + root_marker = "" + protocol = "tar" + cachable = False + + def __init__( + self, + fo="", + index_store=None, + target_options=None, + target_protocol=None, + compression=None, + **kwargs, + ): + super().__init__(**kwargs) + target_options = target_options or {} + + if isinstance(fo, str): + self.of = fsspec.open(fo, protocol=target_protocol, **target_options) + fo = self.of.open() # keep the reference + + # Try to infer compression. + if compression is None: + name = None + + # Try different ways to get hold of the filename. `fo` might either + # be a `fsspec.LocalFileOpener`, an `io.BufferedReader` or an + # `fsspec.AbstractFileSystem` instance. + try: + # Amended io.BufferedReader or similar. + # This uses a "protocol extension" where original filenames are + # propagated to archive-like filesystems in order to let them + # infer the right compression appropriately. + if hasattr(fo, "original"): + name = fo.original + + # fsspec.LocalFileOpener + elif hasattr(fo, "path"): + name = fo.path + + # io.BufferedReader + elif hasattr(fo, "name"): + name = fo.name + + # fsspec.AbstractFileSystem + elif hasattr(fo, "info"): + name = fo.info()["name"] + + except Exception as ex: + logger.warning( + f"Unable to determine file name, not inferring compression: {ex}" + ) + + if name is not None: + compression = infer_compression(name) + logger.info(f"Inferred compression {compression} from file name {name}") + + if compression is not None: + # TODO: tarfile already implements compression with modes like "'r:gz'", + # but then would seek to offset in the file work? + fo = compr[compression](fo) + + self._fo_ref = fo + self.fo = fo # the whole instance is a context + self.tar = tarfile.TarFile(fileobj=self.fo) + self.dir_cache = None + + self.index_store = index_store + self.index = None + self._index() + + def _index(self): + # TODO: load and set saved index, if exists + out = {} + for ti in self.tar: + info = ti.get_info() + info["type"] = typemap.get(info["type"], "file") + name = ti.get_info()["name"].rstrip("/") + out[name] = (info, ti.offset_data) + + self.index = out + # TODO: save index to self.index_store here, if set + + def _get_dirs(self): + if self.dir_cache is not None: + return + + # This enables ls to get directories as children as well as files + self.dir_cache = { + dirname: {"name": dirname, "size": 0, "type": "directory"} + for dirname in self._all_dirnames(self.tar.getnames()) + } + for member in self.tar.getmembers(): + info = member.get_info() + info["name"] = info["name"].rstrip("/") + info["type"] = typemap.get(info["type"], "file") + self.dir_cache[info["name"]] = info + + def _open(self, path, mode="rb", **kwargs): + if mode != "rb": + raise ValueError("Read-only filesystem implementation") + details, offset = self.index[path] + if details["type"] != "file": + raise ValueError("Can only handle regular files") + return self.tar.extractfile(path) + + def close(self): + """Commits any write changes to the file. Done on ``del`` too.""" + self.tar.close() + + def __del__(self): + if hasattr(self, "tar"): + self.close() + del self.tar + if hasattr(self, "of") and hasattr(self.of, "__exit__"): + self.of.__exit__(None, None, None) diff --git a/python/user_packages/Python313/site-packages/fsspec/implementations/webhdfs.py b/python/user_packages/Python313/site-packages/fsspec/implementations/webhdfs.py new file mode 100644 index 0000000000000000000000000000000000000000..e3048b6a3638cf34e400804a3057521e720b6e81 --- /dev/null +++ b/python/user_packages/Python313/site-packages/fsspec/implementations/webhdfs.py @@ -0,0 +1,503 @@ +# https://hadoop.apache.org/docs/r1.0.4/webhdfs.html + +import logging +import os +import secrets +import shutil +import tempfile +import uuid +from contextlib import suppress +from datetime import datetime +from urllib.parse import quote + +import requests + +from ..spec import AbstractBufferedFile, AbstractFileSystem +from ..utils import infer_storage_options, tokenize + +logger = logging.getLogger("webhdfs") + + +class WebHDFS(AbstractFileSystem): + """ + Interface to HDFS over HTTP using the WebHDFS API. Supports also HttpFS gateways. + + Four auth mechanisms are supported: + + insecure: no auth is done, and the user is assumed to be whoever they + say they are (parameter ``user``), or a predefined value such as + "dr.who" if not given + spnego: when kerberos authentication is enabled, auth is negotiated by + requests_kerberos https://github.com/requests/requests-kerberos . + This establishes a session based on existing kinit login and/or + specified principal/password; parameters are passed with ``kerb_kwargs`` + token: uses an existing Hadoop delegation token from another secured + service. Indeed, this client can also generate such tokens when + not insecure. Note that tokens expire, but can be renewed (by a + previously specified user) and may allow for proxying. + basic-auth: used when both parameter ``user`` and parameter ``password`` + are provided. + + """ + + tempdir = str(tempfile.gettempdir()) + protocol = "webhdfs", "webHDFS" + + def __init__( + self, + host, + port=50070, + kerberos=False, + token=None, + user=None, + password=None, + proxy_to=None, + kerb_kwargs=None, + data_proxy=None, + use_https=False, + session_cert=None, + session_verify=True, + **kwargs, + ): + """ + Parameters + ---------- + host: str + Name-node address + port: int + Port for webHDFS + kerberos: bool + Whether to authenticate with kerberos for this connection + token: str or None + If given, use this token on every call to authenticate. A user + and user-proxy may be encoded in the token and should not be also + given + user: str or None + If given, assert the user name to connect with + password: str or None + If given, assert the password to use for basic auth. If password + is provided, user must be provided also + proxy_to: str or None + If given, the user has the authority to proxy, and this value is + the user in who's name actions are taken + kerb_kwargs: dict + Any extra arguments for HTTPKerberosAuth, see + ``_ + data_proxy: dict, callable or None + If given, map data-node addresses. This can be necessary if the + HDFS cluster is behind a proxy, running on Docker or otherwise has + a mismatch between the host-names given by the name-node and the + address by which to refer to them from the client. If a dict, + maps host names ``host->data_proxy[host]``; if a callable, full + URLs are passed, and function must conform to + ``url->data_proxy(url)``. + use_https: bool + Whether to connect to the Name-node using HTTPS instead of HTTP + session_cert: str or Tuple[str, str] or None + Path to a certificate file, or tuple of (cert, key) files to use + for the requests.Session + session_verify: str, bool or None + Path to a certificate file to use for verifying the requests.Session. + kwargs + """ + if self._cached: + return + super().__init__(**kwargs) + self.url = f"{'https' if use_https else 'http'}://{host}:{port}/webhdfs/v1" + self.kerb = kerberos + self.kerb_kwargs = kerb_kwargs or {} + self.pars = {} + self.proxy = data_proxy or {} + if token is not None: + if user is not None or proxy_to is not None: + raise ValueError( + "If passing a delegation token, must not set " + "user or proxy_to, as these are encoded in the" + " token" + ) + self.pars["delegation"] = token + self.user = user + self.password = password + + if password is not None: + if user is None: + raise ValueError( + "If passing a password, the user must also be" + "set in order to set up the basic-auth" + ) + else: + if user is not None: + self.pars["user.name"] = user + + if proxy_to is not None: + self.pars["doas"] = proxy_to + if kerberos and user is not None: + raise ValueError( + "If using Kerberos auth, do not specify the " + "user, this is handled by kinit." + ) + + self.session_cert = session_cert + self.session_verify = session_verify + + self._connect() + + self._fsid = f"webhdfs_{tokenize(host, port)}" + + @property + def fsid(self): + return self._fsid + + def _connect(self): + self.session = requests.Session() + + if self.session_cert: + self.session.cert = self.session_cert + + self.session.verify = self.session_verify + + if self.kerb: + from requests_kerberos import HTTPKerberosAuth + + self.session.auth = HTTPKerberosAuth(**self.kerb_kwargs) + + if self.user is not None and self.password is not None: + from requests.auth import HTTPBasicAuth + + self.session.auth = HTTPBasicAuth(self.user, self.password) + + def _call(self, op, method="get", path=None, data=None, redirect=True, **kwargs): + path = self._strip_protocol(path) if path is not None else "" + url = self._apply_proxy(self.url + quote(path, safe="/=")) + args = kwargs.copy() + args.update(self.pars) + args["op"] = op.upper() + logger.debug("sending %s with %s", url, method) + out = self.session.request( + method=method.upper(), + url=url, + params=args, + data=data, + allow_redirects=redirect, + ) + if out.status_code in [400, 401, 403, 404, 500]: + try: + err = out.json() + msg = err["RemoteException"]["message"] + exp = err["RemoteException"]["exception"] + except (ValueError, KeyError): + pass + else: + if exp in ["IllegalArgumentException", "UnsupportedOperationException"]: + raise ValueError(msg) + elif exp in ["SecurityException", "AccessControlException"]: + raise PermissionError(msg) + elif exp in ["FileNotFoundException"]: + raise FileNotFoundError(msg) + else: + raise RuntimeError(msg) + out.raise_for_status() + return out + + def _open( + self, + path, + mode="rb", + block_size=None, + autocommit=True, + replication=None, + permissions=None, + **kwargs, + ): + """ + + Parameters + ---------- + path: str + File location + mode: str + 'rb', 'wb', etc. + block_size: int + Client buffer size for read-ahead or write buffer + autocommit: bool + If False, writes to temporary file that only gets put in final + location upon commit + replication: int + Number of copies of file on the cluster, write mode only + permissions: str or int + posix permissions, write mode only + kwargs + + Returns + ------- + WebHDFile instance + """ + block_size = block_size or self.blocksize + return WebHDFile( + self, + path, + mode=mode, + block_size=block_size, + tempdir=self.tempdir, + autocommit=autocommit, + replication=replication, + permissions=permissions, + ) + + @staticmethod + def _process_info(info): + info["type"] = info["type"].lower() + info["size"] = info["length"] + return info + + @classmethod + def _strip_protocol(cls, path): + return infer_storage_options(path)["path"] + + @staticmethod + def _get_kwargs_from_urls(urlpath): + out = infer_storage_options(urlpath) + out.pop("path", None) + out.pop("protocol", None) + if "username" in out: + out["user"] = out.pop("username") + return out + + def info(self, path): + out = self._call("GETFILESTATUS", path=path) + info = out.json()["FileStatus"] + info["name"] = path + return self._process_info(info) + + def created(self, path): + """Return the created timestamp of a file as a datetime.datetime""" + # The API does not provide creation time, so we use modification time + info = self.info(path) + mtime = info.get("modificationTime", None) + if mtime is not None: + return datetime.fromtimestamp(mtime / 1000) + raise RuntimeError("Could not retrieve creation time (modification time).") + + def modified(self, path): + """Return the modified timestamp of a file as a datetime.datetime""" + info = self.info(path) + mtime = info.get("modificationTime", None) + if mtime is not None: + return datetime.fromtimestamp(mtime / 1000) + raise RuntimeError("Could not retrieve modification time.") + + def ls(self, path, detail=False, **kwargs): + out = self._call("LISTSTATUS", path=path) + infos = out.json()["FileStatuses"]["FileStatus"] + for info in infos: + self._process_info(info) + info["name"] = path.rstrip("/") + "/" + info["pathSuffix"] + if detail: + return sorted(infos, key=lambda i: i["name"]) + else: + return sorted(info["name"] for info in infos) + + def content_summary(self, path): + """Total numbers of files, directories and bytes under path""" + out = self._call("GETCONTENTSUMMARY", path=path) + return out.json()["ContentSummary"] + + def ukey(self, path): + """Checksum info of file, giving method and result""" + out = self._call("GETFILECHECKSUM", path=path, redirect=False) + if "Location" in out.headers: + location = self._apply_proxy(out.headers["Location"]) + out2 = self.session.get(location) + out2.raise_for_status() + return out2.json()["FileChecksum"] + else: + out.raise_for_status() + return out.json()["FileChecksum"] + + def home_directory(self): + """Get user's home directory""" + out = self._call("GETHOMEDIRECTORY") + return out.json()["Path"] + + def get_delegation_token(self, renewer=None): + """Retrieve token which can give the same authority to other uses + + Parameters + ---------- + renewer: str or None + User who may use this token; if None, will be current user + """ + if renewer: + out = self._call("GETDELEGATIONTOKEN", renewer=renewer) + else: + out = self._call("GETDELEGATIONTOKEN") + t = out.json()["Token"] + if t is None: + raise ValueError("No token available for this user/security context") + return t["urlString"] + + def renew_delegation_token(self, token): + """Make token live longer. Returns new expiry time""" + out = self._call("RENEWDELEGATIONTOKEN", method="put", token=token) + return out.json()["long"] + + def cancel_delegation_token(self, token): + """Stop the token from being useful""" + self._call("CANCELDELEGATIONTOKEN", method="put", token=token) + + def chmod(self, path, mod): + """Set the permission at path + + Parameters + ---------- + path: str + location to set (file or directory) + mod: str or int + posix epresentation or permission, give as oct string, e.g, '777' + or 0o777 + """ + self._call("SETPERMISSION", method="put", path=path, permission=mod) + + def chown(self, path, owner=None, group=None): + """Change owning user and/or group""" + kwargs = {} + if owner is not None: + kwargs["owner"] = owner + if group is not None: + kwargs["group"] = group + self._call("SETOWNER", method="put", path=path, **kwargs) + + def set_replication(self, path, replication): + """ + Set file replication factor + + Parameters + ---------- + path: str + File location (not for directories) + replication: int + Number of copies of file on the cluster. Should be smaller than + number of data nodes; normally 3 on most systems. + """ + self._call("SETREPLICATION", path=path, method="put", replication=replication) + + def mkdir(self, path, **kwargs): + self._call("MKDIRS", method="put", path=path) + + def makedirs(self, path, exist_ok=False): + if exist_ok is False and self.exists(path): + raise FileExistsError(path) + self.mkdir(path) + + def mv(self, path1, path2, **kwargs): + self._call("RENAME", method="put", path=path1, destination=path2) + + def rm(self, path, recursive=False, **kwargs): + self._call( + "DELETE", + method="delete", + path=path, + recursive="true" if recursive else "false", + ) + + def rm_file(self, path, **kwargs): + self.rm(path) + + def cp_file(self, lpath, rpath, **kwargs): + with self.open(lpath) as lstream: + tmp_fname = "/".join([self._parent(rpath), f".tmp.{secrets.token_hex(16)}"]) + # Perform an atomic copy (stream to a temporary file and + # move it to the actual destination). + try: + with self.open(tmp_fname, "wb") as rstream: + shutil.copyfileobj(lstream, rstream) + self.mv(tmp_fname, rpath) + except BaseException: + with suppress(FileNotFoundError): + self.rm(tmp_fname) + raise + + def _apply_proxy(self, location): + if self.proxy and callable(self.proxy): + location = self.proxy(location) + elif self.proxy: + # as a dict + for k, v in self.proxy.items(): + location = location.replace(k, v, 1) + return location + + +class WebHDFile(AbstractBufferedFile): + """A file living in HDFS over webHDFS""" + + def __init__(self, fs, path, **kwargs): + super().__init__(fs, path, **kwargs) + kwargs = kwargs.copy() + if kwargs.get("permissions", None) is None: + kwargs.pop("permissions", None) + if kwargs.get("replication", None) is None: + kwargs.pop("replication", None) + self.permissions = kwargs.pop("permissions", 511) + tempdir = kwargs.pop("tempdir") + if kwargs.pop("autocommit", False) is False: + self.target = self.path + self.path = os.path.join(tempdir, str(uuid.uuid4())) + + def _upload_chunk(self, final=False): + """Write one part of a multi-block file upload + + Parameters + ========== + final: bool + This is the last block, so should complete file, if + self.autocommit is True. + """ + out = self.fs.session.post( + self.location, + data=self.buffer.getvalue(), + headers={"content-type": "application/octet-stream"}, + ) + out.raise_for_status() + return True + + def _initiate_upload(self): + """Create remote file/upload""" + kwargs = self.kwargs.copy() + if "a" in self.mode: + op, method = "APPEND", "POST" + else: + op, method = "CREATE", "PUT" + kwargs["overwrite"] = "true" + out = self.fs._call(op, method, self.path, redirect=False, **kwargs) + location = self.fs._apply_proxy(out.headers["Location"]) + if "w" in self.mode: + # create empty file to append to + out2 = self.fs.session.put( + location, headers={"content-type": "application/octet-stream"} + ) + out2.raise_for_status() + # after creating empty file, change location to append to + out2 = self.fs._call("APPEND", "POST", self.path, redirect=False, **kwargs) + self.location = self.fs._apply_proxy(out2.headers["Location"]) + + def _fetch_range(self, start, end): + start = max(start, 0) + end = min(self.size, end) + if start >= end or start >= self.size: + return b"" + out = self.fs._call( + "OPEN", path=self.path, offset=start, length=end - start, redirect=False + ) + out.raise_for_status() + if "Location" in out.headers: + location = out.headers["Location"] + out2 = self.fs.session.get(self.fs._apply_proxy(location)) + return out2.content + else: + return out.content + + def commit(self): + self.fs.mv(self.path, self.target) + + def discard(self): + self.fs.rm(self.path) diff --git a/python/user_packages/Python313/site-packages/fsspec/implementations/zip.py b/python/user_packages/Python313/site-packages/fsspec/implementations/zip.py new file mode 100644 index 0000000000000000000000000000000000000000..485307a34f8daba70eb30bfda713c95893bbdb0b --- /dev/null +++ b/python/user_packages/Python313/site-packages/fsspec/implementations/zip.py @@ -0,0 +1,183 @@ +import os +import zipfile + +import fsspec +from fsspec.archive import AbstractArchiveFileSystem + + +class ZipFileSystem(AbstractArchiveFileSystem): + """Read/Write contents of ZIP archive as a file-system + + Keeps file object open while instance lives. + + This class is pickleable, but not necessarily thread-safe + """ + + root_marker = "" + protocol = "zip" + cachable = False + + def __init__( + self, + fo="", + mode="r", + target_protocol=None, + target_options=None, + compression=zipfile.ZIP_STORED, + allowZip64=True, + compresslevel=None, + **kwargs, + ): + """ + Parameters + ---------- + fo: str or file-like + Contains ZIP, and must exist. If a str, will fetch file using + :meth:`~fsspec.open_files`, which must return one file exactly. + mode: str + Accept: "r", "w", "a" + target_protocol: str (optional) + If ``fo`` is a string, this value can be used to override the + FS protocol inferred from a URL + target_options: dict (optional) + Kwargs passed when instantiating the target FS, if ``fo`` is + a string. + compression, allowZip64, compresslevel: passed to ZipFile + Only relevant when creating a ZIP + """ + super().__init__(self, **kwargs) + if mode not in set("rwa"): + raise ValueError(f"mode '{mode}' no understood") + self.mode = mode + if isinstance(fo, (str, os.PathLike)): + if mode == "a": + m = "r+b" + else: + m = mode + "b" + fo = fsspec.open( + fo, mode=m, protocol=target_protocol, **(target_options or {}) + ) + self.force_zip_64 = allowZip64 + self.of = fo + self.fo = fo.__enter__() # the whole instance is a context + self.zip = zipfile.ZipFile( + self.fo, + mode=mode, + compression=compression, + allowZip64=allowZip64, + compresslevel=compresslevel, + ) + self.dir_cache = None + + @classmethod + def _strip_protocol(cls, path): + # zip file paths are always relative to the archive root + return super()._strip_protocol(path).lstrip("/") + + def __del__(self): + if hasattr(self, "zip"): + self.close() + del self.zip + if hasattr(self, "of") and hasattr(self.of, "__exit__"): + self.of.__exit__(None, None, None) + + def close(self): + """Commits any write changes to the file. Done on ``del`` too.""" + self.zip.close() + + def _get_dirs(self): + if self.dir_cache is None or self.mode in set("wa"): + # when writing, dir_cache is always in the ZipFile's attributes, + # not read from the file. + files = self.zip.infolist() + self.dir_cache = { + dirname.rstrip("/"): { + "name": dirname.rstrip("/"), + "size": 0, + "type": "directory", + } + for dirname in self._all_dirnames(self.zip.namelist()) + } + for z in files: + f = {s: getattr(z, s, None) for s in zipfile.ZipInfo.__slots__} + f.update( + { + "name": z.filename.rstrip("/"), + "size": z.file_size, + "type": ("directory" if z.is_dir() else "file"), + } + ) + self.dir_cache[f["name"]] = f + + def pipe_file(self, path, value, **kwargs): + # override upstream, because we know the exact file size in this case + self.zip.writestr(path, value, **kwargs) + + def _open( + self, + path, + mode="rb", + block_size=None, + autocommit=True, + cache_options=None, + **kwargs, + ): + path = self._strip_protocol(path) + if "r" in mode and self.mode in set("wa"): + if self.exists(path): + raise OSError("ZipFS can only be open for reading or writing, not both") + raise FileNotFoundError(path) + if "r" in self.mode and "w" in mode: + raise OSError("ZipFS can only be open for reading or writing, not both") + out = self.zip.open(path, mode.strip("b"), force_zip64=self.force_zip_64) + if "r" in mode: + info = self.info(path) + out.size = info["size"] + out.name = info["name"] + return out + + def find(self, path, maxdepth=None, withdirs=False, detail=False, **kwargs): + if maxdepth is not None and maxdepth < 1: + raise ValueError("maxdepth must be at least 1") + + def to_parts(_path: str): + return list(filter(None, _path.replace("\\", "/").split("/"))) + + if not isinstance(path, str): + path = str(path) + + # Remove the leading slash, as the zip file paths are always + # given without a leading slash + path = path.lstrip("/") + path_parts = to_parts(path) + path_depth = len(path_parts) + + self._get_dirs() + + result = {} + # To match posix find, if an exact file name is given, we should + # return only that file + if path in self.dir_cache and self.dir_cache[path]["type"] == "file": + result[path] = self.dir_cache[path] + return result if detail else [path] + + for file_path, file_info in self.dir_cache.items(): + if len(file_parts := to_parts(file_path)) < path_depth or any( + a != b for a, b in zip(path_parts, file_parts) + ): + # skip parent folders and mismatching paths + continue + + if file_info["type"] == "directory": + if withdirs and file_path not in result: + result[file_path.strip("/")] = file_info + continue + + if file_path not in result: + result[file_path] = file_info if detail else None + + if maxdepth: + result = { + k: v for k, v in result.items() if k.count("/") < maxdepth + path_depth + } + return result if detail else sorted(result) diff --git a/python/user_packages/Python313/site-packages/fsspec/tests/abstract/__init__.py b/python/user_packages/Python313/site-packages/fsspec/tests/abstract/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..8ed2ad802ecaf021106c25c03112f29e75c7b2f8 --- /dev/null +++ b/python/user_packages/Python313/site-packages/fsspec/tests/abstract/__init__.py @@ -0,0 +1,289 @@ +import os +from hashlib import md5 + +import pytest + +from fsspec.implementations.local import LocalFileSystem +from fsspec.tests.abstract.copy import AbstractCopyTests # noqa: F401 +from fsspec.tests.abstract.get import AbstractGetTests # noqa: F401 +from fsspec.tests.abstract.open import AbstractOpenTests # noqa: F401 +from fsspec.tests.abstract.pipe import AbstractPipeTests # noqa: F401 +from fsspec.tests.abstract.put import AbstractPutTests # noqa: F401 + + +class BaseAbstractFixtures: + """ + Abstract base class containing fixtures that are used by but never need to + be overridden in derived filesystem-specific classes to run the abstract + tests on such filesystems. + """ + + @pytest.fixture + def fs_bulk_operations_scenario_0(self, fs, fs_join, fs_path): + """ + Scenario on remote filesystem that is used for many cp/get/put tests. + + Cleans up at the end of each test it which it is used. + """ + source = self._bulk_operations_scenario_0(fs, fs_join, fs_path) + yield source + fs.rm(source, recursive=True) + + @pytest.fixture + def fs_glob_edge_cases_files(self, fs, fs_join, fs_path): + """ + Scenario on remote filesystem that is used for glob edge cases cp/get/put tests. + + Cleans up at the end of each test it which it is used. + """ + source = self._glob_edge_cases_files(fs, fs_join, fs_path) + yield source + fs.rm(source, recursive=True) + + @pytest.fixture + def fs_dir_and_file_with_same_name_prefix(self, fs, fs_join, fs_path): + """ + Scenario on remote filesystem that is used to check cp/get/put on directory + and file with the same name prefixes. + + Cleans up at the end of each test it which it is used. + """ + source = self._dir_and_file_with_same_name_prefix(fs, fs_join, fs_path) + yield source + fs.rm(source, recursive=True) + + @pytest.fixture + def fs_10_files_with_hashed_names(self, fs, fs_join, fs_path): + """ + Scenario on remote filesystem that is used to check cp/get/put files order + when source and destination are lists. + + Cleans up at the end of each test it which it is used. + """ + source = self._10_files_with_hashed_names(fs, fs_join, fs_path) + yield source + fs.rm(source, recursive=True) + + @pytest.fixture + def fs_target(self, fs, fs_join, fs_path): + """ + Return name of remote directory that does not yet exist to copy into. + + Cleans up at the end of each test it which it is used. + """ + target = fs_join(fs_path, "target") + yield target + if fs.exists(target): + fs.rm(target, recursive=True) + + @pytest.fixture + def local_bulk_operations_scenario_0(self, local_fs, local_join, local_path): + """ + Scenario on local filesystem that is used for many cp/get/put tests. + + Cleans up at the end of each test it which it is used. + """ + source = self._bulk_operations_scenario_0(local_fs, local_join, local_path) + yield source + local_fs.rm(source, recursive=True) + + @pytest.fixture + def local_glob_edge_cases_files(self, local_fs, local_join, local_path): + """ + Scenario on local filesystem that is used for glob edge cases cp/get/put tests. + + Cleans up at the end of each test it which it is used. + """ + source = self._glob_edge_cases_files(local_fs, local_join, local_path) + yield source + local_fs.rm(source, recursive=True) + + @pytest.fixture + def local_dir_and_file_with_same_name_prefix( + self, local_fs, local_join, local_path + ): + """ + Scenario on local filesystem that is used to check cp/get/put on directory + and file with the same name prefixes. + + Cleans up at the end of each test it which it is used. + """ + source = self._dir_and_file_with_same_name_prefix( + local_fs, local_join, local_path + ) + yield source + local_fs.rm(source, recursive=True) + + @pytest.fixture + def local_10_files_with_hashed_names(self, local_fs, local_join, local_path): + """ + Scenario on local filesystem that is used to check cp/get/put files order + when source and destination are lists. + + Cleans up at the end of each test it which it is used. + """ + source = self._10_files_with_hashed_names(local_fs, local_join, local_path) + yield source + local_fs.rm(source, recursive=True) + + @pytest.fixture + def local_target(self, local_fs, local_join, local_path): + """ + Return name of local directory that does not yet exist to copy into. + + Cleans up at the end of each test it which it is used. + """ + target = local_join(local_path, "target") + yield target + if local_fs.exists(target): + local_fs.rm(target, recursive=True) + + def _glob_edge_cases_files(self, some_fs, some_join, some_path): + """ + Scenario that is used for glob edge cases cp/get/put tests. + Creates the following directory and file structure: + + 📁 source + ├── 📄 file1 + ├── 📄 file2 + ├── 📁 subdir0 + │ ├── 📄 subfile1 + │ ├── 📄 subfile2 + │ └── 📁 nesteddir + │ └── 📄 nestedfile + └── 📁 subdir1 + ├── 📄 subfile1 + ├── 📄 subfile2 + └── 📁 nesteddir + └── 📄 nestedfile + """ + source = some_join(some_path, "source") + some_fs.touch(some_join(source, "file1")) + some_fs.touch(some_join(source, "file2")) + + for subdir_idx in range(2): + subdir = some_join(source, f"subdir{subdir_idx}") + nesteddir = some_join(subdir, "nesteddir") + some_fs.makedirs(nesteddir) + some_fs.touch(some_join(subdir, "subfile1")) + some_fs.touch(some_join(subdir, "subfile2")) + some_fs.touch(some_join(nesteddir, "nestedfile")) + + return source + + def _bulk_operations_scenario_0(self, some_fs, some_join, some_path): + """ + Scenario that is used for many cp/get/put tests. Creates the following + directory and file structure: + + 📁 source + ├── 📄 file1 + ├── 📄 file2 + └── 📁 subdir + ├── 📄 subfile1 + ├── 📄 subfile2 + └── 📁 nesteddir + └── 📄 nestedfile + """ + source = some_join(some_path, "source") + subdir = some_join(source, "subdir") + nesteddir = some_join(subdir, "nesteddir") + some_fs.makedirs(nesteddir) + some_fs.touch(some_join(source, "file1")) + some_fs.touch(some_join(source, "file2")) + some_fs.touch(some_join(subdir, "subfile1")) + some_fs.touch(some_join(subdir, "subfile2")) + some_fs.touch(some_join(nesteddir, "nestedfile")) + return source + + def _dir_and_file_with_same_name_prefix(self, some_fs, some_join, some_path): + """ + Scenario that is used to check cp/get/put on directory and file with + the same name prefixes. Creates the following directory and file structure: + + 📁 source + ├── 📄 subdir.txt + └── 📁 subdir + └── 📄 subfile.txt + """ + source = some_join(some_path, "source") + subdir = some_join(source, "subdir") + file = some_join(source, "subdir.txt") + subfile = some_join(subdir, "subfile.txt") + some_fs.makedirs(subdir) + some_fs.touch(file) + some_fs.touch(subfile) + return source + + def _10_files_with_hashed_names(self, some_fs, some_join, some_path): + """ + Scenario that is used to check cp/get/put files order when source and + destination are lists. Creates the following directory and file structure: + + 📁 source + └── 📄 {hashed([0-9])}.txt + """ + source = some_join(some_path, "source") + for i in range(10): + hashed_i = md5(str(i).encode("utf-8")).hexdigest() + path = some_join(source, f"{hashed_i}.txt") + some_fs.pipe(path=path, value=f"{i}".encode()) + return source + + +class AbstractFixtures(BaseAbstractFixtures): + """ + Abstract base class containing fixtures that may be overridden in derived + filesystem-specific classes to run the abstract tests on such filesystems. + + For any particular filesystem some of these fixtures must be overridden, + such as ``fs`` and ``fs_path``, and others may be overridden if the + default functions here are not appropriate, such as ``fs_join``. + """ + + @pytest.fixture + def fs(self): + raise NotImplementedError("This function must be overridden in derived classes") + + @pytest.fixture + def fs_join(self): + """ + Return a function that joins its arguments together into a path. + + Most fsspec implementations join paths in a platform-dependent way, + but some will override this to always use a forward slash. + """ + return os.path.join + + @pytest.fixture + def fs_path(self): + raise NotImplementedError("This function must be overridden in derived classes") + + @pytest.fixture(scope="class") + def local_fs(self): + # Maybe need an option for auto_mkdir=False? This is only relevant + # for certain implementations. + return LocalFileSystem(auto_mkdir=True) + + @pytest.fixture + def local_join(self): + """ + Return a function that joins its arguments together into a path, on + the local filesystem. + """ + return os.path.join + + @pytest.fixture + def local_path(self, tmpdir): + return tmpdir + + @pytest.fixture + def supports_empty_directories(self): + """ + Return whether this implementation supports empty directories. + """ + return True + + @pytest.fixture + def fs_sanitize_path(self): + return lambda x: x diff --git a/python/user_packages/Python313/site-packages/fsspec/tests/abstract/__pycache__/__init__.cpython-313.pyc b/python/user_packages/Python313/site-packages/fsspec/tests/abstract/__pycache__/__init__.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..04bbbfdd00b6408f7ed29ebc5f7bb7dea3b79674 Binary files /dev/null and b/python/user_packages/Python313/site-packages/fsspec/tests/abstract/__pycache__/__init__.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/fsspec/tests/abstract/__pycache__/common.cpython-313.pyc b/python/user_packages/Python313/site-packages/fsspec/tests/abstract/__pycache__/common.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e2030c2b856e4db388c23d8388e74361af351edd Binary files /dev/null and b/python/user_packages/Python313/site-packages/fsspec/tests/abstract/__pycache__/common.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/fsspec/tests/abstract/__pycache__/copy.cpython-313.pyc b/python/user_packages/Python313/site-packages/fsspec/tests/abstract/__pycache__/copy.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d35f4d583ca840396f0c7970e275b3e953e609b6 Binary files /dev/null and b/python/user_packages/Python313/site-packages/fsspec/tests/abstract/__pycache__/copy.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/fsspec/tests/abstract/__pycache__/get.cpython-313.pyc b/python/user_packages/Python313/site-packages/fsspec/tests/abstract/__pycache__/get.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..da2853f3f38bb853e3489f1c35be0da8728c5cc3 Binary files /dev/null and b/python/user_packages/Python313/site-packages/fsspec/tests/abstract/__pycache__/get.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/fsspec/tests/abstract/__pycache__/mv.cpython-313.pyc b/python/user_packages/Python313/site-packages/fsspec/tests/abstract/__pycache__/mv.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1e302ce9fb3ba36024b192710df535f503788645 Binary files /dev/null and b/python/user_packages/Python313/site-packages/fsspec/tests/abstract/__pycache__/mv.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/fsspec/tests/abstract/__pycache__/open.cpython-313.pyc b/python/user_packages/Python313/site-packages/fsspec/tests/abstract/__pycache__/open.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f10a6f24dc4e39027021f387547235bb9ad6e594 Binary files /dev/null and b/python/user_packages/Python313/site-packages/fsspec/tests/abstract/__pycache__/open.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/fsspec/tests/abstract/__pycache__/pipe.cpython-313.pyc b/python/user_packages/Python313/site-packages/fsspec/tests/abstract/__pycache__/pipe.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..66679b8ba20f921a9dc152ba709e26413333f3fd Binary files /dev/null and b/python/user_packages/Python313/site-packages/fsspec/tests/abstract/__pycache__/pipe.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/fsspec/tests/abstract/__pycache__/put.cpython-313.pyc b/python/user_packages/Python313/site-packages/fsspec/tests/abstract/__pycache__/put.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a3248d9fd78833df7d03148ab02e92f981af2c6f Binary files /dev/null and b/python/user_packages/Python313/site-packages/fsspec/tests/abstract/__pycache__/put.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/fsspec/tests/abstract/common.py b/python/user_packages/Python313/site-packages/fsspec/tests/abstract/common.py new file mode 100644 index 0000000000000000000000000000000000000000..22e7c4140404ab2a8928689721419cf05c2760b9 --- /dev/null +++ b/python/user_packages/Python313/site-packages/fsspec/tests/abstract/common.py @@ -0,0 +1,175 @@ +GLOB_EDGE_CASES_TESTS = { + "argnames": ("path", "recursive", "maxdepth", "expected"), + "argvalues": [ + ("fil?1", False, None, ["file1"]), + ("fil?1", True, None, ["file1"]), + ("file[1-2]", False, None, ["file1", "file2"]), + ("file[1-2]", True, None, ["file1", "file2"]), + ("*", False, None, ["file1", "file2"]), + ( + "*", + True, + None, + [ + "file1", + "file2", + "subdir0/subfile1", + "subdir0/subfile2", + "subdir0/nesteddir/nestedfile", + "subdir1/subfile1", + "subdir1/subfile2", + "subdir1/nesteddir/nestedfile", + ], + ), + ("*", True, 1, ["file1", "file2"]), + ( + "*", + True, + 2, + [ + "file1", + "file2", + "subdir0/subfile1", + "subdir0/subfile2", + "subdir1/subfile1", + "subdir1/subfile2", + ], + ), + ("*1", False, None, ["file1"]), + ( + "*1", + True, + None, + [ + "file1", + "subdir1/subfile1", + "subdir1/subfile2", + "subdir1/nesteddir/nestedfile", + ], + ), + ("*1", True, 2, ["file1", "subdir1/subfile1", "subdir1/subfile2"]), + ( + "**", + False, + None, + [ + "file1", + "file2", + "subdir0/subfile1", + "subdir0/subfile2", + "subdir0/nesteddir/nestedfile", + "subdir1/subfile1", + "subdir1/subfile2", + "subdir1/nesteddir/nestedfile", + ], + ), + ( + "**", + True, + None, + [ + "file1", + "file2", + "subdir0/subfile1", + "subdir0/subfile2", + "subdir0/nesteddir/nestedfile", + "subdir1/subfile1", + "subdir1/subfile2", + "subdir1/nesteddir/nestedfile", + ], + ), + ("**", True, 1, ["file1", "file2"]), + ( + "**", + True, + 2, + [ + "file1", + "file2", + "subdir0/subfile1", + "subdir0/subfile2", + "subdir0/nesteddir/nestedfile", + "subdir1/subfile1", + "subdir1/subfile2", + "subdir1/nesteddir/nestedfile", + ], + ), + ( + "**", + False, + 2, + [ + "file1", + "file2", + "subdir0/subfile1", + "subdir0/subfile2", + "subdir1/subfile1", + "subdir1/subfile2", + ], + ), + ("**/*1", False, None, ["file1", "subdir0/subfile1", "subdir1/subfile1"]), + ( + "**/*1", + True, + None, + [ + "file1", + "subdir0/subfile1", + "subdir1/subfile1", + "subdir1/subfile2", + "subdir1/nesteddir/nestedfile", + ], + ), + ("**/*1", True, 1, ["file1"]), + ( + "**/*1", + True, + 2, + ["file1", "subdir0/subfile1", "subdir1/subfile1", "subdir1/subfile2"], + ), + ("**/*1", False, 2, ["file1", "subdir0/subfile1", "subdir1/subfile1"]), + ("**/subdir0", False, None, []), + ("**/subdir0", True, None, ["subfile1", "subfile2", "nesteddir/nestedfile"]), + ("**/subdir0/nested*", False, 2, []), + ("**/subdir0/nested*", True, 2, ["nestedfile"]), + ("subdir[1-2]", False, None, []), + ("subdir[1-2]", True, None, ["subfile1", "subfile2", "nesteddir/nestedfile"]), + ("subdir[1-2]", True, 2, ["subfile1", "subfile2"]), + ("subdir[0-1]", False, None, []), + ( + "subdir[0-1]", + True, + None, + [ + "subdir0/subfile1", + "subdir0/subfile2", + "subdir0/nesteddir/nestedfile", + "subdir1/subfile1", + "subdir1/subfile2", + "subdir1/nesteddir/nestedfile", + ], + ), + ( + "subdir[0-1]/*fil[e]*", + False, + None, + [ + "subdir0/subfile1", + "subdir0/subfile2", + "subdir1/subfile1", + "subdir1/subfile2", + ], + ), + ( + "subdir[0-1]/*fil[e]*", + True, + None, + [ + "subdir0/subfile1", + "subdir0/subfile2", + "subdir1/subfile1", + "subdir1/subfile2", + ], + ), + ], +} diff --git a/python/user_packages/Python313/site-packages/fsspec/tests/abstract/copy.py b/python/user_packages/Python313/site-packages/fsspec/tests/abstract/copy.py new file mode 100644 index 0000000000000000000000000000000000000000..e39e57e5f7d52bfda8ab5e2398b04cc2303630a0 --- /dev/null +++ b/python/user_packages/Python313/site-packages/fsspec/tests/abstract/copy.py @@ -0,0 +1,557 @@ +from hashlib import md5 +from itertools import product + +import pytest + +from fsspec.tests.abstract.common import GLOB_EDGE_CASES_TESTS + + +class AbstractCopyTests: + def test_copy_file_to_existing_directory( + self, + fs, + fs_join, + fs_bulk_operations_scenario_0, + fs_target, + supports_empty_directories, + ): + # Copy scenario 1a + source = fs_bulk_operations_scenario_0 + + target = fs_target + fs.mkdir(target) + if not supports_empty_directories: + # Force target directory to exist by adding a dummy file + fs.touch(fs_join(target, "dummy")) + assert fs.isdir(target) + + target_file2 = fs_join(target, "file2") + target_subfile1 = fs_join(target, "subfile1") + + # Copy from source directory + fs.cp(fs_join(source, "file2"), target) + assert fs.isfile(target_file2) + + # Copy from sub directory + fs.cp(fs_join(source, "subdir", "subfile1"), target) + assert fs.isfile(target_subfile1) + + # Remove copied files + fs.rm([target_file2, target_subfile1]) + assert not fs.exists(target_file2) + assert not fs.exists(target_subfile1) + + # Repeat with trailing slash on target + fs.cp(fs_join(source, "file2"), target + "/") + assert fs.isdir(target) + assert fs.isfile(target_file2) + + fs.cp(fs_join(source, "subdir", "subfile1"), target + "/") + assert fs.isfile(target_subfile1) + + def test_copy_file_to_new_directory( + self, fs, fs_join, fs_bulk_operations_scenario_0, fs_target + ): + # Copy scenario 1b + source = fs_bulk_operations_scenario_0 + + target = fs_target + fs.mkdir(target) + + fs.cp( + fs_join(source, "subdir", "subfile1"), fs_join(target, "newdir/") + ) # Note trailing slash + assert fs.isdir(target) + assert fs.isdir(fs_join(target, "newdir")) + assert fs.isfile(fs_join(target, "newdir", "subfile1")) + + def test_copy_file_to_file_in_existing_directory( + self, + fs, + fs_join, + fs_bulk_operations_scenario_0, + fs_target, + supports_empty_directories, + ): + # Copy scenario 1c + source = fs_bulk_operations_scenario_0 + + target = fs_target + fs.mkdir(target) + if not supports_empty_directories: + # Force target directory to exist by adding a dummy file + fs.touch(fs_join(target, "dummy")) + assert fs.isdir(target) + + fs.cp(fs_join(source, "subdir", "subfile1"), fs_join(target, "newfile")) + assert fs.isfile(fs_join(target, "newfile")) + + def test_copy_file_to_file_in_new_directory( + self, fs, fs_join, fs_bulk_operations_scenario_0, fs_target + ): + # Copy scenario 1d + source = fs_bulk_operations_scenario_0 + + target = fs_target + fs.mkdir(target) + + fs.cp( + fs_join(source, "subdir", "subfile1"), fs_join(target, "newdir", "newfile") + ) + assert fs.isdir(fs_join(target, "newdir")) + assert fs.isfile(fs_join(target, "newdir", "newfile")) + + def test_copy_directory_to_existing_directory( + self, + fs, + fs_join, + fs_bulk_operations_scenario_0, + fs_target, + supports_empty_directories, + ): + # Copy scenario 1e + source = fs_bulk_operations_scenario_0 + + target = fs_target + fs.mkdir(target) + if not supports_empty_directories: + # Force target directory to exist by adding a dummy file + dummy = fs_join(target, "dummy") + fs.touch(dummy) + assert fs.isdir(target) + + for source_slash, target_slash in zip([False, True], [False, True]): + s = fs_join(source, "subdir") + if source_slash: + s += "/" + t = target + "/" if target_slash else target + + # Without recursive does nothing + fs.cp(s, t) + assert fs.ls(target, detail=False) == ( + [] if supports_empty_directories else [dummy] + ) + + # With recursive + fs.cp(s, t, recursive=True) + if source_slash: + assert fs.isfile(fs_join(target, "subfile1")) + assert fs.isfile(fs_join(target, "subfile2")) + assert fs.isdir(fs_join(target, "nesteddir")) + assert fs.isfile(fs_join(target, "nesteddir", "nestedfile")) + assert not fs.exists(fs_join(target, "subdir")) + + fs.rm( + [ + fs_join(target, "subfile1"), + fs_join(target, "subfile2"), + fs_join(target, "nesteddir"), + ], + recursive=True, + ) + else: + assert fs.isdir(fs_join(target, "subdir")) + assert fs.isfile(fs_join(target, "subdir", "subfile1")) + assert fs.isfile(fs_join(target, "subdir", "subfile2")) + assert fs.isdir(fs_join(target, "subdir", "nesteddir")) + assert fs.isfile(fs_join(target, "subdir", "nesteddir", "nestedfile")) + + fs.rm(fs_join(target, "subdir"), recursive=True) + assert fs.ls(target, detail=False) == ( + [] if supports_empty_directories else [dummy] + ) + + # Limit recursive by maxdepth + fs.cp(s, t, recursive=True, maxdepth=1) + if source_slash: + assert fs.isfile(fs_join(target, "subfile1")) + assert fs.isfile(fs_join(target, "subfile2")) + assert not fs.exists(fs_join(target, "nesteddir")) + assert not fs.exists(fs_join(target, "subdir")) + + fs.rm( + [ + fs_join(target, "subfile1"), + fs_join(target, "subfile2"), + ], + recursive=True, + ) + else: + assert fs.isdir(fs_join(target, "subdir")) + assert fs.isfile(fs_join(target, "subdir", "subfile1")) + assert fs.isfile(fs_join(target, "subdir", "subfile2")) + assert not fs.exists(fs_join(target, "subdir", "nesteddir")) + + fs.rm(fs_join(target, "subdir"), recursive=True) + assert fs.ls(target, detail=False) == ( + [] if supports_empty_directories else [dummy] + ) + + def test_copy_directory_to_new_directory( + self, + fs, + fs_join, + fs_bulk_operations_scenario_0, + fs_target, + supports_empty_directories, + ): + # Copy scenario 1f + source = fs_bulk_operations_scenario_0 + + target = fs_target + fs.mkdir(target) + + for source_slash, target_slash in zip([False, True], [False, True]): + s = fs_join(source, "subdir") + if source_slash: + s += "/" + t = fs_join(target, "newdir") + if target_slash: + t += "/" + + # Without recursive does nothing + fs.cp(s, t) + if supports_empty_directories: + assert fs.ls(target) == [] + else: + with pytest.raises(FileNotFoundError): + fs.ls(target) + + # With recursive + fs.cp(s, t, recursive=True) + assert fs.isdir(fs_join(target, "newdir")) + assert fs.isfile(fs_join(target, "newdir", "subfile1")) + assert fs.isfile(fs_join(target, "newdir", "subfile2")) + assert fs.isdir(fs_join(target, "newdir", "nesteddir")) + assert fs.isfile(fs_join(target, "newdir", "nesteddir", "nestedfile")) + assert not fs.exists(fs_join(target, "subdir")) + + fs.rm(fs_join(target, "newdir"), recursive=True) + assert not fs.exists(fs_join(target, "newdir")) + + # Limit recursive by maxdepth + fs.cp(s, t, recursive=True, maxdepth=1) + assert fs.isdir(fs_join(target, "newdir")) + assert fs.isfile(fs_join(target, "newdir", "subfile1")) + assert fs.isfile(fs_join(target, "newdir", "subfile2")) + assert not fs.exists(fs_join(target, "newdir", "nesteddir")) + assert not fs.exists(fs_join(target, "subdir")) + + fs.rm(fs_join(target, "newdir"), recursive=True) + assert not fs.exists(fs_join(target, "newdir")) + + def test_copy_glob_to_existing_directory( + self, + fs, + fs_join, + fs_bulk_operations_scenario_0, + fs_target, + supports_empty_directories, + ): + # Copy scenario 1g + source = fs_bulk_operations_scenario_0 + + target = fs_target + fs.mkdir(target) + if not supports_empty_directories: + # Force target directory to exist by adding a dummy file + dummy = fs_join(target, "dummy") + fs.touch(dummy) + assert fs.isdir(target) + + for target_slash in [False, True]: + t = target + "/" if target_slash else target + + # Without recursive + fs.cp(fs_join(source, "subdir", "*"), t) + assert fs.isfile(fs_join(target, "subfile1")) + assert fs.isfile(fs_join(target, "subfile2")) + assert not fs.isdir(fs_join(target, "nesteddir")) + assert not fs.exists(fs_join(target, "nesteddir", "nestedfile")) + assert not fs.exists(fs_join(target, "subdir")) + + fs.rm( + [ + fs_join(target, "subfile1"), + fs_join(target, "subfile2"), + ], + recursive=True, + ) + assert fs.ls(target, detail=False) == ( + [] if supports_empty_directories else [dummy] + ) + + # With recursive + for glob, recursive in zip(["*", "**"], [True, False]): + fs.cp(fs_join(source, "subdir", glob), t, recursive=recursive) + assert fs.isfile(fs_join(target, "subfile1")) + assert fs.isfile(fs_join(target, "subfile2")) + assert fs.isdir(fs_join(target, "nesteddir")) + assert fs.isfile(fs_join(target, "nesteddir", "nestedfile")) + assert not fs.exists(fs_join(target, "subdir")) + + fs.rm( + [ + fs_join(target, "subfile1"), + fs_join(target, "subfile2"), + fs_join(target, "nesteddir"), + ], + recursive=True, + ) + assert fs.ls(target, detail=False) == ( + [] if supports_empty_directories else [dummy] + ) + + # Limit recursive by maxdepth + fs.cp( + fs_join(source, "subdir", glob), t, recursive=recursive, maxdepth=1 + ) + assert fs.isfile(fs_join(target, "subfile1")) + assert fs.isfile(fs_join(target, "subfile2")) + assert not fs.exists(fs_join(target, "nesteddir")) + assert not fs.exists(fs_join(target, "subdir")) + + fs.rm( + [ + fs_join(target, "subfile1"), + fs_join(target, "subfile2"), + ], + recursive=True, + ) + assert fs.ls(target, detail=False) == ( + [] if supports_empty_directories else [dummy] + ) + + def test_copy_glob_to_new_directory( + self, fs, fs_join, fs_bulk_operations_scenario_0, fs_target + ): + # Copy scenario 1h + source = fs_bulk_operations_scenario_0 + + target = fs_target + fs.mkdir(target) + + for target_slash in [False, True]: + t = fs_join(target, "newdir") + if target_slash: + t += "/" + + # Without recursive + fs.cp(fs_join(source, "subdir", "*"), t) + assert fs.isdir(fs_join(target, "newdir")) + assert fs.isfile(fs_join(target, "newdir", "subfile1")) + assert fs.isfile(fs_join(target, "newdir", "subfile2")) + assert not fs.exists(fs_join(target, "newdir", "nesteddir")) + assert not fs.exists(fs_join(target, "newdir", "nesteddir", "nestedfile")) + assert not fs.exists(fs_join(target, "subdir")) + assert not fs.exists(fs_join(target, "newdir", "subdir")) + + fs.rm(fs_join(target, "newdir"), recursive=True) + assert not fs.exists(fs_join(target, "newdir")) + + # With recursive + for glob, recursive in zip(["*", "**"], [True, False]): + fs.cp(fs_join(source, "subdir", glob), t, recursive=recursive) + assert fs.isdir(fs_join(target, "newdir")) + assert fs.isfile(fs_join(target, "newdir", "subfile1")) + assert fs.isfile(fs_join(target, "newdir", "subfile2")) + assert fs.isdir(fs_join(target, "newdir", "nesteddir")) + assert fs.isfile(fs_join(target, "newdir", "nesteddir", "nestedfile")) + assert not fs.exists(fs_join(target, "subdir")) + assert not fs.exists(fs_join(target, "newdir", "subdir")) + + fs.rm(fs_join(target, "newdir"), recursive=True) + assert not fs.exists(fs_join(target, "newdir")) + + # Limit recursive by maxdepth + fs.cp( + fs_join(source, "subdir", glob), t, recursive=recursive, maxdepth=1 + ) + assert fs.isdir(fs_join(target, "newdir")) + assert fs.isfile(fs_join(target, "newdir", "subfile1")) + assert fs.isfile(fs_join(target, "newdir", "subfile2")) + assert not fs.exists(fs_join(target, "newdir", "nesteddir")) + assert not fs.exists(fs_join(target, "subdir")) + assert not fs.exists(fs_join(target, "newdir", "subdir")) + + fs.rm(fs_join(target, "newdir"), recursive=True) + assert not fs.exists(fs_join(target, "newdir")) + + @pytest.mark.parametrize( + GLOB_EDGE_CASES_TESTS["argnames"], + GLOB_EDGE_CASES_TESTS["argvalues"], + ) + def test_copy_glob_edge_cases( + self, + path, + recursive, + maxdepth, + expected, + fs, + fs_join, + fs_glob_edge_cases_files, + fs_target, + fs_sanitize_path, + ): + # Copy scenario 1g + source = fs_glob_edge_cases_files + + target = fs_target + + for new_dir, target_slash in product([True, False], [True, False]): + fs.mkdir(target) + + t = fs_join(target, "newdir") if new_dir else target + t = t + "/" if target_slash else t + + fs.copy(fs_join(source, path), t, recursive=recursive, maxdepth=maxdepth) + + output = fs.find(target) + if new_dir: + prefixed_expected = [ + fs_sanitize_path(fs_join(target, "newdir", p)) for p in expected + ] + else: + prefixed_expected = [ + fs_sanitize_path(fs_join(target, p)) for p in expected + ] + assert sorted(output) == sorted(prefixed_expected) + + try: + fs.rm(target, recursive=True) + except FileNotFoundError: + pass + + def test_copy_list_of_files_to_existing_directory( + self, + fs, + fs_join, + fs_bulk_operations_scenario_0, + fs_target, + supports_empty_directories, + ): + # Copy scenario 2a + source = fs_bulk_operations_scenario_0 + + target = fs_target + fs.mkdir(target) + if not supports_empty_directories: + # Force target directory to exist by adding a dummy file + dummy = fs_join(target, "dummy") + fs.touch(dummy) + assert fs.isdir(target) + + source_files = [ + fs_join(source, "file1"), + fs_join(source, "file2"), + fs_join(source, "subdir", "subfile1"), + ] + + for target_slash in [False, True]: + t = target + "/" if target_slash else target + + fs.cp(source_files, t) + assert fs.isfile(fs_join(target, "file1")) + assert fs.isfile(fs_join(target, "file2")) + assert fs.isfile(fs_join(target, "subfile1")) + + fs.rm( + [ + fs_join(target, "file1"), + fs_join(target, "file2"), + fs_join(target, "subfile1"), + ], + recursive=True, + ) + assert fs.ls(target, detail=False) == ( + [] if supports_empty_directories else [dummy] + ) + + def test_copy_list_of_files_to_new_directory( + self, fs, fs_join, fs_bulk_operations_scenario_0, fs_target + ): + # Copy scenario 2b + source = fs_bulk_operations_scenario_0 + + target = fs_target + fs.mkdir(target) + + source_files = [ + fs_join(source, "file1"), + fs_join(source, "file2"), + fs_join(source, "subdir", "subfile1"), + ] + + fs.cp(source_files, fs_join(target, "newdir") + "/") # Note trailing slash + assert fs.isdir(fs_join(target, "newdir")) + assert fs.isfile(fs_join(target, "newdir", "file1")) + assert fs.isfile(fs_join(target, "newdir", "file2")) + assert fs.isfile(fs_join(target, "newdir", "subfile1")) + + def test_copy_two_files_new_directory( + self, fs, fs_join, fs_bulk_operations_scenario_0, fs_target + ): + # This is a duplicate of test_copy_list_of_files_to_new_directory and + # can eventually be removed. + source = fs_bulk_operations_scenario_0 + + target = fs_target + assert not fs.exists(target) + fs.cp([fs_join(source, "file1"), fs_join(source, "file2")], target) + + assert fs.isdir(target) + assert fs.isfile(fs_join(target, "file1")) + assert fs.isfile(fs_join(target, "file2")) + + def test_copy_directory_without_files_with_same_name_prefix( + self, + fs, + fs_join, + fs_target, + fs_dir_and_file_with_same_name_prefix, + supports_empty_directories, + ): + # Create the test dirs + source = fs_dir_and_file_with_same_name_prefix + target = fs_target + + # Test without glob + fs.cp(fs_join(source, "subdir"), target, recursive=True) + + assert fs.isfile(fs_join(target, "subfile.txt")) + assert not fs.isfile(fs_join(target, "subdir.txt")) + + fs.rm([fs_join(target, "subfile.txt")]) + if supports_empty_directories: + assert fs.ls(target) == [] + else: + assert not fs.exists(target) + + # Test with glob + fs.cp(fs_join(source, "subdir*"), target, recursive=True) + + assert fs.isdir(fs_join(target, "subdir")) + assert fs.isfile(fs_join(target, "subdir", "subfile.txt")) + assert fs.isfile(fs_join(target, "subdir.txt")) + + def test_copy_with_source_and_destination_as_list( + self, fs, fs_target, fs_join, fs_10_files_with_hashed_names + ): + # Create the test dir + source = fs_10_files_with_hashed_names + target = fs_target + + # Create list of files for source and destination + source_files = [] + destination_files = [] + for i in range(10): + hashed_i = md5(str(i).encode("utf-8")).hexdigest() + source_files.append(fs_join(source, f"{hashed_i}.txt")) + destination_files.append(fs_join(target, f"{hashed_i}.txt")) + + # Copy and assert order was kept + fs.copy(path1=source_files, path2=destination_files) + + for i in range(10): + file_content = fs.cat(destination_files[i]).decode("utf-8") + assert file_content == str(i) diff --git a/python/user_packages/Python313/site-packages/fsspec/tests/abstract/get.py b/python/user_packages/Python313/site-packages/fsspec/tests/abstract/get.py new file mode 100644 index 0000000000000000000000000000000000000000..851ab81ee581e74cac41c64c83ef0af75826d6b0 --- /dev/null +++ b/python/user_packages/Python313/site-packages/fsspec/tests/abstract/get.py @@ -0,0 +1,587 @@ +from hashlib import md5 +from itertools import product + +import pytest + +from fsspec.implementations.local import make_path_posix +from fsspec.tests.abstract.common import GLOB_EDGE_CASES_TESTS + + +class AbstractGetTests: + def test_get_file_to_existing_directory( + self, + fs, + fs_join, + fs_bulk_operations_scenario_0, + local_fs, + local_join, + local_target, + ): + # Copy scenario 1a + source = fs_bulk_operations_scenario_0 + + target = local_target + local_fs.mkdir(target) + assert local_fs.isdir(target) + + target_file2 = local_join(target, "file2") + target_subfile1 = local_join(target, "subfile1") + + # Copy from source directory + fs.get(fs_join(source, "file2"), target) + assert local_fs.isfile(target_file2) + + # Copy from sub directory + fs.get(fs_join(source, "subdir", "subfile1"), target) + assert local_fs.isfile(target_subfile1) + + # Remove copied files + local_fs.rm([target_file2, target_subfile1]) + assert not local_fs.exists(target_file2) + assert not local_fs.exists(target_subfile1) + + # Repeat with trailing slash on target + fs.get(fs_join(source, "file2"), target + "/") + assert local_fs.isdir(target) + assert local_fs.isfile(target_file2) + + fs.get(fs_join(source, "subdir", "subfile1"), target + "/") + assert local_fs.isfile(target_subfile1) + + def test_get_file_to_new_directory( + self, + fs, + fs_join, + fs_bulk_operations_scenario_0, + local_fs, + local_join, + local_target, + ): + # Copy scenario 1b + source = fs_bulk_operations_scenario_0 + + target = local_target + local_fs.mkdir(target) + + fs.get( + fs_join(source, "subdir", "subfile1"), local_join(target, "newdir/") + ) # Note trailing slash + + assert local_fs.isdir(target) + assert local_fs.isdir(local_join(target, "newdir")) + assert local_fs.isfile(local_join(target, "newdir", "subfile1")) + + def test_get_file_to_file_in_existing_directory( + self, + fs, + fs_join, + fs_bulk_operations_scenario_0, + local_fs, + local_join, + local_target, + ): + # Copy scenario 1c + source = fs_bulk_operations_scenario_0 + + target = local_target + local_fs.mkdir(target) + + fs.get(fs_join(source, "subdir", "subfile1"), local_join(target, "newfile")) + assert local_fs.isfile(local_join(target, "newfile")) + + def test_get_file_to_file_in_new_directory( + self, + fs, + fs_join, + fs_bulk_operations_scenario_0, + local_fs, + local_join, + local_target, + ): + # Copy scenario 1d + source = fs_bulk_operations_scenario_0 + + target = local_target + local_fs.mkdir(target) + + fs.get( + fs_join(source, "subdir", "subfile1"), + local_join(target, "newdir", "newfile"), + ) + assert local_fs.isdir(local_join(target, "newdir")) + assert local_fs.isfile(local_join(target, "newdir", "newfile")) + + def test_get_directory_to_existing_directory( + self, + fs, + fs_join, + fs_bulk_operations_scenario_0, + local_fs, + local_join, + local_target, + ): + # Copy scenario 1e + source = fs_bulk_operations_scenario_0 + + target = local_target + local_fs.mkdir(target) + assert local_fs.isdir(target) + + for source_slash, target_slash in zip([False, True], [False, True]): + s = fs_join(source, "subdir") + if source_slash: + s += "/" + t = target + "/" if target_slash else target + + # Without recursive does nothing + fs.get(s, t) + assert local_fs.ls(target) == [] + + # With recursive + fs.get(s, t, recursive=True) + if source_slash: + assert local_fs.isfile(local_join(target, "subfile1")) + assert local_fs.isfile(local_join(target, "subfile2")) + assert local_fs.isdir(local_join(target, "nesteddir")) + assert local_fs.isfile(local_join(target, "nesteddir", "nestedfile")) + assert not local_fs.exists(local_join(target, "subdir")) + + local_fs.rm( + [ + local_join(target, "subfile1"), + local_join(target, "subfile2"), + local_join(target, "nesteddir"), + ], + recursive=True, + ) + else: + assert local_fs.isdir(local_join(target, "subdir")) + assert local_fs.isfile(local_join(target, "subdir", "subfile1")) + assert local_fs.isfile(local_join(target, "subdir", "subfile2")) + assert local_fs.isdir(local_join(target, "subdir", "nesteddir")) + assert local_fs.isfile( + local_join(target, "subdir", "nesteddir", "nestedfile") + ) + + local_fs.rm(local_join(target, "subdir"), recursive=True) + assert local_fs.ls(target) == [] + + # Limit recursive by maxdepth + fs.get(s, t, recursive=True, maxdepth=1) + if source_slash: + assert local_fs.isfile(local_join(target, "subfile1")) + assert local_fs.isfile(local_join(target, "subfile2")) + assert not local_fs.exists(local_join(target, "nesteddir")) + assert not local_fs.exists(local_join(target, "subdir")) + + local_fs.rm( + [ + local_join(target, "subfile1"), + local_join(target, "subfile2"), + ], + recursive=True, + ) + else: + assert local_fs.isdir(local_join(target, "subdir")) + assert local_fs.isfile(local_join(target, "subdir", "subfile1")) + assert local_fs.isfile(local_join(target, "subdir", "subfile2")) + assert not local_fs.exists(local_join(target, "subdir", "nesteddir")) + + local_fs.rm(local_join(target, "subdir"), recursive=True) + assert local_fs.ls(target) == [] + + def test_get_directory_to_new_directory( + self, + fs, + fs_join, + fs_bulk_operations_scenario_0, + local_fs, + local_join, + local_target, + ): + # Copy scenario 1f + source = fs_bulk_operations_scenario_0 + + target = local_target + local_fs.mkdir(target) + + for source_slash, target_slash in zip([False, True], [False, True]): + s = fs_join(source, "subdir") + if source_slash: + s += "/" + t = local_join(target, "newdir") + if target_slash: + t += "/" + + # Without recursive does nothing + fs.get(s, t) + assert local_fs.ls(target) == [] + + # With recursive + fs.get(s, t, recursive=True) + assert local_fs.isdir(local_join(target, "newdir")) + assert local_fs.isfile(local_join(target, "newdir", "subfile1")) + assert local_fs.isfile(local_join(target, "newdir", "subfile2")) + assert local_fs.isdir(local_join(target, "newdir", "nesteddir")) + assert local_fs.isfile( + local_join(target, "newdir", "nesteddir", "nestedfile") + ) + assert not local_fs.exists(local_join(target, "subdir")) + + local_fs.rm(local_join(target, "newdir"), recursive=True) + assert local_fs.ls(target) == [] + + # Limit recursive by maxdepth + fs.get(s, t, recursive=True, maxdepth=1) + assert local_fs.isdir(local_join(target, "newdir")) + assert local_fs.isfile(local_join(target, "newdir", "subfile1")) + assert local_fs.isfile(local_join(target, "newdir", "subfile2")) + assert not local_fs.exists(local_join(target, "newdir", "nesteddir")) + assert not local_fs.exists(local_join(target, "subdir")) + + local_fs.rm(local_join(target, "newdir"), recursive=True) + assert not local_fs.exists(local_join(target, "newdir")) + + def test_get_glob_to_existing_directory( + self, + fs, + fs_join, + fs_bulk_operations_scenario_0, + local_fs, + local_join, + local_target, + ): + # Copy scenario 1g + source = fs_bulk_operations_scenario_0 + + target = local_target + local_fs.mkdir(target) + + for target_slash in [False, True]: + t = target + "/" if target_slash else target + + # Without recursive + fs.get(fs_join(source, "subdir", "*"), t) + assert local_fs.isfile(local_join(target, "subfile1")) + assert local_fs.isfile(local_join(target, "subfile2")) + assert not local_fs.isdir(local_join(target, "nesteddir")) + assert not local_fs.exists(local_join(target, "nesteddir", "nestedfile")) + assert not local_fs.exists(local_join(target, "subdir")) + + local_fs.rm( + [ + local_join(target, "subfile1"), + local_join(target, "subfile2"), + ], + recursive=True, + ) + assert local_fs.ls(target) == [] + + # With recursive + for glob, recursive in zip(["*", "**"], [True, False]): + fs.get(fs_join(source, "subdir", glob), t, recursive=recursive) + assert local_fs.isfile(local_join(target, "subfile1")) + assert local_fs.isfile(local_join(target, "subfile2")) + assert local_fs.isdir(local_join(target, "nesteddir")) + assert local_fs.isfile(local_join(target, "nesteddir", "nestedfile")) + assert not local_fs.exists(local_join(target, "subdir")) + + local_fs.rm( + [ + local_join(target, "subfile1"), + local_join(target, "subfile2"), + local_join(target, "nesteddir"), + ], + recursive=True, + ) + assert local_fs.ls(target) == [] + + # Limit recursive by maxdepth + fs.get( + fs_join(source, "subdir", glob), t, recursive=recursive, maxdepth=1 + ) + assert local_fs.isfile(local_join(target, "subfile1")) + assert local_fs.isfile(local_join(target, "subfile2")) + assert not local_fs.exists(local_join(target, "nesteddir")) + assert not local_fs.exists(local_join(target, "subdir")) + + local_fs.rm( + [ + local_join(target, "subfile1"), + local_join(target, "subfile2"), + ], + recursive=True, + ) + assert local_fs.ls(target) == [] + + def test_get_glob_to_new_directory( + self, + fs, + fs_join, + fs_bulk_operations_scenario_0, + local_fs, + local_join, + local_target, + ): + # Copy scenario 1h + source = fs_bulk_operations_scenario_0 + + target = local_target + local_fs.mkdir(target) + + for target_slash in [False, True]: + t = fs_join(target, "newdir") + if target_slash: + t += "/" + + # Without recursive + fs.get(fs_join(source, "subdir", "*"), t) + assert local_fs.isdir(local_join(target, "newdir")) + assert local_fs.isfile(local_join(target, "newdir", "subfile1")) + assert local_fs.isfile(local_join(target, "newdir", "subfile2")) + assert not local_fs.exists(local_join(target, "newdir", "nesteddir")) + assert not local_fs.exists( + local_join(target, "newdir", "nesteddir", "nestedfile") + ) + assert not local_fs.exists(local_join(target, "subdir")) + assert not local_fs.exists(local_join(target, "newdir", "subdir")) + + local_fs.rm(local_join(target, "newdir"), recursive=True) + assert local_fs.ls(target) == [] + + # With recursive + for glob, recursive in zip(["*", "**"], [True, False]): + fs.get(fs_join(source, "subdir", glob), t, recursive=recursive) + assert local_fs.isdir(local_join(target, "newdir")) + assert local_fs.isfile(local_join(target, "newdir", "subfile1")) + assert local_fs.isfile(local_join(target, "newdir", "subfile2")) + assert local_fs.isdir(local_join(target, "newdir", "nesteddir")) + assert local_fs.isfile( + local_join(target, "newdir", "nesteddir", "nestedfile") + ) + assert not local_fs.exists(local_join(target, "subdir")) + assert not local_fs.exists(local_join(target, "newdir", "subdir")) + + local_fs.rm(local_join(target, "newdir"), recursive=True) + assert not local_fs.exists(local_join(target, "newdir")) + + # Limit recursive by maxdepth + fs.get( + fs_join(source, "subdir", glob), t, recursive=recursive, maxdepth=1 + ) + assert local_fs.isdir(local_join(target, "newdir")) + assert local_fs.isfile(local_join(target, "newdir", "subfile1")) + assert local_fs.isfile(local_join(target, "newdir", "subfile2")) + assert not local_fs.exists(local_join(target, "newdir", "nesteddir")) + assert not local_fs.exists(local_join(target, "subdir")) + assert not local_fs.exists(local_join(target, "newdir", "subdir")) + + local_fs.rm(local_fs.ls(target, detail=False), recursive=True) + assert not local_fs.exists(local_join(target, "newdir")) + + @pytest.mark.parametrize( + GLOB_EDGE_CASES_TESTS["argnames"], + GLOB_EDGE_CASES_TESTS["argvalues"], + ) + def test_get_glob_edge_cases( + self, + path, + recursive, + maxdepth, + expected, + fs, + fs_join, + fs_glob_edge_cases_files, + local_fs, + local_join, + local_target, + ): + # Copy scenario 1g + source = fs_glob_edge_cases_files + + target = local_target + + for new_dir, target_slash in product([True, False], [True, False]): + local_fs.mkdir(target) + + t = local_join(target, "newdir") if new_dir else target + t = t + "/" if target_slash else t + + fs.get(fs_join(source, path), t, recursive=recursive, maxdepth=maxdepth) + + output = local_fs.find(target) + if new_dir: + prefixed_expected = [ + make_path_posix(local_join(target, "newdir", p)) for p in expected + ] + else: + prefixed_expected = [ + make_path_posix(local_join(target, p)) for p in expected + ] + assert sorted(output) == sorted(prefixed_expected) + + try: + local_fs.rm(target, recursive=True) + except FileNotFoundError: + pass + + def test_get_list_of_files_to_existing_directory( + self, + fs, + fs_join, + fs_bulk_operations_scenario_0, + local_fs, + local_join, + local_target, + ): + # Copy scenario 2a + source = fs_bulk_operations_scenario_0 + + target = local_target + local_fs.mkdir(target) + + source_files = [ + fs_join(source, "file1"), + fs_join(source, "file2"), + fs_join(source, "subdir", "subfile1"), + ] + + for target_slash in [False, True]: + t = target + "/" if target_slash else target + + fs.get(source_files, t) + assert local_fs.isfile(local_join(target, "file1")) + assert local_fs.isfile(local_join(target, "file2")) + assert local_fs.isfile(local_join(target, "subfile1")) + + local_fs.rm( + [ + local_join(target, "file1"), + local_join(target, "file2"), + local_join(target, "subfile1"), + ], + recursive=True, + ) + assert local_fs.ls(target) == [] + + def test_get_list_of_files_to_new_directory( + self, + fs, + fs_join, + fs_bulk_operations_scenario_0, + local_fs, + local_join, + local_target, + ): + # Copy scenario 2b + source = fs_bulk_operations_scenario_0 + + target = local_target + local_fs.mkdir(target) + + source_files = [ + fs_join(source, "file1"), + fs_join(source, "file2"), + fs_join(source, "subdir", "subfile1"), + ] + + fs.get(source_files, local_join(target, "newdir") + "/") # Note trailing slash + assert local_fs.isdir(local_join(target, "newdir")) + assert local_fs.isfile(local_join(target, "newdir", "file1")) + assert local_fs.isfile(local_join(target, "newdir", "file2")) + assert local_fs.isfile(local_join(target, "newdir", "subfile1")) + + def test_get_directory_recursive( + self, fs, fs_join, fs_path, local_fs, local_join, local_target + ): + # https://github.com/fsspec/filesystem_spec/issues/1062 + # Recursive cp/get/put of source directory into non-existent target directory. + src = fs_join(fs_path, "src") + src_file = fs_join(src, "file") + fs.mkdir(src) + fs.touch(src_file) + + target = local_target + + # get without slash + assert not local_fs.exists(target) + for loop in range(2): + fs.get(src, target, recursive=True) + assert local_fs.isdir(target) + + if loop == 0: + assert local_fs.isfile(local_join(target, "file")) + assert not local_fs.exists(local_join(target, "src")) + else: + assert local_fs.isfile(local_join(target, "file")) + assert local_fs.isdir(local_join(target, "src")) + assert local_fs.isfile(local_join(target, "src", "file")) + + local_fs.rm(target, recursive=True) + + # get with slash + assert not local_fs.exists(target) + for loop in range(2): + fs.get(src + "/", target, recursive=True) + assert local_fs.isdir(target) + assert local_fs.isfile(local_join(target, "file")) + assert not local_fs.exists(local_join(target, "src")) + + def test_get_directory_without_files_with_same_name_prefix( + self, + fs, + fs_join, + local_fs, + local_join, + local_target, + fs_dir_and_file_with_same_name_prefix, + ): + # Create the test dirs + source = fs_dir_and_file_with_same_name_prefix + target = local_target + + # Test without glob + fs.get(fs_join(source, "subdir"), target, recursive=True) + + assert local_fs.isfile(local_join(target, "subfile.txt")) + assert not local_fs.isfile(local_join(target, "subdir.txt")) + + local_fs.rm([local_join(target, "subfile.txt")]) + assert local_fs.ls(target) == [] + + # Test with glob + fs.get(fs_join(source, "subdir*"), target, recursive=True) + + assert local_fs.isdir(local_join(target, "subdir")) + assert local_fs.isfile(local_join(target, "subdir", "subfile.txt")) + assert local_fs.isfile(local_join(target, "subdir.txt")) + + def test_get_with_source_and_destination_as_list( + self, + fs, + fs_join, + local_fs, + local_join, + local_target, + fs_10_files_with_hashed_names, + ): + # Create the test dir + source = fs_10_files_with_hashed_names + target = local_target + + # Create list of files for source and destination + source_files = [] + destination_files = [] + for i in range(10): + hashed_i = md5(str(i).encode("utf-8")).hexdigest() + source_files.append(fs_join(source, f"{hashed_i}.txt")) + destination_files.append( + make_path_posix(local_join(target, f"{hashed_i}.txt")) + ) + + # Copy and assert order was kept + fs.get(rpath=source_files, lpath=destination_files) + + for i in range(10): + file_content = local_fs.cat(destination_files[i]).decode("utf-8") + assert file_content == str(i) diff --git a/python/user_packages/Python313/site-packages/fsspec/tests/abstract/mv.py b/python/user_packages/Python313/site-packages/fsspec/tests/abstract/mv.py new file mode 100644 index 0000000000000000000000000000000000000000..39f6caa3de815e024fa84de2acecc986c823ed29 --- /dev/null +++ b/python/user_packages/Python313/site-packages/fsspec/tests/abstract/mv.py @@ -0,0 +1,57 @@ +import os + +import pytest + +import fsspec + + +def test_move_raises_error_with_tmpdir(tmpdir): + # Create a file in the temporary directory + source = tmpdir.join("source_file.txt") + source.write("content") + + # Define a destination that simulates a protected or invalid path + destination = tmpdir.join("non_existent_directory/destination_file.txt") + + # Instantiate the filesystem (assuming the local file system interface) + fs = fsspec.filesystem("file") + + # Use the actual file paths as string + with pytest.raises(FileNotFoundError): + fs.mv(str(source), str(destination)) + + +@pytest.mark.parametrize("recursive", (True, False)) +def test_move_raises_error_with_tmpdir_permission(recursive, tmpdir): + # Create a file in the temporary directory + source = tmpdir.join("source_file.txt") + source.write("content") + + # Create a protected directory (non-writable) + protected_dir = tmpdir.mkdir("protected_directory") + protected_path = str(protected_dir) + + # Set the directory to read-only + if os.name == "nt": + os.system(f'icacls "{protected_path}" /deny Everyone:(W)') + else: + os.chmod(protected_path, 0o555) # Sets the directory to read-only + + # Define a destination inside the protected directory + destination = protected_dir.join("destination_file.txt") + + # Instantiate the filesystem (assuming the local file system interface) + fs = fsspec.filesystem("file") + + # Try to move the file to the read-only directory, expecting a permission error + with pytest.raises(PermissionError): + fs.mv(str(source), str(destination), recursive=recursive) + + # Assert the file was not created in the destination + assert not os.path.exists(destination) + + # Cleanup: Restore permissions so the directory can be cleaned up + if os.name == "nt": + os.system(f'icacls "{protected_path}" /remove:d Everyone') + else: + os.chmod(protected_path, 0o755) # Restore write permission for cleanup diff --git a/python/user_packages/Python313/site-packages/fsspec/tests/abstract/open.py b/python/user_packages/Python313/site-packages/fsspec/tests/abstract/open.py new file mode 100644 index 0000000000000000000000000000000000000000..bb75ea852276fb8d834345883813b8e27a0ae24c --- /dev/null +++ b/python/user_packages/Python313/site-packages/fsspec/tests/abstract/open.py @@ -0,0 +1,11 @@ +import pytest + + +class AbstractOpenTests: + def test_open_exclusive(self, fs, fs_target): + with fs.open(fs_target, "wb") as f: + f.write(b"data") + with fs.open(fs_target, "rb") as f: + assert f.read() == b"data" + with pytest.raises(FileExistsError): + fs.open(fs_target, "xb") diff --git a/python/user_packages/Python313/site-packages/fsspec/tests/abstract/pipe.py b/python/user_packages/Python313/site-packages/fsspec/tests/abstract/pipe.py new file mode 100644 index 0000000000000000000000000000000000000000..8ecca96e9d23ff268a253c48269d5cca451ea270 --- /dev/null +++ b/python/user_packages/Python313/site-packages/fsspec/tests/abstract/pipe.py @@ -0,0 +1,11 @@ +import pytest + + +class AbstractPipeTests: + def test_pipe_exclusive(self, fs, fs_target): + fs.pipe_file(fs_target, b"data") + assert fs.cat_file(fs_target) == b"data" + with pytest.raises(FileExistsError): + fs.pipe_file(fs_target, b"data", mode="create") + fs.pipe_file(fs_target, b"new data", mode="overwrite") + assert fs.cat_file(fs_target) == b"new data" diff --git a/python/user_packages/Python313/site-packages/fsspec/tests/abstract/put.py b/python/user_packages/Python313/site-packages/fsspec/tests/abstract/put.py new file mode 100644 index 0000000000000000000000000000000000000000..9fc349977f0384d9fc86126498be5c6ad99a21d3 --- /dev/null +++ b/python/user_packages/Python313/site-packages/fsspec/tests/abstract/put.py @@ -0,0 +1,591 @@ +from hashlib import md5 +from itertools import product + +import pytest + +from fsspec.tests.abstract.common import GLOB_EDGE_CASES_TESTS + + +class AbstractPutTests: + def test_put_file_to_existing_directory( + self, + fs, + fs_join, + fs_target, + local_join, + local_bulk_operations_scenario_0, + supports_empty_directories, + ): + # Copy scenario 1a + source = local_bulk_operations_scenario_0 + + target = fs_target + fs.mkdir(target) + if not supports_empty_directories: + # Force target directory to exist by adding a dummy file + fs.touch(fs_join(target, "dummy")) + assert fs.isdir(target) + + target_file2 = fs_join(target, "file2") + target_subfile1 = fs_join(target, "subfile1") + + # Copy from source directory + fs.put(local_join(source, "file2"), target) + assert fs.isfile(target_file2) + + # Copy from sub directory + fs.put(local_join(source, "subdir", "subfile1"), target) + assert fs.isfile(target_subfile1) + + # Remove copied files + fs.rm([target_file2, target_subfile1]) + assert not fs.exists(target_file2) + assert not fs.exists(target_subfile1) + + # Repeat with trailing slash on target + fs.put(local_join(source, "file2"), target + "/") + assert fs.isdir(target) + assert fs.isfile(target_file2) + + fs.put(local_join(source, "subdir", "subfile1"), target + "/") + assert fs.isfile(target_subfile1) + + def test_put_file_to_new_directory( + self, fs, fs_join, fs_target, local_join, local_bulk_operations_scenario_0 + ): + # Copy scenario 1b + source = local_bulk_operations_scenario_0 + + target = fs_target + fs.mkdir(target) + + fs.put( + local_join(source, "subdir", "subfile1"), fs_join(target, "newdir/") + ) # Note trailing slash + assert fs.isdir(target) + assert fs.isdir(fs_join(target, "newdir")) + assert fs.isfile(fs_join(target, "newdir", "subfile1")) + + def test_put_file_to_file_in_existing_directory( + self, + fs, + fs_join, + fs_target, + local_join, + supports_empty_directories, + local_bulk_operations_scenario_0, + ): + # Copy scenario 1c + source = local_bulk_operations_scenario_0 + + target = fs_target + fs.mkdir(target) + if not supports_empty_directories: + # Force target directory to exist by adding a dummy file + fs.touch(fs_join(target, "dummy")) + assert fs.isdir(target) + + fs.put(local_join(source, "subdir", "subfile1"), fs_join(target, "newfile")) + assert fs.isfile(fs_join(target, "newfile")) + + def test_put_file_to_file_in_new_directory( + self, fs, fs_join, fs_target, local_join, local_bulk_operations_scenario_0 + ): + # Copy scenario 1d + source = local_bulk_operations_scenario_0 + + target = fs_target + fs.mkdir(target) + + fs.put( + local_join(source, "subdir", "subfile1"), + fs_join(target, "newdir", "newfile"), + ) + assert fs.isdir(fs_join(target, "newdir")) + assert fs.isfile(fs_join(target, "newdir", "newfile")) + + def test_put_directory_to_existing_directory( + self, + fs, + fs_join, + fs_target, + local_bulk_operations_scenario_0, + supports_empty_directories, + ): + # Copy scenario 1e + source = local_bulk_operations_scenario_0 + + target = fs_target + fs.mkdir(target) + if not supports_empty_directories: + # Force target directory to exist by adding a dummy file + dummy = fs_join(target, "dummy") + fs.touch(dummy) + assert fs.isdir(target) + + for source_slash, target_slash in zip([False, True], [False, True]): + s = fs_join(source, "subdir") + if source_slash: + s += "/" + t = target + "/" if target_slash else target + + # Without recursive does nothing + fs.put(s, t) + assert fs.ls(target, detail=False) == ( + [] if supports_empty_directories else [dummy] + ) + + # With recursive + fs.put(s, t, recursive=True) + if source_slash: + assert fs.isfile(fs_join(target, "subfile1")) + assert fs.isfile(fs_join(target, "subfile2")) + assert fs.isdir(fs_join(target, "nesteddir")) + assert fs.isfile(fs_join(target, "nesteddir", "nestedfile")) + assert not fs.exists(fs_join(target, "subdir")) + + fs.rm( + [ + fs_join(target, "subfile1"), + fs_join(target, "subfile2"), + fs_join(target, "nesteddir"), + ], + recursive=True, + ) + else: + assert fs.isdir(fs_join(target, "subdir")) + assert fs.isfile(fs_join(target, "subdir", "subfile1")) + assert fs.isfile(fs_join(target, "subdir", "subfile2")) + assert fs.isdir(fs_join(target, "subdir", "nesteddir")) + assert fs.isfile(fs_join(target, "subdir", "nesteddir", "nestedfile")) + + fs.rm(fs_join(target, "subdir"), recursive=True) + assert fs.ls(target, detail=False) == ( + [] if supports_empty_directories else [dummy] + ) + + # Limit recursive by maxdepth + fs.put(s, t, recursive=True, maxdepth=1) + if source_slash: + assert fs.isfile(fs_join(target, "subfile1")) + assert fs.isfile(fs_join(target, "subfile2")) + assert not fs.exists(fs_join(target, "nesteddir")) + assert not fs.exists(fs_join(target, "subdir")) + + fs.rm( + [ + fs_join(target, "subfile1"), + fs_join(target, "subfile2"), + ], + recursive=True, + ) + else: + assert fs.isdir(fs_join(target, "subdir")) + assert fs.isfile(fs_join(target, "subdir", "subfile1")) + assert fs.isfile(fs_join(target, "subdir", "subfile2")) + assert not fs.exists(fs_join(target, "subdir", "nesteddir")) + + fs.rm(fs_join(target, "subdir"), recursive=True) + assert fs.ls(target, detail=False) == ( + [] if supports_empty_directories else [dummy] + ) + + def test_put_directory_to_new_directory( + self, + fs, + fs_join, + fs_target, + local_bulk_operations_scenario_0, + supports_empty_directories, + ): + # Copy scenario 1f + source = local_bulk_operations_scenario_0 + + target = fs_target + fs.mkdir(target) + + for source_slash, target_slash in zip([False, True], [False, True]): + s = fs_join(source, "subdir") + if source_slash: + s += "/" + t = fs_join(target, "newdir") + if target_slash: + t += "/" + + # Without recursive does nothing + fs.put(s, t) + if supports_empty_directories: + assert fs.ls(target) == [] + else: + with pytest.raises(FileNotFoundError): + fs.ls(target) + + # With recursive + fs.put(s, t, recursive=True) + assert fs.isdir(fs_join(target, "newdir")) + assert fs.isfile(fs_join(target, "newdir", "subfile1")) + assert fs.isfile(fs_join(target, "newdir", "subfile2")) + assert fs.isdir(fs_join(target, "newdir", "nesteddir")) + assert fs.isfile(fs_join(target, "newdir", "nesteddir", "nestedfile")) + assert not fs.exists(fs_join(target, "subdir")) + + fs.rm(fs_join(target, "newdir"), recursive=True) + assert not fs.exists(fs_join(target, "newdir")) + + # Limit recursive by maxdepth + fs.put(s, t, recursive=True, maxdepth=1) + assert fs.isdir(fs_join(target, "newdir")) + assert fs.isfile(fs_join(target, "newdir", "subfile1")) + assert fs.isfile(fs_join(target, "newdir", "subfile2")) + assert not fs.exists(fs_join(target, "newdir", "nesteddir")) + assert not fs.exists(fs_join(target, "subdir")) + + fs.rm(fs_join(target, "newdir"), recursive=True) + assert not fs.exists(fs_join(target, "newdir")) + + def test_put_glob_to_existing_directory( + self, + fs, + fs_join, + fs_target, + local_join, + supports_empty_directories, + local_bulk_operations_scenario_0, + ): + # Copy scenario 1g + source = local_bulk_operations_scenario_0 + + target = fs_target + fs.mkdir(target) + if not supports_empty_directories: + # Force target directory to exist by adding a dummy file + dummy = fs_join(target, "dummy") + fs.touch(dummy) + assert fs.isdir(target) + + for target_slash in [False, True]: + t = target + "/" if target_slash else target + + # Without recursive + fs.put(local_join(source, "subdir", "*"), t) + assert fs.isfile(fs_join(target, "subfile1")) + assert fs.isfile(fs_join(target, "subfile2")) + assert not fs.isdir(fs_join(target, "nesteddir")) + assert not fs.exists(fs_join(target, "nesteddir", "nestedfile")) + assert not fs.exists(fs_join(target, "subdir")) + + fs.rm( + [ + fs_join(target, "subfile1"), + fs_join(target, "subfile2"), + ], + recursive=True, + ) + assert fs.ls(target, detail=False) == ( + [] if supports_empty_directories else [dummy] + ) + + # With recursive + for glob, recursive in zip(["*", "**"], [True, False]): + fs.put(local_join(source, "subdir", glob), t, recursive=recursive) + assert fs.isfile(fs_join(target, "subfile1")) + assert fs.isfile(fs_join(target, "subfile2")) + assert fs.isdir(fs_join(target, "nesteddir")) + assert fs.isfile(fs_join(target, "nesteddir", "nestedfile")) + assert not fs.exists(fs_join(target, "subdir")) + + fs.rm( + [ + fs_join(target, "subfile1"), + fs_join(target, "subfile2"), + fs_join(target, "nesteddir"), + ], + recursive=True, + ) + assert fs.ls(target, detail=False) == ( + [] if supports_empty_directories else [dummy] + ) + + # Limit recursive by maxdepth + fs.put( + local_join(source, "subdir", glob), + t, + recursive=recursive, + maxdepth=1, + ) + assert fs.isfile(fs_join(target, "subfile1")) + assert fs.isfile(fs_join(target, "subfile2")) + assert not fs.exists(fs_join(target, "nesteddir")) + assert not fs.exists(fs_join(target, "subdir")) + + fs.rm( + [ + fs_join(target, "subfile1"), + fs_join(target, "subfile2"), + ], + recursive=True, + ) + assert fs.ls(target, detail=False) == ( + [] if supports_empty_directories else [dummy] + ) + + def test_put_glob_to_new_directory( + self, fs, fs_join, fs_target, local_join, local_bulk_operations_scenario_0 + ): + # Copy scenario 1h + source = local_bulk_operations_scenario_0 + + target = fs_target + fs.mkdir(target) + + for target_slash in [False, True]: + t = fs_join(target, "newdir") + if target_slash: + t += "/" + + # Without recursive + fs.put(local_join(source, "subdir", "*"), t) + assert fs.isdir(fs_join(target, "newdir")) + assert fs.isfile(fs_join(target, "newdir", "subfile1")) + assert fs.isfile(fs_join(target, "newdir", "subfile2")) + assert not fs.exists(fs_join(target, "newdir", "nesteddir")) + assert not fs.exists(fs_join(target, "newdir", "nesteddir", "nestedfile")) + assert not fs.exists(fs_join(target, "subdir")) + assert not fs.exists(fs_join(target, "newdir", "subdir")) + + fs.rm(fs_join(target, "newdir"), recursive=True) + assert not fs.exists(fs_join(target, "newdir")) + + # With recursive + for glob, recursive in zip(["*", "**"], [True, False]): + fs.put(local_join(source, "subdir", glob), t, recursive=recursive) + assert fs.isdir(fs_join(target, "newdir")) + assert fs.isfile(fs_join(target, "newdir", "subfile1")) + assert fs.isfile(fs_join(target, "newdir", "subfile2")) + assert fs.isdir(fs_join(target, "newdir", "nesteddir")) + assert fs.isfile(fs_join(target, "newdir", "nesteddir", "nestedfile")) + assert not fs.exists(fs_join(target, "subdir")) + assert not fs.exists(fs_join(target, "newdir", "subdir")) + + fs.rm(fs_join(target, "newdir"), recursive=True) + assert not fs.exists(fs_join(target, "newdir")) + + # Limit recursive by maxdepth + fs.put( + local_join(source, "subdir", glob), + t, + recursive=recursive, + maxdepth=1, + ) + assert fs.isdir(fs_join(target, "newdir")) + assert fs.isfile(fs_join(target, "newdir", "subfile1")) + assert fs.isfile(fs_join(target, "newdir", "subfile2")) + assert not fs.exists(fs_join(target, "newdir", "nesteddir")) + assert not fs.exists(fs_join(target, "subdir")) + assert not fs.exists(fs_join(target, "newdir", "subdir")) + + fs.rm(fs_join(target, "newdir"), recursive=True) + assert not fs.exists(fs_join(target, "newdir")) + + @pytest.mark.parametrize( + GLOB_EDGE_CASES_TESTS["argnames"], + GLOB_EDGE_CASES_TESTS["argvalues"], + ) + def test_put_glob_edge_cases( + self, + path, + recursive, + maxdepth, + expected, + fs, + fs_join, + fs_target, + local_glob_edge_cases_files, + local_join, + fs_sanitize_path, + ): + # Copy scenario 1g + source = local_glob_edge_cases_files + + target = fs_target + + for new_dir, target_slash in product([True, False], [True, False]): + fs.mkdir(target) + + t = fs_join(target, "newdir") if new_dir else target + t = t + "/" if target_slash else t + + fs.put(local_join(source, path), t, recursive=recursive, maxdepth=maxdepth) + + output = fs.find(target) + if new_dir: + prefixed_expected = [ + fs_sanitize_path(fs_join(target, "newdir", p)) for p in expected + ] + else: + prefixed_expected = [ + fs_sanitize_path(fs_join(target, p)) for p in expected + ] + assert sorted(output) == sorted(prefixed_expected) + + try: + fs.rm(target, recursive=True) + except FileNotFoundError: + pass + + def test_put_list_of_files_to_existing_directory( + self, + fs, + fs_join, + fs_target, + local_join, + local_bulk_operations_scenario_0, + supports_empty_directories, + ): + # Copy scenario 2a + source = local_bulk_operations_scenario_0 + + target = fs_target + fs.mkdir(target) + if not supports_empty_directories: + # Force target directory to exist by adding a dummy file + dummy = fs_join(target, "dummy") + fs.touch(dummy) + assert fs.isdir(target) + + source_files = [ + local_join(source, "file1"), + local_join(source, "file2"), + local_join(source, "subdir", "subfile1"), + ] + + for target_slash in [False, True]: + t = target + "/" if target_slash else target + + fs.put(source_files, t) + assert fs.isfile(fs_join(target, "file1")) + assert fs.isfile(fs_join(target, "file2")) + assert fs.isfile(fs_join(target, "subfile1")) + + fs.rm( + [ + fs_join(target, "file1"), + fs_join(target, "file2"), + fs_join(target, "subfile1"), + ], + recursive=True, + ) + assert fs.ls(target, detail=False) == ( + [] if supports_empty_directories else [dummy] + ) + + def test_put_list_of_files_to_new_directory( + self, fs, fs_join, fs_target, local_join, local_bulk_operations_scenario_0 + ): + # Copy scenario 2b + source = local_bulk_operations_scenario_0 + + target = fs_target + fs.mkdir(target) + + source_files = [ + local_join(source, "file1"), + local_join(source, "file2"), + local_join(source, "subdir", "subfile1"), + ] + + fs.put(source_files, fs_join(target, "newdir") + "/") # Note trailing slash + assert fs.isdir(fs_join(target, "newdir")) + assert fs.isfile(fs_join(target, "newdir", "file1")) + assert fs.isfile(fs_join(target, "newdir", "file2")) + assert fs.isfile(fs_join(target, "newdir", "subfile1")) + + def test_put_directory_recursive( + self, fs, fs_join, fs_target, local_fs, local_join, local_path + ): + # https://github.com/fsspec/filesystem_spec/issues/1062 + # Recursive cp/get/put of source directory into non-existent target directory. + src = local_join(local_path, "src") + src_file = local_join(src, "file") + local_fs.mkdir(src) + local_fs.touch(src_file) + + target = fs_target + + # put without slash + assert not fs.exists(target) + for loop in range(2): + fs.put(src, target, recursive=True) + assert fs.isdir(target) + + if loop == 0: + assert fs.isfile(fs_join(target, "file")) + assert not fs.exists(fs_join(target, "src")) + else: + assert fs.isfile(fs_join(target, "file")) + assert fs.isdir(fs_join(target, "src")) + assert fs.isfile(fs_join(target, "src", "file")) + + fs.rm(target, recursive=True) + + # put with slash + assert not fs.exists(target) + for loop in range(2): + fs.put(src + "/", target, recursive=True) + assert fs.isdir(target) + assert fs.isfile(fs_join(target, "file")) + assert not fs.exists(fs_join(target, "src")) + + def test_put_directory_without_files_with_same_name_prefix( + self, + fs, + fs_join, + fs_target, + local_join, + local_dir_and_file_with_same_name_prefix, + supports_empty_directories, + ): + # Create the test dirs + source = local_dir_and_file_with_same_name_prefix + target = fs_target + + # Test without glob + fs.put(local_join(source, "subdir"), fs_target, recursive=True) + + assert fs.isfile(fs_join(fs_target, "subfile.txt")) + assert not fs.isfile(fs_join(fs_target, "subdir.txt")) + + fs.rm([fs_join(target, "subfile.txt")]) + if supports_empty_directories: + assert fs.ls(target) == [] + else: + assert not fs.exists(target) + + # Test with glob + fs.put(local_join(source, "subdir*"), fs_target, recursive=True) + + assert fs.isdir(fs_join(fs_target, "subdir")) + assert fs.isfile(fs_join(fs_target, "subdir", "subfile.txt")) + assert fs.isfile(fs_join(fs_target, "subdir.txt")) + + def test_copy_with_source_and_destination_as_list( + self, fs, fs_target, fs_join, local_join, local_10_files_with_hashed_names + ): + # Create the test dir + source = local_10_files_with_hashed_names + target = fs_target + + # Create list of files for source and destination + source_files = [] + destination_files = [] + for i in range(10): + hashed_i = md5(str(i).encode("utf-8")).hexdigest() + source_files.append(local_join(source, f"{hashed_i}.txt")) + destination_files.append(fs_join(target, f"{hashed_i}.txt")) + + # Copy and assert order was kept + fs.put(lpath=source_files, rpath=destination_files) + + for i in range(10): + file_content = fs.cat(destination_files[i]).decode("utf-8") + assert file_content == str(i) diff --git a/python/user_packages/Python313/site-packages/google/api/__pycache__/annotations_pb2.cpython-313.pyc b/python/user_packages/Python313/site-packages/google/api/__pycache__/annotations_pb2.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7a762eace6753bfab7f98902a39bcacbe400c31a Binary files /dev/null and b/python/user_packages/Python313/site-packages/google/api/__pycache__/annotations_pb2.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/google/api/__pycache__/auth_pb2.cpython-313.pyc b/python/user_packages/Python313/site-packages/google/api/__pycache__/auth_pb2.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f4ee489a5bb31435554252834683b639157c5492 Binary files /dev/null and b/python/user_packages/Python313/site-packages/google/api/__pycache__/auth_pb2.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/google/api/__pycache__/backend_pb2.cpython-313.pyc b/python/user_packages/Python313/site-packages/google/api/__pycache__/backend_pb2.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f966533b7f51e48c8cd637bdf685a39d6288e0b0 Binary files /dev/null and b/python/user_packages/Python313/site-packages/google/api/__pycache__/backend_pb2.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/google/api/__pycache__/billing_pb2.cpython-313.pyc b/python/user_packages/Python313/site-packages/google/api/__pycache__/billing_pb2.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0c16dd19c6fe9663db666c163b3eee8379304c54 Binary files /dev/null and b/python/user_packages/Python313/site-packages/google/api/__pycache__/billing_pb2.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/google/api/__pycache__/client_pb2.cpython-313.pyc b/python/user_packages/Python313/site-packages/google/api/__pycache__/client_pb2.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3d6a12fb4ec38bfde0ce9ae63f5daef0ed25bd26 Binary files /dev/null and b/python/user_packages/Python313/site-packages/google/api/__pycache__/client_pb2.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/google/api/__pycache__/config_change_pb2.cpython-313.pyc b/python/user_packages/Python313/site-packages/google/api/__pycache__/config_change_pb2.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..faac22ec2939d0945a2775dbf715cdca1902aabe Binary files /dev/null and b/python/user_packages/Python313/site-packages/google/api/__pycache__/config_change_pb2.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/google/api/__pycache__/consumer_pb2.cpython-313.pyc b/python/user_packages/Python313/site-packages/google/api/__pycache__/consumer_pb2.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..fd16d5fd4d49678763b6438d4410f6c6105da8e8 Binary files /dev/null and b/python/user_packages/Python313/site-packages/google/api/__pycache__/consumer_pb2.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/google/api/__pycache__/context_pb2.cpython-313.pyc b/python/user_packages/Python313/site-packages/google/api/__pycache__/context_pb2.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7db8ee08442f895a62e00c572fccafe3e14a5120 Binary files /dev/null and b/python/user_packages/Python313/site-packages/google/api/__pycache__/context_pb2.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/google/api/__pycache__/control_pb2.cpython-313.pyc b/python/user_packages/Python313/site-packages/google/api/__pycache__/control_pb2.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d2d565b2686dbe1fbeca7800290ab63c78976cb3 Binary files /dev/null and b/python/user_packages/Python313/site-packages/google/api/__pycache__/control_pb2.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/google/api/__pycache__/distribution_pb2.cpython-313.pyc b/python/user_packages/Python313/site-packages/google/api/__pycache__/distribution_pb2.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0fb9680905af64854c0ba5cf1e95c30be2770d68 Binary files /dev/null and b/python/user_packages/Python313/site-packages/google/api/__pycache__/distribution_pb2.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/google/api/__pycache__/documentation_pb2.cpython-313.pyc b/python/user_packages/Python313/site-packages/google/api/__pycache__/documentation_pb2.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d23e8c11523ec7a8eb52e040847400f65a294721 Binary files /dev/null and b/python/user_packages/Python313/site-packages/google/api/__pycache__/documentation_pb2.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/google/api/__pycache__/endpoint_pb2.cpython-313.pyc b/python/user_packages/Python313/site-packages/google/api/__pycache__/endpoint_pb2.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b37d0935727733cca08857bb5eaf0eb0ba4d2969 Binary files /dev/null and b/python/user_packages/Python313/site-packages/google/api/__pycache__/endpoint_pb2.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/google/api/__pycache__/error_reason_pb2.cpython-313.pyc b/python/user_packages/Python313/site-packages/google/api/__pycache__/error_reason_pb2.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4a2b5f3de5d4908890085b3dae249b8a89303cf0 Binary files /dev/null and b/python/user_packages/Python313/site-packages/google/api/__pycache__/error_reason_pb2.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/google/api/__pycache__/field_behavior_pb2.cpython-313.pyc b/python/user_packages/Python313/site-packages/google/api/__pycache__/field_behavior_pb2.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ef534839877ea29e7dffa6153a03b4ef453220d3 Binary files /dev/null and b/python/user_packages/Python313/site-packages/google/api/__pycache__/field_behavior_pb2.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/google/api/__pycache__/field_info_pb2.cpython-313.pyc b/python/user_packages/Python313/site-packages/google/api/__pycache__/field_info_pb2.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5d7c0dc825d6aaff4590d4c9653dff27254de3fc Binary files /dev/null and b/python/user_packages/Python313/site-packages/google/api/__pycache__/field_info_pb2.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/google/api/__pycache__/http_pb2.cpython-313.pyc b/python/user_packages/Python313/site-packages/google/api/__pycache__/http_pb2.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..fa7062b9f0f4af01092c015ce918260a925baabf Binary files /dev/null and b/python/user_packages/Python313/site-packages/google/api/__pycache__/http_pb2.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/google/api/__pycache__/httpbody_pb2.cpython-313.pyc b/python/user_packages/Python313/site-packages/google/api/__pycache__/httpbody_pb2.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8aeaa5ac191d1f29fafea4932eb77ef7e9e9d6d5 Binary files /dev/null and b/python/user_packages/Python313/site-packages/google/api/__pycache__/httpbody_pb2.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/google/api/__pycache__/label_pb2.cpython-313.pyc b/python/user_packages/Python313/site-packages/google/api/__pycache__/label_pb2.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2bf0c803c965ba4050b82551abddb9baab3fc548 Binary files /dev/null and b/python/user_packages/Python313/site-packages/google/api/__pycache__/label_pb2.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/google/api/__pycache__/launch_stage_pb2.cpython-313.pyc b/python/user_packages/Python313/site-packages/google/api/__pycache__/launch_stage_pb2.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..779478e5e5d7a8ae6f3d528c7a5b2fb53a8a7cb0 Binary files /dev/null and b/python/user_packages/Python313/site-packages/google/api/__pycache__/launch_stage_pb2.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/google/api/__pycache__/log_pb2.cpython-313.pyc b/python/user_packages/Python313/site-packages/google/api/__pycache__/log_pb2.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..893bb77972c703ac5f29320d5ca8a8a58f90bcb3 Binary files /dev/null and b/python/user_packages/Python313/site-packages/google/api/__pycache__/log_pb2.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/google/api/__pycache__/logging_pb2.cpython-313.pyc b/python/user_packages/Python313/site-packages/google/api/__pycache__/logging_pb2.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..21773e715ef2fb34247aa6302489cf9826b0df94 Binary files /dev/null and b/python/user_packages/Python313/site-packages/google/api/__pycache__/logging_pb2.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/google/api/__pycache__/metric_pb2.cpython-313.pyc b/python/user_packages/Python313/site-packages/google/api/__pycache__/metric_pb2.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..90a4e3dfa11db62c4069ccfaf276d6759ad7ac74 Binary files /dev/null and b/python/user_packages/Python313/site-packages/google/api/__pycache__/metric_pb2.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/google/api/__pycache__/monitored_resource_pb2.cpython-313.pyc b/python/user_packages/Python313/site-packages/google/api/__pycache__/monitored_resource_pb2.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9e78b6e1bb0b097d80a01d030ebf6bca4fdf75fd Binary files /dev/null and b/python/user_packages/Python313/site-packages/google/api/__pycache__/monitored_resource_pb2.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/google/api/__pycache__/monitoring_pb2.cpython-313.pyc b/python/user_packages/Python313/site-packages/google/api/__pycache__/monitoring_pb2.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..71a7c9b0f11eafa687308d9e332a315f0e131f38 Binary files /dev/null and b/python/user_packages/Python313/site-packages/google/api/__pycache__/monitoring_pb2.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/google/api/__pycache__/policy_pb2.cpython-313.pyc b/python/user_packages/Python313/site-packages/google/api/__pycache__/policy_pb2.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e3c7cde0dbf06aacdb9afde811d4430c189a0f2b Binary files /dev/null and b/python/user_packages/Python313/site-packages/google/api/__pycache__/policy_pb2.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/google/api/__pycache__/quota_pb2.cpython-313.pyc b/python/user_packages/Python313/site-packages/google/api/__pycache__/quota_pb2.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b626fea3801a5ef13a48186cf4962c0a5892a9dd Binary files /dev/null and b/python/user_packages/Python313/site-packages/google/api/__pycache__/quota_pb2.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/google/api/__pycache__/resource_pb2.cpython-313.pyc b/python/user_packages/Python313/site-packages/google/api/__pycache__/resource_pb2.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..69fa59615f70219f0c485eef5aa82c7fd1db67da Binary files /dev/null and b/python/user_packages/Python313/site-packages/google/api/__pycache__/resource_pb2.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/google/api/__pycache__/routing_pb2.cpython-313.pyc b/python/user_packages/Python313/site-packages/google/api/__pycache__/routing_pb2.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..70e524be94d926255118aa04ddf56106e031d56a Binary files /dev/null and b/python/user_packages/Python313/site-packages/google/api/__pycache__/routing_pb2.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/google/api/__pycache__/service_pb2.cpython-313.pyc b/python/user_packages/Python313/site-packages/google/api/__pycache__/service_pb2.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ea9a867c8bf4dda1f01d65cf47b6566161089bcd Binary files /dev/null and b/python/user_packages/Python313/site-packages/google/api/__pycache__/service_pb2.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/google/api/__pycache__/source_info_pb2.cpython-313.pyc b/python/user_packages/Python313/site-packages/google/api/__pycache__/source_info_pb2.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..216c4b2e4695451dd153c0c9f3b52b4ec4b4d228 Binary files /dev/null and b/python/user_packages/Python313/site-packages/google/api/__pycache__/source_info_pb2.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/google/api/__pycache__/system_parameter_pb2.cpython-313.pyc b/python/user_packages/Python313/site-packages/google/api/__pycache__/system_parameter_pb2.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b963db5d2a3997e92428276fa4b3acf37eac3ae7 Binary files /dev/null and b/python/user_packages/Python313/site-packages/google/api/__pycache__/system_parameter_pb2.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/google/api/__pycache__/usage_pb2.cpython-313.pyc b/python/user_packages/Python313/site-packages/google/api/__pycache__/usage_pb2.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..16c11de23040e90cc0945490cccbafd37b6d1d5b Binary files /dev/null and b/python/user_packages/Python313/site-packages/google/api/__pycache__/usage_pb2.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/google/api/__pycache__/visibility_pb2.cpython-313.pyc b/python/user_packages/Python313/site-packages/google/api/__pycache__/visibility_pb2.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..028d60f2d2efbfc0671a2b9673d7edd812c513a0 Binary files /dev/null and b/python/user_packages/Python313/site-packages/google/api/__pycache__/visibility_pb2.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/google/cloud/__pycache__/common_resources_pb2.cpython-313.pyc b/python/user_packages/Python313/site-packages/google/cloud/__pycache__/common_resources_pb2.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b037852c3939b6749c55264116fff13698323a27 Binary files /dev/null and b/python/user_packages/Python313/site-packages/google/cloud/__pycache__/common_resources_pb2.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/google/cloud/__pycache__/extended_operations_pb2.cpython-313.pyc b/python/user_packages/Python313/site-packages/google/cloud/__pycache__/extended_operations_pb2.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..62582c8fefb1527f4fe8a76f3c765e96699b628b Binary files /dev/null and b/python/user_packages/Python313/site-packages/google/cloud/__pycache__/extended_operations_pb2.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/google/cloud/location/__pycache__/locations_pb2.cpython-313.pyc b/python/user_packages/Python313/site-packages/google/cloud/location/__pycache__/locations_pb2.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ca54cf277951ac3a0f350d4bc3bbacab5cae1632 Binary files /dev/null and b/python/user_packages/Python313/site-packages/google/cloud/location/__pycache__/locations_pb2.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/google/cloud/location/locations.proto b/python/user_packages/Python313/site-packages/google/cloud/location/locations.proto new file mode 100644 index 0000000000000000000000000000000000000000..36a0b0e89ddcfdbf42a73239a006d804abbde341 --- /dev/null +++ b/python/user_packages/Python313/site-packages/google/cloud/location/locations.proto @@ -0,0 +1,108 @@ +// Copyright 2025 Google LLC +// +// 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. + +syntax = "proto3"; + +package google.cloud.location; + +import "google/api/annotations.proto"; +import "google/protobuf/any.proto"; +import "google/api/client.proto"; + +option cc_enable_arenas = true; +option go_package = "google.golang.org/genproto/googleapis/cloud/location;location"; +option java_multiple_files = true; +option java_outer_classname = "LocationsProto"; +option java_package = "com.google.cloud.location"; + +// An abstract interface that provides location-related information for +// a service. Service-specific metadata is provided through the +// [Location.metadata][google.cloud.location.Location.metadata] field. +service Locations { + option (google.api.default_host) = "cloud.googleapis.com"; + option (google.api.oauth_scopes) = "https://www.googleapis.com/auth/cloud-platform"; + + // Lists information about the supported locations for this service. + rpc ListLocations(ListLocationsRequest) returns (ListLocationsResponse) { + option (google.api.http) = { + get: "/v1/{name=locations}" + additional_bindings { + get: "/v1/{name=projects/*}/locations" + } + }; + } + + // Gets information about a location. + rpc GetLocation(GetLocationRequest) returns (Location) { + option (google.api.http) = { + get: "/v1/{name=locations/*}" + additional_bindings { + get: "/v1/{name=projects/*/locations/*}" + } + }; + } +} + +// The request message for [Locations.ListLocations][google.cloud.location.Locations.ListLocations]. +message ListLocationsRequest { + // The resource that owns the locations collection, if applicable. + string name = 1; + + // The standard list filter. + string filter = 2; + + // The standard list page size. + int32 page_size = 3; + + // The standard list page token. + string page_token = 4; +} + +// The response message for [Locations.ListLocations][google.cloud.location.Locations.ListLocations]. +message ListLocationsResponse { + // A list of locations that matches the specified filter in the request. + repeated Location locations = 1; + + // The standard List next-page token. + string next_page_token = 2; +} + +// The request message for [Locations.GetLocation][google.cloud.location.Locations.GetLocation]. +message GetLocationRequest { + // Resource name for the location. + string name = 1; +} + +// A resource that represents Google Cloud Platform location. +message Location { + // Resource name for the location, which may vary between implementations. + // For example: `"projects/example-project/locations/us-east1"` + string name = 1; + + // The canonical id for this location. For example: `"us-east1"`. + string location_id = 4; + + // The friendly name for this location, typically a nearby city name. + // For example, "Tokyo". + string display_name = 5; + + // Cross-service attributes for the location. For example + // + // {"cloud.googleapis.com/region": "us-east1"} + map labels = 2; + + // Service-specific metadata. For example the available capacity at the given + // location. + google.protobuf.Any metadata = 3; +} diff --git a/python/user_packages/Python313/site-packages/google/cloud/location/locations_pb2.py b/python/user_packages/Python313/site-packages/google/cloud/location/locations_pb2.py new file mode 100644 index 0000000000000000000000000000000000000000..d903a84385ade43ebf1f9aa874baab4cb62ec9c9 --- /dev/null +++ b/python/user_packages/Python313/site-packages/google/cloud/location/locations_pb2.py @@ -0,0 +1,77 @@ +# -*- coding: utf-8 -*- + +# Copyright 2025 Google LLC +# +# 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. + +# Generated by the protocol buffer compiler. DO NOT EDIT! +# source: google/cloud/location/locations.proto +# Protobuf Python Version: 4.25.3 +"""Generated protocol buffer code.""" + +from google.protobuf import descriptor as _descriptor +from google.protobuf import descriptor_pool as _descriptor_pool +from google.protobuf import symbol_database as _symbol_database +from google.protobuf.internal import builder as _builder + +# @@protoc_insertion_point(imports) + +_sym_db = _symbol_database.Default() + + +from google.protobuf import any_pb2 as google_dot_protobuf_dot_any__pb2 + +from google.api import annotations_pb2 as google_dot_api_dot_annotations__pb2 +from google.api import client_pb2 as google_dot_api_dot_client__pb2 + +DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile( + b'\n%google/cloud/location/locations.proto\x12\x15google.cloud.location\x1a\x1cgoogle/api/annotations.proto\x1a\x19google/protobuf/any.proto\x1a\x17google/api/client.proto"[\n\x14ListLocationsRequest\x12\x0c\n\x04name\x18\x01 \x01(\t\x12\x0e\n\x06\x66ilter\x18\x02 \x01(\t\x12\x11\n\tpage_size\x18\x03 \x01(\x05\x12\x12\n\npage_token\x18\x04 \x01(\t"d\n\x15ListLocationsResponse\x12\x32\n\tlocations\x18\x01 \x03(\x0b\x32\x1f.google.cloud.location.Location\x12\x17\n\x0fnext_page_token\x18\x02 \x01(\t""\n\x12GetLocationRequest\x12\x0c\n\x04name\x18\x01 \x01(\t"\xd7\x01\n\x08Location\x12\x0c\n\x04name\x18\x01 \x01(\t\x12\x13\n\x0blocation_id\x18\x04 \x01(\t\x12\x14\n\x0c\x64isplay_name\x18\x05 \x01(\t\x12;\n\x06labels\x18\x02 \x03(\x0b\x32+.google.cloud.location.Location.LabelsEntry\x12&\n\x08metadata\x18\x03 \x01(\x0b\x32\x14.google.protobuf.Any\x1a-\n\x0bLabelsEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12\r\n\x05value\x18\x02 \x01(\t:\x02\x38\x01\x32\xa4\x03\n\tLocations\x12\xab\x01\n\rListLocations\x12+.google.cloud.location.ListLocationsRequest\x1a,.google.cloud.location.ListLocationsResponse"?\x82\xd3\xe4\x93\x02\x39\x12\x14/v1/{name=locations}Z!\x12\x1f/v1/{name=projects/*}/locations\x12\x9e\x01\n\x0bGetLocation\x12).google.cloud.location.GetLocationRequest\x1a\x1f.google.cloud.location.Location"C\x82\xd3\xe4\x93\x02=\x12\x16/v1/{name=locations/*}Z#\x12!/v1/{name=projects/*/locations/*}\x1aH\xca\x41\x14\x63loud.googleapis.com\xd2\x41.https://www.googleapis.com/auth/cloud-platformBo\n\x19\x63om.google.cloud.locationB\x0eLocationsProtoP\x01Z=google.golang.org/genproto/googleapis/cloud/location;location\xf8\x01\x01\x62\x06proto3' +) + +_globals = globals() +_builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, _globals) +_builder.BuildTopDescriptorsAndMessages( + DESCRIPTOR, "google.cloud.location.locations_pb2", _globals +) +if _descriptor._USE_C_DESCRIPTORS == False: + _globals["DESCRIPTOR"]._options = None + _globals[ + "DESCRIPTOR" + ]._serialized_options = b"\n\031com.google.cloud.locationB\016LocationsProtoP\001Z=google.golang.org/genproto/googleapis/cloud/location;location\370\001\001" + _globals["_LOCATION_LABELSENTRY"]._options = None + _globals["_LOCATION_LABELSENTRY"]._serialized_options = b"8\001" + _globals["_LOCATIONS"]._options = None + _globals[ + "_LOCATIONS" + ]._serialized_options = b"\312A\024cloud.googleapis.com\322A.https://www.googleapis.com/auth/cloud-platform" + _globals["_LOCATIONS"].methods_by_name["ListLocations"]._options = None + _globals["_LOCATIONS"].methods_by_name[ + "ListLocations" + ]._serialized_options = b"\202\323\344\223\0029\022\024/v1/{name=locations}Z!\022\037/v1/{name=projects/*}/locations" + _globals["_LOCATIONS"].methods_by_name["GetLocation"]._options = None + _globals["_LOCATIONS"].methods_by_name[ + "GetLocation" + ]._serialized_options = b"\202\323\344\223\002=\022\026/v1/{name=locations/*}Z#\022!/v1/{name=projects/*/locations/*}" + _globals["_LISTLOCATIONSREQUEST"]._serialized_start = 146 + _globals["_LISTLOCATIONSREQUEST"]._serialized_end = 237 + _globals["_LISTLOCATIONSRESPONSE"]._serialized_start = 239 + _globals["_LISTLOCATIONSRESPONSE"]._serialized_end = 339 + _globals["_GETLOCATIONREQUEST"]._serialized_start = 341 + _globals["_GETLOCATIONREQUEST"]._serialized_end = 375 + _globals["_LOCATION"]._serialized_start = 378 + _globals["_LOCATION"]._serialized_end = 593 + _globals["_LOCATION_LABELSENTRY"]._serialized_start = 548 + _globals["_LOCATION_LABELSENTRY"]._serialized_end = 593 + _globals["_LOCATIONS"]._serialized_start = 596 + _globals["_LOCATIONS"]._serialized_end = 1016 +# @@protoc_insertion_point(module_scope) diff --git a/python/user_packages/Python313/site-packages/google/cloud/location/locations_pb2.pyi b/python/user_packages/Python313/site-packages/google/cloud/location/locations_pb2.pyi new file mode 100644 index 0000000000000000000000000000000000000000..714050027ecf156383bc64fc5526626dcae8828e --- /dev/null +++ b/python/user_packages/Python313/site-packages/google/cloud/location/locations_pb2.pyi @@ -0,0 +1,96 @@ +# Copyright 2025 Google LLC +# +# 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. + +from typing import ClassVar as _ClassVar +from typing import Iterable as _Iterable +from typing import Mapping as _Mapping +from typing import Optional as _Optional +from typing import Union as _Union + +from google.protobuf import any_pb2 as _any_pb2 +from google.protobuf import descriptor as _descriptor +from google.protobuf import message as _message +from google.protobuf.internal import containers as _containers + +from google.api import annotations_pb2 as _annotations_pb2 +from google.api import client_pb2 as _client_pb2 + +DESCRIPTOR: _descriptor.FileDescriptor + +class ListLocationsRequest(_message.Message): + __slots__ = ("name", "filter", "page_size", "page_token") + NAME_FIELD_NUMBER: _ClassVar[int] + FILTER_FIELD_NUMBER: _ClassVar[int] + PAGE_SIZE_FIELD_NUMBER: _ClassVar[int] + PAGE_TOKEN_FIELD_NUMBER: _ClassVar[int] + name: str + filter: str + page_size: int + page_token: str + def __init__( + self, + name: _Optional[str] = ..., + filter: _Optional[str] = ..., + page_size: _Optional[int] = ..., + page_token: _Optional[str] = ..., + ) -> None: ... + +class ListLocationsResponse(_message.Message): + __slots__ = ("locations", "next_page_token") + LOCATIONS_FIELD_NUMBER: _ClassVar[int] + NEXT_PAGE_TOKEN_FIELD_NUMBER: _ClassVar[int] + locations: _containers.RepeatedCompositeFieldContainer[Location] + next_page_token: str + def __init__( + self, + locations: _Optional[_Iterable[_Union[Location, _Mapping]]] = ..., + next_page_token: _Optional[str] = ..., + ) -> None: ... + +class GetLocationRequest(_message.Message): + __slots__ = ("name",) + NAME_FIELD_NUMBER: _ClassVar[int] + name: str + def __init__(self, name: _Optional[str] = ...) -> None: ... + +class Location(_message.Message): + __slots__ = ("name", "location_id", "display_name", "labels", "metadata") + class LabelsEntry(_message.Message): + __slots__ = ("key", "value") + KEY_FIELD_NUMBER: _ClassVar[int] + VALUE_FIELD_NUMBER: _ClassVar[int] + key: str + value: str + def __init__( + self, key: _Optional[str] = ..., value: _Optional[str] = ... + ) -> None: ... + + NAME_FIELD_NUMBER: _ClassVar[int] + LOCATION_ID_FIELD_NUMBER: _ClassVar[int] + DISPLAY_NAME_FIELD_NUMBER: _ClassVar[int] + LABELS_FIELD_NUMBER: _ClassVar[int] + METADATA_FIELD_NUMBER: _ClassVar[int] + name: str + location_id: str + display_name: str + labels: _containers.ScalarMap[str, str] + metadata: _any_pb2.Any + def __init__( + self, + name: _Optional[str] = ..., + location_id: _Optional[str] = ..., + display_name: _Optional[str] = ..., + labels: _Optional[_Mapping[str, str]] = ..., + metadata: _Optional[_Union[_any_pb2.Any, _Mapping]] = ..., + ) -> None: ... diff --git a/python/user_packages/Python313/site-packages/google/gapic/metadata/__pycache__/gapic_metadata_pb2.cpython-313.pyc b/python/user_packages/Python313/site-packages/google/gapic/metadata/__pycache__/gapic_metadata_pb2.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..96ff33789d90dfeb233716752bc2ad7f3b3cc19d Binary files /dev/null and b/python/user_packages/Python313/site-packages/google/gapic/metadata/__pycache__/gapic_metadata_pb2.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/google/gapic/metadata/gapic_metadata.proto b/python/user_packages/Python313/site-packages/google/gapic/metadata/gapic_metadata.proto new file mode 100644 index 0000000000000000000000000000000000000000..0f2855c15a66716f379115e79c54b2a2a3b88a03 --- /dev/null +++ b/python/user_packages/Python313/site-packages/google/gapic/metadata/gapic_metadata.proto @@ -0,0 +1,98 @@ +// Copyright 2020 Google LLC. +// +// 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. +// + +syntax = "proto3"; + +package google.gapic.metadata; + +option csharp_namespace = "Google.Gapic.Metadata"; +option go_package = "google.golang.org/genproto/googleapis/gapic/metadata;metadata"; +option java_multiple_files = true; +option java_outer_classname = "GapicMetadataProto"; +option java_package = "com.google.gapic.metadata"; +option php_namespace = "Google\\Gapic\\Metadata"; +option ruby_package = "Google::Gapic::Metadata"; + +// Metadata about a GAPIC library service for a specific combination of API, +// version, and computer language. +message GapicMetadata { + // Schema version of this proto. Current value: 1.0 + string schema = 1; + + // Any human-readable comments to be included in this file. + string comment = 2; + + // Computer language of this generated language. This must be + // spelled out as it spoken in English, with no capitalization or + // separators (e.g. "csharp", "nodejs"). + string language = 3; + + // The proto package containing the API definition for which this + // GAPIC library was generated. + string proto_package = 4; + + // The language-specific library package for this GAPIC library. + string library_package = 5; + + // A map from each proto-defined service to ServiceForTransports, + // which allows listing information about transport-specific + // implementations of the service. + // + // The key is the name of the service as it appears in the .proto + // file. + map services = 6; + + // A map from a transport name to ServiceAsClient, which allows + // listing information about the client objects that implement the + // parent RPC service for the specified transport. + message ServiceForTransport { + // Map of transport name to ServiceAsClient. The key name is the transport, + // lower-cased with no separators (e.g. "grpc", "rest"). + map clients = 1; + + // The API version for the interface definition found in the + // `google.api.api_version` annotation of this proto-defined service during + // code generation. + // This is the value populated by the client in the API version request + // parameter as per + // [AIP-4236](https://google.aip.dev/client-libraries/4236). + string api_version = 2; + } + + // Information about a specific client implementing a proto-defined service. + message ServiceAsClient { + // The name of the library client formatted as it appears in the source code + string library_client = 1; + + // A mapping from each proto-defined RPC name to the the list of + // methods in library_client that implement it. There can be more + // than one library_client method for each RPC. RPCs with no + // library_client methods need not be included. + // + // The key name is the name of the RPC as defined and formatted in + // the proto file. + map rpcs = 2; + } + + // List of GAPIC client methods implementing the proto-defined RPC + // for the transport and service specified in the containing + // structures. + message MethodList { + // List of methods for a specific proto-service client in the + // GAPIC. These names should be formatted as they appear in the + // source code. + repeated string methods = 1; + } +} diff --git a/python/user_packages/Python313/site-packages/google/gapic/metadata/gapic_metadata_pb2.py b/python/user_packages/Python313/site-packages/google/gapic/metadata/gapic_metadata_pb2.py new file mode 100644 index 0000000000000000000000000000000000000000..8665a4a4aeefe8706fbb093ff07fa6b8655eb8a8 --- /dev/null +++ b/python/user_packages/Python313/site-packages/google/gapic/metadata/gapic_metadata_pb2.py @@ -0,0 +1,68 @@ +# -*- coding: utf-8 -*- + +# Copyright 2025 Google LLC +# +# 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. + +# Generated by the protocol buffer compiler. DO NOT EDIT! +# source: google/gapic/metadata/gapic_metadata.proto +# Protobuf Python Version: 4.25.3 +"""Generated protocol buffer code.""" + +from google.protobuf import descriptor as _descriptor +from google.protobuf import descriptor_pool as _descriptor_pool +from google.protobuf import symbol_database as _symbol_database +from google.protobuf.internal import builder as _builder + +# @@protoc_insertion_point(imports) + +_sym_db = _symbol_database.Default() + + +DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile( + b'\n*google/gapic/metadata/gapic_metadata.proto\x12\x15google.gapic.metadata"\x85\x06\n\rGapicMetadata\x12\x0e\n\x06schema\x18\x01 \x01(\t\x12\x0f\n\x07\x63omment\x18\x02 \x01(\t\x12\x10\n\x08language\x18\x03 \x01(\t\x12\x15\n\rproto_package\x18\x04 \x01(\t\x12\x17\n\x0flibrary_package\x18\x05 \x01(\t\x12\x44\n\x08services\x18\x06 \x03(\x0b\x32\x32.google.gapic.metadata.GapicMetadata.ServicesEntry\x1ai\n\rServicesEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12G\n\x05value\x18\x02 \x01(\x0b\x32\x38.google.gapic.metadata.GapicMetadata.ServiceForTransport:\x02\x38\x01\x1a\xe8\x01\n\x13ServiceForTransport\x12V\n\x07\x63lients\x18\x01 \x03(\x0b\x32\x45.google.gapic.metadata.GapicMetadata.ServiceForTransport.ClientsEntry\x12\x13\n\x0b\x61pi_version\x18\x02 \x01(\t\x1a\x64\n\x0c\x43lientsEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12\x43\n\x05value\x18\x02 \x01(\x0b\x32\x34.google.gapic.metadata.GapicMetadata.ServiceAsClient:\x02\x38\x01\x1a\xd5\x01\n\x0fServiceAsClient\x12\x16\n\x0elibrary_client\x18\x01 \x01(\t\x12L\n\x04rpcs\x18\x02 \x03(\x0b\x32>.google.gapic.metadata.GapicMetadata.ServiceAsClient.RpcsEntry\x1a\\\n\tRpcsEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12>\n\x05value\x18\x02 \x01(\x0b\x32/.google.gapic.metadata.GapicMetadata.MethodList:\x02\x38\x01\x1a\x1d\n\nMethodList\x12\x0f\n\x07methods\x18\x01 \x03(\tB\xba\x01\n\x19\x63om.google.gapic.metadataB\x12GapicMetadataProtoP\x01Z=google.golang.org/genproto/googleapis/gapic/metadata;metadata\xaa\x02\x15Google.Gapic.Metadata\xca\x02\x15Google\\Gapic\\Metadata\xea\x02\x17Google::Gapic::Metadatab\x06proto3' +) + +_globals = globals() +_builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, _globals) +_builder.BuildTopDescriptorsAndMessages( + DESCRIPTOR, "google.gapic.metadata.gapic_metadata_pb2", _globals +) +if _descriptor._USE_C_DESCRIPTORS == False: + _globals["DESCRIPTOR"]._options = None + _globals[ + "DESCRIPTOR" + ]._serialized_options = b"\n\031com.google.gapic.metadataB\022GapicMetadataProtoP\001Z=google.golang.org/genproto/googleapis/gapic/metadata;metadata\252\002\025Google.Gapic.Metadata\312\002\025Google\\Gapic\\Metadata\352\002\027Google::Gapic::Metadata" + _globals["_GAPICMETADATA_SERVICESENTRY"]._options = None + _globals["_GAPICMETADATA_SERVICESENTRY"]._serialized_options = b"8\001" + _globals["_GAPICMETADATA_SERVICEFORTRANSPORT_CLIENTSENTRY"]._options = None + _globals[ + "_GAPICMETADATA_SERVICEFORTRANSPORT_CLIENTSENTRY" + ]._serialized_options = b"8\001" + _globals["_GAPICMETADATA_SERVICEASCLIENT_RPCSENTRY"]._options = None + _globals["_GAPICMETADATA_SERVICEASCLIENT_RPCSENTRY"]._serialized_options = b"8\001" + _globals["_GAPICMETADATA"]._serialized_start = 70 + _globals["_GAPICMETADATA"]._serialized_end = 843 + _globals["_GAPICMETADATA_SERVICESENTRY"]._serialized_start = 256 + _globals["_GAPICMETADATA_SERVICESENTRY"]._serialized_end = 361 + _globals["_GAPICMETADATA_SERVICEFORTRANSPORT"]._serialized_start = 364 + _globals["_GAPICMETADATA_SERVICEFORTRANSPORT"]._serialized_end = 596 + _globals["_GAPICMETADATA_SERVICEFORTRANSPORT_CLIENTSENTRY"]._serialized_start = 496 + _globals["_GAPICMETADATA_SERVICEFORTRANSPORT_CLIENTSENTRY"]._serialized_end = 596 + _globals["_GAPICMETADATA_SERVICEASCLIENT"]._serialized_start = 599 + _globals["_GAPICMETADATA_SERVICEASCLIENT"]._serialized_end = 812 + _globals["_GAPICMETADATA_SERVICEASCLIENT_RPCSENTRY"]._serialized_start = 720 + _globals["_GAPICMETADATA_SERVICEASCLIENT_RPCSENTRY"]._serialized_end = 812 + _globals["_GAPICMETADATA_METHODLIST"]._serialized_start = 814 + _globals["_GAPICMETADATA_METHODLIST"]._serialized_end = 843 +# @@protoc_insertion_point(module_scope) diff --git a/python/user_packages/Python313/site-packages/google/gapic/metadata/gapic_metadata_pb2.pyi b/python/user_packages/Python313/site-packages/google/gapic/metadata/gapic_metadata_pb2.pyi new file mode 100644 index 0000000000000000000000000000000000000000..aed974f2cf54f3983f200587fb336159e810139f --- /dev/null +++ b/python/user_packages/Python313/site-packages/google/gapic/metadata/gapic_metadata_pb2.pyi @@ -0,0 +1,125 @@ +# Copyright 2025 Google LLC +# +# 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. + +from typing import ClassVar as _ClassVar +from typing import Iterable as _Iterable +from typing import Mapping as _Mapping +from typing import Optional as _Optional +from typing import Union as _Union + +from google.protobuf import descriptor as _descriptor +from google.protobuf import message as _message +from google.protobuf.internal import containers as _containers + +DESCRIPTOR: _descriptor.FileDescriptor + +class GapicMetadata(_message.Message): + __slots__ = ( + "schema", + "comment", + "language", + "proto_package", + "library_package", + "services", + ) + + class ServicesEntry(_message.Message): + __slots__ = ("key", "value") + KEY_FIELD_NUMBER: _ClassVar[int] + VALUE_FIELD_NUMBER: _ClassVar[int] + key: str + value: GapicMetadata.ServiceForTransport + def __init__( + self, + key: _Optional[str] = ..., + value: _Optional[_Union[GapicMetadata.ServiceForTransport, _Mapping]] = ..., + ) -> None: ... + + class ServiceForTransport(_message.Message): + __slots__ = ("clients", "api_version") + + class ClientsEntry(_message.Message): + __slots__ = ("key", "value") + KEY_FIELD_NUMBER: _ClassVar[int] + VALUE_FIELD_NUMBER: _ClassVar[int] + key: str + value: GapicMetadata.ServiceAsClient + def __init__( + self, + key: _Optional[str] = ..., + value: _Optional[_Union[GapicMetadata.ServiceAsClient, _Mapping]] = ..., + ) -> None: ... + + CLIENTS_FIELD_NUMBER: _ClassVar[int] + API_VERSION_FIELD_NUMBER: _ClassVar[int] + clients: _containers.MessageMap[str, GapicMetadata.ServiceAsClient] + api_version: str + def __init__( + self, + clients: _Optional[_Mapping[str, GapicMetadata.ServiceAsClient]] = ..., + api_version: _Optional[str] = ..., + ) -> None: ... + + class ServiceAsClient(_message.Message): + __slots__ = ("library_client", "rpcs") + + class RpcsEntry(_message.Message): + __slots__ = ("key", "value") + KEY_FIELD_NUMBER: _ClassVar[int] + VALUE_FIELD_NUMBER: _ClassVar[int] + key: str + value: GapicMetadata.MethodList + def __init__( + self, + key: _Optional[str] = ..., + value: _Optional[_Union[GapicMetadata.MethodList, _Mapping]] = ..., + ) -> None: ... + + LIBRARY_CLIENT_FIELD_NUMBER: _ClassVar[int] + RPCS_FIELD_NUMBER: _ClassVar[int] + library_client: str + rpcs: _containers.MessageMap[str, GapicMetadata.MethodList] + def __init__( + self, + library_client: _Optional[str] = ..., + rpcs: _Optional[_Mapping[str, GapicMetadata.MethodList]] = ..., + ) -> None: ... + + class MethodList(_message.Message): + __slots__ = ("methods",) + METHODS_FIELD_NUMBER: _ClassVar[int] + methods: _containers.RepeatedScalarFieldContainer[str] + def __init__(self, methods: _Optional[_Iterable[str]] = ...) -> None: ... + + SCHEMA_FIELD_NUMBER: _ClassVar[int] + COMMENT_FIELD_NUMBER: _ClassVar[int] + LANGUAGE_FIELD_NUMBER: _ClassVar[int] + PROTO_PACKAGE_FIELD_NUMBER: _ClassVar[int] + LIBRARY_PACKAGE_FIELD_NUMBER: _ClassVar[int] + SERVICES_FIELD_NUMBER: _ClassVar[int] + schema: str + comment: str + language: str + proto_package: str + library_package: str + services: _containers.MessageMap[str, GapicMetadata.ServiceForTransport] + def __init__( + self, + schema: _Optional[str] = ..., + comment: _Optional[str] = ..., + language: _Optional[str] = ..., + proto_package: _Optional[str] = ..., + library_package: _Optional[str] = ..., + services: _Optional[_Mapping[str, GapicMetadata.ServiceForTransport]] = ..., + ) -> None: ... diff --git a/python/user_packages/Python313/site-packages/google/logging/type/__pycache__/http_request_pb2.cpython-313.pyc b/python/user_packages/Python313/site-packages/google/logging/type/__pycache__/http_request_pb2.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..69d122090287c22956dc8b5e20e5f0fc0ee8d587 Binary files /dev/null and b/python/user_packages/Python313/site-packages/google/logging/type/__pycache__/http_request_pb2.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/google/logging/type/__pycache__/log_severity_pb2.cpython-313.pyc b/python/user_packages/Python313/site-packages/google/logging/type/__pycache__/log_severity_pb2.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7c16ab0243dfb63bac9492e7754d2fe9bb94f3e6 Binary files /dev/null and b/python/user_packages/Python313/site-packages/google/logging/type/__pycache__/log_severity_pb2.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/google/logging/type/http_request.proto b/python/user_packages/Python313/site-packages/google/logging/type/http_request.proto new file mode 100644 index 0000000000000000000000000000000000000000..b31522b69c7c292d855bb806cc80aa7b1b57362b --- /dev/null +++ b/python/user_packages/Python313/site-packages/google/logging/type/http_request.proto @@ -0,0 +1,95 @@ +// Copyright 2025 Google LLC +// +// 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. + +syntax = "proto3"; + +package google.logging.type; + +import "google/protobuf/duration.proto"; + +option csharp_namespace = "Google.Cloud.Logging.Type"; +option go_package = "google.golang.org/genproto/googleapis/logging/type;ltype"; +option java_multiple_files = true; +option java_outer_classname = "HttpRequestProto"; +option java_package = "com.google.logging.type"; +option php_namespace = "Google\\Cloud\\Logging\\Type"; +option ruby_package = "Google::Cloud::Logging::Type"; + +// A common proto for logging HTTP requests. Only contains semantics +// defined by the HTTP specification. Product-specific logging +// information MUST be defined in a separate message. +message HttpRequest { + // The request method. Examples: `"GET"`, `"HEAD"`, `"PUT"`, `"POST"`. + string request_method = 1; + + // The scheme (http, https), the host name, the path and the query + // portion of the URL that was requested. + // Example: `"http://example.com/some/info?color=red"`. + string request_url = 2; + + // The size of the HTTP request message in bytes, including the request + // headers and the request body. + int64 request_size = 3; + + // The response code indicating the status of response. + // Examples: 200, 404. + int32 status = 4; + + // The size of the HTTP response message sent back to the client, in bytes, + // including the response headers and the response body. + int64 response_size = 5; + + // The user agent sent by the client. Example: + // `"Mozilla/4.0 (compatible; MSIE 6.0; Windows 98; Q312461; .NET + // CLR 1.0.3705)"`. + string user_agent = 6; + + // The IP address (IPv4 or IPv6) of the client that issued the HTTP + // request. This field can include port information. Examples: + // `"192.168.1.1"`, `"10.0.0.1:80"`, `"FE80::0202:B3FF:FE1E:8329"`. + string remote_ip = 7; + + // The IP address (IPv4 or IPv6) of the origin server that the request was + // sent to. This field can include port information. Examples: + // `"192.168.1.1"`, `"10.0.0.1:80"`, `"FE80::0202:B3FF:FE1E:8329"`. + string server_ip = 13; + + // The referer URL of the request, as defined in + // [HTTP/1.1 Header Field + // Definitions](https://datatracker.ietf.org/doc/html/rfc2616#section-14.36). + string referer = 8; + + // The request processing latency on the server, from the time the request was + // received until the response was sent. + google.protobuf.Duration latency = 14; + + // Whether or not a cache lookup was attempted. + bool cache_lookup = 11; + + // Whether or not an entity was served from cache + // (with or without validation). + bool cache_hit = 9; + + // Whether or not the response was validated with the origin server before + // being served from cache. This field is only meaningful if `cache_hit` is + // True. + bool cache_validated_with_origin_server = 10; + + // The number of HTTP response bytes inserted into cache. Set only when a + // cache fill was attempted. + int64 cache_fill_bytes = 12; + + // Protocol used for the request. Examples: "HTTP/1.1", "HTTP/2", "websocket" + string protocol = 15; +} diff --git a/python/user_packages/Python313/site-packages/google/logging/type/http_request_pb2.py b/python/user_packages/Python313/site-packages/google/logging/type/http_request_pb2.py new file mode 100644 index 0000000000000000000000000000000000000000..521a91f1e9afff03f6097be8f2ed8c80ee2daea9 --- /dev/null +++ b/python/user_packages/Python313/site-packages/google/logging/type/http_request_pb2.py @@ -0,0 +1,50 @@ +# -*- coding: utf-8 -*- + +# Copyright 2025 Google LLC +# +# 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. + +# Generated by the protocol buffer compiler. DO NOT EDIT! +# source: google/logging/type/http_request.proto +# Protobuf Python Version: 4.25.3 +"""Generated protocol buffer code.""" + +from google.protobuf import descriptor as _descriptor +from google.protobuf import descriptor_pool as _descriptor_pool +from google.protobuf import symbol_database as _symbol_database +from google.protobuf.internal import builder as _builder + +# @@protoc_insertion_point(imports) + +_sym_db = _symbol_database.Default() + + +from google.protobuf import duration_pb2 as google_dot_protobuf_dot_duration__pb2 + +DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile( + b'\n&google/logging/type/http_request.proto\x12\x13google.logging.type\x1a\x1egoogle/protobuf/duration.proto"\xef\x02\n\x0bHttpRequest\x12\x16\n\x0erequest_method\x18\x01 \x01(\t\x12\x13\n\x0brequest_url\x18\x02 \x01(\t\x12\x14\n\x0crequest_size\x18\x03 \x01(\x03\x12\x0e\n\x06status\x18\x04 \x01(\x05\x12\x15\n\rresponse_size\x18\x05 \x01(\x03\x12\x12\n\nuser_agent\x18\x06 \x01(\t\x12\x11\n\tremote_ip\x18\x07 \x01(\t\x12\x11\n\tserver_ip\x18\r \x01(\t\x12\x0f\n\x07referer\x18\x08 \x01(\t\x12*\n\x07latency\x18\x0e \x01(\x0b\x32\x19.google.protobuf.Duration\x12\x14\n\x0c\x63\x61\x63he_lookup\x18\x0b \x01(\x08\x12\x11\n\tcache_hit\x18\t \x01(\x08\x12*\n"cache_validated_with_origin_server\x18\n \x01(\x08\x12\x18\n\x10\x63\x61\x63he_fill_bytes\x18\x0c \x01(\x03\x12\x10\n\x08protocol\x18\x0f \x01(\tB\xbe\x01\n\x17\x63om.google.logging.typeB\x10HttpRequestProtoP\x01Z8google.golang.org/genproto/googleapis/logging/type;ltype\xaa\x02\x19Google.Cloud.Logging.Type\xca\x02\x19Google\\Cloud\\Logging\\Type\xea\x02\x1cGoogle::Cloud::Logging::Typeb\x06proto3' +) + +_globals = globals() +_builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, _globals) +_builder.BuildTopDescriptorsAndMessages( + DESCRIPTOR, "google.logging.type.http_request_pb2", _globals +) +if _descriptor._USE_C_DESCRIPTORS == False: + _globals["DESCRIPTOR"]._options = None + _globals[ + "DESCRIPTOR" + ]._serialized_options = b"\n\027com.google.logging.typeB\020HttpRequestProtoP\001Z8google.golang.org/genproto/googleapis/logging/type;ltype\252\002\031Google.Cloud.Logging.Type\312\002\031Google\\Cloud\\Logging\\Type\352\002\034Google::Cloud::Logging::Type" + _globals["_HTTPREQUEST"]._serialized_start = 96 + _globals["_HTTPREQUEST"]._serialized_end = 463 +# @@protoc_insertion_point(module_scope) diff --git a/python/user_packages/Python313/site-packages/google/logging/type/http_request_pb2.pyi b/python/user_packages/Python313/site-packages/google/logging/type/http_request_pb2.pyi new file mode 100644 index 0000000000000000000000000000000000000000..b808ded1359f6c9b5722ef553a923efa59761ef5 --- /dev/null +++ b/python/user_packages/Python313/site-packages/google/logging/type/http_request_pb2.pyi @@ -0,0 +1,91 @@ +# Copyright 2025 Google LLC +# +# 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. + +from typing import ClassVar as _ClassVar +from typing import Mapping as _Mapping +from typing import Optional as _Optional +from typing import Union as _Union + +from google.protobuf import descriptor as _descriptor +from google.protobuf import duration_pb2 as _duration_pb2 +from google.protobuf import message as _message + +DESCRIPTOR: _descriptor.FileDescriptor + +class HttpRequest(_message.Message): + __slots__ = ( + "request_method", + "request_url", + "request_size", + "status", + "response_size", + "user_agent", + "remote_ip", + "server_ip", + "referer", + "latency", + "cache_lookup", + "cache_hit", + "cache_validated_with_origin_server", + "cache_fill_bytes", + "protocol", + ) + REQUEST_METHOD_FIELD_NUMBER: _ClassVar[int] + REQUEST_URL_FIELD_NUMBER: _ClassVar[int] + REQUEST_SIZE_FIELD_NUMBER: _ClassVar[int] + STATUS_FIELD_NUMBER: _ClassVar[int] + RESPONSE_SIZE_FIELD_NUMBER: _ClassVar[int] + USER_AGENT_FIELD_NUMBER: _ClassVar[int] + REMOTE_IP_FIELD_NUMBER: _ClassVar[int] + SERVER_IP_FIELD_NUMBER: _ClassVar[int] + REFERER_FIELD_NUMBER: _ClassVar[int] + LATENCY_FIELD_NUMBER: _ClassVar[int] + CACHE_LOOKUP_FIELD_NUMBER: _ClassVar[int] + CACHE_HIT_FIELD_NUMBER: _ClassVar[int] + CACHE_VALIDATED_WITH_ORIGIN_SERVER_FIELD_NUMBER: _ClassVar[int] + CACHE_FILL_BYTES_FIELD_NUMBER: _ClassVar[int] + PROTOCOL_FIELD_NUMBER: _ClassVar[int] + request_method: str + request_url: str + request_size: int + status: int + response_size: int + user_agent: str + remote_ip: str + server_ip: str + referer: str + latency: _duration_pb2.Duration + cache_lookup: bool + cache_hit: bool + cache_validated_with_origin_server: bool + cache_fill_bytes: int + protocol: str + def __init__( + self, + request_method: _Optional[str] = ..., + request_url: _Optional[str] = ..., + request_size: _Optional[int] = ..., + status: _Optional[int] = ..., + response_size: _Optional[int] = ..., + user_agent: _Optional[str] = ..., + remote_ip: _Optional[str] = ..., + server_ip: _Optional[str] = ..., + referer: _Optional[str] = ..., + latency: _Optional[_Union[_duration_pb2.Duration, _Mapping]] = ..., + cache_lookup: bool = ..., + cache_hit: bool = ..., + cache_validated_with_origin_server: bool = ..., + cache_fill_bytes: _Optional[int] = ..., + protocol: _Optional[str] = ..., + ) -> None: ... diff --git a/python/user_packages/Python313/site-packages/google/logging/type/log_severity.proto b/python/user_packages/Python313/site-packages/google/logging/type/log_severity.proto new file mode 100644 index 0000000000000000000000000000000000000000..406b8173a3aa056d8dab749db0ae731811d681c1 --- /dev/null +++ b/python/user_packages/Python313/site-packages/google/logging/type/log_severity.proto @@ -0,0 +1,71 @@ +// Copyright 2025 Google LLC +// +// 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. + +syntax = "proto3"; + +package google.logging.type; + +option csharp_namespace = "Google.Cloud.Logging.Type"; +option go_package = "google.golang.org/genproto/googleapis/logging/type;ltype"; +option java_multiple_files = true; +option java_outer_classname = "LogSeverityProto"; +option java_package = "com.google.logging.type"; +option objc_class_prefix = "GLOG"; +option php_namespace = "Google\\Cloud\\Logging\\Type"; +option ruby_package = "Google::Cloud::Logging::Type"; + +// The severity of the event described in a log entry, expressed as one of the +// standard severity levels listed below. For your reference, the levels are +// assigned the listed numeric values. The effect of using numeric values other +// than those listed is undefined. +// +// You can filter for log entries by severity. For example, the following +// filter expression will match log entries with severities `INFO`, `NOTICE`, +// and `WARNING`: +// +// severity > DEBUG AND severity <= WARNING +// +// If you are writing log entries, you should map other severity encodings to +// one of these standard levels. For example, you might map all of Java's FINE, +// FINER, and FINEST levels to `LogSeverity.DEBUG`. You can preserve the +// original severity level in the log entry payload if you wish. +enum LogSeverity { + // (0) The log entry has no assigned severity level. + DEFAULT = 0; + + // (100) Debug or trace information. + DEBUG = 100; + + // (200) Routine information, such as ongoing status or performance. + INFO = 200; + + // (300) Normal but significant events, such as start up, shut down, or + // a configuration change. + NOTICE = 300; + + // (400) Warning events might cause problems. + WARNING = 400; + + // (500) Error events are likely to cause problems. + ERROR = 500; + + // (600) Critical events cause more severe problems or outages. + CRITICAL = 600; + + // (700) A person must take an action immediately. + ALERT = 700; + + // (800) One or more systems are unusable. + EMERGENCY = 800; +} diff --git a/python/user_packages/Python313/site-packages/google/logging/type/log_severity_pb2.py b/python/user_packages/Python313/site-packages/google/logging/type/log_severity_pb2.py new file mode 100644 index 0000000000000000000000000000000000000000..67958a4084ca9206c55e8b62efb78ef4b22e33be --- /dev/null +++ b/python/user_packages/Python313/site-packages/google/logging/type/log_severity_pb2.py @@ -0,0 +1,48 @@ +# -*- coding: utf-8 -*- + +# Copyright 2025 Google LLC +# +# 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. + +# Generated by the protocol buffer compiler. DO NOT EDIT! +# source: google/logging/type/log_severity.proto +# Protobuf Python Version: 4.25.3 +"""Generated protocol buffer code.""" + +from google.protobuf import descriptor as _descriptor +from google.protobuf import descriptor_pool as _descriptor_pool +from google.protobuf import symbol_database as _symbol_database +from google.protobuf.internal import builder as _builder + +# @@protoc_insertion_point(imports) + +_sym_db = _symbol_database.Default() + + +DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile( + b"\n&google/logging/type/log_severity.proto\x12\x13google.logging.type*\x82\x01\n\x0bLogSeverity\x12\x0b\n\x07\x44\x45\x46\x41ULT\x10\x00\x12\t\n\x05\x44\x45\x42UG\x10\x64\x12\t\n\x04INFO\x10\xc8\x01\x12\x0b\n\x06NOTICE\x10\xac\x02\x12\x0c\n\x07WARNING\x10\x90\x03\x12\n\n\x05\x45RROR\x10\xf4\x03\x12\r\n\x08\x43RITICAL\x10\xd8\x04\x12\n\n\x05\x41LERT\x10\xbc\x05\x12\x0e\n\tEMERGENCY\x10\xa0\x06\x42\xc5\x01\n\x17\x63om.google.logging.typeB\x10LogSeverityProtoP\x01Z8google.golang.org/genproto/googleapis/logging/type;ltype\xa2\x02\x04GLOG\xaa\x02\x19Google.Cloud.Logging.Type\xca\x02\x19Google\\Cloud\\Logging\\Type\xea\x02\x1cGoogle::Cloud::Logging::Typeb\x06proto3" +) + +_globals = globals() +_builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, _globals) +_builder.BuildTopDescriptorsAndMessages( + DESCRIPTOR, "google.logging.type.log_severity_pb2", _globals +) +if _descriptor._USE_C_DESCRIPTORS == False: + _globals["DESCRIPTOR"]._options = None + _globals[ + "DESCRIPTOR" + ]._serialized_options = b"\n\027com.google.logging.typeB\020LogSeverityProtoP\001Z8google.golang.org/genproto/googleapis/logging/type;ltype\242\002\004GLOG\252\002\031Google.Cloud.Logging.Type\312\002\031Google\\Cloud\\Logging\\Type\352\002\034Google::Cloud::Logging::Type" + _globals["_LOGSEVERITY"]._serialized_start = 64 + _globals["_LOGSEVERITY"]._serialized_end = 194 +# @@protoc_insertion_point(module_scope) diff --git a/python/user_packages/Python313/site-packages/google/logging/type/log_severity_pb2.pyi b/python/user_packages/Python313/site-packages/google/logging/type/log_severity_pb2.pyi new file mode 100644 index 0000000000000000000000000000000000000000..eeafb8ed88df6bb1c6012341973a172fc2d90165 --- /dev/null +++ b/python/user_packages/Python313/site-packages/google/logging/type/log_severity_pb2.pyi @@ -0,0 +1,42 @@ +# Copyright 2025 Google LLC +# +# 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. + +from typing import ClassVar as _ClassVar + +from google.protobuf import descriptor as _descriptor +from google.protobuf.internal import enum_type_wrapper as _enum_type_wrapper + +DESCRIPTOR: _descriptor.FileDescriptor + +class LogSeverity(int, metaclass=_enum_type_wrapper.EnumTypeWrapper): + __slots__ = () + DEFAULT: _ClassVar[LogSeverity] + DEBUG: _ClassVar[LogSeverity] + INFO: _ClassVar[LogSeverity] + NOTICE: _ClassVar[LogSeverity] + WARNING: _ClassVar[LogSeverity] + ERROR: _ClassVar[LogSeverity] + CRITICAL: _ClassVar[LogSeverity] + ALERT: _ClassVar[LogSeverity] + EMERGENCY: _ClassVar[LogSeverity] + +DEFAULT: LogSeverity +DEBUG: LogSeverity +INFO: LogSeverity +NOTICE: LogSeverity +WARNING: LogSeverity +ERROR: LogSeverity +CRITICAL: LogSeverity +ALERT: LogSeverity +EMERGENCY: LogSeverity diff --git a/python/user_packages/Python313/site-packages/google/longrunning/__pycache__/operations_grpc.cpython-313.pyc b/python/user_packages/Python313/site-packages/google/longrunning/__pycache__/operations_grpc.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..403444de74d864426411d621b9e2dd488eebb95f Binary files /dev/null and b/python/user_packages/Python313/site-packages/google/longrunning/__pycache__/operations_grpc.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/google/longrunning/__pycache__/operations_grpc_pb2.cpython-313.pyc b/python/user_packages/Python313/site-packages/google/longrunning/__pycache__/operations_grpc_pb2.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f7f7c6ba76f3717eb965c953bab53170a2d248f0 Binary files /dev/null and b/python/user_packages/Python313/site-packages/google/longrunning/__pycache__/operations_grpc_pb2.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/google/longrunning/__pycache__/operations_pb2.cpython-313.pyc b/python/user_packages/Python313/site-packages/google/longrunning/__pycache__/operations_pb2.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..82bd89ca0501fd1f4fa4d37436743f82d34c4db4 Binary files /dev/null and b/python/user_packages/Python313/site-packages/google/longrunning/__pycache__/operations_pb2.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/google/longrunning/__pycache__/operations_pb2_grpc.cpython-313.pyc b/python/user_packages/Python313/site-packages/google/longrunning/__pycache__/operations_pb2_grpc.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..48d790b1a806c02db0ca603598261df45ec8f11d Binary files /dev/null and b/python/user_packages/Python313/site-packages/google/longrunning/__pycache__/operations_pb2_grpc.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/google/longrunning/__pycache__/operations_proto.cpython-313.pyc b/python/user_packages/Python313/site-packages/google/longrunning/__pycache__/operations_proto.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a9454dbc52236ae32bce26d6ecb4062ebb01d96a Binary files /dev/null and b/python/user_packages/Python313/site-packages/google/longrunning/__pycache__/operations_proto.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/google/longrunning/__pycache__/operations_proto_pb2.cpython-313.pyc b/python/user_packages/Python313/site-packages/google/longrunning/__pycache__/operations_proto_pb2.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..93ebe9bf0fe491612552a74c0a5f3b5bf8b6e57c Binary files /dev/null and b/python/user_packages/Python313/site-packages/google/longrunning/__pycache__/operations_proto_pb2.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/google/protobuf/__pycache__/__init__.cpython-313.pyc b/python/user_packages/Python313/site-packages/google/protobuf/__pycache__/__init__.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2bdeff59737b928e9406873a7e456627bfeda04b Binary files /dev/null and b/python/user_packages/Python313/site-packages/google/protobuf/__pycache__/__init__.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/google/protobuf/__pycache__/any.cpython-313.pyc b/python/user_packages/Python313/site-packages/google/protobuf/__pycache__/any.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..daef58412925fceb3a809204cbc1ebfc7613442b Binary files /dev/null and b/python/user_packages/Python313/site-packages/google/protobuf/__pycache__/any.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/google/protobuf/__pycache__/any_pb2.cpython-313.pyc b/python/user_packages/Python313/site-packages/google/protobuf/__pycache__/any_pb2.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8825f90827ecb27851fa8fe6dd05f35f40102362 Binary files /dev/null and b/python/user_packages/Python313/site-packages/google/protobuf/__pycache__/any_pb2.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/google/protobuf/__pycache__/api_pb2.cpython-313.pyc b/python/user_packages/Python313/site-packages/google/protobuf/__pycache__/api_pb2.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0cc78ec42d9a9a9097583ecd974408625510a198 Binary files /dev/null and b/python/user_packages/Python313/site-packages/google/protobuf/__pycache__/api_pb2.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/google/protobuf/__pycache__/descriptor.cpython-313.pyc b/python/user_packages/Python313/site-packages/google/protobuf/__pycache__/descriptor.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..18204af9249d3536bcd50f152d686c1660bf6aa5 Binary files /dev/null and b/python/user_packages/Python313/site-packages/google/protobuf/__pycache__/descriptor.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/google/protobuf/__pycache__/descriptor_database.cpython-313.pyc b/python/user_packages/Python313/site-packages/google/protobuf/__pycache__/descriptor_database.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..eaf93dfe3c415ea009a9b68ad28b9a1500cf38c9 Binary files /dev/null and b/python/user_packages/Python313/site-packages/google/protobuf/__pycache__/descriptor_database.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/google/protobuf/__pycache__/descriptor_pool.cpython-313.pyc b/python/user_packages/Python313/site-packages/google/protobuf/__pycache__/descriptor_pool.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6763c02b7b8613836434c7d9054d13d9491d3c81 Binary files /dev/null and b/python/user_packages/Python313/site-packages/google/protobuf/__pycache__/descriptor_pool.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/google/protobuf/__pycache__/duration.cpython-313.pyc b/python/user_packages/Python313/site-packages/google/protobuf/__pycache__/duration.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..212fc7ccae898c335c0db77a0392669b02a8b7ea Binary files /dev/null and b/python/user_packages/Python313/site-packages/google/protobuf/__pycache__/duration.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/google/protobuf/__pycache__/duration_pb2.cpython-313.pyc b/python/user_packages/Python313/site-packages/google/protobuf/__pycache__/duration_pb2.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..66586a5d93731d61bc156500ab3ff4ea15af366e Binary files /dev/null and b/python/user_packages/Python313/site-packages/google/protobuf/__pycache__/duration_pb2.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/google/protobuf/__pycache__/empty_pb2.cpython-313.pyc b/python/user_packages/Python313/site-packages/google/protobuf/__pycache__/empty_pb2.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8d5d3441b378ad5505c64288df9aaa7cbfa73c7f Binary files /dev/null and b/python/user_packages/Python313/site-packages/google/protobuf/__pycache__/empty_pb2.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/google/protobuf/__pycache__/field_mask_pb2.cpython-313.pyc b/python/user_packages/Python313/site-packages/google/protobuf/__pycache__/field_mask_pb2.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a3afd0d565bac041fc0b13914d65d4190b55a7f8 Binary files /dev/null and b/python/user_packages/Python313/site-packages/google/protobuf/__pycache__/field_mask_pb2.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/google/protobuf/__pycache__/json_format.cpython-313.pyc b/python/user_packages/Python313/site-packages/google/protobuf/__pycache__/json_format.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..acdcf1e7e525a8a25c0cd46830fb44c020ced5fb Binary files /dev/null and b/python/user_packages/Python313/site-packages/google/protobuf/__pycache__/json_format.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/google/protobuf/__pycache__/message.cpython-313.pyc b/python/user_packages/Python313/site-packages/google/protobuf/__pycache__/message.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4b461b94fc794659d15316692e94bb92471b255a Binary files /dev/null and b/python/user_packages/Python313/site-packages/google/protobuf/__pycache__/message.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/google/protobuf/__pycache__/message_factory.cpython-313.pyc b/python/user_packages/Python313/site-packages/google/protobuf/__pycache__/message_factory.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7657ddf93dd27fa555bdae5d55af2be9a369aebd Binary files /dev/null and b/python/user_packages/Python313/site-packages/google/protobuf/__pycache__/message_factory.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/google/protobuf/__pycache__/proto.cpython-313.pyc b/python/user_packages/Python313/site-packages/google/protobuf/__pycache__/proto.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c7f4498b0cb0aae9cee459b73d6ce6327dac0632 Binary files /dev/null and b/python/user_packages/Python313/site-packages/google/protobuf/__pycache__/proto.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/google/protobuf/__pycache__/proto_builder.cpython-313.pyc b/python/user_packages/Python313/site-packages/google/protobuf/__pycache__/proto_builder.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..aa531b519e9e6b4cf84f40d9df6d41fc95eb2745 Binary files /dev/null and b/python/user_packages/Python313/site-packages/google/protobuf/__pycache__/proto_builder.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/google/protobuf/__pycache__/proto_json.cpython-313.pyc b/python/user_packages/Python313/site-packages/google/protobuf/__pycache__/proto_json.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ccd459bcd1a3be08956f49749ce2faf5e6b935e7 Binary files /dev/null and b/python/user_packages/Python313/site-packages/google/protobuf/__pycache__/proto_json.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/google/protobuf/__pycache__/proto_text.cpython-313.pyc b/python/user_packages/Python313/site-packages/google/protobuf/__pycache__/proto_text.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..41364e37c5d6ee4b23a65dea11ce72c8f4fc4e93 Binary files /dev/null and b/python/user_packages/Python313/site-packages/google/protobuf/__pycache__/proto_text.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/google/protobuf/__pycache__/reflection.cpython-313.pyc b/python/user_packages/Python313/site-packages/google/protobuf/__pycache__/reflection.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..cbc1f5bfedcdaef2134ae844fca87be2fe30dd1c Binary files /dev/null and b/python/user_packages/Python313/site-packages/google/protobuf/__pycache__/reflection.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/google/protobuf/__pycache__/runtime_version.cpython-313.pyc b/python/user_packages/Python313/site-packages/google/protobuf/__pycache__/runtime_version.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3729d4e365a044406648e1c286bdbd4017f3a604 Binary files /dev/null and b/python/user_packages/Python313/site-packages/google/protobuf/__pycache__/runtime_version.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/google/protobuf/__pycache__/service_reflection.cpython-313.pyc b/python/user_packages/Python313/site-packages/google/protobuf/__pycache__/service_reflection.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..62026df3db80fee279557289ddb92aeacb9732d7 Binary files /dev/null and b/python/user_packages/Python313/site-packages/google/protobuf/__pycache__/service_reflection.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/google/protobuf/__pycache__/source_context_pb2.cpython-313.pyc b/python/user_packages/Python313/site-packages/google/protobuf/__pycache__/source_context_pb2.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1ec473cbdf7fbcbba3cd821f49abd9f3f2801a46 Binary files /dev/null and b/python/user_packages/Python313/site-packages/google/protobuf/__pycache__/source_context_pb2.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/google/protobuf/__pycache__/struct_pb2.cpython-313.pyc b/python/user_packages/Python313/site-packages/google/protobuf/__pycache__/struct_pb2.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3c5594daf61dfebf41550920855964544d03bea9 Binary files /dev/null and b/python/user_packages/Python313/site-packages/google/protobuf/__pycache__/struct_pb2.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/google/protobuf/__pycache__/symbol_database.cpython-313.pyc b/python/user_packages/Python313/site-packages/google/protobuf/__pycache__/symbol_database.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..adfb2d48467e862db79c2f567d006f0b00baaf5e Binary files /dev/null and b/python/user_packages/Python313/site-packages/google/protobuf/__pycache__/symbol_database.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/google/protobuf/__pycache__/text_encoding.cpython-313.pyc b/python/user_packages/Python313/site-packages/google/protobuf/__pycache__/text_encoding.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..837a1a0332dc22bf02ff78638ea460aaf226adc8 Binary files /dev/null and b/python/user_packages/Python313/site-packages/google/protobuf/__pycache__/text_encoding.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/google/protobuf/__pycache__/text_format.cpython-313.pyc b/python/user_packages/Python313/site-packages/google/protobuf/__pycache__/text_format.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..858ab351b702b9e64d92081f7f949a73e1f44cbc Binary files /dev/null and b/python/user_packages/Python313/site-packages/google/protobuf/__pycache__/text_format.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/google/protobuf/__pycache__/timestamp.cpython-313.pyc b/python/user_packages/Python313/site-packages/google/protobuf/__pycache__/timestamp.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8226d03696a2cdfaff43256d27f8ced95ac684c8 Binary files /dev/null and b/python/user_packages/Python313/site-packages/google/protobuf/__pycache__/timestamp.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/google/protobuf/__pycache__/timestamp_pb2.cpython-313.pyc b/python/user_packages/Python313/site-packages/google/protobuf/__pycache__/timestamp_pb2.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7dee0a5bd8cf30e9aa340cc4dcadaf652082b319 Binary files /dev/null and b/python/user_packages/Python313/site-packages/google/protobuf/__pycache__/timestamp_pb2.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/google/protobuf/__pycache__/type_pb2.cpython-313.pyc b/python/user_packages/Python313/site-packages/google/protobuf/__pycache__/type_pb2.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..026d48d82a01b44c467ad63b4d36f0e2387b0f8e Binary files /dev/null and b/python/user_packages/Python313/site-packages/google/protobuf/__pycache__/type_pb2.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/google/protobuf/__pycache__/unknown_fields.cpython-313.pyc b/python/user_packages/Python313/site-packages/google/protobuf/__pycache__/unknown_fields.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..149c1ecab2d0db098d6d980b55f9997b0067714f Binary files /dev/null and b/python/user_packages/Python313/site-packages/google/protobuf/__pycache__/unknown_fields.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/google/protobuf/__pycache__/wrappers_pb2.cpython-313.pyc b/python/user_packages/Python313/site-packages/google/protobuf/__pycache__/wrappers_pb2.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..87f2c681f031d1b1846554dd8669dbd19a02c68c Binary files /dev/null and b/python/user_packages/Python313/site-packages/google/protobuf/__pycache__/wrappers_pb2.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/google/protobuf/compiler/__init__.py b/python/user_packages/Python313/site-packages/google/protobuf/compiler/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/python/user_packages/Python313/site-packages/google/protobuf/compiler/__pycache__/__init__.cpython-313.pyc b/python/user_packages/Python313/site-packages/google/protobuf/compiler/__pycache__/__init__.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8de2b5000252f37100af3834f1c5023407a5137d Binary files /dev/null and b/python/user_packages/Python313/site-packages/google/protobuf/compiler/__pycache__/__init__.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/google/protobuf/compiler/__pycache__/plugin_pb2.cpython-313.pyc b/python/user_packages/Python313/site-packages/google/protobuf/compiler/__pycache__/plugin_pb2.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e0897814527c5767eee4ac778eeabfaa408de96e Binary files /dev/null and b/python/user_packages/Python313/site-packages/google/protobuf/compiler/__pycache__/plugin_pb2.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/google/protobuf/compiler/plugin_pb2.py b/python/user_packages/Python313/site-packages/google/protobuf/compiler/plugin_pb2.py new file mode 100644 index 0000000000000000000000000000000000000000..8d882dedd5e97e10020d3cee64240420398b61bd --- /dev/null +++ b/python/user_packages/Python313/site-packages/google/protobuf/compiler/plugin_pb2.py @@ -0,0 +1,46 @@ +# -*- coding: utf-8 -*- +# Generated by the protocol buffer compiler. DO NOT EDIT! +# NO CHECKED-IN PROTOBUF GENCODE +# source: google/protobuf/compiler/plugin.proto +# Protobuf Python Version: 6.33.6 +"""Generated protocol buffer code.""" +from google.protobuf import descriptor as _descriptor +from google.protobuf import descriptor_pool as _descriptor_pool +from google.protobuf import runtime_version as _runtime_version +from google.protobuf import symbol_database as _symbol_database +from google.protobuf.internal import builder as _builder +_runtime_version.ValidateProtobufRuntimeVersion( + _runtime_version.Domain.PUBLIC, + 6, + 33, + 6, + '', + 'google/protobuf/compiler/plugin.proto' +) +# @@protoc_insertion_point(imports) + +_sym_db = _symbol_database.Default() + + +from google.protobuf import descriptor_pb2 as google_dot_protobuf_dot_descriptor__pb2 + + +DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile(b'\n%google/protobuf/compiler/plugin.proto\x12\x18google.protobuf.compiler\x1a google/protobuf/descriptor.proto\"c\n\x07Version\x12\x14\n\x05major\x18\x01 \x01(\x05R\x05major\x12\x14\n\x05minor\x18\x02 \x01(\x05R\x05minor\x12\x14\n\x05patch\x18\x03 \x01(\x05R\x05patch\x12\x16\n\x06suffix\x18\x04 \x01(\tR\x06suffix\"\xcf\x02\n\x14\x43odeGeneratorRequest\x12(\n\x10\x66ile_to_generate\x18\x01 \x03(\tR\x0e\x66ileToGenerate\x12\x1c\n\tparameter\x18\x02 \x01(\tR\tparameter\x12\x43\n\nproto_file\x18\x0f \x03(\x0b\x32$.google.protobuf.FileDescriptorProtoR\tprotoFile\x12\\\n\x17source_file_descriptors\x18\x11 \x03(\x0b\x32$.google.protobuf.FileDescriptorProtoR\x15sourceFileDescriptors\x12L\n\x10\x63ompiler_version\x18\x03 \x01(\x0b\x32!.google.protobuf.compiler.VersionR\x0f\x63ompilerVersion\"\x85\x04\n\x15\x43odeGeneratorResponse\x12\x14\n\x05\x65rror\x18\x01 \x01(\tR\x05\x65rror\x12-\n\x12supported_features\x18\x02 \x01(\x04R\x11supportedFeatures\x12\'\n\x0fminimum_edition\x18\x03 \x01(\x05R\x0eminimumEdition\x12\'\n\x0fmaximum_edition\x18\x04 \x01(\x05R\x0emaximumEdition\x12H\n\x04\x66ile\x18\x0f \x03(\x0b\x32\x34.google.protobuf.compiler.CodeGeneratorResponse.FileR\x04\x66ile\x1a\xb1\x01\n\x04\x46ile\x12\x12\n\x04name\x18\x01 \x01(\tR\x04name\x12\'\n\x0finsertion_point\x18\x02 \x01(\tR\x0einsertionPoint\x12\x18\n\x07\x63ontent\x18\x0f \x01(\tR\x07\x63ontent\x12R\n\x13generated_code_info\x18\x10 \x01(\x0b\x32\".google.protobuf.GeneratedCodeInfoR\x11generatedCodeInfo\"W\n\x07\x46\x65\x61ture\x12\x10\n\x0c\x46\x45\x41TURE_NONE\x10\x00\x12\x1b\n\x17\x46\x45\x41TURE_PROTO3_OPTIONAL\x10\x01\x12\x1d\n\x19\x46\x45\x41TURE_SUPPORTS_EDITIONS\x10\x02\x42r\n\x1c\x63om.google.protobuf.compilerB\x0cPluginProtosZ)google.golang.org/protobuf/types/pluginpb\xaa\x02\x18Google.Protobuf.Compiler') + +_globals = globals() +_builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, _globals) +_builder.BuildTopDescriptorsAndMessages(DESCRIPTOR, 'google.protobuf.compiler.plugin_pb2', _globals) +if not _descriptor._USE_C_DESCRIPTORS: + _globals['DESCRIPTOR']._loaded_options = None + _globals['DESCRIPTOR']._serialized_options = b'\n\034com.google.protobuf.compilerB\014PluginProtosZ)google.golang.org/protobuf/types/pluginpb\252\002\030Google.Protobuf.Compiler' + _globals['_VERSION']._serialized_start=101 + _globals['_VERSION']._serialized_end=200 + _globals['_CODEGENERATORREQUEST']._serialized_start=203 + _globals['_CODEGENERATORREQUEST']._serialized_end=538 + _globals['_CODEGENERATORRESPONSE']._serialized_start=541 + _globals['_CODEGENERATORRESPONSE']._serialized_end=1058 + _globals['_CODEGENERATORRESPONSE_FILE']._serialized_start=792 + _globals['_CODEGENERATORRESPONSE_FILE']._serialized_end=969 + _globals['_CODEGENERATORRESPONSE_FEATURE']._serialized_start=971 + _globals['_CODEGENERATORRESPONSE_FEATURE']._serialized_end=1058 +# @@protoc_insertion_point(module_scope) diff --git a/python/user_packages/Python313/site-packages/google/protobuf/internal/__init__.py b/python/user_packages/Python313/site-packages/google/protobuf/internal/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e676e288161e00ae5c266d080ca5018336849a7d --- /dev/null +++ b/python/user_packages/Python313/site-packages/google/protobuf/internal/__init__.py @@ -0,0 +1,7 @@ +# Protocol Buffers - Google's data interchange format +# Copyright 2008 Google Inc. All rights reserved. +# +# Use of this source code is governed by a BSD-style +# license that can be found in the LICENSE file or at +# https://developers.google.com/open-source/licenses/bsd + diff --git a/python/user_packages/Python313/site-packages/google/protobuf/internal/__pycache__/__init__.cpython-313.pyc b/python/user_packages/Python313/site-packages/google/protobuf/internal/__pycache__/__init__.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..730ea9ee5670bf13a899f3c0c28d5c9a14f70e03 Binary files /dev/null and b/python/user_packages/Python313/site-packages/google/protobuf/internal/__pycache__/__init__.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/google/protobuf/internal/__pycache__/api_implementation.cpython-313.pyc b/python/user_packages/Python313/site-packages/google/protobuf/internal/__pycache__/api_implementation.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..09a383c038f7e8edff6719dcc7782a71c47842e5 Binary files /dev/null and b/python/user_packages/Python313/site-packages/google/protobuf/internal/__pycache__/api_implementation.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/google/protobuf/internal/__pycache__/builder.cpython-313.pyc b/python/user_packages/Python313/site-packages/google/protobuf/internal/__pycache__/builder.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..fcde9c989fda827968e1a145f67e062337ea80ce Binary files /dev/null and b/python/user_packages/Python313/site-packages/google/protobuf/internal/__pycache__/builder.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/google/protobuf/internal/__pycache__/containers.cpython-313.pyc b/python/user_packages/Python313/site-packages/google/protobuf/internal/__pycache__/containers.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0d4cedc785d073e43bf3772586c15250e6cdb601 Binary files /dev/null and b/python/user_packages/Python313/site-packages/google/protobuf/internal/__pycache__/containers.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/google/protobuf/internal/__pycache__/decoder.cpython-313.pyc b/python/user_packages/Python313/site-packages/google/protobuf/internal/__pycache__/decoder.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4e74125b7ece275e080db235c27d65099524fa98 Binary files /dev/null and b/python/user_packages/Python313/site-packages/google/protobuf/internal/__pycache__/decoder.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/google/protobuf/internal/__pycache__/encoder.cpython-313.pyc b/python/user_packages/Python313/site-packages/google/protobuf/internal/__pycache__/encoder.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2185abf9ca6a6d4f8933a3ce223910ef9bf3ff54 Binary files /dev/null and b/python/user_packages/Python313/site-packages/google/protobuf/internal/__pycache__/encoder.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/google/protobuf/internal/__pycache__/enum_type_wrapper.cpython-313.pyc b/python/user_packages/Python313/site-packages/google/protobuf/internal/__pycache__/enum_type_wrapper.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..faac7afe854911e50bb2ca5287a01d2f47edad66 Binary files /dev/null and b/python/user_packages/Python313/site-packages/google/protobuf/internal/__pycache__/enum_type_wrapper.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/google/protobuf/internal/__pycache__/extension_dict.cpython-313.pyc b/python/user_packages/Python313/site-packages/google/protobuf/internal/__pycache__/extension_dict.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8d401284128318897037e323c81b30eb43013b18 Binary files /dev/null and b/python/user_packages/Python313/site-packages/google/protobuf/internal/__pycache__/extension_dict.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/google/protobuf/internal/__pycache__/field_mask.cpython-313.pyc b/python/user_packages/Python313/site-packages/google/protobuf/internal/__pycache__/field_mask.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5d205d55f8cccad6633895467838bcc3d1ca99c0 Binary files /dev/null and b/python/user_packages/Python313/site-packages/google/protobuf/internal/__pycache__/field_mask.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/google/protobuf/internal/__pycache__/message_listener.cpython-313.pyc b/python/user_packages/Python313/site-packages/google/protobuf/internal/__pycache__/message_listener.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4bfe421dadc3443bfc9efa61a03e1113b42afa11 Binary files /dev/null and b/python/user_packages/Python313/site-packages/google/protobuf/internal/__pycache__/message_listener.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/google/protobuf/internal/__pycache__/python_edition_defaults.cpython-313.pyc b/python/user_packages/Python313/site-packages/google/protobuf/internal/__pycache__/python_edition_defaults.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..dfca9bbae79667250151dd3745305c1a0bc986f0 Binary files /dev/null and b/python/user_packages/Python313/site-packages/google/protobuf/internal/__pycache__/python_edition_defaults.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/google/protobuf/internal/__pycache__/python_message.cpython-313.pyc b/python/user_packages/Python313/site-packages/google/protobuf/internal/__pycache__/python_message.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5499c4fd275d4709823c67a9e0b304666a08254a Binary files /dev/null and b/python/user_packages/Python313/site-packages/google/protobuf/internal/__pycache__/python_message.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/google/protobuf/internal/__pycache__/testing_refleaks.cpython-313.pyc b/python/user_packages/Python313/site-packages/google/protobuf/internal/__pycache__/testing_refleaks.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9e8bc7f4af69bb6fcf54a16e5e275483f12f8416 Binary files /dev/null and b/python/user_packages/Python313/site-packages/google/protobuf/internal/__pycache__/testing_refleaks.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/google/protobuf/internal/__pycache__/type_checkers.cpython-313.pyc b/python/user_packages/Python313/site-packages/google/protobuf/internal/__pycache__/type_checkers.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..aba0a2825be1732922cc4f920f75d03ce0d621de Binary files /dev/null and b/python/user_packages/Python313/site-packages/google/protobuf/internal/__pycache__/type_checkers.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/google/protobuf/internal/__pycache__/well_known_types.cpython-313.pyc b/python/user_packages/Python313/site-packages/google/protobuf/internal/__pycache__/well_known_types.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..84346b8185b2e6124bbd721a9fb0ea5af088976a Binary files /dev/null and b/python/user_packages/Python313/site-packages/google/protobuf/internal/__pycache__/well_known_types.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/google/protobuf/internal/__pycache__/wire_format.cpython-313.pyc b/python/user_packages/Python313/site-packages/google/protobuf/internal/__pycache__/wire_format.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7658192878a5f3b6122096583be0ec8127d35b49 Binary files /dev/null and b/python/user_packages/Python313/site-packages/google/protobuf/internal/__pycache__/wire_format.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/google/protobuf/internal/api_implementation.py b/python/user_packages/Python313/site-packages/google/protobuf/internal/api_implementation.py new file mode 100644 index 0000000000000000000000000000000000000000..f4346bce945fc943d39394012e1817c49a57ed47 --- /dev/null +++ b/python/user_packages/Python313/site-packages/google/protobuf/internal/api_implementation.py @@ -0,0 +1,136 @@ +# Protocol Buffers - Google's data interchange format +# Copyright 2008 Google Inc. All rights reserved. +# +# Use of this source code is governed by a BSD-style +# license that can be found in the LICENSE file or at +# https://developers.google.com/open-source/licenses/bsd + +"""Determine which implementation of the protobuf API is used in this process. +""" + +import importlib +import os +import sys +import warnings + +_GOOGLE3_PYTHON_UPB_DEFAULT = True + + +def _ApiVersionToImplementationType(api_version): + if api_version == 2: + return 'cpp' + if api_version == 1: + raise ValueError('api_version=1 is no longer supported.') + if api_version == 0: + return 'python' + return None + + +_implementation_type = None +try: + # pylint: disable=g-import-not-at-top + from google.protobuf.internal import _api_implementation + # The compile-time constants in the _api_implementation module can be used to + # switch to a certain implementation of the Python API at build time. + _implementation_type = _ApiVersionToImplementationType( + _api_implementation.api_version) +except ImportError: + pass # Unspecified by compiler flags. + + +def _CanImport(mod_name): + try: + mod = importlib.import_module(mod_name) + # Work around a known issue in the classic bootstrap .par import hook. + if not mod: + raise ImportError(mod_name + ' import succeeded but was None') + return True + except ImportError: + return False + + +if _implementation_type is None: + if _CanImport('google._upb._message'): + _implementation_type = 'upb' + elif _CanImport('google.protobuf.pyext._message'): + _implementation_type = 'cpp' + else: + _implementation_type = 'python' + + +# This environment variable can be used to switch to a certain implementation +# of the Python API, overriding the compile-time constants in the +# _api_implementation module. Right now only 'python', 'cpp' and 'upb' are +# valid values. Any other value will raise error. +_implementation_type = os.getenv('PROTOCOL_BUFFERS_PYTHON_IMPLEMENTATION', + _implementation_type) + +if _implementation_type not in ('python', 'cpp', 'upb'): + raise ValueError('PROTOCOL_BUFFERS_PYTHON_IMPLEMENTATION {0} is not ' + 'supported. Please set to \'python\', \'cpp\' or ' + '\'upb\'.'.format(_implementation_type)) + +if 'PyPy' in sys.version and _implementation_type == 'cpp': + warnings.warn('PyPy does not work yet with cpp protocol buffers. ' + 'Falling back to the python implementation.') + _implementation_type = 'python' + +_c_module = None + +if _implementation_type == 'cpp': + try: + # pylint: disable=g-import-not-at-top + from google.protobuf.pyext import _message + sys.modules['google3.net.proto2.python.internal.cpp._message'] = _message + _c_module = _message + del _message + except ImportError: + # TODO: fail back to python + warnings.warn( + 'Selected implementation cpp is not available.') + pass + +if _implementation_type == 'upb': + try: + # pylint: disable=g-import-not-at-top + from google._upb import _message + _c_module = _message + del _message + except ImportError: + warnings.warn('Selected implementation upb is not available. ' + 'Falling back to the python implementation.') + _implementation_type = 'python' + pass + +# Detect if serialization should be deterministic by default +try: + # The presence of this module in a build allows the proto implementation to + # be upgraded merely via build deps. + # + # NOTE: Merely importing this automatically enables deterministic proto + # serialization for C++ code, but we still need to export it as a boolean so + # that we can do the same for `_implementation_type == 'python'`. + # + # NOTE2: It is possible for C++ code to enable deterministic serialization by + # default _without_ affecting Python code, if the C++ implementation is not in + # use by this module. That is intended behavior, so we don't actually expose + # this boolean outside of this module. + # + # pylint: disable=g-import-not-at-top,unused-import + from google.protobuf import enable_deterministic_proto_serialization + _python_deterministic_proto_serialization = True +except ImportError: + _python_deterministic_proto_serialization = False + + +# Usage of this function is discouraged. Clients shouldn't care which +# implementation of the API is in use. Note that there is no guarantee +# that differences between APIs will be maintained. +# Please don't use this function if possible. +def Type(): + return _implementation_type + + +# For internal use only +def IsPythonDefaultSerializationDeterministic(): + return _python_deterministic_proto_serialization diff --git a/python/user_packages/Python313/site-packages/google/protobuf/internal/builder.py b/python/user_packages/Python313/site-packages/google/protobuf/internal/builder.py new file mode 100644 index 0000000000000000000000000000000000000000..9859e490e6415c3d6222f131631062156d2a4890 --- /dev/null +++ b/python/user_packages/Python313/site-packages/google/protobuf/internal/builder.py @@ -0,0 +1,118 @@ +# Protocol Buffers - Google's data interchange format +# Copyright 2008 Google Inc. All rights reserved. +# +# Use of this source code is governed by a BSD-style +# license that can be found in the LICENSE file or at +# https://developers.google.com/open-source/licenses/bsd + +"""Builds descriptors, message classes and services for generated _pb2.py. + +This file is only called in python generated _pb2.py files. It builds +descriptors, message classes and services that users can directly use +in generated code. +""" + +__author__ = 'jieluo@google.com (Jie Luo)' + +from google.protobuf.internal import enum_type_wrapper +from google.protobuf.internal import python_message +from google.protobuf import message as _message +from google.protobuf import reflection as _reflection +from google.protobuf import symbol_database as _symbol_database + +_sym_db = _symbol_database.Default() + + +def BuildMessageAndEnumDescriptors(file_des, module): + """Builds message and enum descriptors. + + Args: + file_des: FileDescriptor of the .proto file + module: Generated _pb2 module + """ + + def BuildNestedDescriptors(msg_des, prefix): + for (name, nested_msg) in msg_des.nested_types_by_name.items(): + module_name = prefix + name.upper() + module[module_name] = nested_msg + BuildNestedDescriptors(nested_msg, module_name + '_') + for enum_des in msg_des.enum_types: + module[prefix + enum_des.name.upper()] = enum_des + + for (name, msg_des) in file_des.message_types_by_name.items(): + module_name = '_' + name.upper() + module[module_name] = msg_des + BuildNestedDescriptors(msg_des, module_name + '_') + + +def BuildTopDescriptorsAndMessages(file_des, module_name, module): + """Builds top level descriptors and message classes. + + Args: + file_des: FileDescriptor of the .proto file + module_name: str, the name of generated _pb2 module + module: Generated _pb2 module + """ + + def BuildMessage(msg_des, prefix): + create_dict = {} + for (name, nested_msg) in msg_des.nested_types_by_name.items(): + create_dict[name] = BuildMessage(nested_msg, prefix + msg_des.name + '.') + create_dict['DESCRIPTOR'] = msg_des + create_dict['__module__'] = module_name + create_dict['__qualname__'] = prefix + msg_des.name + message_class = _reflection.GeneratedProtocolMessageType( + msg_des.name, (_message.Message,), create_dict) + _sym_db.RegisterMessage(message_class) + return message_class + + # top level enums + for (name, enum_des) in file_des.enum_types_by_name.items(): + module['_' + name.upper()] = enum_des + module[name] = enum_type_wrapper.EnumTypeWrapper(enum_des) + for enum_value in enum_des.values: + module[enum_value.name] = enum_value.number + + # top level extensions + for (name, extension_des) in file_des.extensions_by_name.items(): + module[name.upper() + '_FIELD_NUMBER'] = extension_des.number + module[name] = extension_des + + # services + for (name, service) in file_des.services_by_name.items(): + module['_' + name.upper()] = service + + # Build messages. + for (name, msg_des) in file_des.message_types_by_name.items(): + module[name] = BuildMessage(msg_des, '') + + +def AddHelpersToExtensions(file_des): + """no-op to keep old generated code work with new runtime. + + Args: + file_des: FileDescriptor of the .proto file + """ + # TODO: Remove this on-op + return + + +def BuildServices(file_des, module_name, module): + """Builds services classes and services stub class. + + Args: + file_des: FileDescriptor of the .proto file + module_name: str, the name of generated _pb2 module + module: Generated _pb2 module + """ + # pylint: disable=g-import-not-at-top + from google.protobuf import service_reflection + # pylint: enable=g-import-not-at-top + for (name, service) in file_des.services_by_name.items(): + module[name] = service_reflection.GeneratedServiceType( + name, (), + dict(DESCRIPTOR=service, __module__=module_name)) + stub_name = name + '_Stub' + module[stub_name] = service_reflection.GeneratedServiceStubType( + stub_name, (module[name],), + dict(DESCRIPTOR=service, __module__=module_name)) diff --git a/python/user_packages/Python313/site-packages/google/protobuf/internal/containers.py b/python/user_packages/Python313/site-packages/google/protobuf/internal/containers.py new file mode 100644 index 0000000000000000000000000000000000000000..7298bc5c7a33dad27b1e933fc04c1435ae4b6986 --- /dev/null +++ b/python/user_packages/Python313/site-packages/google/protobuf/internal/containers.py @@ -0,0 +1,690 @@ +# Protocol Buffers - Google's data interchange format +# Copyright 2008 Google Inc. All rights reserved. +# +# Use of this source code is governed by a BSD-style +# license that can be found in the LICENSE file or at +# https://developers.google.com/open-source/licenses/bsd + +"""Contains container classes to represent different protocol buffer types. + +This file defines container classes which represent categories of protocol +buffer field types which need extra maintenance. Currently these categories +are: + +- Repeated scalar fields - These are all repeated fields which aren't + composite (e.g. they are of simple types like int32, string, etc). +- Repeated composite fields - Repeated fields which are composite. This + includes groups and nested messages. +""" + +import collections.abc +import copy +import pickle +from typing import ( + Any, + Iterable, + Iterator, + List, + MutableMapping, + MutableSequence, + NoReturn, + Optional, + Sequence, + TypeVar, + Union, + overload, +) + + +_T = TypeVar('_T') +_K = TypeVar('_K') +_V = TypeVar('_V') + + +class BaseContainer(Sequence[_T]): + """Base container class.""" + + # Minimizes memory usage and disallows assignment to other attributes. + __slots__ = ['_message_listener', '_values'] + + def __init__(self, message_listener: Any) -> None: + """ + Args: + message_listener: A MessageListener implementation. + The RepeatedScalarFieldContainer will call this object's + Modified() method when it is modified. + """ + self._message_listener = message_listener + self._values = [] + + @overload + def __getitem__(self, key: int) -> _T: + ... + + @overload + def __getitem__(self, key: slice) -> List[_T]: + ... + + def __getitem__(self, key): + """Retrieves item by the specified key.""" + return self._values[key] + + def __len__(self) -> int: + """Returns the number of elements in the container.""" + return len(self._values) + + def __ne__(self, other: Any) -> bool: + """Checks if another instance isn't equal to this one.""" + # The concrete classes should define __eq__. + return not self == other + + __hash__ = None + + def __repr__(self) -> str: + return repr(self._values) + + def sort(self, *args, **kwargs) -> None: + # Continue to support the old sort_function keyword argument. + # This is expected to be a rare occurrence, so use LBYL to avoid + # the overhead of actually catching KeyError. + if 'sort_function' in kwargs: + kwargs['cmp'] = kwargs.pop('sort_function') + self._values.sort(*args, **kwargs) + + def reverse(self) -> None: + self._values.reverse() + + +# TODO: Remove this. BaseContainer does *not* conform to +# MutableSequence, only its subclasses do. +collections.abc.MutableSequence.register(BaseContainer) + + +class RepeatedScalarFieldContainer(BaseContainer[_T], MutableSequence[_T]): + """Simple, type-checked, list-like container for holding repeated scalars.""" + + # Disallows assignment to other attributes. + __slots__ = ['_type_checker'] + + def __init__( + self, + message_listener: Any, + type_checker: Any, + ) -> None: + """Args: + + message_listener: A MessageListener implementation. The + RepeatedScalarFieldContainer will call this object's Modified() method + when it is modified. + type_checker: A type_checkers.ValueChecker instance to run on elements + inserted into this container. + """ + super().__init__(message_listener) + self._type_checker = type_checker + + def append(self, value: _T) -> None: + """Appends an item to the list. Similar to list.append().""" + self._values.append(self._type_checker.CheckValue(value)) + if not self._message_listener.dirty: + self._message_listener.Modified() + + def insert(self, key: int, value: _T) -> None: + """Inserts the item at the specified position. Similar to list.insert().""" + self._values.insert(key, self._type_checker.CheckValue(value)) + if not self._message_listener.dirty: + self._message_listener.Modified() + + def extend(self, elem_seq: Iterable[_T]) -> None: + """Extends by appending the given iterable. Similar to list.extend().""" + elem_seq_iter = iter(elem_seq) + new_values = [self._type_checker.CheckValue(elem) for elem in elem_seq_iter] + if new_values: + self._values.extend(new_values) + self._message_listener.Modified() + + def MergeFrom( + self, + other: Union['RepeatedScalarFieldContainer[_T]', Iterable[_T]], + ) -> None: + """Appends the contents of another repeated field of the same type to this + one. We do not check the types of the individual fields. + """ + self._values.extend(other) + self._message_listener.Modified() + + def remove(self, elem: _T): + """Removes an item from the list. Similar to list.remove().""" + self._values.remove(elem) + self._message_listener.Modified() + + def pop(self, key: Optional[int] = -1) -> _T: + """Removes and returns an item at a given index. Similar to list.pop().""" + value = self._values[key] + self.__delitem__(key) + return value + + @overload + def __setitem__(self, key: int, value: _T) -> None: + ... + + @overload + def __setitem__(self, key: slice, value: Iterable[_T]) -> None: + ... + + def __setitem__(self, key, value) -> None: + """Sets the item on the specified position.""" + if isinstance(key, slice): + if key.step is not None: + raise ValueError('Extended slices not supported') + self._values[key] = map(self._type_checker.CheckValue, value) + self._message_listener.Modified() + else: + self._values[key] = self._type_checker.CheckValue(value) + self._message_listener.Modified() + + def __delitem__(self, key: Union[int, slice]) -> None: + """Deletes the item at the specified position.""" + del self._values[key] + self._message_listener.Modified() + + def __eq__(self, other: Any) -> bool: + """Compares the current instance with another one.""" + if self is other: + return True + # Special case for the same type which should be common and fast. + if isinstance(other, self.__class__): + return other._values == self._values + # We are presumably comparing against some other sequence type. + return other == self._values + + def __deepcopy__( + self, + unused_memo: Any = None, + ) -> 'RepeatedScalarFieldContainer[_T]': + clone = RepeatedScalarFieldContainer( + copy.deepcopy(self._message_listener), self._type_checker) + clone.MergeFrom(self) + return clone + + def __reduce__(self, **kwargs) -> NoReturn: + raise pickle.PickleError( + "Can't pickle repeated scalar fields, convert to list first") + + +# TODO: Constrain T to be a subtype of Message. +class RepeatedCompositeFieldContainer(BaseContainer[_T], MutableSequence[_T]): + """Simple, list-like container for holding repeated composite fields.""" + + # Disallows assignment to other attributes. + __slots__ = ['_message_descriptor'] + + def __init__(self, message_listener: Any, message_descriptor: Any) -> None: + """ + Note that we pass in a descriptor instead of the generated directly, + since at the time we construct a _RepeatedCompositeFieldContainer we + haven't yet necessarily initialized the type that will be contained in the + container. + + Args: + message_listener: A MessageListener implementation. + The RepeatedCompositeFieldContainer will call this object's + Modified() method when it is modified. + message_descriptor: A Descriptor instance describing the protocol type + that should be present in this container. We'll use the + _concrete_class field of this descriptor when the client calls add(). + """ + super().__init__(message_listener) + self._message_descriptor = message_descriptor + + def add(self, **kwargs: Any) -> _T: + """Adds a new element at the end of the list and returns it. Keyword + arguments may be used to initialize the element. + """ + new_element = self._message_descriptor._concrete_class(**kwargs) + new_element._SetListener(self._message_listener) + self._values.append(new_element) + if not self._message_listener.dirty: + self._message_listener.Modified() + return new_element + + def append(self, value: _T) -> None: + """Appends one element by copying the message.""" + new_element = self._message_descriptor._concrete_class() + new_element._SetListener(self._message_listener) + new_element.CopyFrom(value) + self._values.append(new_element) + if not self._message_listener.dirty: + self._message_listener.Modified() + + def insert(self, key: int, value: _T) -> None: + """Inserts the item at the specified position by copying.""" + new_element = self._message_descriptor._concrete_class() + new_element._SetListener(self._message_listener) + new_element.CopyFrom(value) + self._values.insert(key, new_element) + if not self._message_listener.dirty: + self._message_listener.Modified() + + def extend(self, elem_seq: Iterable[_T]) -> None: + """Extends by appending the given sequence of elements of the same type + + as this one, copying each individual message. + """ + message_class = self._message_descriptor._concrete_class + listener = self._message_listener + values = self._values + for message in elem_seq: + new_element = message_class() + new_element._SetListener(listener) + new_element.MergeFrom(message) + values.append(new_element) + listener.Modified() + + def MergeFrom( + self, + other: Union['RepeatedCompositeFieldContainer[_T]', Iterable[_T]], + ) -> None: + """Appends the contents of another repeated field of the same type to this + one, copying each individual message. + """ + self.extend(other) + + def remove(self, elem: _T) -> None: + """Removes an item from the list. Similar to list.remove().""" + self._values.remove(elem) + self._message_listener.Modified() + + def pop(self, key: Optional[int] = -1) -> _T: + """Removes and returns an item at a given index. Similar to list.pop().""" + value = self._values[key] + self.__delitem__(key) + return value + + @overload + def __setitem__(self, key: int, value: _T) -> None: + ... + + @overload + def __setitem__(self, key: slice, value: Iterable[_T]) -> None: + ... + + def __setitem__(self, key, value): + # This method is implemented to make RepeatedCompositeFieldContainer + # structurally compatible with typing.MutableSequence. It is + # otherwise unsupported and will always raise an error. + raise TypeError( + f'{self.__class__.__name__} object does not support item assignment') + + def __delitem__(self, key: Union[int, slice]) -> None: + """Deletes the item at the specified position.""" + del self._values[key] + self._message_listener.Modified() + + def __eq__(self, other: Any) -> bool: + """Compares the current instance with another one.""" + if self is other: + return True + if not isinstance(other, self.__class__): + raise TypeError('Can only compare repeated composite fields against ' + 'other repeated composite fields.') + return self._values == other._values + + +class ScalarMap(MutableMapping[_K, _V]): + """Simple, type-checked, dict-like container for holding repeated scalars.""" + + # Disallows assignment to other attributes. + __slots__ = ['_key_checker', '_value_checker', '_values', '_message_listener', + '_entry_descriptor'] + + def __init__( + self, + message_listener: Any, + key_checker: Any, + value_checker: Any, + entry_descriptor: Any, + ) -> None: + """ + Args: + message_listener: A MessageListener implementation. + The ScalarMap will call this object's Modified() method when it + is modified. + key_checker: A type_checkers.ValueChecker instance to run on keys + inserted into this container. + value_checker: A type_checkers.ValueChecker instance to run on values + inserted into this container. + entry_descriptor: The MessageDescriptor of a map entry: key and value. + """ + self._message_listener = message_listener + self._key_checker = key_checker + self._value_checker = value_checker + self._entry_descriptor = entry_descriptor + self._values = {} + + def __getitem__(self, key: _K) -> _V: + try: + return self._values[key] + except KeyError: + key = self._key_checker.CheckValue(key) + val = self._value_checker.DefaultValue() + self._values[key] = val + return val + + def __contains__(self, item: _K) -> bool: + # We check the key's type to match the strong-typing flavor of the API. + # Also this makes it easier to match the behavior of the C++ implementation. + self._key_checker.CheckValue(item) + return item in self._values + + @overload + def get(self, key: _K) -> Optional[_V]: + ... + + @overload + def get(self, key: _K, default: _T) -> Union[_V, _T]: + ... + + # We need to override this explicitly, because our defaultdict-like behavior + # will make the default implementation (from our base class) always insert + # the key. + def get(self, key, default=None): + if key in self: + return self[key] + else: + return default + + def __setitem__(self, key: _K, value: _V) -> _T: + checked_key = self._key_checker.CheckValue(key) + checked_value = self._value_checker.CheckValue(value) + self._values[checked_key] = checked_value + self._message_listener.Modified() + + def __delitem__(self, key: _K) -> None: + del self._values[key] + self._message_listener.Modified() + + def __len__(self) -> int: + return len(self._values) + + def __iter__(self) -> Iterator[_K]: + return iter(self._values) + + def __repr__(self) -> str: + return repr(self._values) + + def setdefault(self, key: _K, value: Optional[_V] = None) -> _V: + if value == None: + raise ValueError('The value for scalar map setdefault must be set.') + if key not in self._values: + self.__setitem__(key, value) + return self[key] + + def MergeFrom(self, other: 'ScalarMap[_K, _V]') -> None: + self._values.update(other._values) + self._message_listener.Modified() + + def InvalidateIterators(self) -> None: + # It appears that the only way to reliably invalidate iterators to + # self._values is to ensure that its size changes. + original = self._values + self._values = original.copy() + original[None] = None + + # This is defined in the abstract base, but we can do it much more cheaply. + def clear(self) -> None: + self._values.clear() + self._message_listener.Modified() + + def GetEntryClass(self) -> Any: + return self._entry_descriptor._concrete_class + + +class MessageMap(MutableMapping[_K, _V]): + """Simple, type-checked, dict-like container for with submessage values.""" + + # Disallows assignment to other attributes. + __slots__ = ['_key_checker', '_values', '_message_listener', + '_message_descriptor', '_entry_descriptor'] + + def __init__( + self, + message_listener: Any, + message_descriptor: Any, + key_checker: Any, + entry_descriptor: Any, + ) -> None: + """ + Args: + message_listener: A MessageListener implementation. + The ScalarMap will call this object's Modified() method when it + is modified. + key_checker: A type_checkers.ValueChecker instance to run on keys + inserted into this container. + value_checker: A type_checkers.ValueChecker instance to run on values + inserted into this container. + entry_descriptor: The MessageDescriptor of a map entry: key and value. + """ + self._message_listener = message_listener + self._message_descriptor = message_descriptor + self._key_checker = key_checker + self._entry_descriptor = entry_descriptor + self._values = {} + + def __getitem__(self, key: _K) -> _V: + key = self._key_checker.CheckValue(key) + try: + return self._values[key] + except KeyError: + new_element = self._message_descriptor._concrete_class() + new_element._SetListener(self._message_listener) + self._values[key] = new_element + self._message_listener.Modified() + return new_element + + def get_or_create(self, key: _K) -> _V: + """get_or_create() is an alias for getitem (ie. map[key]). + + Args: + key: The key to get or create in the map. + + This is useful in cases where you want to be explicit that the call is + mutating the map. This can avoid lint errors for statements like this + that otherwise would appear to be pointless statements: + + msg.my_map[key] + """ + return self[key] + + @overload + def get(self, key: _K) -> Optional[_V]: + ... + + @overload + def get(self, key: _K, default: _T) -> Union[_V, _T]: + ... + + # We need to override this explicitly, because our defaultdict-like behavior + # will make the default implementation (from our base class) always insert + # the key. + def get(self, key, default=None): + if key in self: + return self[key] + else: + return default + + def __contains__(self, item: _K) -> bool: + item = self._key_checker.CheckValue(item) + return item in self._values + + def __setitem__(self, key: _K, value: _V) -> NoReturn: + raise ValueError('May not set values directly, call my_map[key].foo = 5') + + def __delitem__(self, key: _K) -> None: + key = self._key_checker.CheckValue(key) + del self._values[key] + self._message_listener.Modified() + + def __len__(self) -> int: + return len(self._values) + + def __iter__(self) -> Iterator[_K]: + return iter(self._values) + + def __repr__(self) -> str: + return repr(self._values) + + def setdefault(self, key: _K, value: Optional[_V] = None) -> _V: + raise NotImplementedError( + 'Set message map value directly is not supported, call' + ' my_map[key].foo = 5' + ) + + def MergeFrom(self, other: 'MessageMap[_K, _V]') -> None: + # pylint: disable=protected-access + for key in other._values: + # According to documentation: "When parsing from the wire or when merging, + # if there are duplicate map keys the last key seen is used". + if key in self: + del self[key] + self[key].CopyFrom(other[key]) + # self._message_listener.Modified() not required here, because + # mutations to submessages already propagate. + + def InvalidateIterators(self) -> None: + # It appears that the only way to reliably invalidate iterators to + # self._values is to ensure that its size changes. + original = self._values + self._values = original.copy() + original[None] = None + + # This is defined in the abstract base, but we can do it much more cheaply. + def clear(self) -> None: + self._values.clear() + self._message_listener.Modified() + + def GetEntryClass(self) -> Any: + return self._entry_descriptor._concrete_class + + +class _UnknownField: + """A parsed unknown field.""" + + # Disallows assignment to other attributes. + __slots__ = ['_field_number', '_wire_type', '_data'] + + def __init__(self, field_number, wire_type, data): + self._field_number = field_number + self._wire_type = wire_type + self._data = data + return + + def __lt__(self, other): + # pylint: disable=protected-access + return self._field_number < other._field_number + + def __eq__(self, other): + if self is other: + return True + # pylint: disable=protected-access + return (self._field_number == other._field_number and + self._wire_type == other._wire_type and + self._data == other._data) + + +class UnknownFieldRef: # pylint: disable=missing-class-docstring + + def __init__(self, parent, index): + self._parent = parent + self._index = index + + def _check_valid(self): + if not self._parent: + raise ValueError('UnknownField does not exist. ' + 'The parent message might be cleared.') + if self._index >= len(self._parent): + raise ValueError('UnknownField does not exist. ' + 'The parent message might be cleared.') + + @property + def field_number(self): + self._check_valid() + # pylint: disable=protected-access + return self._parent._internal_get(self._index)._field_number + + @property + def wire_type(self): + self._check_valid() + # pylint: disable=protected-access + return self._parent._internal_get(self._index)._wire_type + + @property + def data(self): + self._check_valid() + # pylint: disable=protected-access + return self._parent._internal_get(self._index)._data + + +class UnknownFieldSet: + """UnknownField container""" + + # Disallows assignment to other attributes. + __slots__ = ['_values'] + + def __init__(self): + self._values = [] + + def __getitem__(self, index): + if self._values is None: + raise ValueError('UnknownFields does not exist. ' + 'The parent message might be cleared.') + size = len(self._values) + if index < 0: + index += size + if index < 0 or index >= size: + raise IndexError('index %d out of range'.index) + + return UnknownFieldRef(self, index) + + def _internal_get(self, index): + return self._values[index] + + def __len__(self): + if self._values is None: + raise ValueError('UnknownFields does not exist. ' + 'The parent message might be cleared.') + return len(self._values) + + def _add(self, field_number, wire_type, data): + unknown_field = _UnknownField(field_number, wire_type, data) + self._values.append(unknown_field) + return unknown_field + + def __iter__(self): + for i in range(len(self)): + yield UnknownFieldRef(self, i) + + def _extend(self, other): + if other is None: + return + # pylint: disable=protected-access + self._values.extend(other._values) + + def __eq__(self, other): + if self is other: + return True + # Sort unknown fields because their order shouldn't + # affect equality test. + values = list(self._values) + if other is None: + return not values + values.sort() + # pylint: disable=protected-access + other_values = sorted(other._values) + return values == other_values + + def _clear(self): + for value in self._values: + # pylint: disable=protected-access + if isinstance(value._data, UnknownFieldSet): + value._data._clear() # pylint: disable=protected-access + self._values = None diff --git a/python/user_packages/Python313/site-packages/google/protobuf/internal/decoder.py b/python/user_packages/Python313/site-packages/google/protobuf/internal/decoder.py new file mode 100644 index 0000000000000000000000000000000000000000..dbf848bf31083d0c4dfbc32fed58e701049f6ede --- /dev/null +++ b/python/user_packages/Python313/site-packages/google/protobuf/internal/decoder.py @@ -0,0 +1,1066 @@ +# Protocol Buffers - Google's data interchange format +# Copyright 2008 Google Inc. All rights reserved. +# +# Use of this source code is governed by a BSD-style +# license that can be found in the LICENSE file or at +# https://developers.google.com/open-source/licenses/bsd + +"""Code for decoding protocol buffer primitives. + +This code is very similar to encoder.py -- read the docs for that module first. + +A "decoder" is a function with the signature: + Decode(buffer, pos, end, message, field_dict) +The arguments are: + buffer: The string containing the encoded message. + pos: The current position in the string. + end: The position in the string where the current message ends. May be + less than len(buffer) if we're reading a sub-message. + message: The message object into which we're parsing. + field_dict: message._fields (avoids a hashtable lookup). +The decoder reads the field and stores it into field_dict, returning the new +buffer position. A decoder for a repeated field may proactively decode all of +the elements of that field, if they appear consecutively. + +Note that decoders may throw any of the following: + IndexError: Indicates a truncated message. + struct.error: Unpacking of a fixed-width field failed. + message.DecodeError: Other errors. + +Decoders are expected to raise an exception if they are called with pos > end. +This allows callers to be lax about bounds checking: it's fineto read past +"end" as long as you are sure that someone else will notice and throw an +exception later on. + +Something up the call stack is expected to catch IndexError and struct.error +and convert them to message.DecodeError. + +Decoders are constructed using decoder constructors with the signature: + MakeDecoder(field_number, is_repeated, is_packed, key, new_default) +The arguments are: + field_number: The field number of the field we want to decode. + is_repeated: Is the field a repeated field? (bool) + is_packed: Is the field a packed field? (bool) + key: The key to use when looking up the field within field_dict. + (This is actually the FieldDescriptor but nothing in this + file should depend on that.) + new_default: A function which takes a message object as a parameter and + returns a new instance of the default value for this field. + (This is called for repeated fields and sub-messages, when an + instance does not already exist.) + +As with encoders, we define a decoder constructor for every type of field. +Then, for every field of every message class we construct an actual decoder. +That decoder goes into a dict indexed by tag, so when we decode a message +we repeatedly read a tag, look up the corresponding decoder, and invoke it. +""" + +__author__ = 'kenton@google.com (Kenton Varda)' + +import math +import numbers +import struct + +from google.protobuf import message +from google.protobuf.internal import containers +from google.protobuf.internal import encoder +from google.protobuf.internal import wire_format + + +# This is not for optimization, but rather to avoid conflicts with local +# variables named "message". +_DecodeError = message.DecodeError + + +def IsDefaultScalarValue(value): + """Returns whether or not a scalar value is the default value of its type. + + Specifically, this should be used to determine presence of implicit-presence + fields, where we disallow custom defaults. + + Args: + value: A scalar value to check. + + Returns: + True if the value is equivalent to a default value, False otherwise. + """ + if isinstance(value, numbers.Number) and math.copysign(1.0, value) < 0: + # Special case for negative zero, where "truthiness" fails to give the right + # answer. + return False + + # Normally, we can just use Python's boolean conversion. + return not value + + +def _VarintDecoder(mask, result_type): + """Return an encoder for a basic varint value (does not include tag). + + Decoded values will be bitwise-anded with the given mask before being + returned, e.g. to limit them to 32 bits. The returned decoder does not + take the usual "end" parameter -- the caller is expected to do bounds checking + after the fact (often the caller can defer such checking until later). The + decoder returns a (value, new_pos) pair. + """ + + def DecodeVarint(buffer, pos: int=None): + result = 0 + shift = 0 + while 1: + if pos is None: + # Read from BytesIO + try: + b = buffer.read(1)[0] + except IndexError as e: + if shift == 0: + # End of BytesIO. + return None + else: + raise ValueError('Fail to read varint %s' % str(e)) + else: + b = buffer[pos] + pos += 1 + result |= ((b & 0x7f) << shift) + if not (b & 0x80): + result &= mask + result = result_type(result) + return result if pos is None else (result, pos) + shift += 7 + if shift >= 64: + raise _DecodeError('Too many bytes when decoding varint.') + + return DecodeVarint + + +def _SignedVarintDecoder(bits, result_type): + """Like _VarintDecoder() but decodes signed values.""" + + signbit = 1 << (bits - 1) + mask = (1 << bits) - 1 + + def DecodeVarint(buffer, pos): + result = 0 + shift = 0 + while 1: + b = buffer[pos] + result |= ((b & 0x7f) << shift) + pos += 1 + if not (b & 0x80): + result &= mask + result = (result ^ signbit) - signbit + result = result_type(result) + return (result, pos) + shift += 7 + if shift >= 64: + raise _DecodeError('Too many bytes when decoding varint.') + return DecodeVarint + +# All 32-bit and 64-bit values are represented as int. +_DecodeVarint = _VarintDecoder((1 << 64) - 1, int) +_DecodeSignedVarint = _SignedVarintDecoder(64, int) + +# Use these versions for values which must be limited to 32 bits. +_DecodeVarint32 = _VarintDecoder((1 << 32) - 1, int) +_DecodeSignedVarint32 = _SignedVarintDecoder(32, int) + + +def ReadTag(buffer, pos): + """Read a tag from the memoryview, and return a (tag_bytes, new_pos) tuple. + + We return the raw bytes of the tag rather than decoding them. The raw + bytes can then be used to look up the proper decoder. This effectively allows + us to trade some work that would be done in pure-python (decoding a varint) + for work that is done in C (searching for a byte string in a hash table). + In a low-level language it would be much cheaper to decode the varint and + use that, but not in Python. + + Args: + buffer: memoryview object of the encoded bytes + pos: int of the current position to start from + + Returns: + Tuple[bytes, int] of the tag data and new position. + """ + start = pos + while buffer[pos] & 0x80: + pos += 1 + pos += 1 + + tag_bytes = buffer[start:pos].tobytes() + return tag_bytes, pos + + +def DecodeTag(tag_bytes): + """Decode a tag from the bytes. + + Args: + tag_bytes: the bytes of the tag + + Returns: + Tuple[int, int] of the tag field number and wire type. + """ + (tag, _) = _DecodeVarint(tag_bytes, 0) + return wire_format.UnpackTag(tag) + + +# -------------------------------------------------------------------- + + +def _SimpleDecoder(wire_type, decode_value): + """Return a constructor for a decoder for fields of a particular type. + + Args: + wire_type: The field's wire type. + decode_value: A function which decodes an individual value, e.g. + _DecodeVarint() + """ + + def SpecificDecoder(field_number, is_repeated, is_packed, key, new_default, + clear_if_default=False): + if is_packed: + local_DecodeVarint = _DecodeVarint + def DecodePackedField( + buffer, pos, end, message, field_dict, current_depth=0 + ): + del current_depth # unused + value = field_dict.get(key) + if value is None: + value = field_dict.setdefault(key, new_default(message)) + (endpoint, pos) = local_DecodeVarint(buffer, pos) + endpoint += pos + if endpoint > end: + raise _DecodeError('Truncated message.') + while pos < endpoint: + (element, pos) = decode_value(buffer, pos) + value.append(element) + if pos > endpoint: + del value[-1] # Discard corrupt value. + raise _DecodeError('Packed element was truncated.') + return pos + + return DecodePackedField + elif is_repeated: + tag_bytes = encoder.TagBytes(field_number, wire_type) + tag_len = len(tag_bytes) + def DecodeRepeatedField( + buffer, pos, end, message, field_dict, current_depth=0 + ): + del current_depth # unused + value = field_dict.get(key) + if value is None: + value = field_dict.setdefault(key, new_default(message)) + while 1: + (element, new_pos) = decode_value(buffer, pos) + value.append(element) + # Predict that the next tag is another copy of the same repeated + # field. + pos = new_pos + tag_len + if buffer[new_pos:pos] != tag_bytes or new_pos >= end: + # Prediction failed. Return. + if new_pos > end: + raise _DecodeError('Truncated message.') + return new_pos + + return DecodeRepeatedField + else: + + def DecodeField(buffer, pos, end, message, field_dict, current_depth=0): + del current_depth # unused + (new_value, pos) = decode_value(buffer, pos) + if pos > end: + raise _DecodeError('Truncated message.') + if clear_if_default and IsDefaultScalarValue(new_value): + field_dict.pop(key, None) + else: + field_dict[key] = new_value + return pos + + return DecodeField + + return SpecificDecoder + + +def _ModifiedDecoder(wire_type, decode_value, modify_value): + """Like SimpleDecoder but additionally invokes modify_value on every value + before storing it. Usually modify_value is ZigZagDecode. + """ + + # Reusing _SimpleDecoder is slightly slower than copying a bunch of code, but + # not enough to make a significant difference. + + def InnerDecode(buffer, pos): + (result, new_pos) = decode_value(buffer, pos) + return (modify_value(result), new_pos) + return _SimpleDecoder(wire_type, InnerDecode) + + +def _StructPackDecoder(wire_type, format): + """Return a constructor for a decoder for a fixed-width field. + + Args: + wire_type: The field's wire type. + format: The format string to pass to struct.unpack(). + """ + + value_size = struct.calcsize(format) + local_unpack = struct.unpack + + # Reusing _SimpleDecoder is slightly slower than copying a bunch of code, but + # not enough to make a significant difference. + + # Note that we expect someone up-stack to catch struct.error and convert + # it to _DecodeError -- this way we don't have to set up exception- + # handling blocks every time we parse one value. + + def InnerDecode(buffer, pos): + new_pos = pos + value_size + result = local_unpack(format, buffer[pos:new_pos])[0] + return (result, new_pos) + return _SimpleDecoder(wire_type, InnerDecode) + + +def _FloatDecoder(): + """Returns a decoder for a float field. + + This code works around a bug in struct.unpack for non-finite 32-bit + floating-point values. + """ + + local_unpack = struct.unpack + + def InnerDecode(buffer, pos): + """Decode serialized float to a float and new position. + + Args: + buffer: memoryview of the serialized bytes + pos: int, position in the memory view to start at. + + Returns: + Tuple[float, int] of the deserialized float value and new position + in the serialized data. + """ + # We expect a 32-bit value in little-endian byte order. Bit 1 is the sign + # bit, bits 2-9 represent the exponent, and bits 10-32 are the significand. + new_pos = pos + 4 + float_bytes = buffer[pos:new_pos].tobytes() + + # If this value has all its exponent bits set, then it's non-finite. + # In Python 2.4, struct.unpack will convert it to a finite 64-bit value. + # To avoid that, we parse it specially. + if (float_bytes[3:4] in b'\x7F\xFF' and float_bytes[2:3] >= b'\x80'): + # If at least one significand bit is set... + if float_bytes[0:3] != b'\x00\x00\x80': + return (math.nan, new_pos) + # If sign bit is set... + if float_bytes[3:4] == b'\xFF': + return (-math.inf, new_pos) + return (math.inf, new_pos) + + # Note that we expect someone up-stack to catch struct.error and convert + # it to _DecodeError -- this way we don't have to set up exception- + # handling blocks every time we parse one value. + result = local_unpack('= b'\xF0') + and (double_bytes[0:7] != b'\x00\x00\x00\x00\x00\x00\xF0')): + return (math.nan, new_pos) + + # Note that we expect someone up-stack to catch struct.error and convert + # it to _DecodeError -- this way we don't have to set up exception- + # handling blocks every time we parse one value. + result = local_unpack(' end: + raise _DecodeError('Truncated message.') + while pos < endpoint: + value_start_pos = pos + (element, pos) = _DecodeSignedVarint32(buffer, pos) + # pylint: disable=protected-access + if element in enum_type.values_by_number: + value.append(element) + else: + if not message._unknown_fields: + message._unknown_fields = [] + tag_bytes = encoder.TagBytes(field_number, + wire_format.WIRETYPE_VARINT) + + message._unknown_fields.append( + (tag_bytes, buffer[value_start_pos:pos].tobytes())) + # pylint: enable=protected-access + if pos > endpoint: + if element in enum_type.values_by_number: + del value[-1] # Discard corrupt value. + else: + del message._unknown_fields[-1] + # pylint: enable=protected-access + raise _DecodeError('Packed element was truncated.') + return pos + + return DecodePackedField + elif is_repeated: + tag_bytes = encoder.TagBytes(field_number, wire_format.WIRETYPE_VARINT) + tag_len = len(tag_bytes) + def DecodeRepeatedField( + buffer, pos, end, message, field_dict, current_depth=0 + ): + """Decode serialized repeated enum to its value and a new position. + + Args: + buffer: memoryview of the serialized bytes. + pos: int, position in the memory view to start at. + end: int, end position of serialized data + message: Message object to store unknown fields in + field_dict: Map[Descriptor, Any] to store decoded values in. + + Returns: + int, new position in serialized data. + """ + del current_depth # unused + value = field_dict.get(key) + if value is None: + value = field_dict.setdefault(key, new_default(message)) + while 1: + (element, new_pos) = _DecodeSignedVarint32(buffer, pos) + # pylint: disable=protected-access + if element in enum_type.values_by_number: + value.append(element) + else: + if not message._unknown_fields: + message._unknown_fields = [] + message._unknown_fields.append( + (tag_bytes, buffer[pos:new_pos].tobytes())) + # pylint: enable=protected-access + # Predict that the next tag is another copy of the same repeated + # field. + pos = new_pos + tag_len + if buffer[new_pos:pos] != tag_bytes or new_pos >= end: + # Prediction failed. Return. + if new_pos > end: + raise _DecodeError('Truncated message.') + return new_pos + + return DecodeRepeatedField + else: + + def DecodeField(buffer, pos, end, message, field_dict, current_depth=0): + """Decode serialized repeated enum to its value and a new position. + + Args: + buffer: memoryview of the serialized bytes. + pos: int, position in the memory view to start at. + end: int, end position of serialized data + message: Message object to store unknown fields in + field_dict: Map[Descriptor, Any] to store decoded values in. + + Returns: + int, new position in serialized data. + """ + del current_depth # unused + value_start_pos = pos + (enum_value, pos) = _DecodeSignedVarint32(buffer, pos) + if pos > end: + raise _DecodeError('Truncated message.') + if clear_if_default and IsDefaultScalarValue(enum_value): + field_dict.pop(key, None) + return pos + # pylint: disable=protected-access + if enum_value in enum_type.values_by_number: + field_dict[key] = enum_value + else: + if not message._unknown_fields: + message._unknown_fields = [] + tag_bytes = encoder.TagBytes(field_number, + wire_format.WIRETYPE_VARINT) + message._unknown_fields.append( + (tag_bytes, buffer[value_start_pos:pos].tobytes())) + # pylint: enable=protected-access + return pos + + return DecodeField + + +# -------------------------------------------------------------------- + + +Int32Decoder = _SimpleDecoder( + wire_format.WIRETYPE_VARINT, _DecodeSignedVarint32) + +Int64Decoder = _SimpleDecoder( + wire_format.WIRETYPE_VARINT, _DecodeSignedVarint) + +UInt32Decoder = _SimpleDecoder(wire_format.WIRETYPE_VARINT, _DecodeVarint32) +UInt64Decoder = _SimpleDecoder(wire_format.WIRETYPE_VARINT, _DecodeVarint) + +SInt32Decoder = _ModifiedDecoder( + wire_format.WIRETYPE_VARINT, _DecodeVarint32, wire_format.ZigZagDecode) +SInt64Decoder = _ModifiedDecoder( + wire_format.WIRETYPE_VARINT, _DecodeVarint, wire_format.ZigZagDecode) + +# Note that Python conveniently guarantees that when using the '<' prefix on +# formats, they will also have the same size across all platforms (as opposed +# to without the prefix, where their sizes depend on the C compiler's basic +# type sizes). +Fixed32Decoder = _StructPackDecoder(wire_format.WIRETYPE_FIXED32, ' end: + raise _DecodeError('Truncated string.') + value.append(_ConvertToUnicode(buffer[pos:new_pos])) + # Predict that the next tag is another copy of the same repeated field. + pos = new_pos + tag_len + if buffer[new_pos:pos] != tag_bytes or new_pos == end: + # Prediction failed. Return. + return new_pos + + return DecodeRepeatedField + else: + + def DecodeField(buffer, pos, end, message, field_dict, current_depth=0): + del current_depth # unused + (size, pos) = local_DecodeVarint(buffer, pos) + new_pos = pos + size + if new_pos > end: + raise _DecodeError('Truncated string.') + if clear_if_default and IsDefaultScalarValue(size): + field_dict.pop(key, None) + else: + field_dict[key] = _ConvertToUnicode(buffer[pos:new_pos]) + return new_pos + + return DecodeField + + +def BytesDecoder(field_number, is_repeated, is_packed, key, new_default, + clear_if_default=False): + """Returns a decoder for a bytes field.""" + + local_DecodeVarint = _DecodeVarint + + assert not is_packed + if is_repeated: + tag_bytes = encoder.TagBytes(field_number, + wire_format.WIRETYPE_LENGTH_DELIMITED) + tag_len = len(tag_bytes) + def DecodeRepeatedField( + buffer, pos, end, message, field_dict, current_depth=0 + ): + del current_depth # unused + value = field_dict.get(key) + if value is None: + value = field_dict.setdefault(key, new_default(message)) + while 1: + (size, pos) = local_DecodeVarint(buffer, pos) + new_pos = pos + size + if new_pos > end: + raise _DecodeError('Truncated string.') + value.append(buffer[pos:new_pos].tobytes()) + # Predict that the next tag is another copy of the same repeated field. + pos = new_pos + tag_len + if buffer[new_pos:pos] != tag_bytes or new_pos == end: + # Prediction failed. Return. + return new_pos + + return DecodeRepeatedField + else: + + def DecodeField(buffer, pos, end, message, field_dict, current_depth=0): + del current_depth # unused + (size, pos) = local_DecodeVarint(buffer, pos) + new_pos = pos + size + if new_pos > end: + raise _DecodeError('Truncated string.') + if clear_if_default and IsDefaultScalarValue(size): + field_dict.pop(key, None) + else: + field_dict[key] = buffer[pos:new_pos].tobytes() + return new_pos + + return DecodeField + + +def GroupDecoder(field_number, is_repeated, is_packed, key, new_default): + """Returns a decoder for a group field.""" + + end_tag_bytes = encoder.TagBytes(field_number, + wire_format.WIRETYPE_END_GROUP) + end_tag_len = len(end_tag_bytes) + + assert not is_packed + if is_repeated: + tag_bytes = encoder.TagBytes(field_number, + wire_format.WIRETYPE_START_GROUP) + tag_len = len(tag_bytes) + def DecodeRepeatedField( + buffer, pos, end, message, field_dict, current_depth=0 + ): + value = field_dict.get(key) + if value is None: + value = field_dict.setdefault(key, new_default(message)) + while 1: + value = field_dict.get(key) + if value is None: + value = field_dict.setdefault(key, new_default(message)) + # Read sub-message. + current_depth += 1 + if current_depth > _recursion_limit: + raise _DecodeError( + 'Error parsing message: too many levels of nesting.' + ) + pos = value.add()._InternalParse(buffer, pos, end, current_depth) + current_depth -= 1 + # Read end tag. + new_pos = pos+end_tag_len + if buffer[pos:new_pos] != end_tag_bytes or new_pos > end: + raise _DecodeError('Missing group end tag.') + # Predict that the next tag is another copy of the same repeated field. + pos = new_pos + tag_len + if buffer[new_pos:pos] != tag_bytes or new_pos == end: + # Prediction failed. Return. + return new_pos + + return DecodeRepeatedField + else: + + def DecodeField(buffer, pos, end, message, field_dict, current_depth=0): + value = field_dict.get(key) + if value is None: + value = field_dict.setdefault(key, new_default(message)) + # Read sub-message. + current_depth += 1 + if current_depth > _recursion_limit: + raise _DecodeError('Error parsing message: too many levels of nesting.') + pos = value._InternalParse(buffer, pos, end, current_depth) + current_depth -= 1 + # Read end tag. + new_pos = pos+end_tag_len + if buffer[pos:new_pos] != end_tag_bytes or new_pos > end: + raise _DecodeError('Missing group end tag.') + return new_pos + + return DecodeField + + +def MessageDecoder(field_number, is_repeated, is_packed, key, new_default): + """Returns a decoder for a message field.""" + + local_DecodeVarint = _DecodeVarint + + assert not is_packed + if is_repeated: + tag_bytes = encoder.TagBytes(field_number, + wire_format.WIRETYPE_LENGTH_DELIMITED) + tag_len = len(tag_bytes) + def DecodeRepeatedField( + buffer, pos, end, message, field_dict, current_depth=0 + ): + value = field_dict.get(key) + if value is None: + value = field_dict.setdefault(key, new_default(message)) + while 1: + # Read length. + (size, pos) = local_DecodeVarint(buffer, pos) + new_pos = pos + size + if new_pos > end: + raise _DecodeError('Truncated message.') + # Read sub-message. + current_depth += 1 + if current_depth > _recursion_limit: + raise _DecodeError( + 'Error parsing message: too many levels of nesting.' + ) + if ( + value.add()._InternalParse(buffer, pos, new_pos, current_depth) + != new_pos + ): + # The only reason _InternalParse would return early is if it + # encountered an end-group tag. + raise _DecodeError('Unexpected end-group tag.') + current_depth -= 1 + # Predict that the next tag is another copy of the same repeated field. + pos = new_pos + tag_len + if buffer[new_pos:pos] != tag_bytes or new_pos == end: + # Prediction failed. Return. + return new_pos + + return DecodeRepeatedField + else: + + def DecodeField(buffer, pos, end, message, field_dict, current_depth=0): + value = field_dict.get(key) + if value is None: + value = field_dict.setdefault(key, new_default(message)) + # Read length. + (size, pos) = local_DecodeVarint(buffer, pos) + new_pos = pos + size + if new_pos > end: + raise _DecodeError('Truncated message.') + # Read sub-message. + current_depth += 1 + if current_depth > _recursion_limit: + raise _DecodeError('Error parsing message: too many levels of nesting.') + if value._InternalParse(buffer, pos, new_pos, current_depth) != new_pos: + # The only reason _InternalParse would return early is if it encountered + # an end-group tag. + raise _DecodeError('Unexpected end-group tag.') + current_depth -= 1 + return new_pos + + return DecodeField + + +# -------------------------------------------------------------------- + +MESSAGE_SET_ITEM_TAG = encoder.TagBytes(1, wire_format.WIRETYPE_START_GROUP) + +def MessageSetItemDecoder(descriptor): + """Returns a decoder for a MessageSet item. + + The parameter is the message Descriptor. + + The message set message looks like this: + message MessageSet { + repeated group Item = 1 { + required int32 type_id = 2; + required string message = 3; + } + } + """ + + type_id_tag_bytes = encoder.TagBytes(2, wire_format.WIRETYPE_VARINT) + message_tag_bytes = encoder.TagBytes(3, wire_format.WIRETYPE_LENGTH_DELIMITED) + item_end_tag_bytes = encoder.TagBytes(1, wire_format.WIRETYPE_END_GROUP) + + local_ReadTag = ReadTag + local_DecodeVarint = _DecodeVarint + + def DecodeItem(buffer, pos, end, message, field_dict): + """Decode serialized message set to its value and new position. + + Args: + buffer: memoryview of the serialized bytes. + pos: int, position in the memory view to start at. + end: int, end position of serialized data + message: Message object to store unknown fields in + field_dict: Map[Descriptor, Any] to store decoded values in. + + Returns: + int, new position in serialized data. + """ + message_set_item_start = pos + type_id = -1 + message_start = -1 + message_end = -1 + + # Technically, type_id and message can appear in any order, so we need + # a little loop here. + while 1: + (tag_bytes, pos) = local_ReadTag(buffer, pos) + if tag_bytes == type_id_tag_bytes: + (type_id, pos) = local_DecodeVarint(buffer, pos) + elif tag_bytes == message_tag_bytes: + (size, message_start) = local_DecodeVarint(buffer, pos) + pos = message_end = message_start + size + elif tag_bytes == item_end_tag_bytes: + break + else: + field_number, wire_type = DecodeTag(tag_bytes) + _, pos = _DecodeUnknownField(buffer, pos, end, field_number, wire_type) + if pos == -1: + raise _DecodeError('Unexpected end-group tag.') + + if pos > end: + raise _DecodeError('Truncated message.') + + if type_id == -1: + raise _DecodeError('MessageSet item missing type_id.') + if message_start == -1: + raise _DecodeError('MessageSet item missing message.') + + extension = message.Extensions._FindExtensionByNumber(type_id) + # pylint: disable=protected-access + if extension is not None: + value = field_dict.get(extension) + if value is None: + message_type = extension.message_type + if not hasattr(message_type, '_concrete_class'): + message_factory.GetMessageClass(message_type) + value = field_dict.setdefault( + extension, message_type._concrete_class()) + if value._InternalParse(buffer, message_start,message_end) != message_end: + # The only reason _InternalParse would return early is if it encountered + # an end-group tag. + raise _DecodeError('Unexpected end-group tag.') + else: + if not message._unknown_fields: + message._unknown_fields = [] + message._unknown_fields.append( + (MESSAGE_SET_ITEM_TAG, buffer[message_set_item_start:pos].tobytes())) + # pylint: enable=protected-access + + return pos + + return DecodeItem + + +def UnknownMessageSetItemDecoder(): + """Returns a decoder for a Unknown MessageSet item.""" + + type_id_tag_bytes = encoder.TagBytes(2, wire_format.WIRETYPE_VARINT) + message_tag_bytes = encoder.TagBytes(3, wire_format.WIRETYPE_LENGTH_DELIMITED) + item_end_tag_bytes = encoder.TagBytes(1, wire_format.WIRETYPE_END_GROUP) + + def DecodeUnknownItem(buffer): + pos = 0 + end = len(buffer) + message_start = -1 + message_end = -1 + while 1: + (tag_bytes, pos) = ReadTag(buffer, pos) + if tag_bytes == type_id_tag_bytes: + (type_id, pos) = _DecodeVarint(buffer, pos) + elif tag_bytes == message_tag_bytes: + (size, message_start) = _DecodeVarint(buffer, pos) + pos = message_end = message_start + size + elif tag_bytes == item_end_tag_bytes: + break + else: + field_number, wire_type = DecodeTag(tag_bytes) + _, pos = _DecodeUnknownField(buffer, pos, end, field_number, wire_type) + if pos == -1: + raise _DecodeError('Unexpected end-group tag.') + + if pos > end: + raise _DecodeError('Truncated message.') + + if type_id == -1: + raise _DecodeError('MessageSet item missing type_id.') + if message_start == -1: + raise _DecodeError('MessageSet item missing message.') + + return (type_id, buffer[message_start:message_end].tobytes()) + + return DecodeUnknownItem + +# -------------------------------------------------------------------- + +def MapDecoder(field_descriptor, new_default, is_message_map): + """Returns a decoder for a map field.""" + + key = field_descriptor + tag_bytes = encoder.TagBytes(field_descriptor.number, + wire_format.WIRETYPE_LENGTH_DELIMITED) + tag_len = len(tag_bytes) + local_DecodeVarint = _DecodeVarint + # Can't read _concrete_class yet; might not be initialized. + message_type = field_descriptor.message_type + + def DecodeMap(buffer, pos, end, message, field_dict, current_depth=0): + del current_depth # Unused. + submsg = message_type._concrete_class() + value = field_dict.get(key) + if value is None: + value = field_dict.setdefault(key, new_default(message)) + while 1: + # Read length. + (size, pos) = local_DecodeVarint(buffer, pos) + new_pos = pos + size + if new_pos > end: + raise _DecodeError('Truncated message.') + # Read sub-message. + submsg.Clear() + if submsg._InternalParse(buffer, pos, new_pos) != new_pos: + # The only reason _InternalParse would return early is if it + # encountered an end-group tag. + raise _DecodeError('Unexpected end-group tag.') + + if is_message_map: + value[submsg.key].CopyFrom(submsg.value) + else: + value[submsg.key] = submsg.value + + # Predict that the next tag is another copy of the same repeated field. + pos = new_pos + tag_len + if buffer[new_pos:pos] != tag_bytes or new_pos == end: + # Prediction failed. Return. + return new_pos + + return DecodeMap + + +def _DecodeFixed64(buffer, pos): + """Decode a fixed64.""" + new_pos = pos + 8 + return (struct.unpack('= _recursion_limit: + raise _DecodeError('Error parsing message: too many levels of nesting.') + data, pos = _DecodeUnknownFieldSet(buffer, pos, end_pos, current_depth) + current_depth -= 1 + # Check end tag. + if buffer[pos - len(end_tag_bytes) : pos] != end_tag_bytes: + raise _DecodeError('Missing group end tag.') + elif wire_type == wire_format.WIRETYPE_END_GROUP: + return (0, -1) + else: + raise _DecodeError('Wrong wire type in tag.') + + if pos > end_pos: + raise _DecodeError('Truncated message.') + + return (data, pos) diff --git a/python/user_packages/Python313/site-packages/google/protobuf/internal/encoder.py b/python/user_packages/Python313/site-packages/google/protobuf/internal/encoder.py new file mode 100644 index 0000000000000000000000000000000000000000..df7bf1b537f6a3d5f1f4e10009f7e23be91382dd --- /dev/null +++ b/python/user_packages/Python313/site-packages/google/protobuf/internal/encoder.py @@ -0,0 +1,806 @@ +# Protocol Buffers - Google's data interchange format +# Copyright 2008 Google Inc. All rights reserved. +# +# Use of this source code is governed by a BSD-style +# license that can be found in the LICENSE file or at +# https://developers.google.com/open-source/licenses/bsd + +"""Code for encoding protocol message primitives. + +Contains the logic for encoding every logical protocol field type +into one of the 5 physical wire types. + +This code is designed to push the Python interpreter's performance to the +limits. + +The basic idea is that at startup time, for every field (i.e. every +FieldDescriptor) we construct two functions: a "sizer" and an "encoder". The +sizer takes a value of this field's type and computes its byte size. The +encoder takes a writer function and a value. It encodes the value into byte +strings and invokes the writer function to write those strings. Typically the +writer function is the write() method of a BytesIO. + +We try to do as much work as possible when constructing the writer and the +sizer rather than when calling them. In particular: +* We copy any needed global functions to local variables, so that we do not need + to do costly global table lookups at runtime. +* Similarly, we try to do any attribute lookups at startup time if possible. +* Every field's tag is encoded to bytes at startup, since it can't change at + runtime. +* Whatever component of the field size we can compute at startup, we do. +* We *avoid* sharing code if doing so would make the code slower and not sharing + does not burden us too much. For example, encoders for repeated fields do + not just call the encoders for singular fields in a loop because this would + add an extra function call overhead for every loop iteration; instead, we + manually inline the single-value encoder into the loop. +* If a Python function lacks a return statement, Python actually generates + instructions to pop the result of the last statement off the stack, push + None onto the stack, and then return that. If we really don't care what + value is returned, then we can save two instructions by returning the + result of the last statement. It looks funny but it helps. +* We assume that type and bounds checking has happened at a higher level. +""" + +__author__ = 'kenton@google.com (Kenton Varda)' + +import struct + +from google.protobuf.internal import wire_format + + +# This will overflow and thus become IEEE-754 "infinity". We would use +# "float('inf')" but it doesn't work on Windows pre-Python-2.6. +_POS_INF = 1e10000 +_NEG_INF = -_POS_INF + + +def _VarintSize(value): + """Compute the size of a varint value.""" + if value <= 0x7f: return 1 + if value <= 0x3fff: return 2 + if value <= 0x1fffff: return 3 + if value <= 0xfffffff: return 4 + if value <= 0x7ffffffff: return 5 + if value <= 0x3ffffffffff: return 6 + if value <= 0x1ffffffffffff: return 7 + if value <= 0xffffffffffffff: return 8 + if value <= 0x7fffffffffffffff: return 9 + return 10 + + +def _SignedVarintSize(value): + """Compute the size of a signed varint value.""" + if value < 0: return 10 + if value <= 0x7f: return 1 + if value <= 0x3fff: return 2 + if value <= 0x1fffff: return 3 + if value <= 0xfffffff: return 4 + if value <= 0x7ffffffff: return 5 + if value <= 0x3ffffffffff: return 6 + if value <= 0x1ffffffffffff: return 7 + if value <= 0xffffffffffffff: return 8 + if value <= 0x7fffffffffffffff: return 9 + return 10 + + +def _TagSize(field_number): + """Returns the number of bytes required to serialize a tag with this field + number.""" + # Just pass in type 0, since the type won't affect the tag+type size. + return _VarintSize(wire_format.PackTag(field_number, 0)) + + +# -------------------------------------------------------------------- +# In this section we define some generic sizers. Each of these functions +# takes parameters specific to a particular field type, e.g. int32 or fixed64. +# It returns another function which in turn takes parameters specific to a +# particular field, e.g. the field number and whether it is repeated or packed. +# Look at the next section to see how these are used. + + +def _SimpleSizer(compute_value_size): + """A sizer which uses the function compute_value_size to compute the size of + each value. Typically compute_value_size is _VarintSize.""" + + def SpecificSizer(field_number, is_repeated, is_packed): + tag_size = _TagSize(field_number) + if is_packed: + local_VarintSize = _VarintSize + def PackedFieldSize(value): + result = 0 + for element in value: + result += compute_value_size(element) + return result + local_VarintSize(result) + tag_size + return PackedFieldSize + elif is_repeated: + def RepeatedFieldSize(value): + result = tag_size * len(value) + for element in value: + result += compute_value_size(element) + return result + return RepeatedFieldSize + else: + def FieldSize(value): + return tag_size + compute_value_size(value) + return FieldSize + + return SpecificSizer + + +def _ModifiedSizer(compute_value_size, modify_value): + """Like SimpleSizer, but modify_value is invoked on each value before it is + passed to compute_value_size. modify_value is typically ZigZagEncode.""" + + def SpecificSizer(field_number, is_repeated, is_packed): + tag_size = _TagSize(field_number) + if is_packed: + local_VarintSize = _VarintSize + def PackedFieldSize(value): + result = 0 + for element in value: + result += compute_value_size(modify_value(element)) + return result + local_VarintSize(result) + tag_size + return PackedFieldSize + elif is_repeated: + def RepeatedFieldSize(value): + result = tag_size * len(value) + for element in value: + result += compute_value_size(modify_value(element)) + return result + return RepeatedFieldSize + else: + def FieldSize(value): + return tag_size + compute_value_size(modify_value(value)) + return FieldSize + + return SpecificSizer + + +def _FixedSizer(value_size): + """Like _SimpleSizer except for a fixed-size field. The input is the size + of one value.""" + + def SpecificSizer(field_number, is_repeated, is_packed): + tag_size = _TagSize(field_number) + if is_packed: + local_VarintSize = _VarintSize + def PackedFieldSize(value): + result = len(value) * value_size + return result + local_VarintSize(result) + tag_size + return PackedFieldSize + elif is_repeated: + element_size = value_size + tag_size + def RepeatedFieldSize(value): + return len(value) * element_size + return RepeatedFieldSize + else: + field_size = value_size + tag_size + def FieldSize(value): + return field_size + return FieldSize + + return SpecificSizer + + +# ==================================================================== +# Here we declare a sizer constructor for each field type. Each "sizer +# constructor" is a function that takes (field_number, is_repeated, is_packed) +# as parameters and returns a sizer, which in turn takes a field value as +# a parameter and returns its encoded size. + + +Int32Sizer = Int64Sizer = EnumSizer = _SimpleSizer(_SignedVarintSize) + +UInt32Sizer = UInt64Sizer = _SimpleSizer(_VarintSize) + +SInt32Sizer = SInt64Sizer = _ModifiedSizer( + _SignedVarintSize, wire_format.ZigZagEncode) + +Fixed32Sizer = SFixed32Sizer = FloatSizer = _FixedSizer(4) +Fixed64Sizer = SFixed64Sizer = DoubleSizer = _FixedSizer(8) + +BoolSizer = _FixedSizer(1) + + +def StringSizer(field_number, is_repeated, is_packed): + """Returns a sizer for a string field.""" + + tag_size = _TagSize(field_number) + local_VarintSize = _VarintSize + local_len = len + assert not is_packed + if is_repeated: + def RepeatedFieldSize(value): + result = tag_size * len(value) + for element in value: + l = local_len(element.encode('utf-8')) + result += local_VarintSize(l) + l + return result + return RepeatedFieldSize + else: + def FieldSize(value): + l = local_len(value.encode('utf-8')) + return tag_size + local_VarintSize(l) + l + return FieldSize + + +def BytesSizer(field_number, is_repeated, is_packed): + """Returns a sizer for a bytes field.""" + + tag_size = _TagSize(field_number) + local_VarintSize = _VarintSize + local_len = len + assert not is_packed + if is_repeated: + def RepeatedFieldSize(value): + result = tag_size * len(value) + for element in value: + l = local_len(element) + result += local_VarintSize(l) + l + return result + return RepeatedFieldSize + else: + def FieldSize(value): + l = local_len(value) + return tag_size + local_VarintSize(l) + l + return FieldSize + + +def GroupSizer(field_number, is_repeated, is_packed): + """Returns a sizer for a group field.""" + + tag_size = _TagSize(field_number) * 2 + assert not is_packed + if is_repeated: + def RepeatedFieldSize(value): + result = tag_size * len(value) + for element in value: + result += element.ByteSize() + return result + return RepeatedFieldSize + else: + def FieldSize(value): + return tag_size + value.ByteSize() + return FieldSize + + +def MessageSizer(field_number, is_repeated, is_packed): + """Returns a sizer for a message field.""" + + tag_size = _TagSize(field_number) + local_VarintSize = _VarintSize + assert not is_packed + if is_repeated: + def RepeatedFieldSize(value): + result = tag_size * len(value) + for element in value: + l = element.ByteSize() + result += local_VarintSize(l) + l + return result + return RepeatedFieldSize + else: + def FieldSize(value): + l = value.ByteSize() + return tag_size + local_VarintSize(l) + l + return FieldSize + + +# -------------------------------------------------------------------- +# MessageSet is special: it needs custom logic to compute its size properly. + + +def MessageSetItemSizer(field_number): + """Returns a sizer for extensions of MessageSet. + + The message set message looks like this: + message MessageSet { + repeated group Item = 1 { + required int32 type_id = 2; + required string message = 3; + } + } + """ + static_size = (_TagSize(1) * 2 + _TagSize(2) + _VarintSize(field_number) + + _TagSize(3)) + local_VarintSize = _VarintSize + + def FieldSize(value): + l = value.ByteSize() + return static_size + local_VarintSize(l) + l + + return FieldSize + + +# -------------------------------------------------------------------- +# Map is special: it needs custom logic to compute its size properly. + + +def MapSizer(field_descriptor, is_message_map): + """Returns a sizer for a map field.""" + + # Can't look at field_descriptor.message_type._concrete_class because it may + # not have been initialized yet. + message_type = field_descriptor.message_type + message_sizer = MessageSizer(field_descriptor.number, False, False) + + def FieldSize(map_value): + total = 0 + for key in map_value: + value = map_value[key] + # It's wasteful to create the messages and throw them away one second + # later since we'll do the same for the actual encode. But there's not an + # obvious way to avoid this within the current design without tons of code + # duplication. For message map, value.ByteSize() should be called to + # update the status. + entry_msg = message_type._concrete_class(key=key, value=value) + total += message_sizer(entry_msg) + if is_message_map: + value.ByteSize() + return total + + return FieldSize + +# ==================================================================== +# Encoders! + + +def _VarintEncoder(): + """Return an encoder for a basic varint value (does not include tag).""" + + local_int2byte = struct.Struct('>B').pack + + def EncodeVarint(write, value, unused_deterministic=None): + bits = value & 0x7f + value >>= 7 + while value: + write(local_int2byte(0x80|bits)) + bits = value & 0x7f + value >>= 7 + return write(local_int2byte(bits)) + + return EncodeVarint + + +def _SignedVarintEncoder(): + """Return an encoder for a basic signed varint value (does not include + tag).""" + + local_int2byte = struct.Struct('>B').pack + + def EncodeSignedVarint(write, value, unused_deterministic=None): + if value < 0: + value += (1 << 64) + bits = value & 0x7f + value >>= 7 + while value: + write(local_int2byte(0x80|bits)) + bits = value & 0x7f + value >>= 7 + return write(local_int2byte(bits)) + + return EncodeSignedVarint + + +_EncodeVarint = _VarintEncoder() +_EncodeSignedVarint = _SignedVarintEncoder() + + +def _VarintBytes(value): + """Encode the given integer as a varint and return the bytes. This is only + called at startup time so it doesn't need to be fast.""" + + pieces = [] + _EncodeVarint(pieces.append, value, True) + return b"".join(pieces) + + +def TagBytes(field_number, wire_type): + """Encode the given tag and return the bytes. Only called at startup.""" + + return bytes(_VarintBytes(wire_format.PackTag(field_number, wire_type))) + +# -------------------------------------------------------------------- +# As with sizers (see above), we have a number of common encoder +# implementations. + + +def _SimpleEncoder(wire_type, encode_value, compute_value_size): + """Return a constructor for an encoder for fields of a particular type. + + Args: + wire_type: The field's wire type, for encoding tags. + encode_value: A function which encodes an individual value, e.g. + _EncodeVarint(). + compute_value_size: A function which computes the size of an individual + value, e.g. _VarintSize(). + """ + + def SpecificEncoder(field_number, is_repeated, is_packed): + if is_packed: + tag_bytes = TagBytes(field_number, wire_format.WIRETYPE_LENGTH_DELIMITED) + local_EncodeVarint = _EncodeVarint + def EncodePackedField(write, value, deterministic): + write(tag_bytes) + size = 0 + for element in value: + size += compute_value_size(element) + local_EncodeVarint(write, size, deterministic) + for element in value: + encode_value(write, element, deterministic) + return EncodePackedField + elif is_repeated: + tag_bytes = TagBytes(field_number, wire_type) + def EncodeRepeatedField(write, value, deterministic): + for element in value: + write(tag_bytes) + encode_value(write, element, deterministic) + return EncodeRepeatedField + else: + tag_bytes = TagBytes(field_number, wire_type) + def EncodeField(write, value, deterministic): + write(tag_bytes) + return encode_value(write, value, deterministic) + return EncodeField + + return SpecificEncoder + + +def _ModifiedEncoder(wire_type, encode_value, compute_value_size, modify_value): + """Like SimpleEncoder but additionally invokes modify_value on every value + before passing it to encode_value. Usually modify_value is ZigZagEncode.""" + + def SpecificEncoder(field_number, is_repeated, is_packed): + if is_packed: + tag_bytes = TagBytes(field_number, wire_format.WIRETYPE_LENGTH_DELIMITED) + local_EncodeVarint = _EncodeVarint + def EncodePackedField(write, value, deterministic): + write(tag_bytes) + size = 0 + for element in value: + size += compute_value_size(modify_value(element)) + local_EncodeVarint(write, size, deterministic) + for element in value: + encode_value(write, modify_value(element), deterministic) + return EncodePackedField + elif is_repeated: + tag_bytes = TagBytes(field_number, wire_type) + def EncodeRepeatedField(write, value, deterministic): + for element in value: + write(tag_bytes) + encode_value(write, modify_value(element), deterministic) + return EncodeRepeatedField + else: + tag_bytes = TagBytes(field_number, wire_type) + def EncodeField(write, value, deterministic): + write(tag_bytes) + return encode_value(write, modify_value(value), deterministic) + return EncodeField + + return SpecificEncoder + + +def _StructPackEncoder(wire_type, format): + """Return a constructor for an encoder for a fixed-width field. + + Args: + wire_type: The field's wire type, for encoding tags. + format: The format string to pass to struct.pack(). + """ + + value_size = struct.calcsize(format) + + def SpecificEncoder(field_number, is_repeated, is_packed): + local_struct_pack = struct.pack + if is_packed: + tag_bytes = TagBytes(field_number, wire_format.WIRETYPE_LENGTH_DELIMITED) + local_EncodeVarint = _EncodeVarint + def EncodePackedField(write, value, deterministic): + write(tag_bytes) + local_EncodeVarint(write, len(value) * value_size, deterministic) + for element in value: + write(local_struct_pack(format, element)) + return EncodePackedField + elif is_repeated: + tag_bytes = TagBytes(field_number, wire_type) + def EncodeRepeatedField(write, value, unused_deterministic=None): + for element in value: + write(tag_bytes) + write(local_struct_pack(format, element)) + return EncodeRepeatedField + else: + tag_bytes = TagBytes(field_number, wire_type) + def EncodeField(write, value, unused_deterministic=None): + write(tag_bytes) + return write(local_struct_pack(format, value)) + return EncodeField + + return SpecificEncoder + + +def _FloatingPointEncoder(wire_type, format): + """Return a constructor for an encoder for float fields. + + This is like StructPackEncoder, but catches errors that may be due to + passing non-finite floating-point values to struct.pack, and makes a + second attempt to encode those values. + + Args: + wire_type: The field's wire type, for encoding tags. + format: The format string to pass to struct.pack(). + """ + + value_size = struct.calcsize(format) + if value_size == 4: + def EncodeNonFiniteOrRaise(write, value): + # Remember that the serialized form uses little-endian byte order. + if value == _POS_INF: + write(b'\x00\x00\x80\x7F') + elif value == _NEG_INF: + write(b'\x00\x00\x80\xFF') + elif value != value: # NaN + write(b'\x00\x00\xC0\x7F') + else: + raise + elif value_size == 8: + def EncodeNonFiniteOrRaise(write, value): + if value == _POS_INF: + write(b'\x00\x00\x00\x00\x00\x00\xF0\x7F') + elif value == _NEG_INF: + write(b'\x00\x00\x00\x00\x00\x00\xF0\xFF') + elif value != value: # NaN + write(b'\x00\x00\x00\x00\x00\x00\xF8\x7F') + else: + raise + else: + raise ValueError('Can\'t encode floating-point values that are ' + '%d bytes long (only 4 or 8)' % value_size) + + def SpecificEncoder(field_number, is_repeated, is_packed): + local_struct_pack = struct.pack + if is_packed: + tag_bytes = TagBytes(field_number, wire_format.WIRETYPE_LENGTH_DELIMITED) + local_EncodeVarint = _EncodeVarint + def EncodePackedField(write, value, deterministic): + write(tag_bytes) + local_EncodeVarint(write, len(value) * value_size, deterministic) + for element in value: + # This try/except block is going to be faster than any code that + # we could write to check whether element is finite. + try: + write(local_struct_pack(format, element)) + except SystemError: + EncodeNonFiniteOrRaise(write, element) + return EncodePackedField + elif is_repeated: + tag_bytes = TagBytes(field_number, wire_type) + def EncodeRepeatedField(write, value, unused_deterministic=None): + for element in value: + write(tag_bytes) + try: + write(local_struct_pack(format, element)) + except SystemError: + EncodeNonFiniteOrRaise(write, element) + return EncodeRepeatedField + else: + tag_bytes = TagBytes(field_number, wire_type) + def EncodeField(write, value, unused_deterministic=None): + write(tag_bytes) + try: + write(local_struct_pack(format, value)) + except SystemError: + EncodeNonFiniteOrRaise(write, value) + return EncodeField + + return SpecificEncoder + + +# ==================================================================== +# Here we declare an encoder constructor for each field type. These work +# very similarly to sizer constructors, described earlier. + + +Int32Encoder = Int64Encoder = EnumEncoder = _SimpleEncoder( + wire_format.WIRETYPE_VARINT, _EncodeSignedVarint, _SignedVarintSize) + +UInt32Encoder = UInt64Encoder = _SimpleEncoder( + wire_format.WIRETYPE_VARINT, _EncodeVarint, _VarintSize) + +SInt32Encoder = SInt64Encoder = _ModifiedEncoder( + wire_format.WIRETYPE_VARINT, _EncodeVarint, _VarintSize, + wire_format.ZigZagEncode) + +# Note that Python conveniently guarantees that when using the '<' prefix on +# formats, they will also have the same size across all platforms (as opposed +# to without the prefix, where their sizes depend on the C compiler's basic +# type sizes). +Fixed32Encoder = _StructPackEncoder(wire_format.WIRETYPE_FIXED32, ' str + ValueType = int + + def __init__(self, enum_type): + """Inits EnumTypeWrapper with an EnumDescriptor.""" + self._enum_type = enum_type + self.DESCRIPTOR = enum_type # pylint: disable=invalid-name + + def Name(self, number): # pylint: disable=invalid-name + """Returns a string containing the name of an enum value.""" + try: + return self._enum_type.values_by_number[number].name + except KeyError: + pass # fall out to break exception chaining + + if not isinstance(number, int): + raise TypeError( + 'Enum value for {} must be an int, but got {} {!r}.'.format( + self._enum_type.name, type(number), number)) + else: + # repr here to handle the odd case when you pass in a boolean. + raise ValueError('Enum {} has no name defined for value {!r}'.format( + self._enum_type.name, number)) + + def Value(self, name): # pylint: disable=invalid-name + """Returns the value corresponding to the given enum name.""" + try: + return self._enum_type.values_by_name[name].number + except KeyError: + pass # fall out to break exception chaining + raise ValueError('Enum {} has no value defined for name {!r}'.format( + self._enum_type.name, name)) + + def keys(self): + """Return a list of the string names in the enum. + + Returns: + A list of strs, in the order they were defined in the .proto file. + """ + + return [value_descriptor.name + for value_descriptor in self._enum_type.values] + + def values(self): + """Return a list of the integer values in the enum. + + Returns: + A list of ints, in the order they were defined in the .proto file. + """ + + return [value_descriptor.number + for value_descriptor in self._enum_type.values] + + def items(self): + """Return a list of the (name, value) pairs of the enum. + + Returns: + A list of (str, int) pairs, in the order they were defined + in the .proto file. + """ + return [(value_descriptor.name, value_descriptor.number) + for value_descriptor in self._enum_type.values] + + def __getattr__(self, name): + """Returns the value corresponding to the given enum name.""" + try: + return super( + EnumTypeWrapper, + self).__getattribute__('_enum_type').values_by_name[name].number + except KeyError: + pass # fall out to break exception chaining + raise AttributeError('Enum {} has no value defined for name {!r}'.format( + self._enum_type.name, name)) + + def __or__(self, other): + """Returns the union type of self and other.""" + if sys.version_info >= (3, 10): + return type(self) | other + else: + raise NotImplementedError( + 'You may not use | on EnumTypes (or classes) below python 3.10' + ) diff --git a/python/user_packages/Python313/site-packages/google/protobuf/internal/extension_dict.py b/python/user_packages/Python313/site-packages/google/protobuf/internal/extension_dict.py new file mode 100644 index 0000000000000000000000000000000000000000..8163ab94b1bd2a1e3a61ff3dc63e608cf315c105 --- /dev/null +++ b/python/user_packages/Python313/site-packages/google/protobuf/internal/extension_dict.py @@ -0,0 +1,194 @@ +# Protocol Buffers - Google's data interchange format +# Copyright 2008 Google Inc. All rights reserved. +# +# Use of this source code is governed by a BSD-style +# license that can be found in the LICENSE file or at +# https://developers.google.com/open-source/licenses/bsd + +"""Contains _ExtensionDict class to represent extensions. +""" + +from google.protobuf.internal import type_checkers +from google.protobuf.descriptor import FieldDescriptor + + +def _VerifyExtensionHandle(message, extension_handle): + """Verify that the given extension handle is valid.""" + + if not isinstance(extension_handle, FieldDescriptor): + raise KeyError('HasExtension() expects an extension handle, got: %s' % + extension_handle) + + if not extension_handle.is_extension: + raise KeyError('"%s" is not an extension.' % extension_handle.full_name) + + if not extension_handle.containing_type: + raise KeyError('"%s" is missing a containing_type.' + % extension_handle.full_name) + + if extension_handle.containing_type is not message.DESCRIPTOR: + raise KeyError('Extension "%s" extends message type "%s", but this ' + 'message is of type "%s".' % + (extension_handle.full_name, + extension_handle.containing_type.full_name, + message.DESCRIPTOR.full_name)) + + +# TODO: Unify error handling of "unknown extension" crap. +# TODO: Support iteritems()-style iteration over all +# extensions with the "has" bits turned on? +class _ExtensionDict(object): + + """Dict-like container for Extension fields on proto instances. + + Note that in all cases we expect extension handles to be + FieldDescriptors. + """ + + def __init__(self, extended_message): + """ + Args: + extended_message: Message instance for which we are the Extensions dict. + """ + self._extended_message = extended_message + + def __getitem__(self, extension_handle): + """Returns the current value of the given extension handle.""" + + _VerifyExtensionHandle(self._extended_message, extension_handle) + + result = self._extended_message._fields.get(extension_handle) + if result is not None: + return result + + if extension_handle.is_repeated: + result = extension_handle._default_constructor(self._extended_message) + elif extension_handle.cpp_type == FieldDescriptor.CPPTYPE_MESSAGE: + message_type = extension_handle.message_type + if not hasattr(message_type, '_concrete_class'): + # pylint: disable=g-import-not-at-top + from google.protobuf import message_factory + message_factory.GetMessageClass(message_type) + if not hasattr(extension_handle.message_type, '_concrete_class'): + from google.protobuf import message_factory + message_factory.GetMessageClass(extension_handle.message_type) + result = extension_handle.message_type._concrete_class() + try: + result._SetListener(self._extended_message._listener_for_children) + except ReferenceError: + pass + else: + # Singular scalar -- just return the default without inserting into the + # dict. + return extension_handle.default_value + + # Atomically check if another thread has preempted us and, if not, swap + # in the new object we just created. If someone has preempted us, we + # take that object and discard ours. + # WARNING: We are relying on setdefault() being atomic. This is true + # in CPython but we haven't investigated others. This warning appears + # in several other locations in this file. + result = self._extended_message._fields.setdefault( + extension_handle, result) + + return result + + def __eq__(self, other): + if not isinstance(other, self.__class__): + return False + + my_fields = self._extended_message.ListFields() + other_fields = other._extended_message.ListFields() + + # Get rid of non-extension fields. + my_fields = [field for field in my_fields if field.is_extension] + other_fields = [field for field in other_fields if field.is_extension] + + return my_fields == other_fields + + def __ne__(self, other): + return not self == other + + def __len__(self): + fields = self._extended_message.ListFields() + # Get rid of non-extension fields. + extension_fields = [field for field in fields if field[0].is_extension] + return len(extension_fields) + + def __hash__(self): + raise TypeError('unhashable object') + + # Note that this is only meaningful for non-repeated, scalar extension + # fields. Note also that we may have to call _Modified() when we do + # successfully set a field this way, to set any necessary "has" bits in the + # ancestors of the extended message. + def __setitem__(self, extension_handle, value): + """If extension_handle specifies a non-repeated, scalar extension + field, sets the value of that field. + """ + + _VerifyExtensionHandle(self._extended_message, extension_handle) + + if (extension_handle.is_repeated or + extension_handle.cpp_type == FieldDescriptor.CPPTYPE_MESSAGE): + raise TypeError( + 'Cannot assign to extension "%s" because it is a repeated or ' + 'composite type.' % extension_handle.full_name) + + # It's slightly wasteful to lookup the type checker each time, + # but we expect this to be a vanishingly uncommon case anyway. + type_checker = type_checkers.GetTypeChecker(extension_handle) + # pylint: disable=protected-access + self._extended_message._fields[extension_handle] = ( + type_checker.CheckValue(value)) + self._extended_message._Modified() + + def __delitem__(self, extension_handle): + self._extended_message.ClearExtension(extension_handle) + + def _FindExtensionByName(self, name): + """Tries to find a known extension with the specified name. + + Args: + name: Extension full name. + + Returns: + Extension field descriptor. + """ + descriptor = self._extended_message.DESCRIPTOR + extensions = descriptor.file.pool._extensions_by_name[descriptor] + return extensions.get(name, None) + + def _FindExtensionByNumber(self, number): + """Tries to find a known extension with the field number. + + Args: + number: Extension field number. + + Returns: + Extension field descriptor. + """ + descriptor = self._extended_message.DESCRIPTOR + extensions = descriptor.file.pool._extensions_by_number[descriptor] + return extensions.get(number, None) + + def __iter__(self): + # Return a generator over the populated extension fields + return (f[0] for f in self._extended_message.ListFields() + if f[0].is_extension) + + def __contains__(self, extension_handle): + _VerifyExtensionHandle(self._extended_message, extension_handle) + + if extension_handle not in self._extended_message._fields: + return False + + if extension_handle.is_repeated: + return bool(self._extended_message._fields.get(extension_handle)) + + if extension_handle.cpp_type == FieldDescriptor.CPPTYPE_MESSAGE: + value = self._extended_message._fields.get(extension_handle) + # pylint: disable=protected-access + return value is not None and value._is_present_in_parent + + return True diff --git a/python/user_packages/Python313/site-packages/google/protobuf/internal/field_mask.py b/python/user_packages/Python313/site-packages/google/protobuf/internal/field_mask.py new file mode 100644 index 0000000000000000000000000000000000000000..0357486e9fd1b5e7dbdb79c59dda33eaa0a452dc --- /dev/null +++ b/python/user_packages/Python313/site-packages/google/protobuf/internal/field_mask.py @@ -0,0 +1,312 @@ +# Protocol Buffers - Google's data interchange format +# Copyright 2008 Google Inc. All rights reserved. +# +# Use of this source code is governed by a BSD-style +# license that can be found in the LICENSE file or at +# https://developers.google.com/open-source/licenses/bsd + +"""Contains FieldMask class.""" + +from google.protobuf.descriptor import FieldDescriptor + + +class FieldMask(object): + """Class for FieldMask message type.""" + + __slots__ = () + + def ToJsonString(self): + """Converts FieldMask to string according to proto3 JSON spec.""" + camelcase_paths = [] + for path in self.paths: + camelcase_paths.append(_SnakeCaseToCamelCase(path)) + return ','.join(camelcase_paths) + + def FromJsonString(self, value): + """Converts string to FieldMask according to proto3 JSON spec.""" + if not isinstance(value, str): + raise ValueError('FieldMask JSON value not a string: {!r}'.format(value)) + self.Clear() + if value: + for path in value.split(','): + self.paths.append(_CamelCaseToSnakeCase(path)) + + def IsValidForDescriptor(self, message_descriptor): + """Checks whether the FieldMask is valid for Message Descriptor.""" + for path in self.paths: + if not _IsValidPath(message_descriptor, path): + return False + return True + + def AllFieldsFromDescriptor(self, message_descriptor): + """Gets all direct fields of Message Descriptor to FieldMask.""" + self.Clear() + for field in message_descriptor.fields: + self.paths.append(field.name) + + def CanonicalFormFromMask(self, mask): + """Converts a FieldMask to the canonical form. + + Removes paths that are covered by another path. For example, + "foo.bar" is covered by "foo" and will be removed if "foo" + is also in the FieldMask. Then sorts all paths in alphabetical order. + + Args: + mask: The original FieldMask to be converted. + """ + tree = _FieldMaskTree(mask) + tree.ToFieldMask(self) + + def Union(self, mask1, mask2): + """Merges mask1 and mask2 into this FieldMask.""" + _CheckFieldMaskMessage(mask1) + _CheckFieldMaskMessage(mask2) + tree = _FieldMaskTree(mask1) + tree.MergeFromFieldMask(mask2) + tree.ToFieldMask(self) + + def Intersect(self, mask1, mask2): + """Intersects mask1 and mask2 into this FieldMask.""" + _CheckFieldMaskMessage(mask1) + _CheckFieldMaskMessage(mask2) + tree = _FieldMaskTree(mask1) + intersection = _FieldMaskTree() + for path in mask2.paths: + tree.IntersectPath(path, intersection) + intersection.ToFieldMask(self) + + def MergeMessage( + self, source, destination, + replace_message_field=False, replace_repeated_field=False): + """Merges fields specified in FieldMask from source to destination. + + Args: + source: Source message. + destination: The destination message to be merged into. + replace_message_field: Replace message field if True. Merge message + field if False. + replace_repeated_field: Replace repeated field if True. Append + elements of repeated field if False. + """ + tree = _FieldMaskTree(self) + tree.MergeMessage( + source, destination, replace_message_field, replace_repeated_field) + + +def _IsValidPath(message_descriptor, path): + """Checks whether the path is valid for Message Descriptor.""" + parts = path.split('.') + last = parts.pop() + for name in parts: + field = message_descriptor.fields_by_name.get(name) + if (field is None or + field.is_repeated or + field.type != FieldDescriptor.TYPE_MESSAGE): + return False + message_descriptor = field.message_type + return last in message_descriptor.fields_by_name + + +def _CheckFieldMaskMessage(message): + """Raises ValueError if message is not a FieldMask.""" + message_descriptor = message.DESCRIPTOR + if (message_descriptor.name != 'FieldMask' or + message_descriptor.file.name != 'google/protobuf/field_mask.proto'): + raise ValueError('Message {0} is not a FieldMask.'.format( + message_descriptor.full_name)) + + +def _SnakeCaseToCamelCase(path_name): + """Converts a path name from snake_case to camelCase.""" + result = [] + after_underscore = False + for c in path_name: + if c.isupper(): + raise ValueError( + 'Fail to print FieldMask to Json string: Path name ' + '{0} must not contain uppercase letters.'.format(path_name)) + if after_underscore: + if c.islower(): + result.append(c.upper()) + after_underscore = False + else: + raise ValueError( + 'Fail to print FieldMask to Json string: The ' + 'character after a "_" must be a lowercase letter ' + 'in path name {0}.'.format(path_name)) + elif c == '_': + after_underscore = True + else: + result += c + + if after_underscore: + raise ValueError('Fail to print FieldMask to Json string: Trailing "_" ' + 'in path name {0}.'.format(path_name)) + return ''.join(result) + + +def _CamelCaseToSnakeCase(path_name): + """Converts a field name from camelCase to snake_case.""" + result = [] + for c in path_name: + if c == '_': + raise ValueError('Fail to parse FieldMask: Path name ' + '{0} must not contain "_"s.'.format(path_name)) + if c.isupper(): + result += '_' + result += c.lower() + else: + result += c + return ''.join(result) + + +class _FieldMaskTree(object): + """Represents a FieldMask in a tree structure. + + For example, given a FieldMask "foo.bar,foo.baz,bar.baz", + the FieldMaskTree will be: + [_root] -+- foo -+- bar + | | + | +- baz + | + +- bar --- baz + In the tree, each leaf node represents a field path. + """ + + __slots__ = ('_root',) + + def __init__(self, field_mask=None): + """Initializes the tree by FieldMask.""" + self._root = {} + if field_mask: + self.MergeFromFieldMask(field_mask) + + def MergeFromFieldMask(self, field_mask): + """Merges a FieldMask to the tree.""" + for path in field_mask.paths: + self.AddPath(path) + + def AddPath(self, path): + """Adds a field path into the tree. + + If the field path to add is a sub-path of an existing field path + in the tree (i.e., a leaf node), it means the tree already matches + the given path so nothing will be added to the tree. If the path + matches an existing non-leaf node in the tree, that non-leaf node + will be turned into a leaf node with all its children removed because + the path matches all the node's children. Otherwise, a new path will + be added. + + Args: + path: The field path to add. + """ + node = self._root + for name in path.split('.'): + if name not in node: + node[name] = {} + elif not node[name]: + # Pre-existing empty node implies we already have this entire tree. + return + node = node[name] + # Remove any sub-trees we might have had. + node.clear() + + def ToFieldMask(self, field_mask): + """Converts the tree to a FieldMask.""" + field_mask.Clear() + _AddFieldPaths(self._root, '', field_mask) + + def IntersectPath(self, path, intersection): + """Calculates the intersection part of a field path with this tree. + + Args: + path: The field path to calculates. + intersection: The out tree to record the intersection part. + """ + node = self._root + for name in path.split('.'): + if name not in node: + return + elif not node[name]: + intersection.AddPath(path) + return + node = node[name] + intersection.AddLeafNodes(path, node) + + def AddLeafNodes(self, prefix, node): + """Adds leaf nodes begin with prefix to this tree.""" + if not node: + self.AddPath(prefix) + for name in node: + child_path = prefix + '.' + name + self.AddLeafNodes(child_path, node[name]) + + def MergeMessage( + self, source, destination, + replace_message, replace_repeated): + """Merge all fields specified by this tree from source to destination.""" + _MergeMessage( + self._root, source, destination, replace_message, replace_repeated) + + +def _StrConvert(value): + """Converts value to str if it is not.""" + # This file is imported by c extension and some methods like ClearField + # requires string for the field name. py2/py3 has different text + # type and may use unicode. + if not isinstance(value, str): + return value.encode('utf-8') + return value + + +def _MergeMessage( + node, source, destination, replace_message, replace_repeated): + """Merge all fields specified by a sub-tree from source to destination.""" + source_descriptor = source.DESCRIPTOR + for name in node: + child = node[name] + field = source_descriptor.fields_by_name[name] + if field is None: + raise ValueError('Error: Can\'t find field {0} in message {1}.'.format( + name, source_descriptor.full_name)) + if child: + # Sub-paths are only allowed for singular message fields. + if (field.is_repeated or + field.cpp_type != FieldDescriptor.CPPTYPE_MESSAGE): + raise ValueError('Error: Field {0} in message {1} is not a singular ' + 'message field and cannot have sub-fields.'.format( + name, source_descriptor.full_name)) + if source.HasField(name): + _MergeMessage( + child, getattr(source, name), getattr(destination, name), + replace_message, replace_repeated) + continue + if field.is_repeated: + if replace_repeated: + destination.ClearField(_StrConvert(name)) + repeated_source = getattr(source, name) + repeated_destination = getattr(destination, name) + repeated_destination.MergeFrom(repeated_source) + else: + if field.cpp_type == FieldDescriptor.CPPTYPE_MESSAGE: + if replace_message: + destination.ClearField(_StrConvert(name)) + if source.HasField(name): + getattr(destination, name).MergeFrom(getattr(source, name)) + elif not field.has_presence or source.HasField(name): + setattr(destination, name, getattr(source, name)) + else: + destination.ClearField(_StrConvert(name)) + + +def _AddFieldPaths(node, prefix, field_mask): + """Adds the field paths descended from node to field_mask.""" + if not node and prefix: + field_mask.paths.append(prefix) + return + for name in sorted(node): + if prefix: + child_path = prefix + '.' + name + else: + child_path = name + _AddFieldPaths(node[name], child_path, field_mask) diff --git a/python/user_packages/Python313/site-packages/google/protobuf/internal/message_listener.py b/python/user_packages/Python313/site-packages/google/protobuf/internal/message_listener.py new file mode 100644 index 0000000000000000000000000000000000000000..ff1c127d549dcd8973fdbe67fda09b9ce3460abe --- /dev/null +++ b/python/user_packages/Python313/site-packages/google/protobuf/internal/message_listener.py @@ -0,0 +1,55 @@ +# Protocol Buffers - Google's data interchange format +# Copyright 2008 Google Inc. All rights reserved. +# +# Use of this source code is governed by a BSD-style +# license that can be found in the LICENSE file or at +# https://developers.google.com/open-source/licenses/bsd + +"""Defines a listener interface for observing certain +state transitions on Message objects. + +Also defines a null implementation of this interface. +""" + +__author__ = 'robinson@google.com (Will Robinson)' + + +class MessageListener(object): + + """Listens for modifications made to a message. Meant to be registered via + Message._SetListener(). + + Attributes: + dirty: If True, then calling Modified() would be a no-op. This can be + used to avoid these calls entirely in the common case. + """ + + def Modified(self): + """Called every time the message is modified in such a way that the parent + message may need to be updated. This currently means either: + (a) The message was modified for the first time, so the parent message + should henceforth mark the message as present. + (b) The message's cached byte size became dirty -- i.e. the message was + modified for the first time after a previous call to ByteSize(). + Therefore the parent should also mark its byte size as dirty. + Note that (a) implies (b), since new objects start out with a client cached + size (zero). However, we document (a) explicitly because it is important. + + Modified() will *only* be called in response to one of these two events -- + not every time the sub-message is modified. + + Note that if the listener's |dirty| attribute is true, then calling + Modified at the moment would be a no-op, so it can be skipped. Performance- + sensitive callers should check this attribute directly before calling since + it will be true most of the time. + """ + + raise NotImplementedError + + +class NullMessageListener(object): + + """No-op MessageListener implementation.""" + + def Modified(self): + pass diff --git a/python/user_packages/Python313/site-packages/google/protobuf/internal/python_edition_defaults.py b/python/user_packages/Python313/site-packages/google/protobuf/internal/python_edition_defaults.py new file mode 100644 index 0000000000000000000000000000000000000000..97d2be08f3c15464c4b3ea90a080a90b3b25cf31 --- /dev/null +++ b/python/user_packages/Python313/site-packages/google/protobuf/internal/python_edition_defaults.py @@ -0,0 +1,5 @@ +""" +This file contains the serialized FeatureSetDefaults object corresponding to +the Pure Python runtime. This is used for feature resolution under Editions. +""" +_PROTOBUF_INTERNAL_PYTHON_EDITION_DEFAULTS = b"\n\027\030\204\007\"\000*\020\010\001\020\002\030\002 \003(\0010\0028\002@\001\n\027\030\347\007\"\000*\020\010\002\020\001\030\001 \002(\0010\0018\002@\001\n\027\030\350\007\"\014\010\001\020\001\030\001 \002(\0010\001*\0048\002@\001\n\027\030\351\007\"\020\010\001\020\001\030\001 \002(\0010\0018\001@\002*\000 \346\007(\351\007" diff --git a/python/user_packages/Python313/site-packages/google/protobuf/internal/python_message.py b/python/user_packages/Python313/site-packages/google/protobuf/internal/python_message.py new file mode 100644 index 0000000000000000000000000000000000000000..ba79963dd97d4413cfd735e42301bce98fca29bd --- /dev/null +++ b/python/user_packages/Python313/site-packages/google/protobuf/internal/python_message.py @@ -0,0 +1,1599 @@ +# Protocol Buffers - Google's data interchange format +# Copyright 2008 Google Inc. All rights reserved. +# +# Use of this source code is governed by a BSD-style +# license that can be found in the LICENSE file or at +# https://developers.google.com/open-source/licenses/bsd + +# This code is meant to work on Python 2.4 and above only. +# +# TODO: Helpers for verbose, common checks like seeing if a +# descriptor's cpp_type is CPPTYPE_MESSAGE. + +"""Contains a metaclass and helper functions used to create +protocol message classes from Descriptor objects at runtime. + +Recall that a metaclass is the "type" of a class. +(A class is to a metaclass what an instance is to a class.) + +In this case, we use the GeneratedProtocolMessageType metaclass +to inject all the useful functionality into the classes +output by the protocol compiler at compile-time. + +The upshot of all this is that the real implementation +details for ALL pure-Python protocol buffers are *here in +this file*. +""" + +__author__ = 'robinson@google.com (Will Robinson)' + +import datetime +from io import BytesIO +import math +import struct +import sys +import warnings +import weakref + +from google.protobuf import descriptor as descriptor_mod +from google.protobuf import message as message_mod +from google.protobuf import text_format +# We use "as" to avoid name collisions with variables. +from google.protobuf.internal import api_implementation +from google.protobuf.internal import containers +from google.protobuf.internal import decoder +from google.protobuf.internal import encoder +from google.protobuf.internal import enum_type_wrapper +from google.protobuf.internal import extension_dict +from google.protobuf.internal import message_listener as message_listener_mod +from google.protobuf.internal import type_checkers +from google.protobuf.internal import well_known_types +from google.protobuf.internal import wire_format + +_FieldDescriptor = descriptor_mod.FieldDescriptor +_AnyFullTypeName = 'google.protobuf.Any' +_StructFullTypeName = 'google.protobuf.Struct' +_ListValueFullTypeName = 'google.protobuf.ListValue' +_ExtensionDict = extension_dict._ExtensionDict + +class GeneratedProtocolMessageType(type): + + """Metaclass for protocol message classes created at runtime from Descriptors. + + We add implementations for all methods described in the Message class. We + also create properties to allow getting/setting all fields in the protocol + message. Finally, we create slots to prevent users from accidentally + "setting" nonexistent fields in the protocol message, which then wouldn't get + serialized / deserialized properly. + + The protocol compiler currently uses this metaclass to create protocol + message classes at runtime. Clients can also manually create their own + classes at runtime, as in this example: + + mydescriptor = Descriptor(.....) + factory = symbol_database.Default() + factory.pool.AddDescriptor(mydescriptor) + MyProtoClass = message_factory.GetMessageClass(mydescriptor) + myproto_instance = MyProtoClass() + myproto.foo_field = 23 + ... + """ + + # Must be consistent with the protocol-compiler code in + # proto2/compiler/internal/generator.*. + _DESCRIPTOR_KEY = 'DESCRIPTOR' + + def __new__(cls, name, bases, dictionary): + """Custom allocation for runtime-generated class types. + + We override __new__ because this is apparently the only place + where we can meaningfully set __slots__ on the class we're creating(?). + (The interplay between metaclasses and slots is not very well-documented). + + Args: + name: Name of the class (ignored, but required by the + metaclass protocol). + bases: Base classes of the class we're constructing. + (Should be message.Message). We ignore this field, but + it's required by the metaclass protocol + dictionary: The class dictionary of the class we're + constructing. dictionary[_DESCRIPTOR_KEY] must contain + a Descriptor object describing this protocol message + type. + + Returns: + Newly-allocated class. + + Raises: + RuntimeError: Generated code only work with python cpp extension. + """ + descriptor = dictionary[GeneratedProtocolMessageType._DESCRIPTOR_KEY] + + if isinstance(descriptor, str): + raise RuntimeError('The generated code only work with python cpp ' + 'extension, but it is using pure python runtime.') + + # If a concrete class already exists for this descriptor, don't try to + # create another. Doing so will break any messages that already exist with + # the existing class. + # + # The C++ implementation appears to have its own internal `PyMessageFactory` + # to achieve similar results. + # + # This most commonly happens in `text_format.py` when using descriptors from + # a custom pool; it calls message_factory.GetMessageClass() on a + # descriptor which already has an existing concrete class. + new_class = getattr(descriptor, '_concrete_class', None) + if new_class: + return new_class + + if descriptor.full_name in well_known_types.WKTBASES: + bases += (well_known_types.WKTBASES[descriptor.full_name],) + _AddClassAttributesForNestedExtensions(descriptor, dictionary) + _AddSlots(descriptor, dictionary) + + superclass = super(GeneratedProtocolMessageType, cls) + new_class = superclass.__new__(cls, name, bases, dictionary) + return new_class + + def __init__(cls, name, bases, dictionary): + """Here we perform the majority of our work on the class. + We add enum getters, an __init__ method, implementations + of all Message methods, and properties for all fields + in the protocol type. + + Args: + name: Name of the class (ignored, but required by the + metaclass protocol). + bases: Base classes of the class we're constructing. + (Should be message.Message). We ignore this field, but + it's required by the metaclass protocol + dictionary: The class dictionary of the class we're + constructing. dictionary[_DESCRIPTOR_KEY] must contain + a Descriptor object describing this protocol message + type. + """ + descriptor = dictionary[GeneratedProtocolMessageType._DESCRIPTOR_KEY] + + # If this is an _existing_ class looked up via `_concrete_class` in the + # __new__ method above, then we don't need to re-initialize anything. + existing_class = getattr(descriptor, '_concrete_class', None) + if existing_class: + assert existing_class is cls, ( + 'Duplicate `GeneratedProtocolMessageType` created for descriptor %r' + % (descriptor.full_name)) + return + + cls._message_set_decoders_by_tag = {} + cls._fields_by_tag = {} + if (descriptor.has_options and + descriptor.GetOptions().message_set_wire_format): + cls._message_set_decoders_by_tag[decoder.MESSAGE_SET_ITEM_TAG] = ( + decoder.MessageSetItemDecoder(descriptor), + None, + ) + + # Attach stuff to each FieldDescriptor for quick lookup later on. + for field in descriptor.fields: + _AttachFieldHelpers(cls, field) + + if descriptor.is_extendable and hasattr(descriptor.file, 'pool'): + extensions = descriptor.file.pool.FindAllExtensions(descriptor) + for ext in extensions: + _AttachFieldHelpers(cls, ext) + + descriptor._concrete_class = cls # pylint: disable=protected-access + _AddEnumValues(descriptor, cls) + _AddInitMethod(descriptor, cls) + _AddPropertiesForFields(descriptor, cls) + _AddPropertiesForExtensions(descriptor, cls) + _AddStaticMethods(cls) + _AddMessageMethods(descriptor, cls) + _AddPrivateHelperMethods(descriptor, cls) + + superclass = super(GeneratedProtocolMessageType, cls) + superclass.__init__(name, bases, dictionary) + + +# Stateless helpers for GeneratedProtocolMessageType below. +# Outside clients should not access these directly. +# +# I opted not to make any of these methods on the metaclass, to make it more +# clear that I'm not really using any state there and to keep clients from +# thinking that they have direct access to these construction helpers. + + +def _PropertyName(proto_field_name): + """Returns the name of the public property attribute which + clients can use to get and (in some cases) set the value + of a protocol message field. + + Args: + proto_field_name: The protocol message field name, exactly + as it appears (or would appear) in a .proto file. + """ + # TODO: Escape Python keywords (e.g., yield), and test this support. + # nnorwitz makes my day by writing: + # """ + # FYI. See the keyword module in the stdlib. This could be as simple as: + # + # if keyword.iskeyword(proto_field_name): + # return proto_field_name + "_" + # return proto_field_name + # """ + # Kenton says: The above is a BAD IDEA. People rely on being able to use + # getattr() and setattr() to reflectively manipulate field values. If we + # rename the properties, then every such user has to also make sure to apply + # the same transformation. Note that currently if you name a field "yield", + # you can still access it just fine using getattr/setattr -- it's not even + # that cumbersome to do so. + # TODO: Remove this method entirely if/when everyone agrees with my + # position. + return proto_field_name + + +def _AddSlots(message_descriptor, dictionary): + """Adds a __slots__ entry to dictionary, containing the names of all valid + attributes for this message type. + + Args: + message_descriptor: A Descriptor instance describing this message type. + dictionary: Class dictionary to which we'll add a '__slots__' entry. + """ + dictionary['__slots__'] = ['_cached_byte_size', + '_cached_byte_size_dirty', + '_fields', + '_unknown_fields', + '_is_present_in_parent', + '_listener', + '_listener_for_children', + '__weakref__', + '_oneofs'] + + +def _IsMessageSetExtension(field): + return (field.is_extension and + field.containing_type.has_options and + field.containing_type.GetOptions().message_set_wire_format and + field.type == _FieldDescriptor.TYPE_MESSAGE and + not field.is_required and + not field.is_repeated) + + +def _IsMapField(field): + return (field.type == _FieldDescriptor.TYPE_MESSAGE and + field.message_type._is_map_entry) + + +def _IsMessageMapField(field): + value_type = field.message_type.fields_by_name['value'] + return value_type.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE + +def _AttachFieldHelpers(cls, field_descriptor): + field_descriptor._default_constructor = _DefaultValueConstructorForField( + field_descriptor + ) + + def AddFieldByTag(wiretype, is_packed): + tag_bytes = encoder.TagBytes(field_descriptor.number, wiretype) + cls._fields_by_tag[tag_bytes] = (field_descriptor, is_packed) + + AddFieldByTag( + type_checkers.FIELD_TYPE_TO_WIRE_TYPE[field_descriptor.type], False + ) + + if field_descriptor.is_repeated and wire_format.IsTypePackable( + field_descriptor.type + ): + # To support wire compatibility of adding packed = true, add a decoder for + # packed values regardless of the field's options. + AddFieldByTag(wire_format.WIRETYPE_LENGTH_DELIMITED, True) + + +def _MaybeAddEncoder(cls, field_descriptor): + if hasattr(field_descriptor, '_encoder'): + return + is_repeated = field_descriptor.is_repeated + is_map_entry = _IsMapField(field_descriptor) + is_packed = field_descriptor.is_packed + + if is_map_entry: + field_encoder = encoder.MapEncoder(field_descriptor) + sizer = encoder.MapSizer(field_descriptor, + _IsMessageMapField(field_descriptor)) + elif _IsMessageSetExtension(field_descriptor): + field_encoder = encoder.MessageSetItemEncoder(field_descriptor.number) + sizer = encoder.MessageSetItemSizer(field_descriptor.number) + else: + field_encoder = type_checkers.TYPE_TO_ENCODER[field_descriptor.type]( + field_descriptor.number, is_repeated, is_packed) + sizer = type_checkers.TYPE_TO_SIZER[field_descriptor.type]( + field_descriptor.number, is_repeated, is_packed) + + field_descriptor._sizer = sizer + field_descriptor._encoder = field_encoder + + +def _MaybeAddDecoder(cls, field_descriptor): + if hasattr(field_descriptor, '_decoders'): + return + + is_repeated = field_descriptor.is_repeated + is_map_entry = _IsMapField(field_descriptor) + helper_decoders = {} + + def AddDecoder(is_packed): + decode_type = field_descriptor.type + if (decode_type == _FieldDescriptor.TYPE_ENUM and + not field_descriptor.enum_type.is_closed): + decode_type = _FieldDescriptor.TYPE_INT32 + + oneof_descriptor = None + if field_descriptor.containing_oneof is not None: + oneof_descriptor = field_descriptor + + if is_map_entry: + is_message_map = _IsMessageMapField(field_descriptor) + + field_decoder = decoder.MapDecoder( + field_descriptor, _GetInitializeDefaultForMap(field_descriptor), + is_message_map) + elif decode_type == _FieldDescriptor.TYPE_STRING: + field_decoder = decoder.StringDecoder( + field_descriptor.number, is_repeated, is_packed, + field_descriptor, field_descriptor._default_constructor, + not field_descriptor.has_presence) + elif field_descriptor.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE: + field_decoder = type_checkers.TYPE_TO_DECODER[decode_type]( + field_descriptor.number, is_repeated, is_packed, + field_descriptor, field_descriptor._default_constructor) + else: + field_decoder = type_checkers.TYPE_TO_DECODER[decode_type]( + field_descriptor.number, is_repeated, is_packed, + # pylint: disable=protected-access + field_descriptor, field_descriptor._default_constructor, + not field_descriptor.has_presence) + + helper_decoders[is_packed] = field_decoder + + AddDecoder(False) + + if is_repeated and wire_format.IsTypePackable(field_descriptor.type): + # To support wire compatibility of adding packed = true, add a decoder for + # packed values regardless of the field's options. + AddDecoder(True) + + field_descriptor._decoders = helper_decoders + + +def _AddClassAttributesForNestedExtensions(descriptor, dictionary): + extensions = descriptor.extensions_by_name + for extension_name, extension_field in extensions.items(): + assert extension_name not in dictionary + dictionary[extension_name] = extension_field + + +def _AddEnumValues(descriptor, cls): + """Sets class-level attributes for all enum fields defined in this message. + + Also exporting a class-level object that can name enum values. + + Args: + descriptor: Descriptor object for this message type. + cls: Class we're constructing for this message type. + """ + for enum_type in descriptor.enum_types: + setattr(cls, enum_type.name, enum_type_wrapper.EnumTypeWrapper(enum_type)) + for enum_value in enum_type.values: + setattr(cls, enum_value.name, enum_value.number) + + +def _GetInitializeDefaultForMap(field): + if not field.is_repeated: + raise ValueError('map_entry set on non-repeated field %s' % ( + field.name)) + fields_by_name = field.message_type.fields_by_name + key_checker = type_checkers.GetTypeChecker(fields_by_name['key']) + + value_field = fields_by_name['value'] + if _IsMessageMapField(field): + def MakeMessageMapDefault(message): + return containers.MessageMap( + message._listener_for_children, value_field.message_type, key_checker, + field.message_type) + return MakeMessageMapDefault + else: + value_checker = type_checkers.GetTypeChecker(value_field) + def MakePrimitiveMapDefault(message): + return containers.ScalarMap( + message._listener_for_children, key_checker, value_checker, + field.message_type) + return MakePrimitiveMapDefault + +def _DefaultValueConstructorForField(field): + """Returns a function which returns a default value for a field. + + Args: + field: FieldDescriptor object for this field. + + The returned function has one argument: + message: Message instance containing this field, or a weakref proxy + of same. + + That function in turn returns a default value for this field. The default + value may refer back to |message| via a weak reference. + """ + + if _IsMapField(field): + return _GetInitializeDefaultForMap(field) + + if field.is_repeated: + if field.has_default_value and field.default_value != []: + raise ValueError('Repeated field default value not empty list: %s' % ( + field.default_value)) + if field.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE: + # We can't look at _concrete_class yet since it might not have + # been set. (Depends on order in which we initialize the classes). + message_type = field.message_type + def MakeRepeatedMessageDefault(message): + return containers.RepeatedCompositeFieldContainer( + message._listener_for_children, field.message_type) + return MakeRepeatedMessageDefault + else: + type_checker = type_checkers.GetTypeChecker(field) + def MakeRepeatedScalarDefault(message): + return containers.RepeatedScalarFieldContainer( + message._listener_for_children, type_checker) + return MakeRepeatedScalarDefault + + if field.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE: + message_type = field.message_type + def MakeSubMessageDefault(message): + # _concrete_class may not yet be initialized. + if not hasattr(message_type, '_concrete_class'): + from google.protobuf import message_factory + message_factory.GetMessageClass(message_type) + result = message_type._concrete_class() + result._SetListener( + _OneofListener(message, field) + if field.containing_oneof is not None + else message._listener_for_children) + return result + return MakeSubMessageDefault + + def MakeScalarDefault(message): + # TODO: This may be broken since there may not be + # default_value. Combine with has_default_value somehow. + return field.default_value + return MakeScalarDefault + + +def _ReraiseTypeErrorWithFieldName(message_name, field_name): + """Re-raise the currently-handled TypeError with the field name added.""" + exc = sys.exc_info()[1] + if len(exc.args) == 1 and type(exc) is TypeError: + # simple TypeError; add field name to exception message + exc = TypeError('%s for field %s.%s' % (str(exc), message_name, field_name)) + + # re-raise possibly-amended exception with original traceback: + raise exc.with_traceback(sys.exc_info()[2]) + + +def _AddInitMethod(message_descriptor, cls): + """Adds an __init__ method to cls.""" + + def _GetIntegerEnumValue(enum_type, value): + """Convert a string or integer enum value to an integer. + + If the value is a string, it is converted to the enum value in + enum_type with the same name. If the value is not a string, it's + returned as-is. (No conversion or bounds-checking is done.) + """ + if isinstance(value, str): + try: + return enum_type.values_by_name[value].number + except KeyError: + raise ValueError('Enum type %s: unknown label "%s"' % ( + enum_type.full_name, value)) + return value + + def init(self, **kwargs): + + def init_wkt_or_merge(field, msg, value): + if isinstance(value, message_mod.Message): + msg.MergeFrom(value) + elif ( + isinstance(value, dict) + and field.message_type.full_name == _StructFullTypeName + ): + msg.Clear() + if len(value) == 1 and 'fields' in value: + try: + msg.update(value) + except: + msg.Clear() + msg.__init__(**value) + else: + msg.update(value) + elif hasattr(msg, '_internal_assign'): + msg._internal_assign(value) + else: + raise TypeError( + 'Message field {0}.{1} must be initialized with a ' + 'dict or instance of same class, got {2}.'.format( + message_descriptor.name, + field.name, + type(value).__name__, + ) + ) + + self._cached_byte_size = 0 + self._cached_byte_size_dirty = len(kwargs) > 0 + self._fields = {} + # Contains a mapping from oneof field descriptors to the descriptor + # of the currently set field in that oneof field. + self._oneofs = {} + + # _unknown_fields is () when empty for efficiency, and will be turned into + # a list if fields are added. + self._unknown_fields = () + self._is_present_in_parent = False + self._listener = message_listener_mod.NullMessageListener() + self._listener_for_children = _Listener(self) + for field_name, field_value in kwargs.items(): + field = _GetFieldByName(message_descriptor, field_name) + if field is None: + raise TypeError('%s() got an unexpected keyword argument "%s"' % + (message_descriptor.name, field_name)) + if field_value is None: + # field=None is the same as no field at all. + continue + if field.is_repeated: + field_copy = field._default_constructor(self) + if field.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE: # Composite + if _IsMapField(field): + if _IsMessageMapField(field): + for key in field_value: + item_value = field_value[key] + if isinstance(item_value, dict): + field_copy[key].__init__(**item_value) + else: + field_copy[key].MergeFrom(item_value) + else: + field_copy.update(field_value) + else: + for val in field_value: + if isinstance(val, dict) and ( + field.message_type.full_name != _StructFullTypeName + ): + field_copy.add(**val) + else: + new_msg = field_copy.add() + init_wkt_or_merge(field, new_msg, val) + else: # Scalar + if field.cpp_type == _FieldDescriptor.CPPTYPE_ENUM: + field_value = [_GetIntegerEnumValue(field.enum_type, val) + for val in field_value] + field_copy.extend(field_value) + self._fields[field] = field_copy + elif field.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE: + field_copy = field._default_constructor(self) + if isinstance(field_value, dict) and ( + field.message_type.full_name != _StructFullTypeName + ): + new_val = field.message_type._concrete_class(**field_value) + field_copy.MergeFrom(new_val) + else: + try: + init_wkt_or_merge(field, field_copy, field_value) + except TypeError: + _ReraiseTypeErrorWithFieldName(message_descriptor.name, field_name) + self._fields[field] = field_copy + else: + if field.cpp_type == _FieldDescriptor.CPPTYPE_ENUM: + field_value = _GetIntegerEnumValue(field.enum_type, field_value) + try: + setattr(self, field_name, field_value) + except TypeError: + _ReraiseTypeErrorWithFieldName(message_descriptor.name, field_name) + + init.__module__ = None + init.__doc__ = None + cls.__init__ = init + + +def _GetFieldByName(message_descriptor, field_name): + """Returns a field descriptor by field name. + + Args: + message_descriptor: A Descriptor describing all fields in message. + field_name: The name of the field to retrieve. + Returns: + The field descriptor associated with the field name. + """ + try: + return message_descriptor.fields_by_name[field_name] + except KeyError: + raise ValueError('Protocol message %s has no "%s" field.' % + (message_descriptor.name, field_name)) + + +def _AddPropertiesForFields(descriptor, cls): + """Adds properties for all fields in this protocol message type.""" + for field in descriptor.fields: + _AddPropertiesForField(field, cls) + + if descriptor.is_extendable: + # _ExtensionDict is just an adaptor with no state so we allocate a new one + # every time it is accessed. + cls.Extensions = property(lambda self: _ExtensionDict(self)) + + +def _AddPropertiesForField(field, cls): + """Adds a public property for a protocol message field. + Clients can use this property to get and (in the case + of non-repeated scalar fields) directly set the value + of a protocol message field. + + Args: + field: A FieldDescriptor for this field. + cls: The class we're constructing. + """ + # Catch it if we add other types that we should + # handle specially here. + assert _FieldDescriptor.MAX_CPPTYPE == 10 + + constant_name = field.name.upper() + '_FIELD_NUMBER' + setattr(cls, constant_name, field.number) + + if field.is_repeated: + _AddPropertiesForRepeatedField(field, cls) + elif field.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE: + _AddPropertiesForNonRepeatedCompositeField(field, cls) + else: + _AddPropertiesForNonRepeatedScalarField(field, cls) + + +class _FieldProperty(property): + __slots__ = ('DESCRIPTOR',) + + def __init__(self, descriptor, getter, setter, doc): + property.__init__(self, getter, setter, doc=doc) + self.DESCRIPTOR = descriptor + + +def _AddPropertiesForRepeatedField(field, cls): + """Adds a public property for a "repeated" protocol message field. Clients + can use this property to get the value of the field, which will be either a + RepeatedScalarFieldContainer or RepeatedCompositeFieldContainer (see + below). + + Note that when clients add values to these containers, we perform + type-checking in the case of repeated scalar fields, and we also set any + necessary "has" bits as a side-effect. + + Args: + field: A FieldDescriptor for this field. + cls: The class we're constructing. + """ + proto_field_name = field.name + property_name = _PropertyName(proto_field_name) + + def getter(self): + field_value = self._fields.get(field) + if field_value is None: + # Construct a new object to represent this field. + field_value = field._default_constructor(self) + + # Atomically check if another thread has preempted us and, if not, swap + # in the new object we just created. If someone has preempted us, we + # take that object and discard ours. + # WARNING: We are relying on setdefault() being atomic. This is true + # in CPython but we haven't investigated others. This warning appears + # in several other locations in this file. + field_value = self._fields.setdefault(field, field_value) + return field_value + getter.__module__ = None + getter.__doc__ = 'Getter for %s.' % proto_field_name + + # We define a setter just so we can throw an exception with a more + # helpful error message. + def setter(self, new_value): + raise AttributeError('Assignment not allowed to repeated field ' + '"%s" in protocol message object.' % proto_field_name) + + doc = 'Magic attribute generated for "%s" proto field.' % proto_field_name + setattr(cls, property_name, _FieldProperty(field, getter, setter, doc=doc)) + + +def _AddPropertiesForNonRepeatedScalarField(field, cls): + """Adds a public property for a nonrepeated, scalar protocol message field. + Clients can use this property to get and directly set the value of the field. + Note that when the client sets the value of a field by using this property, + all necessary "has" bits are set as a side-effect, and we also perform + type-checking. + + Args: + field: A FieldDescriptor for this field. + cls: The class we're constructing. + """ + proto_field_name = field.name + property_name = _PropertyName(proto_field_name) + type_checker = type_checkers.GetTypeChecker(field) + default_value = field.default_value + + def getter(self): + # TODO: This may be broken since there may not be + # default_value. Combine with has_default_value somehow. + return self._fields.get(field, default_value) + getter.__module__ = None + getter.__doc__ = 'Getter for %s.' % proto_field_name + + def field_setter(self, new_value): + # pylint: disable=protected-access + # Testing the value for truthiness captures all of the implicit presence + # defaults (0, 0.0, enum 0, and False), except for -0.0. + try: + new_value = type_checker.CheckValue(new_value) + except TypeError as e: + raise TypeError( + 'Cannot set %s to %.1024r: %s' % (field.full_name, new_value, e)) + if not field.has_presence and decoder.IsDefaultScalarValue(new_value): + self._fields.pop(field, None) + else: + self._fields[field] = new_value + # Check _cached_byte_size_dirty inline to improve performance, since scalar + # setters are called frequently. + if not self._cached_byte_size_dirty: + self._Modified() + + if field.containing_oneof: + def setter(self, new_value): + field_setter(self, new_value) + self._UpdateOneofState(field) + else: + setter = field_setter + + setter.__module__ = None + setter.__doc__ = 'Setter for %s.' % proto_field_name + + # Add a property to encapsulate the getter/setter. + doc = 'Magic attribute generated for "%s" proto field.' % proto_field_name + setattr(cls, property_name, _FieldProperty(field, getter, setter, doc=doc)) + + +def _AddPropertiesForNonRepeatedCompositeField(field, cls): + """Adds a public property for a nonrepeated, composite protocol message field. + A composite field is a "group" or "message" field. + + Clients can use this property to get the value of the field, but cannot + assign to the property directly. + + Args: + field: A FieldDescriptor for this field. + cls: The class we're constructing. + """ + # TODO: Remove duplication with similar method + # for non-repeated scalars. + proto_field_name = field.name + property_name = _PropertyName(proto_field_name) + + def getter(self): + field_value = self._fields.get(field) + if field_value is None: + # Construct a new object to represent this field. + field_value = field._default_constructor(self) + + # Atomically check if another thread has preempted us and, if not, swap + # in the new object we just created. If someone has preempted us, we + # take that object and discard ours. + # WARNING: We are relying on setdefault() being atomic. This is true + # in CPython but we haven't investigated others. This warning appears + # in several other locations in this file. + field_value = self._fields.setdefault(field, field_value) + return field_value + getter.__module__ = None + getter.__doc__ = 'Getter for %s.' % proto_field_name + + # We define a setter just so we can throw an exception with a more + # helpful error message. + def setter(self, new_value): + if field.message_type.full_name == 'google.protobuf.Timestamp': + getter(self) + self._fields[field].FromDatetime(new_value) + elif field.message_type.full_name == 'google.protobuf.Duration': + getter(self) + self._fields[field].FromTimedelta(new_value) + elif field.message_type.full_name == _StructFullTypeName: + getter(self) + self._fields[field].Clear() + self._fields[field].update(new_value) + elif field.message_type.full_name == _ListValueFullTypeName: + getter(self) + self._fields[field].Clear() + self._fields[field].extend(new_value) + else: + raise AttributeError( + 'Assignment not allowed to composite field ' + '"%s" in protocol message object.' % proto_field_name + ) + + # Add a property to encapsulate the getter. + doc = 'Magic attribute generated for "%s" proto field.' % proto_field_name + setattr(cls, property_name, _FieldProperty(field, getter, setter, doc=doc)) + + +def _AddPropertiesForExtensions(descriptor, cls): + """Adds properties for all fields in this protocol message type.""" + extensions = descriptor.extensions_by_name + for extension_name, extension_field in extensions.items(): + constant_name = extension_name.upper() + '_FIELD_NUMBER' + setattr(cls, constant_name, extension_field.number) + + # TODO: Migrate all users of these attributes to functions like + # pool.FindExtensionByNumber(descriptor). + if descriptor.file is not None: + # TODO: Use cls.MESSAGE_FACTORY.pool when available. + pool = descriptor.file.pool + +def _AddStaticMethods(cls): + + def RegisterExtension(_): + """no-op to keep generated code <=4.23 working with new runtimes.""" + # This was originally removed in 5.26 (cl/595989309). + pass + + cls.RegisterExtension = staticmethod(RegisterExtension) + def FromString(s): + message = cls() + message.MergeFromString(s) + return message + cls.FromString = staticmethod(FromString) + + +def _IsPresent(item): + """Given a (FieldDescriptor, value) tuple from _fields, return true if the + value should be included in the list returned by ListFields().""" + + if item[0].is_repeated: + return bool(item[1]) + elif item[0].cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE: + return item[1]._is_present_in_parent + else: + return True + + +def _AddListFieldsMethod(message_descriptor, cls): + """Helper for _AddMessageMethods().""" + + def ListFields(self): + all_fields = [item for item in self._fields.items() if _IsPresent(item)] + all_fields.sort(key = lambda item: item[0].number) + return all_fields + + cls.ListFields = ListFields + + +def _AddHasFieldMethod(message_descriptor, cls): + """Helper for _AddMessageMethods().""" + + hassable_fields = {} + for field in message_descriptor.fields: + if field.is_repeated: + continue + # For proto3, only submessages and fields inside a oneof have presence. + if not field.has_presence: + continue + hassable_fields[field.name] = field + + # Has methods are supported for oneof descriptors. + for oneof in message_descriptor.oneofs: + hassable_fields[oneof.name] = oneof + + def HasField(self, field_name): + try: + field = hassable_fields[field_name] + except KeyError as exc: + raise ValueError('Protocol message %s has no non-repeated field "%s" ' + 'nor has presence is not available for this field.' % ( + message_descriptor.full_name, field_name)) from exc + + if isinstance(field, descriptor_mod.OneofDescriptor): + try: + return HasField(self, self._oneofs[field].name) + except KeyError: + return False + else: + if field.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE: + value = self._fields.get(field) + return value is not None and value._is_present_in_parent + else: + return field in self._fields + + cls.HasField = HasField + + +def _AddClearFieldMethod(message_descriptor, cls): + """Helper for _AddMessageMethods().""" + def ClearField(self, field_name): + try: + field = message_descriptor.fields_by_name[field_name] + except KeyError: + try: + field = message_descriptor.oneofs_by_name[field_name] + if field in self._oneofs: + field = self._oneofs[field] + else: + return + except KeyError: + raise ValueError('Protocol message %s has no "%s" field.' % + (message_descriptor.name, field_name)) + + if field in self._fields: + # To match the C++ implementation, we need to invalidate iterators + # for map fields when ClearField() happens. + if hasattr(self._fields[field], 'InvalidateIterators'): + self._fields[field].InvalidateIterators() + + # Note: If the field is a sub-message, its listener will still point + # at us. That's fine, because the worst than can happen is that it + # will call _Modified() and invalidate our byte size. Big deal. + del self._fields[field] + + if self._oneofs.get(field.containing_oneof, None) is field: + del self._oneofs[field.containing_oneof] + + # Always call _Modified() -- even if nothing was changed, this is + # a mutating method, and thus calling it should cause the field to become + # present in the parent message. + self._Modified() + + cls.ClearField = ClearField + + +def _AddClearExtensionMethod(cls): + """Helper for _AddMessageMethods().""" + def ClearExtension(self, field_descriptor): + extension_dict._VerifyExtensionHandle(self, field_descriptor) + + # Similar to ClearField(), above. + if field_descriptor in self._fields: + del self._fields[field_descriptor] + self._Modified() + cls.ClearExtension = ClearExtension + + +def _AddHasExtensionMethod(cls): + """Helper for _AddMessageMethods().""" + def HasExtension(self, field_descriptor): + extension_dict._VerifyExtensionHandle(self, field_descriptor) + if field_descriptor.is_repeated: + raise KeyError('"%s" is repeated.' % field_descriptor.full_name) + + if field_descriptor.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE: + value = self._fields.get(field_descriptor) + return value is not None and value._is_present_in_parent + else: + return field_descriptor in self._fields + cls.HasExtension = HasExtension + +def _InternalUnpackAny(msg): + """Unpacks Any message and returns the unpacked message. + + This internal method is different from public Any Unpack method which takes + the target message as argument. _InternalUnpackAny method does not have + target message type and need to find the message type in descriptor pool. + + Args: + msg: An Any message to be unpacked. + + Returns: + The unpacked message. + """ + # TODO: Don't use the factory of generated messages. + # To make Any work with custom factories, use the message factory of the + # parent message. + # pylint: disable=g-import-not-at-top + from google.protobuf import symbol_database + factory = symbol_database.Default() + + type_url = msg.type_url + + if not type_url: + return None + + # TODO: For now we just strip the hostname. Better logic will be + # required. + type_name = type_url.split('/')[-1] + descriptor = factory.pool.FindMessageTypeByName(type_name) + + if descriptor is None: + return None + + # Unable to import message_factory at top because of circular import. + # pylint: disable=g-import-not-at-top + from google.protobuf import message_factory + message_class = message_factory.GetMessageClass(descriptor) + message = message_class() + + message.ParseFromString(msg.value) + return message + + +def _AddEqualsMethod(message_descriptor, cls): + """Helper for _AddMessageMethods().""" + def __eq__(self, other): + if self.DESCRIPTOR.full_name == _ListValueFullTypeName and isinstance( + other, list + ): + return self._internal_compare(other) + if self.DESCRIPTOR.full_name == _StructFullTypeName and isinstance( + other, dict + ): + return self._internal_compare(other) + + if (not isinstance(other, message_mod.Message) or + other.DESCRIPTOR != self.DESCRIPTOR): + return NotImplemented + + if self is other: + return True + + if self.DESCRIPTOR.full_name == _AnyFullTypeName: + any_a = _InternalUnpackAny(self) + any_b = _InternalUnpackAny(other) + if any_a and any_b: + return any_a == any_b + + if not self.ListFields() == other.ListFields(): + return False + + # TODO: Fix UnknownFieldSet to consider MessageSet extensions, + # then use it for the comparison. + unknown_fields = list(self._unknown_fields) + unknown_fields.sort() + other_unknown_fields = list(other._unknown_fields) + other_unknown_fields.sort() + return unknown_fields == other_unknown_fields + + cls.__eq__ = __eq__ + + +def _AddStrMethod(message_descriptor, cls): + """Helper for _AddMessageMethods().""" + def __str__(self): + return text_format.MessageToString(self) + cls.__str__ = __str__ + + +def _AddReprMethod(message_descriptor, cls): + """Helper for _AddMessageMethods().""" + def __repr__(self): + return text_format.MessageToString(self) + cls.__repr__ = __repr__ + + +def _AddUnicodeMethod(unused_message_descriptor, cls): + """Helper for _AddMessageMethods().""" + + def __unicode__(self): + return text_format.MessageToString(self, as_utf8=True).decode('utf-8') + cls.__unicode__ = __unicode__ + + +def _AddContainsMethod(message_descriptor, cls): + + if message_descriptor.full_name == 'google.protobuf.Struct': + def __contains__(self, key): + return key in self.fields + elif message_descriptor.full_name == 'google.protobuf.ListValue': + def __contains__(self, value): + return value in self.items() + else: + def __contains__(self, field): + return self.HasField(field) + + cls.__contains__ = __contains__ + + +def _BytesForNonRepeatedElement(value, field_number, field_type): + """Returns the number of bytes needed to serialize a non-repeated element. + The returned byte count includes space for tag information and any + other additional space associated with serializing value. + + Args: + value: Value we're serializing. + field_number: Field number of this value. (Since the field number + is stored as part of a varint-encoded tag, this has an impact + on the total bytes required to serialize the value). + field_type: The type of the field. One of the TYPE_* constants + within FieldDescriptor. + """ + try: + fn = type_checkers.TYPE_TO_BYTE_SIZE_FN[field_type] + return fn(field_number, value) + except KeyError: + raise message_mod.EncodeError('Unrecognized field type: %d' % field_type) + + +def _AddByteSizeMethod(message_descriptor, cls): + """Helper for _AddMessageMethods().""" + + def ByteSize(self): + if not self._cached_byte_size_dirty: + return self._cached_byte_size + + size = 0 + descriptor = self.DESCRIPTOR + if descriptor._is_map_entry: + # Fields of map entry should always be serialized. + key_field = descriptor.fields_by_name['key'] + _MaybeAddEncoder(cls, key_field) + size = key_field._sizer(self.key) + value_field = descriptor.fields_by_name['value'] + _MaybeAddEncoder(cls, value_field) + size += value_field._sizer(self.value) + else: + for field_descriptor, field_value in self.ListFields(): + _MaybeAddEncoder(cls, field_descriptor) + size += field_descriptor._sizer(field_value) + for tag_bytes, value_bytes in self._unknown_fields: + size += len(tag_bytes) + len(value_bytes) + + self._cached_byte_size = size + self._cached_byte_size_dirty = False + self._listener_for_children.dirty = False + return size + + cls.ByteSize = ByteSize + + +def _AddSerializeToStringMethod(message_descriptor, cls): + """Helper for _AddMessageMethods().""" + + def SerializeToString(self, **kwargs): + # Check if the message has all of its required fields set. + if not self.IsInitialized(): + raise message_mod.EncodeError( + 'Message %s is missing required fields: %s' % ( + self.DESCRIPTOR.full_name, ','.join(self.FindInitializationErrors()))) + return self.SerializePartialToString(**kwargs) + cls.SerializeToString = SerializeToString + + +def _AddSerializePartialToStringMethod(message_descriptor, cls): + """Helper for _AddMessageMethods().""" + + def SerializePartialToString(self, **kwargs): + out = BytesIO() + self._InternalSerialize(out.write, **kwargs) + return out.getvalue() + cls.SerializePartialToString = SerializePartialToString + + def InternalSerialize(self, write_bytes, deterministic=None): + if deterministic is None: + deterministic = ( + api_implementation.IsPythonDefaultSerializationDeterministic()) + else: + deterministic = bool(deterministic) + + descriptor = self.DESCRIPTOR + if descriptor._is_map_entry: + # Fields of map entry should always be serialized. + key_field = descriptor.fields_by_name['key'] + _MaybeAddEncoder(cls, key_field) + key_field._encoder(write_bytes, self.key, deterministic) + value_field = descriptor.fields_by_name['value'] + _MaybeAddEncoder(cls, value_field) + value_field._encoder(write_bytes, self.value, deterministic) + else: + for field_descriptor, field_value in self.ListFields(): + _MaybeAddEncoder(cls, field_descriptor) + field_descriptor._encoder(write_bytes, field_value, deterministic) + for tag_bytes, value_bytes in self._unknown_fields: + write_bytes(tag_bytes) + write_bytes(value_bytes) + cls._InternalSerialize = InternalSerialize + + +def _AddMergeFromStringMethod(message_descriptor, cls): + """Helper for _AddMessageMethods().""" + def MergeFromString(self, serialized): + serialized = memoryview(serialized) + length = len(serialized) + try: + if self._InternalParse(serialized, 0, length) != length: + # The only reason _InternalParse would return early is if it + # encountered an end-group tag. + raise message_mod.DecodeError('Unexpected end-group tag.') + except (IndexError, TypeError): + # Now ord(buf[p:p+1]) == ord('') gets TypeError. + raise message_mod.DecodeError('Truncated message.') + except struct.error as e: + raise message_mod.DecodeError(e) + return length # Return this for legacy reasons. + cls.MergeFromString = MergeFromString + + fields_by_tag = cls._fields_by_tag + message_set_decoders_by_tag = cls._message_set_decoders_by_tag + + def InternalParse(self, buffer, pos, end, current_depth=0): + """Create a message from serialized bytes. + + Args: + self: Message, instance of the proto message object. + buffer: memoryview of the serialized data. + pos: int, position to start in the serialized data. + end: int, end position of the serialized data. + + Returns: + Message object. + """ + # Guard against internal misuse, since this function is called internally + # quite extensively, and its easy to accidentally pass bytes. + assert isinstance(buffer, memoryview) + self._Modified() + field_dict = self._fields + while pos != end: + (tag_bytes, new_pos) = decoder.ReadTag(buffer, pos) + field_decoder, field_des = message_set_decoders_by_tag.get( + tag_bytes, (None, None) + ) + if field_decoder: + pos = field_decoder(buffer, new_pos, end, self, field_dict) + continue + field_des, is_packed = fields_by_tag.get(tag_bytes, (None, None)) + if field_des is None: + if not self._unknown_fields: # pylint: disable=protected-access + self._unknown_fields = [] # pylint: disable=protected-access + field_number, wire_type = decoder.DecodeTag(tag_bytes) + if field_number == 0: + raise message_mod.DecodeError('Field number 0 is illegal.') + (data, new_pos) = decoder._DecodeUnknownField( + buffer, new_pos, end, field_number, wire_type + ) # pylint: disable=protected-access + if new_pos == -1: + return pos + self._unknown_fields.append( + (tag_bytes, buffer[pos + len(tag_bytes) : new_pos].tobytes()) + ) + pos = new_pos + else: + _MaybeAddDecoder(cls, field_des) + field_decoder = field_des._decoders[is_packed] + pos = field_decoder( + buffer, new_pos, end, self, field_dict, current_depth + ) + if field_des.containing_oneof: + self._UpdateOneofState(field_des) + return pos + + cls._InternalParse = InternalParse + + +def _AddIsInitializedMethod(message_descriptor, cls): + """Adds the IsInitialized and FindInitializationError methods to the + protocol message class.""" + + required_fields = [field for field in message_descriptor.fields + if field.is_required] + + def IsInitialized(self, errors=None): + """Checks if all required fields of a message are set. + + Args: + errors: A list which, if provided, will be populated with the field + paths of all missing required fields. + + Returns: + True iff the specified message has all required fields set. + """ + + # Performance is critical so we avoid HasField() and ListFields(). + + for field in required_fields: + if (field not in self._fields or + (field.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE and + not self._fields[field]._is_present_in_parent)): + if errors is not None: + errors.extend(self.FindInitializationErrors()) + return False + + for field, value in list(self._fields.items()): # dict can change size! + if field.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE: + if field.is_repeated: + if (field.message_type._is_map_entry): + continue + for element in value: + if not element.IsInitialized(): + if errors is not None: + errors.extend(self.FindInitializationErrors()) + return False + elif value._is_present_in_parent and not value.IsInitialized(): + if errors is not None: + errors.extend(self.FindInitializationErrors()) + return False + + return True + + cls.IsInitialized = IsInitialized + + def FindInitializationErrors(self): + """Finds required fields which are not initialized. + + Returns: + A list of strings. Each string is a path to an uninitialized field from + the top-level message, e.g. "foo.bar[5].baz". + """ + + errors = [] # simplify things + + for field in required_fields: + if not self.HasField(field.name): + errors.append(field.name) + + for field, value in self.ListFields(): + if field.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE: + if field.is_extension: + name = '(%s)' % field.full_name + else: + name = field.name + + if _IsMapField(field): + if _IsMessageMapField(field): + for key in value: + element = value[key] + prefix = '%s[%s].' % (name, key) + sub_errors = element.FindInitializationErrors() + errors += [prefix + error for error in sub_errors] + else: + # ScalarMaps can't have any initialization errors. + pass + elif field.is_repeated: + for i in range(len(value)): + element = value[i] + prefix = '%s[%d].' % (name, i) + sub_errors = element.FindInitializationErrors() + errors += [prefix + error for error in sub_errors] + else: + prefix = name + '.' + sub_errors = value.FindInitializationErrors() + errors += [prefix + error for error in sub_errors] + + return errors + + cls.FindInitializationErrors = FindInitializationErrors + + +def _FullyQualifiedClassName(klass): + module = klass.__module__ + name = getattr(klass, '__qualname__', klass.__name__) + if module in (None, 'builtins', '__builtin__'): + return name + return module + '.' + name + + +def _AddMergeFromMethod(cls): + CPPTYPE_MESSAGE = _FieldDescriptor.CPPTYPE_MESSAGE + + def MergeFrom(self, msg): + if not isinstance(msg, cls): + raise TypeError( + 'Parameter to MergeFrom() must be instance of same class: ' + 'expected %s got %s.' % (_FullyQualifiedClassName(cls), + _FullyQualifiedClassName(msg.__class__))) + + assert msg is not self + self._Modified() + + fields = self._fields + + for field, value in msg._fields.items(): + if field.is_repeated: + field_value = fields.get(field) + if field_value is None: + # Construct a new object to represent this field. + field_value = field._default_constructor(self) + fields[field] = field_value + field_value.MergeFrom(value) + elif field.cpp_type == CPPTYPE_MESSAGE: + if value._is_present_in_parent: + field_value = fields.get(field) + if field_value is None: + # Construct a new object to represent this field. + field_value = field._default_constructor(self) + fields[field] = field_value + field_value.MergeFrom(value) + else: + self._fields[field] = value + if field.containing_oneof: + self._UpdateOneofState(field) + + if msg._unknown_fields: + if not self._unknown_fields: + self._unknown_fields = [] + self._unknown_fields.extend(msg._unknown_fields) + + cls.MergeFrom = MergeFrom + + +def _AddWhichOneofMethod(message_descriptor, cls): + def WhichOneof(self, oneof_name): + """Returns the name of the currently set field inside a oneof, or None.""" + try: + field = message_descriptor.oneofs_by_name[oneof_name] + except KeyError: + raise ValueError( + 'Protocol message has no oneof "%s" field.' % oneof_name) + + nested_field = self._oneofs.get(field, None) + if nested_field is not None and self.HasField(nested_field.name): + return nested_field.name + else: + return None + + cls.WhichOneof = WhichOneof + + +def _Clear(self): + # Clear fields. + self._fields = {} + self._unknown_fields = () + + self._oneofs = {} + self._Modified() + + +def _UnknownFields(self): + raise NotImplementedError('Please use the add-on feaure ' + 'unknown_fields.UnknownFieldSet(message) in ' + 'unknown_fields.py instead.') + + +def _DiscardUnknownFields(self): + self._unknown_fields = [] + for field, value in self.ListFields(): + if field.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE: + if _IsMapField(field): + if _IsMessageMapField(field): + for key in value: + value[key].DiscardUnknownFields() + elif field.is_repeated: + for sub_message in value: + sub_message.DiscardUnknownFields() + else: + value.DiscardUnknownFields() + + +def _SetListener(self, listener): + if listener is None: + self._listener = message_listener_mod.NullMessageListener() + else: + self._listener = listener + + +def _AddMessageMethods(message_descriptor, cls): + """Adds implementations of all Message methods to cls.""" + _AddListFieldsMethod(message_descriptor, cls) + _AddHasFieldMethod(message_descriptor, cls) + _AddClearFieldMethod(message_descriptor, cls) + if message_descriptor.is_extendable: + _AddClearExtensionMethod(cls) + _AddHasExtensionMethod(cls) + _AddEqualsMethod(message_descriptor, cls) + _AddStrMethod(message_descriptor, cls) + _AddReprMethod(message_descriptor, cls) + _AddUnicodeMethod(message_descriptor, cls) + _AddContainsMethod(message_descriptor, cls) + _AddByteSizeMethod(message_descriptor, cls) + _AddSerializeToStringMethod(message_descriptor, cls) + _AddSerializePartialToStringMethod(message_descriptor, cls) + _AddMergeFromStringMethod(message_descriptor, cls) + _AddIsInitializedMethod(message_descriptor, cls) + _AddMergeFromMethod(cls) + _AddWhichOneofMethod(message_descriptor, cls) + # Adds methods which do not depend on cls. + cls.Clear = _Clear + cls.DiscardUnknownFields = _DiscardUnknownFields + cls._SetListener = _SetListener + + +def _AddPrivateHelperMethods(message_descriptor, cls): + """Adds implementation of private helper methods to cls.""" + + def Modified(self): + """Sets the _cached_byte_size_dirty bit to true, + and propagates this to our listener iff this was a state change. + """ + + # Note: Some callers check _cached_byte_size_dirty before calling + # _Modified() as an extra optimization. So, if this method is ever + # changed such that it does stuff even when _cached_byte_size_dirty is + # already true, the callers need to be updated. + if not self._cached_byte_size_dirty: + self._cached_byte_size_dirty = True + self._listener_for_children.dirty = True + self._is_present_in_parent = True + self._listener.Modified() + + def _UpdateOneofState(self, field): + """Sets field as the active field in its containing oneof. + + Will also delete currently active field in the oneof, if it is different + from the argument. Does not mark the message as modified. + """ + other_field = self._oneofs.setdefault(field.containing_oneof, field) + if other_field is not field: + del self._fields[other_field] + self._oneofs[field.containing_oneof] = field + + cls._Modified = Modified + cls.SetInParent = Modified + cls._UpdateOneofState = _UpdateOneofState + + +class _Listener(object): + + """MessageListener implementation that a parent message registers with its + child message. + + In order to support semantics like: + + foo.bar.baz.moo = 23 + assert foo.HasField('bar') + + ...child objects must have back references to their parents. + This helper class is at the heart of this support. + """ + + def __init__(self, parent_message): + """Args: + parent_message: The message whose _Modified() method we should call when + we receive Modified() messages. + """ + # This listener establishes a back reference from a child (contained) object + # to its parent (containing) object. We make this a weak reference to avoid + # creating cyclic garbage when the client finishes with the 'parent' object + # in the tree. + if isinstance(parent_message, weakref.ProxyType): + self._parent_message_weakref = parent_message + else: + self._parent_message_weakref = weakref.proxy(parent_message) + + # As an optimization, we also indicate directly on the listener whether + # or not the parent message is dirty. This way we can avoid traversing + # up the tree in the common case. + self.dirty = False + + def Modified(self): + if self.dirty: + return + try: + # Propagate the signal to our parents iff this is the first field set. + self._parent_message_weakref._Modified() + except ReferenceError: + # We can get here if a client has kept a reference to a child object, + # and is now setting a field on it, but the child's parent has been + # garbage-collected. This is not an error. + pass + + +class _OneofListener(_Listener): + """Special listener implementation for setting composite oneof fields.""" + + def __init__(self, parent_message, field): + """Args: + parent_message: The message whose _Modified() method we should call when + we receive Modified() messages. + field: The descriptor of the field being set in the parent message. + """ + super(_OneofListener, self).__init__(parent_message) + self._field = field + + def Modified(self): + """Also updates the state of the containing oneof in the parent message.""" + try: + self._parent_message_weakref._UpdateOneofState(self._field) + super(_OneofListener, self).Modified() + except ReferenceError: + pass diff --git a/python/user_packages/Python313/site-packages/google/protobuf/internal/testing_refleaks.py b/python/user_packages/Python313/site-packages/google/protobuf/internal/testing_refleaks.py new file mode 100644 index 0000000000000000000000000000000000000000..f94ef2b9d6128b82cc832409843e7d8a57d935c8 --- /dev/null +++ b/python/user_packages/Python313/site-packages/google/protobuf/internal/testing_refleaks.py @@ -0,0 +1,128 @@ +# Protocol Buffers - Google's data interchange format +# Copyright 2008 Google Inc. All rights reserved. +# +# Use of this source code is governed by a BSD-style +# license that can be found in the LICENSE file or at +# https://developers.google.com/open-source/licenses/bsd + +"""A subclass of unittest.TestCase which checks for reference leaks. + +To use: +- Use testing_refleak.BaseTestCase instead of unittest.TestCase +- Configure and compile Python with --with-pydebug + +If sys.gettotalrefcount() is not available (because Python was built without +the Py_DEBUG option), then this module is a no-op and tests will run normally. +""" + +import copyreg +import gc +import sys +import unittest + + +class LocalTestResult(unittest.TestResult): + """A TestResult which forwards events to a parent object, except for Skips.""" + + def __init__(self, parent_result): + unittest.TestResult.__init__(self) + self.parent_result = parent_result + + def addError(self, test, error): + self.parent_result.addError(test, error) + + def addFailure(self, test, error): + self.parent_result.addFailure(test, error) + + def addSkip(self, test, reason): + pass + + def addDuration(self, test, duration): + pass + + +class ReferenceLeakCheckerMixin(object): + """A mixin class for TestCase, which checks reference counts.""" + + NB_RUNS = 3 + + def run(self, result=None): + testMethod = getattr(self, self._testMethodName) + expecting_failure_method = getattr(testMethod, "__unittest_expecting_failure__", False) + expecting_failure_class = getattr(self, "__unittest_expecting_failure__", False) + if expecting_failure_class or expecting_failure_method: + return + + # python_message.py registers all Message classes to some pickle global + # registry, which makes the classes immortal. + # We save a copy of this registry, and reset it before we could references. + self._saved_pickle_registry = copyreg.dispatch_table.copy() + + # Run the test twice, to warm up the instance attributes. + super(ReferenceLeakCheckerMixin, self).run(result=result) + super(ReferenceLeakCheckerMixin, self).run(result=result) + + local_result = LocalTestResult(result) + num_flakes = 0 + refcount_deltas = [] + + # Observe the refcount, then create oldrefcount which actually makes the + # refcount 1 higher than the recorded value immediately + oldrefcount = self._getRefcounts() + while len(refcount_deltas) < self.NB_RUNS: + oldrefcount = self._getRefcounts() + super(ReferenceLeakCheckerMixin, self).run(result=local_result) + newrefcount = self._getRefcounts() + # If the GC was able to collect some objects after the call to run() that + # it could not collect before the call, then the counts won't match. + if newrefcount < oldrefcount and num_flakes < 2: + # This result is (probably) a flake -- garbage collectors aren't very + # predictable, but a lower ending refcount is the opposite of the + # failure we are testing for. If the result is repeatable, then we will + # eventually report it, but not after trying to eliminate it. + num_flakes += 1 + continue + num_flakes = 0 + refcount_deltas.append(newrefcount - oldrefcount) + print(refcount_deltas, self) + + try: + self.assertEqual(refcount_deltas, [0] * self.NB_RUNS) + except Exception: # pylint: disable=broad-except + result.addError(self, sys.exc_info()) + + def _getRefcounts(self): + if hasattr(sys, "_clear_internal_caches"): # Since 3.13 + sys._clear_internal_caches() # pylint: disable=protected-access + else: + sys._clear_type_cache() # pylint: disable=protected-access + copyreg.dispatch_table.clear() + copyreg.dispatch_table.update(self._saved_pickle_registry) + # It is sometimes necessary to gc.collect() multiple times, to ensure + # that all objects can be collected. + gc.collect() + gc.collect() + gc.collect() + return sys.gettotalrefcount() + + +if hasattr(sys, 'gettotalrefcount'): + + def TestCase(test_class): + new_bases = (ReferenceLeakCheckerMixin,) + test_class.__bases__ + new_class = type(test_class)( + test_class.__name__, new_bases, dict(test_class.__dict__)) + return new_class + SkipReferenceLeakChecker = unittest.skip + +else: + # When PyDEBUG is not enabled, run the tests normally. + + def TestCase(test_class): + return test_class + + def SkipReferenceLeakChecker(reason): + del reason # Don't skip, so don't need a reason. + def Same(func): + return func + return Same diff --git a/python/user_packages/Python313/site-packages/google/protobuf/internal/type_checkers.py b/python/user_packages/Python313/site-packages/google/protobuf/internal/type_checkers.py new file mode 100644 index 0000000000000000000000000000000000000000..17e814ed9738123af4ece0676b44696479d4833b --- /dev/null +++ b/python/user_packages/Python313/site-packages/google/protobuf/internal/type_checkers.py @@ -0,0 +1,455 @@ +# Protocol Buffers - Google's data interchange format +# Copyright 2008 Google Inc. All rights reserved. +# +# Use of this source code is governed by a BSD-style +# license that can be found in the LICENSE file or at +# https://developers.google.com/open-source/licenses/bsd + +"""Provides type checking routines. + +This module defines type checking utilities in the forms of dictionaries: + +VALUE_CHECKERS: A dictionary of field types and a value validation object. +TYPE_TO_BYTE_SIZE_FN: A dictionary with field types and a size computing + function. +TYPE_TO_SERIALIZE_METHOD: A dictionary with field types and serialization + function. +FIELD_TYPE_TO_WIRE_TYPE: A dictionary with field typed and their + corresponding wire types. +TYPE_TO_DESERIALIZE_METHOD: A dictionary with field types and deserialization + function. +""" + +__author__ = 'robinson@google.com (Will Robinson)' + +import numbers +import struct +import warnings + +from google.protobuf import descriptor +from google.protobuf.internal import decoder +from google.protobuf.internal import encoder +from google.protobuf.internal import wire_format + +_FieldDescriptor = descriptor.FieldDescriptor +# TODO: Remove this warning count after 34.0 +# Assign bool to int/enum warnings will print 100 times at most which should +# be enough for users to notice and do not cause timeout. +_BoolWarningCount = 100 + +def TruncateToFourByteFloat(original): + return struct.unpack(' 0: + _BoolWarningCount -= 1 + message = ( + '%.1024r has type %s, but expected one of: %s. This warning ' + 'will turn into error in 7.34.0, please fix it before that.' + % ( + proposed_value, + type(proposed_value), + (int,), + ) + ) + # TODO: Raise errors in 2026 Q1 release + warnings.warn(message) + + if not hasattr(proposed_value, '__index__') or ( + type(proposed_value).__module__ == 'numpy' and + type(proposed_value).__name__ == 'ndarray'): + message = ('%.1024r has type %s, but expected one of: %s' % + (proposed_value, type(proposed_value), (int,))) + raise TypeError(message) + + if not self._MIN <= int(proposed_value) <= self._MAX: + raise ValueError('Value out of range: %d' % proposed_value) + # We force all values to int to make alternate implementations where the + # distinction is more significant (e.g. the C++ implementation) simpler. + proposed_value = int(proposed_value) + return proposed_value + + def DefaultValue(self): + return 0 + + +class EnumValueChecker(object): + + """Checker used for enum fields. Performs type-check and range check.""" + + def __init__(self, enum_type): + self._enum_type = enum_type + + def CheckValue(self, proposed_value): + global _BoolWarningCount + if type(proposed_value) == bool and _BoolWarningCount > 0: + _BoolWarningCount -= 1 + message = ( + '%.1024r has type %s, but expected one of: %s. This warning ' + 'will turn into error in 7.34.0, please fix it before that.' + % ( + proposed_value, + type(proposed_value), + (int,), + ) + ) + # TODO: Raise errors in 2026 Q1 release + warnings.warn(message) + if not isinstance(proposed_value, numbers.Integral): + message = ('%.1024r has type %s, but expected one of: %s' % + (proposed_value, type(proposed_value), (int,))) + raise TypeError(message) + if int(proposed_value) not in self._enum_type.values_by_number: + raise ValueError('Unknown enum value: %d' % proposed_value) + return proposed_value + + def DefaultValue(self): + return self._enum_type.values[0].number + + +class UnicodeValueChecker(object): + + """Checker used for string fields. + + Always returns a unicode value, even if the input is of type str. + """ + + def CheckValue(self, proposed_value): + if not isinstance(proposed_value, (bytes, str)): + message = ('%.1024r has type %s, but expected one of: %s' % + (proposed_value, type(proposed_value), (bytes, str))) + raise TypeError(message) + + # If the value is of type 'bytes' make sure that it is valid UTF-8 data. + if isinstance(proposed_value, bytes): + try: + proposed_value = proposed_value.decode('utf-8') + except UnicodeDecodeError: + raise ValueError('%.1024r has type bytes, but isn\'t valid UTF-8 ' + 'encoding. Non-UTF-8 strings must be converted to ' + 'unicode objects before being added.' % + (proposed_value)) + else: + try: + proposed_value.encode('utf8') + except UnicodeEncodeError: + raise ValueError('%.1024r isn\'t a valid unicode string and ' + 'can\'t be encoded in UTF-8.'% + (proposed_value)) + + return proposed_value + + def DefaultValue(self): + return u"" + + +class Int32ValueChecker(IntValueChecker): + # We're sure to use ints instead of longs here since comparison may be more + # efficient. + _MIN = -2147483648 + _MAX = 2147483647 + + +class Uint32ValueChecker(IntValueChecker): + _MIN = 0 + _MAX = (1 << 32) - 1 + + +class Int64ValueChecker(IntValueChecker): + _MIN = -(1 << 63) + _MAX = (1 << 63) - 1 + + +class Uint64ValueChecker(IntValueChecker): + _MIN = 0 + _MAX = (1 << 64) - 1 + + +# The max 4 bytes float is about 3.4028234663852886e+38 +_FLOAT_MAX = float.fromhex('0x1.fffffep+127') +_FLOAT_MIN = -_FLOAT_MAX +_MAX_FLOAT_AS_DOUBLE_ROUNDED = 3.4028235677973366e38 +_INF = float('inf') +_NEG_INF = float('-inf') + + +class DoubleValueChecker(object): + """Checker used for double fields. + + Performs type-check and range check. + """ + + def CheckValue(self, proposed_value): + """Check and convert proposed_value to float.""" + if (not hasattr(proposed_value, '__float__') and + not hasattr(proposed_value, '__index__')) or ( + type(proposed_value).__module__ == 'numpy' and + type(proposed_value).__name__ == 'ndarray'): + message = ('%.1024r has type %s, but expected one of: int, float' % + (proposed_value, type(proposed_value))) + raise TypeError(message) + return float(proposed_value) + + def DefaultValue(self): + return 0.0 + + +class FloatValueChecker(DoubleValueChecker): + """Checker used for float fields. + + Performs type-check and range check. + + Values exceeding a 32-bit float will be converted to inf/-inf. + """ + + def CheckValue(self, proposed_value): + """Check and convert proposed_value to float.""" + converted_value = super().CheckValue(proposed_value) + # This inf rounding matches the C++ proto SafeDoubleToFloat logic. + if converted_value > _FLOAT_MAX: + if converted_value <= _MAX_FLOAT_AS_DOUBLE_ROUNDED: + return _FLOAT_MAX + return _INF + if converted_value < _FLOAT_MIN: + if converted_value >= -_MAX_FLOAT_AS_DOUBLE_ROUNDED: + return _FLOAT_MIN + return _NEG_INF + + return TruncateToFourByteFloat(converted_value) + +# Type-checkers for all scalar CPPTYPEs. +_VALUE_CHECKERS = { + _FieldDescriptor.CPPTYPE_INT32: Int32ValueChecker(), + _FieldDescriptor.CPPTYPE_INT64: Int64ValueChecker(), + _FieldDescriptor.CPPTYPE_UINT32: Uint32ValueChecker(), + _FieldDescriptor.CPPTYPE_UINT64: Uint64ValueChecker(), + _FieldDescriptor.CPPTYPE_DOUBLE: DoubleValueChecker(), + _FieldDescriptor.CPPTYPE_FLOAT: FloatValueChecker(), + _FieldDescriptor.CPPTYPE_BOOL: BoolValueChecker(), + _FieldDescriptor.CPPTYPE_STRING: TypeCheckerWithDefault(b'', bytes), +} + + +# Map from field type to a function F, such that F(field_num, value) +# gives the total byte size for a value of the given type. This +# byte size includes tag information and any other additional space +# associated with serializing "value". +TYPE_TO_BYTE_SIZE_FN = { + _FieldDescriptor.TYPE_DOUBLE: wire_format.DoubleByteSize, + _FieldDescriptor.TYPE_FLOAT: wire_format.FloatByteSize, + _FieldDescriptor.TYPE_INT64: wire_format.Int64ByteSize, + _FieldDescriptor.TYPE_UINT64: wire_format.UInt64ByteSize, + _FieldDescriptor.TYPE_INT32: wire_format.Int32ByteSize, + _FieldDescriptor.TYPE_FIXED64: wire_format.Fixed64ByteSize, + _FieldDescriptor.TYPE_FIXED32: wire_format.Fixed32ByteSize, + _FieldDescriptor.TYPE_BOOL: wire_format.BoolByteSize, + _FieldDescriptor.TYPE_STRING: wire_format.StringByteSize, + _FieldDescriptor.TYPE_GROUP: wire_format.GroupByteSize, + _FieldDescriptor.TYPE_MESSAGE: wire_format.MessageByteSize, + _FieldDescriptor.TYPE_BYTES: wire_format.BytesByteSize, + _FieldDescriptor.TYPE_UINT32: wire_format.UInt32ByteSize, + _FieldDescriptor.TYPE_ENUM: wire_format.EnumByteSize, + _FieldDescriptor.TYPE_SFIXED32: wire_format.SFixed32ByteSize, + _FieldDescriptor.TYPE_SFIXED64: wire_format.SFixed64ByteSize, + _FieldDescriptor.TYPE_SINT32: wire_format.SInt32ByteSize, + _FieldDescriptor.TYPE_SINT64: wire_format.SInt64ByteSize + } + + +# Maps from field types to encoder constructors. +TYPE_TO_ENCODER = { + _FieldDescriptor.TYPE_DOUBLE: encoder.DoubleEncoder, + _FieldDescriptor.TYPE_FLOAT: encoder.FloatEncoder, + _FieldDescriptor.TYPE_INT64: encoder.Int64Encoder, + _FieldDescriptor.TYPE_UINT64: encoder.UInt64Encoder, + _FieldDescriptor.TYPE_INT32: encoder.Int32Encoder, + _FieldDescriptor.TYPE_FIXED64: encoder.Fixed64Encoder, + _FieldDescriptor.TYPE_FIXED32: encoder.Fixed32Encoder, + _FieldDescriptor.TYPE_BOOL: encoder.BoolEncoder, + _FieldDescriptor.TYPE_STRING: encoder.StringEncoder, + _FieldDescriptor.TYPE_GROUP: encoder.GroupEncoder, + _FieldDescriptor.TYPE_MESSAGE: encoder.MessageEncoder, + _FieldDescriptor.TYPE_BYTES: encoder.BytesEncoder, + _FieldDescriptor.TYPE_UINT32: encoder.UInt32Encoder, + _FieldDescriptor.TYPE_ENUM: encoder.EnumEncoder, + _FieldDescriptor.TYPE_SFIXED32: encoder.SFixed32Encoder, + _FieldDescriptor.TYPE_SFIXED64: encoder.SFixed64Encoder, + _FieldDescriptor.TYPE_SINT32: encoder.SInt32Encoder, + _FieldDescriptor.TYPE_SINT64: encoder.SInt64Encoder, + } + + +# Maps from field types to sizer constructors. +TYPE_TO_SIZER = { + _FieldDescriptor.TYPE_DOUBLE: encoder.DoubleSizer, + _FieldDescriptor.TYPE_FLOAT: encoder.FloatSizer, + _FieldDescriptor.TYPE_INT64: encoder.Int64Sizer, + _FieldDescriptor.TYPE_UINT64: encoder.UInt64Sizer, + _FieldDescriptor.TYPE_INT32: encoder.Int32Sizer, + _FieldDescriptor.TYPE_FIXED64: encoder.Fixed64Sizer, + _FieldDescriptor.TYPE_FIXED32: encoder.Fixed32Sizer, + _FieldDescriptor.TYPE_BOOL: encoder.BoolSizer, + _FieldDescriptor.TYPE_STRING: encoder.StringSizer, + _FieldDescriptor.TYPE_GROUP: encoder.GroupSizer, + _FieldDescriptor.TYPE_MESSAGE: encoder.MessageSizer, + _FieldDescriptor.TYPE_BYTES: encoder.BytesSizer, + _FieldDescriptor.TYPE_UINT32: encoder.UInt32Sizer, + _FieldDescriptor.TYPE_ENUM: encoder.EnumSizer, + _FieldDescriptor.TYPE_SFIXED32: encoder.SFixed32Sizer, + _FieldDescriptor.TYPE_SFIXED64: encoder.SFixed64Sizer, + _FieldDescriptor.TYPE_SINT32: encoder.SInt32Sizer, + _FieldDescriptor.TYPE_SINT64: encoder.SInt64Sizer, + } + + +# Maps from field type to a decoder constructor. +TYPE_TO_DECODER = { + _FieldDescriptor.TYPE_DOUBLE: decoder.DoubleDecoder, + _FieldDescriptor.TYPE_FLOAT: decoder.FloatDecoder, + _FieldDescriptor.TYPE_INT64: decoder.Int64Decoder, + _FieldDescriptor.TYPE_UINT64: decoder.UInt64Decoder, + _FieldDescriptor.TYPE_INT32: decoder.Int32Decoder, + _FieldDescriptor.TYPE_FIXED64: decoder.Fixed64Decoder, + _FieldDescriptor.TYPE_FIXED32: decoder.Fixed32Decoder, + _FieldDescriptor.TYPE_BOOL: decoder.BoolDecoder, + _FieldDescriptor.TYPE_STRING: decoder.StringDecoder, + _FieldDescriptor.TYPE_GROUP: decoder.GroupDecoder, + _FieldDescriptor.TYPE_MESSAGE: decoder.MessageDecoder, + _FieldDescriptor.TYPE_BYTES: decoder.BytesDecoder, + _FieldDescriptor.TYPE_UINT32: decoder.UInt32Decoder, + _FieldDescriptor.TYPE_ENUM: decoder.EnumDecoder, + _FieldDescriptor.TYPE_SFIXED32: decoder.SFixed32Decoder, + _FieldDescriptor.TYPE_SFIXED64: decoder.SFixed64Decoder, + _FieldDescriptor.TYPE_SINT32: decoder.SInt32Decoder, + _FieldDescriptor.TYPE_SINT64: decoder.SInt64Decoder, + } + +# Maps from field type to expected wiretype. +FIELD_TYPE_TO_WIRE_TYPE = { + _FieldDescriptor.TYPE_DOUBLE: wire_format.WIRETYPE_FIXED64, + _FieldDescriptor.TYPE_FLOAT: wire_format.WIRETYPE_FIXED32, + _FieldDescriptor.TYPE_INT64: wire_format.WIRETYPE_VARINT, + _FieldDescriptor.TYPE_UINT64: wire_format.WIRETYPE_VARINT, + _FieldDescriptor.TYPE_INT32: wire_format.WIRETYPE_VARINT, + _FieldDescriptor.TYPE_FIXED64: wire_format.WIRETYPE_FIXED64, + _FieldDescriptor.TYPE_FIXED32: wire_format.WIRETYPE_FIXED32, + _FieldDescriptor.TYPE_BOOL: wire_format.WIRETYPE_VARINT, + _FieldDescriptor.TYPE_STRING: + wire_format.WIRETYPE_LENGTH_DELIMITED, + _FieldDescriptor.TYPE_GROUP: wire_format.WIRETYPE_START_GROUP, + _FieldDescriptor.TYPE_MESSAGE: + wire_format.WIRETYPE_LENGTH_DELIMITED, + _FieldDescriptor.TYPE_BYTES: + wire_format.WIRETYPE_LENGTH_DELIMITED, + _FieldDescriptor.TYPE_UINT32: wire_format.WIRETYPE_VARINT, + _FieldDescriptor.TYPE_ENUM: wire_format.WIRETYPE_VARINT, + _FieldDescriptor.TYPE_SFIXED32: wire_format.WIRETYPE_FIXED32, + _FieldDescriptor.TYPE_SFIXED64: wire_format.WIRETYPE_FIXED64, + _FieldDescriptor.TYPE_SINT32: wire_format.WIRETYPE_VARINT, + _FieldDescriptor.TYPE_SINT64: wire_format.WIRETYPE_VARINT, + } diff --git a/python/user_packages/Python313/site-packages/google/protobuf/internal/well_known_types.py b/python/user_packages/Python313/site-packages/google/protobuf/internal/well_known_types.py new file mode 100644 index 0000000000000000000000000000000000000000..32b625a3022e4f30b820b1d24ac15ffefb9b9c93 --- /dev/null +++ b/python/user_packages/Python313/site-packages/google/protobuf/internal/well_known_types.py @@ -0,0 +1,695 @@ +# Protocol Buffers - Google's data interchange format +# Copyright 2008 Google Inc. All rights reserved. +# +# Use of this source code is governed by a BSD-style +# license that can be found in the LICENSE file or at +# https://developers.google.com/open-source/licenses/bsd + +"""Contains well known classes. + +This files defines well known classes which need extra maintenance including: + - Any + - Duration + - FieldMask + - Struct + - Timestamp +""" + +__author__ = 'jieluo@google.com (Jie Luo)' + +import calendar +import collections.abc +import datetime +from typing import Union +import warnings +from google.protobuf.internal import field_mask + +FieldMask = field_mask.FieldMask + +_TIMESTAMPFORMAT = '%Y-%m-%dT%H:%M:%S' +_NANOS_PER_SECOND = 1000000000 +_NANOS_PER_MILLISECOND = 1000000 +_NANOS_PER_MICROSECOND = 1000 +_MILLIS_PER_SECOND = 1000 +_MICROS_PER_SECOND = 1000000 +_SECONDS_PER_DAY = 24 * 3600 +_DURATION_SECONDS_MAX = 315576000000 +_TIMESTAMP_SECONDS_MIN = -62135596800 +_TIMESTAMP_SECONDS_MAX = 253402300799 + +_EPOCH_DATETIME_NAIVE = datetime.datetime(1970, 1, 1, tzinfo=None) +_EPOCH_DATETIME_AWARE = _EPOCH_DATETIME_NAIVE.replace( + tzinfo=datetime.timezone.utc +) + + +class Any(object): + """Class for Any Message type.""" + + __slots__ = () + + def Pack( + self, msg, type_url_prefix='type.googleapis.com/', deterministic=None + ): + """Packs the specified message into current Any message.""" + if len(type_url_prefix) < 1 or type_url_prefix[-1] != '/': + self.type_url = '%s/%s' % (type_url_prefix, msg.DESCRIPTOR.full_name) + else: + self.type_url = '%s%s' % (type_url_prefix, msg.DESCRIPTOR.full_name) + self.value = msg.SerializeToString(deterministic=deterministic) + + def Unpack(self, msg): + """Unpacks the current Any message into specified message.""" + descriptor = msg.DESCRIPTOR + if not self.Is(descriptor): + return False + msg.ParseFromString(self.value) + return True + + def TypeName(self): + """Returns the protobuf type name of the inner message.""" + # Only last part is to be used: b/25630112 + return self.type_url.rpartition('/')[2] + + def Is(self, descriptor): + """Checks if this Any represents the given protobuf type.""" + return '/' in self.type_url and self.TypeName() == descriptor.full_name + + +class Timestamp(object): + """Class for Timestamp message type.""" + + __slots__ = () + + def ToJsonString(self): + """Converts Timestamp to RFC 3339 date string format. + + Returns: + A string converted from timestamp. The string is always Z-normalized + and uses 3, 6 or 9 fractional digits as required to represent the + exact time. Example of the return format: '1972-01-01T10:00:20.021Z' + """ + _CheckTimestampValid(self.seconds, self.nanos) + nanos = self.nanos + seconds = self.seconds % _SECONDS_PER_DAY + days = (self.seconds - seconds) // _SECONDS_PER_DAY + dt = datetime.datetime(1970, 1, 1) + datetime.timedelta(days, seconds) + + result = dt.isoformat() + if (nanos % 1e9) == 0: + # If there are 0 fractional digits, the fractional + # point '.' should be omitted when serializing. + return result + 'Z' + if (nanos % 1e6) == 0: + # Serialize 3 fractional digits. + return result + '.%03dZ' % (nanos / 1e6) + if (nanos % 1e3) == 0: + # Serialize 6 fractional digits. + return result + '.%06dZ' % (nanos / 1e3) + # Serialize 9 fractional digits. + return result + '.%09dZ' % nanos + + def FromJsonString(self, value): + """Parse a RFC 3339 date string format to Timestamp. + + Args: + value: A date string. Any fractional digits (or none) and any offset are + accepted as long as they fit into nano-seconds precision. Example of + accepted format: '1972-01-01T10:00:20.021-05:00' + + Raises: + ValueError: On parsing problems. + """ + if not isinstance(value, str): + raise ValueError('Timestamp JSON value not a string: {!r}'.format(value)) + timezone_offset = value.find('Z') + if timezone_offset == -1: + timezone_offset = value.find('+') + if timezone_offset == -1: + timezone_offset = value.rfind('-') + if timezone_offset == -1: + raise ValueError( + 'Failed to parse timestamp: missing valid timezone offset.' + ) + time_value = value[0:timezone_offset] + # Parse datetime and nanos. + point_position = time_value.find('.') + if point_position == -1: + second_value = time_value + nano_value = '' + else: + second_value = time_value[:point_position] + nano_value = time_value[point_position + 1 :] + if 't' in second_value: + raise ValueError( + "time data '{0}' does not match format '%Y-%m-%dT%H:%M:%S', " + "lowercase 't' is not accepted".format(second_value) + ) + date_object = datetime.datetime.strptime(second_value, _TIMESTAMPFORMAT) + td = date_object - datetime.datetime(1970, 1, 1) + seconds = td.seconds + td.days * _SECONDS_PER_DAY + if len(nano_value) > 9: + raise ValueError( + 'Failed to parse Timestamp: nanos {0} more than ' + '9 fractional digits.'.format(nano_value) + ) + if nano_value: + nanos = round(float('0.' + nano_value) * 1e9) + else: + nanos = 0 + # Parse timezone offsets. + if value[timezone_offset] == 'Z': + if len(value) != timezone_offset + 1: + raise ValueError( + 'Failed to parse timestamp: invalid trailing data {0}.'.format( + value + ) + ) + else: + timezone = value[timezone_offset:] + pos = timezone.find(':') + if pos == -1: + raise ValueError('Invalid timezone offset value: {0}.'.format(timezone)) + if timezone[0] == '+': + seconds -= (int(timezone[1:pos]) * 60 + int(timezone[pos + 1 :])) * 60 + else: + seconds += (int(timezone[1:pos]) * 60 + int(timezone[pos + 1 :])) * 60 + # Set seconds and nanos + _CheckTimestampValid(seconds, nanos) + self.seconds = int(seconds) + self.nanos = int(nanos) + + def GetCurrentTime(self): + """Get the current UTC into Timestamp.""" + self.FromDatetime(datetime.datetime.now(tz=datetime.timezone.utc)) + + def ToNanoseconds(self): + """Converts Timestamp to nanoseconds since epoch.""" + _CheckTimestampValid(self.seconds, self.nanos) + return self.seconds * _NANOS_PER_SECOND + self.nanos + + def ToMicroseconds(self): + """Converts Timestamp to microseconds since epoch.""" + _CheckTimestampValid(self.seconds, self.nanos) + return ( + self.seconds * _MICROS_PER_SECOND + self.nanos // _NANOS_PER_MICROSECOND + ) + + def ToMilliseconds(self): + """Converts Timestamp to milliseconds since epoch.""" + _CheckTimestampValid(self.seconds, self.nanos) + return ( + self.seconds * _MILLIS_PER_SECOND + self.nanos // _NANOS_PER_MILLISECOND + ) + + def ToSeconds(self): + """Converts Timestamp to seconds since epoch.""" + _CheckTimestampValid(self.seconds, self.nanos) + return self.seconds + + def FromNanoseconds(self, nanos): + """Converts nanoseconds since epoch to Timestamp.""" + seconds = nanos // _NANOS_PER_SECOND + nanos = nanos % _NANOS_PER_SECOND + _CheckTimestampValid(seconds, nanos) + self.seconds = seconds + self.nanos = nanos + + def FromMicroseconds(self, micros): + """Converts microseconds since epoch to Timestamp.""" + seconds = micros // _MICROS_PER_SECOND + nanos = (micros % _MICROS_PER_SECOND) * _NANOS_PER_MICROSECOND + _CheckTimestampValid(seconds, nanos) + self.seconds = seconds + self.nanos = nanos + + def FromMilliseconds(self, millis): + """Converts milliseconds since epoch to Timestamp.""" + seconds = millis // _MILLIS_PER_SECOND + nanos = (millis % _MILLIS_PER_SECOND) * _NANOS_PER_MILLISECOND + _CheckTimestampValid(seconds, nanos) + self.seconds = seconds + self.nanos = nanos + + def FromSeconds(self, seconds): + """Converts seconds since epoch to Timestamp.""" + _CheckTimestampValid(seconds, 0) + self.seconds = seconds + self.nanos = 0 + + def ToDatetime(self, tzinfo=None): + """Converts Timestamp to a datetime. + + Args: + tzinfo: A datetime.tzinfo subclass; defaults to None. + + Returns: + If tzinfo is None, returns a timezone-naive UTC datetime (with no timezone + information, i.e. not aware that it's UTC). + + Otherwise, returns a timezone-aware datetime in the input timezone. + """ + # Using datetime.fromtimestamp for this would avoid constructing an extra + # timedelta object and possibly an extra datetime. Unfortunately, that has + # the disadvantage of not handling the full precision (on all platforms, see + # https://github.com/python/cpython/issues/109849) or full range (on some + # platforms, see https://github.com/python/cpython/issues/110042) of + # datetime. + _CheckTimestampValid(self.seconds, self.nanos) + delta = datetime.timedelta( + seconds=self.seconds, + microseconds=_RoundTowardZero(self.nanos, _NANOS_PER_MICROSECOND), + ) + if tzinfo is None: + return _EPOCH_DATETIME_NAIVE + delta + else: + # Note the tz conversion has to come after the timedelta arithmetic. + return (_EPOCH_DATETIME_AWARE + delta).astimezone(tzinfo) + + def FromDatetime(self, dt): + """Converts datetime to Timestamp. + + Args: + dt: A datetime. If it's timezone-naive, it's assumed to be in UTC. + """ + # Using this guide: http://wiki.python.org/moin/WorkingWithTime + # And this conversion guide: http://docs.python.org/library/time.html + + # Turn the date parameter into a tuple (struct_time) that can then be + # manipulated into a long value of seconds. During the conversion from + # struct_time to long, the source date in UTC, and so it follows that the + # correct transformation is calendar.timegm() + try: + seconds = calendar.timegm(dt.utctimetuple()) + nanos = dt.microsecond * _NANOS_PER_MICROSECOND + except AttributeError as e: + raise AttributeError( + 'Fail to convert to Timestamp. Expected a datetime like ' + 'object got {0} : {1}'.format(type(dt).__name__, e) + ) from e + _CheckTimestampValid(seconds, nanos) + self.seconds = seconds + self.nanos = nanos + + def _internal_assign(self, dt): + self.FromDatetime(dt) + + def __add__(self, value) -> datetime.datetime: + if isinstance(value, Duration): + return self.ToDatetime() + value.ToTimedelta() + return self.ToDatetime() + value + + __radd__ = __add__ + + def __sub__(self, value) -> Union[datetime.datetime, datetime.timedelta]: + if isinstance(value, Timestamp): + return self.ToDatetime() - value.ToDatetime() + elif isinstance(value, Duration): + return self.ToDatetime() - value.ToTimedelta() + return self.ToDatetime() - value + + def __rsub__(self, dt) -> datetime.timedelta: + return dt - self.ToDatetime() + + +def _CheckTimestampValid(seconds, nanos): + if seconds < _TIMESTAMP_SECONDS_MIN or seconds > _TIMESTAMP_SECONDS_MAX: + raise ValueError( + 'Timestamp is not valid: Seconds {0} must be in range ' + '[-62135596800, 253402300799].'.format(seconds)) + if nanos < 0 or nanos >= _NANOS_PER_SECOND: + raise ValueError( + 'Timestamp is not valid: Nanos {} must be in a range ' + '[0, 999999].'.format(nanos) + ) + + +class Duration(object): + """Class for Duration message type.""" + + __slots__ = () + + def ToJsonString(self): + """Converts Duration to string format. + + Returns: + A string converted from self. The string format will contains + 3, 6, or 9 fractional digits depending on the precision required to + represent the exact Duration value. For example: "1s", "1.010s", + "1.000000100s", "-3.100s" + """ + _CheckDurationValid(self.seconds, self.nanos) + if self.seconds < 0 or self.nanos < 0: + result = '-' + seconds = -self.seconds + int((0 - self.nanos) // 1e9) + nanos = (0 - self.nanos) % 1e9 + else: + result = '' + seconds = self.seconds + int(self.nanos // 1e9) + nanos = self.nanos % 1e9 + result += '%d' % seconds + if (nanos % 1e9) == 0: + # If there are 0 fractional digits, the fractional + # point '.' should be omitted when serializing. + return result + 's' + if (nanos % 1e6) == 0: + # Serialize 3 fractional digits. + return result + '.%03ds' % (nanos / 1e6) + if (nanos % 1e3) == 0: + # Serialize 6 fractional digits. + return result + '.%06ds' % (nanos / 1e3) + # Serialize 9 fractional digits. + return result + '.%09ds' % nanos + + def FromJsonString(self, value): + """Converts a string to Duration. + + Args: + value: A string to be converted. The string must end with 's'. Any + fractional digits (or none) are accepted as long as they fit into + precision. For example: "1s", "1.01s", "1.0000001s", "-3.100s + + Raises: + ValueError: On parsing problems. + """ + if not isinstance(value, str): + raise ValueError('Duration JSON value not a string: {!r}'.format(value)) + if len(value) < 1 or value[-1] != 's': + raise ValueError('Duration must end with letter "s": {0}.'.format(value)) + try: + pos = value.find('.') + if pos == -1: + seconds = int(value[:-1]) + nanos = 0 + else: + seconds = int(value[:pos]) + if value[0] == '-': + nanos = int(round(float('-0{0}'.format(value[pos:-1])) * 1e9)) + else: + nanos = int(round(float('0{0}'.format(value[pos:-1])) * 1e9)) + _CheckDurationValid(seconds, nanos) + self.seconds = seconds + self.nanos = nanos + except ValueError as e: + raise ValueError("Couldn't parse duration: {0} : {1}.".format(value, e)) + + def ToNanoseconds(self): + """Converts a Duration to nanoseconds.""" + return self.seconds * _NANOS_PER_SECOND + self.nanos + + def ToMicroseconds(self): + """Converts a Duration to microseconds.""" + micros = _RoundTowardZero(self.nanos, _NANOS_PER_MICROSECOND) + return self.seconds * _MICROS_PER_SECOND + micros + + def ToMilliseconds(self): + """Converts a Duration to milliseconds.""" + millis = _RoundTowardZero(self.nanos, _NANOS_PER_MILLISECOND) + return self.seconds * _MILLIS_PER_SECOND + millis + + def ToSeconds(self): + """Converts a Duration to seconds.""" + return self.seconds + + def FromNanoseconds(self, nanos): + """Converts nanoseconds to Duration.""" + self._NormalizeDuration( + nanos // _NANOS_PER_SECOND, nanos % _NANOS_PER_SECOND + ) + + def FromMicroseconds(self, micros): + """Converts microseconds to Duration.""" + self._NormalizeDuration( + micros // _MICROS_PER_SECOND, + (micros % _MICROS_PER_SECOND) * _NANOS_PER_MICROSECOND, + ) + + def FromMilliseconds(self, millis): + """Converts milliseconds to Duration.""" + self._NormalizeDuration( + millis // _MILLIS_PER_SECOND, + (millis % _MILLIS_PER_SECOND) * _NANOS_PER_MILLISECOND, + ) + + def FromSeconds(self, seconds): + """Converts seconds to Duration.""" + self.seconds = seconds + self.nanos = 0 + + def ToTimedelta(self) -> datetime.timedelta: + """Converts Duration to timedelta.""" + return datetime.timedelta( + seconds=self.seconds, + microseconds=_RoundTowardZero(self.nanos, _NANOS_PER_MICROSECOND), + ) + + def FromTimedelta(self, td): + """Converts timedelta to Duration.""" + try: + self._NormalizeDuration( + td.seconds + td.days * _SECONDS_PER_DAY, + td.microseconds * _NANOS_PER_MICROSECOND, + ) + except AttributeError as e: + raise AttributeError( + 'Fail to convert to Duration. Expected a timedelta like ' + 'object got {0}: {1}'.format(type(td).__name__, e) + ) from e + + def _internal_assign(self, td): + self.FromTimedelta(td) + + def _NormalizeDuration(self, seconds, nanos): + """Set Duration by seconds and nanos.""" + # Force nanos to be negative if the duration is negative. + if seconds < 0 and nanos > 0: + seconds += 1 + nanos -= _NANOS_PER_SECOND + self.seconds = seconds + self.nanos = nanos + + def __add__(self, value) -> Union[datetime.datetime, datetime.timedelta]: + if isinstance(value, Timestamp): + return self.ToTimedelta() + value.ToDatetime() + return self.ToTimedelta() + value + + __radd__ = __add__ + + def __sub__(self, value) -> datetime.timedelta: + return self.ToTimedelta() - value + + def __rsub__(self, value) -> Union[datetime.datetime, datetime.timedelta]: + return value - self.ToTimedelta() + + +def _CheckDurationValid(seconds, nanos): + if seconds < -_DURATION_SECONDS_MAX or seconds > _DURATION_SECONDS_MAX: + raise ValueError( + 'Duration is not valid: Seconds {0} must be in range ' + '[-315576000000, 315576000000].'.format(seconds) + ) + if nanos <= -_NANOS_PER_SECOND or nanos >= _NANOS_PER_SECOND: + raise ValueError( + 'Duration is not valid: Nanos {0} must be in range ' + '[-999999999, 999999999].'.format(nanos) + ) + if (nanos < 0 and seconds > 0) or (nanos > 0 and seconds < 0): + raise ValueError('Duration is not valid: Sign mismatch.') + + +def _RoundTowardZero(value, divider): + """Truncates the remainder part after division.""" + # For some languages, the sign of the remainder is implementation + # dependent if any of the operands is negative. Here we enforce + # "rounded toward zero" semantics. For example, for (-5) / 2 an + # implementation may give -3 as the result with the remainder being + # 1. This function ensures we always return -2 (closer to zero). + result = value // divider + remainder = value % divider + if result < 0 and remainder > 0: + return result + 1 + else: + return result + + +def _SetStructValue(struct_value, value): + if value is None: + struct_value.null_value = 0 + elif isinstance(value, bool): + # Note: this check must come before the number check because in Python + # True and False are also considered numbers. + struct_value.bool_value = value + elif isinstance(value, str): + struct_value.string_value = value + elif isinstance(value, (int, float)): + struct_value.number_value = value + elif isinstance(value, (dict, Struct)): + struct_value.struct_value.Clear() + struct_value.struct_value.update(value) + elif isinstance(value, (list, tuple, ListValue)): + struct_value.list_value.Clear() + struct_value.list_value.extend(value) + else: + raise ValueError('Unexpected type') + + +def _GetStructValue(struct_value): + which = struct_value.WhichOneof('kind') + if which == 'struct_value': + return struct_value.struct_value + elif which == 'null_value': + return None + elif which == 'number_value': + return struct_value.number_value + elif which == 'string_value': + return struct_value.string_value + elif which == 'bool_value': + return struct_value.bool_value + elif which == 'list_value': + return struct_value.list_value + elif which is None: + raise ValueError('Value not set') + + +class Struct(object): + """Class for Struct message type.""" + + __slots__ = () + + def __getitem__(self, key): + return _GetStructValue(self.fields[key]) + + def __setitem__(self, key, value): + _SetStructValue(self.fields[key], value) + + def __delitem__(self, key): + del self.fields[key] + + def __len__(self): + return len(self.fields) + + def __iter__(self): + return iter(self.fields) + + def _internal_assign(self, dictionary): + self.Clear() + self.update(dictionary) + + def _internal_compare(self, other): + size = len(self) + if size != len(other): + return False + for key, value in self.items(): + if key not in other: + return False + if isinstance(other[key], (dict, list)): + if not value._internal_compare(other[key]): + return False + elif value != other[key]: + return False + return True + + def keys(self): # pylint: disable=invalid-name + return self.fields.keys() + + def values(self): # pylint: disable=invalid-name + return [self[key] for key in self] + + def items(self): # pylint: disable=invalid-name + return [(key, self[key]) for key in self] + + def get_or_create_list(self, key): + """Returns a list for this key, creating if it didn't exist already.""" + if not self.fields[key].HasField('list_value'): + # Clear will mark list_value modified which will indeed create a list. + self.fields[key].list_value.Clear() + return self.fields[key].list_value + + def get_or_create_struct(self, key): + """Returns a struct for this key, creating if it didn't exist already.""" + if not self.fields[key].HasField('struct_value'): + # Clear will mark struct_value modified which will indeed create a struct. + self.fields[key].struct_value.Clear() + return self.fields[key].struct_value + + def update(self, dictionary): # pylint: disable=invalid-name + for key, value in dictionary.items(): + _SetStructValue(self.fields[key], value) + + +collections.abc.MutableMapping.register(Struct) + + +class ListValue(object): + """Class for ListValue message type.""" + + __slots__ = () + + def __len__(self): + return len(self.values) + + def append(self, value): + _SetStructValue(self.values.add(), value) + + def extend(self, elem_seq): + for value in elem_seq: + self.append(value) + + def __getitem__(self, index): + """Retrieves item by the specified index.""" + return _GetStructValue(self.values.__getitem__(index)) + + def __setitem__(self, index, value): + _SetStructValue(self.values.__getitem__(index), value) + + def __delitem__(self, key): + del self.values[key] + + def _internal_assign(self, elem_seq): + self.Clear() + self.extend(elem_seq) + + def _internal_compare(self, other): + size = len(self) + if size != len(other): + return False + for i in range(size): + if isinstance(other[i], (dict, list)): + if not self[i]._internal_compare(other[i]): + return False + elif self[i] != other[i]: + return False + return True + + def items(self): + for i in range(len(self)): + yield self[i] + + def add_struct(self): + """Appends and returns a struct value as the next value in the list.""" + struct_value = self.values.add().struct_value + # Clear will mark struct_value modified which will indeed create a struct. + struct_value.Clear() + return struct_value + + def add_list(self): + """Appends and returns a list value as the next value in the list.""" + list_value = self.values.add().list_value + # Clear will mark list_value modified which will indeed create a list. + list_value.Clear() + return list_value + + +collections.abc.MutableSequence.register(ListValue) + + +# LINT.IfChange(wktbases) +WKTBASES = { + 'google.protobuf.Any': Any, + 'google.protobuf.Duration': Duration, + 'google.protobuf.FieldMask': FieldMask, + 'google.protobuf.ListValue': ListValue, + 'google.protobuf.Struct': Struct, + 'google.protobuf.Timestamp': Timestamp, +} +# LINT.ThenChange(//depot/google.protobuf/compiler/python/pyi_generator.cc:wktbases) diff --git a/python/user_packages/Python313/site-packages/google/protobuf/internal/wire_format.py b/python/user_packages/Python313/site-packages/google/protobuf/internal/wire_format.py new file mode 100644 index 0000000000000000000000000000000000000000..6237dabf950e49d2d6124340c06724f41c1c2c8d --- /dev/null +++ b/python/user_packages/Python313/site-packages/google/protobuf/internal/wire_format.py @@ -0,0 +1,245 @@ +# Protocol Buffers - Google's data interchange format +# Copyright 2008 Google Inc. All rights reserved. +# +# Use of this source code is governed by a BSD-style +# license that can be found in the LICENSE file or at +# https://developers.google.com/open-source/licenses/bsd + +"""Constants and static functions to support protocol buffer wire format.""" + +__author__ = 'robinson@google.com (Will Robinson)' + +import struct +from google.protobuf import descriptor +from google.protobuf import message + + +TAG_TYPE_BITS = 3 # Number of bits used to hold type info in a proto tag. +TAG_TYPE_MASK = (1 << TAG_TYPE_BITS) - 1 # 0x7 + +# These numbers identify the wire type of a protocol buffer value. +# We use the least-significant TAG_TYPE_BITS bits of the varint-encoded +# tag-and-type to store one of these WIRETYPE_* constants. +# These values must match WireType enum in //google/protobuf/wire_format.h. +WIRETYPE_VARINT = 0 +WIRETYPE_FIXED64 = 1 +WIRETYPE_LENGTH_DELIMITED = 2 +WIRETYPE_START_GROUP = 3 +WIRETYPE_END_GROUP = 4 +WIRETYPE_FIXED32 = 5 +_WIRETYPE_MAX = 5 + + +# Bounds for various integer types. +INT32_MAX = int((1 << 31) - 1) +INT32_MIN = int(-(1 << 31)) +UINT32_MAX = (1 << 32) - 1 + +INT64_MAX = (1 << 63) - 1 +INT64_MIN = -(1 << 63) +UINT64_MAX = (1 << 64) - 1 + +# "struct" format strings that will encode/decode the specified formats. +FORMAT_UINT32_LITTLE_ENDIAN = '> TAG_TYPE_BITS), (tag & TAG_TYPE_MASK) + + +def ZigZagEncode(value): + """ZigZag Transform: Encodes signed integers so that they can be + effectively used with varint encoding. See wire_format.h for + more details. + """ + if value >= 0: + return value << 1 + return (value << 1) ^ (~0) + + +def ZigZagDecode(value): + """Inverse of ZigZagEncode().""" + if not value & 0x1: + return value >> 1 + return (value >> 1) ^ (~0) + + + +# The *ByteSize() functions below return the number of bytes required to +# serialize "field number + type" information and then serialize the value. + + +def Int32ByteSize(field_number, int32): + return Int64ByteSize(field_number, int32) + + +def Int32ByteSizeNoTag(int32): + return _VarUInt64ByteSizeNoTag(0xffffffffffffffff & int32) + + +def Int64ByteSize(field_number, int64): + # Have to convert to uint before calling UInt64ByteSize(). + return UInt64ByteSize(field_number, 0xffffffffffffffff & int64) + + +def UInt32ByteSize(field_number, uint32): + return UInt64ByteSize(field_number, uint32) + + +def UInt64ByteSize(field_number, uint64): + return TagByteSize(field_number) + _VarUInt64ByteSizeNoTag(uint64) + + +def SInt32ByteSize(field_number, int32): + return UInt32ByteSize(field_number, ZigZagEncode(int32)) + + +def SInt64ByteSize(field_number, int64): + return UInt64ByteSize(field_number, ZigZagEncode(int64)) + + +def Fixed32ByteSize(field_number, fixed32): + return TagByteSize(field_number) + 4 + + +def Fixed64ByteSize(field_number, fixed64): + return TagByteSize(field_number) + 8 + + +def SFixed32ByteSize(field_number, sfixed32): + return TagByteSize(field_number) + 4 + + +def SFixed64ByteSize(field_number, sfixed64): + return TagByteSize(field_number) + 8 + + +def FloatByteSize(field_number, flt): + return TagByteSize(field_number) + 4 + + +def DoubleByteSize(field_number, double): + return TagByteSize(field_number) + 8 + + +def BoolByteSize(field_number, b): + return TagByteSize(field_number) + 1 + + +def EnumByteSize(field_number, enum): + return UInt32ByteSize(field_number, enum) + + +def StringByteSize(field_number, string): + return BytesByteSize(field_number, string.encode('utf-8')) + + +def BytesByteSize(field_number, b): + return (TagByteSize(field_number) + + _VarUInt64ByteSizeNoTag(len(b)) + + len(b)) + + +def GroupByteSize(field_number, message): + return (2 * TagByteSize(field_number) # START and END group. + + message.ByteSize()) + + +def MessageByteSize(field_number, message): + return (TagByteSize(field_number) + + _VarUInt64ByteSizeNoTag(message.ByteSize()) + + message.ByteSize()) + + +def MessageSetItemByteSize(field_number, msg): + # First compute the sizes of the tags. + # There are 2 tags for the beginning and ending of the repeated group, that + # is field number 1, one with field number 2 (type_id) and one with field + # number 3 (message). + total_size = (2 * TagByteSize(1) + TagByteSize(2) + TagByteSize(3)) + + # Add the number of bytes for type_id. + total_size += _VarUInt64ByteSizeNoTag(field_number) + + message_size = msg.ByteSize() + + # The number of bytes for encoding the length of the message. + total_size += _VarUInt64ByteSizeNoTag(message_size) + + # The size of the message. + total_size += message_size + return total_size + + +def TagByteSize(field_number): + """Returns the bytes required to serialize a tag with this field number.""" + # Just pass in type 0, since the type won't affect the tag+type size. + return _VarUInt64ByteSizeNoTag(PackTag(field_number, 0)) + + +# Private helper function for the *ByteSize() functions above. + +def _VarUInt64ByteSizeNoTag(uint64): + """Returns the number of bytes required to serialize a single varint + using boundary value comparisons. (unrolled loop optimization -WPierce) + uint64 must be unsigned. + """ + if uint64 <= 0x7f: return 1 + if uint64 <= 0x3fff: return 2 + if uint64 <= 0x1fffff: return 3 + if uint64 <= 0xfffffff: return 4 + if uint64 <= 0x7ffffffff: return 5 + if uint64 <= 0x3ffffffffff: return 6 + if uint64 <= 0x1ffffffffffff: return 7 + if uint64 <= 0xffffffffffffff: return 8 + if uint64 <= 0x7fffffffffffffff: return 9 + if uint64 > UINT64_MAX: + raise message.EncodeError('Value out of range: %d' % uint64) + return 10 + + +NON_PACKABLE_TYPES = ( + descriptor.FieldDescriptor.TYPE_STRING, + descriptor.FieldDescriptor.TYPE_GROUP, + descriptor.FieldDescriptor.TYPE_MESSAGE, + descriptor.FieldDescriptor.TYPE_BYTES +) + + +def IsTypePackable(field_type): + """Return true iff packable = true is valid for fields of this type. + + Args: + field_type: a FieldDescriptor::Type value. + + Returns: + True iff fields of this type are packable. + """ + return field_type not in NON_PACKABLE_TYPES diff --git a/python/user_packages/Python313/site-packages/google/protobuf/pyext/__init__.py b/python/user_packages/Python313/site-packages/google/protobuf/pyext/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/python/user_packages/Python313/site-packages/google/protobuf/pyext/__pycache__/__init__.cpython-313.pyc b/python/user_packages/Python313/site-packages/google/protobuf/pyext/__pycache__/__init__.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f406342355fd7a26f29fa97c977d113eca4ae5ee Binary files /dev/null and b/python/user_packages/Python313/site-packages/google/protobuf/pyext/__pycache__/__init__.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/google/protobuf/pyext/__pycache__/cpp_message.cpython-313.pyc b/python/user_packages/Python313/site-packages/google/protobuf/pyext/__pycache__/cpp_message.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..75ef8c06918933c15e0194966ee307f99e1293ba Binary files /dev/null and b/python/user_packages/Python313/site-packages/google/protobuf/pyext/__pycache__/cpp_message.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/google/protobuf/pyext/cpp_message.py b/python/user_packages/Python313/site-packages/google/protobuf/pyext/cpp_message.py new file mode 100644 index 0000000000000000000000000000000000000000..54cfe30646aaaed023e4b6228ad291aa7c53d147 --- /dev/null +++ b/python/user_packages/Python313/site-packages/google/protobuf/pyext/cpp_message.py @@ -0,0 +1,49 @@ +# Protocol Buffers - Google's data interchange format +# Copyright 2008 Google Inc. All rights reserved. +# +# Use of this source code is governed by a BSD-style +# license that can be found in the LICENSE file or at +# https://developers.google.com/open-source/licenses/bsd + +"""Protocol message implementation hooks for C++ implementation. + +Contains helper functions used to create protocol message classes from +Descriptor objects at runtime backed by the protocol buffer C++ API. +""" + +__author__ = 'tibell@google.com (Johan Tibell)' + +from google.protobuf.internal import api_implementation + + +# pylint: disable=protected-access +_message = api_implementation._c_module +# TODO: Remove this import after fix api_implementation +if _message is None: + from google.protobuf.pyext import _message + + +class GeneratedProtocolMessageType(_message.MessageMeta): + + """Metaclass for protocol message classes created at runtime from Descriptors. + + The protocol compiler currently uses this metaclass to create protocol + message classes at runtime. Clients can also manually create their own + classes at runtime, as in this example: + + mydescriptor = Descriptor(.....) + factory = symbol_database.Default() + factory.pool.AddDescriptor(mydescriptor) + MyProtoClass = message_factory.GetMessageClass(mydescriptor) + myproto_instance = MyProtoClass() + myproto.foo_field = 23 + ... + + The above example will not work for nested types. If you wish to include them, + use reflection.MakeClass() instead of manually instantiating the class in + order to create the appropriate class structure. + """ + + # Must be consistent with the protocol-compiler code in + # proto2/compiler/internal/generator.*. + _DESCRIPTOR_KEY = 'DESCRIPTOR' diff --git a/python/user_packages/Python313/site-packages/google/protobuf/testdata/__init__.py b/python/user_packages/Python313/site-packages/google/protobuf/testdata/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/python/user_packages/Python313/site-packages/google/protobuf/testdata/__pycache__/__init__.cpython-313.pyc b/python/user_packages/Python313/site-packages/google/protobuf/testdata/__pycache__/__init__.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5d15bf10d9c6064103eca5e38d151aadc1c640e8 Binary files /dev/null and b/python/user_packages/Python313/site-packages/google/protobuf/testdata/__pycache__/__init__.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/google/protobuf/util/__init__.py b/python/user_packages/Python313/site-packages/google/protobuf/util/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/python/user_packages/Python313/site-packages/google/protobuf/util/__pycache__/__init__.cpython-313.pyc b/python/user_packages/Python313/site-packages/google/protobuf/util/__pycache__/__init__.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0ef5ca5d7ae9c8fedbdb0da1b041e5c3f719622c Binary files /dev/null and b/python/user_packages/Python313/site-packages/google/protobuf/util/__pycache__/__init__.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/google/rpc/__pycache__/code_pb2.cpython-313.pyc b/python/user_packages/Python313/site-packages/google/rpc/__pycache__/code_pb2.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..041f3559ef7c4063574f85c08b9a56825c49f078 Binary files /dev/null and b/python/user_packages/Python313/site-packages/google/rpc/__pycache__/code_pb2.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/google/rpc/__pycache__/error_details_pb2.cpython-313.pyc b/python/user_packages/Python313/site-packages/google/rpc/__pycache__/error_details_pb2.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f8115ccc640f085c39810550866b3b03f5e55d9b Binary files /dev/null and b/python/user_packages/Python313/site-packages/google/rpc/__pycache__/error_details_pb2.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/google/rpc/__pycache__/http_pb2.cpython-313.pyc b/python/user_packages/Python313/site-packages/google/rpc/__pycache__/http_pb2.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f504f90ad3d2c066cb4ffaf672a0c92a2acf5177 Binary files /dev/null and b/python/user_packages/Python313/site-packages/google/rpc/__pycache__/http_pb2.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/google/rpc/__pycache__/status_pb2.cpython-313.pyc b/python/user_packages/Python313/site-packages/google/rpc/__pycache__/status_pb2.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ebfbb7c1c425333a09a728296d4bdd1a08966288 Binary files /dev/null and b/python/user_packages/Python313/site-packages/google/rpc/__pycache__/status_pb2.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/google/rpc/context/__pycache__/attribute_context_pb2.cpython-313.pyc b/python/user_packages/Python313/site-packages/google/rpc/context/__pycache__/attribute_context_pb2.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..831b9168b6bded233fe8638e67496d1790206565 Binary files /dev/null and b/python/user_packages/Python313/site-packages/google/rpc/context/__pycache__/attribute_context_pb2.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/google/rpc/context/__pycache__/audit_context_pb2.cpython-313.pyc b/python/user_packages/Python313/site-packages/google/rpc/context/__pycache__/audit_context_pb2.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a0d0dc5c4b84293317f4b14c9b83218760360bd5 Binary files /dev/null and b/python/user_packages/Python313/site-packages/google/rpc/context/__pycache__/audit_context_pb2.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/google/rpc/context/attribute_context.proto b/python/user_packages/Python313/site-packages/google/rpc/context/attribute_context.proto new file mode 100644 index 0000000000000000000000000000000000000000..55f95f844e74ac98185515a9f84cff941d8de188 --- /dev/null +++ b/python/user_packages/Python313/site-packages/google/rpc/context/attribute_context.proto @@ -0,0 +1,350 @@ +// Copyright 2026 Google LLC +// +// 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. + +syntax = "proto3"; + +package google.rpc.context; + +import "google/protobuf/any.proto"; +import "google/protobuf/duration.proto"; +import "google/protobuf/struct.proto"; +import "google/protobuf/timestamp.proto"; + +option go_package = "google.golang.org/genproto/googleapis/rpc/context/attribute_context;attribute_context"; +option java_multiple_files = true; +option java_outer_classname = "AttributeContextProto"; +option java_package = "com.google.rpc.context"; + +// This message defines the standard attribute vocabulary for Google APIs. +// +// An attribute is a piece of metadata that describes an activity on a network +// service. For example, the size of an HTTP request, or the status code of +// an HTTP response. +// +// Each attribute has a type and a name, which is logically defined as +// a proto message field in `AttributeContext`. The field type becomes the +// attribute type, and the field path becomes the attribute name. For example, +// the attribute `source.ip` maps to field `AttributeContext.source.ip`. +// +// This message definition is guaranteed not to have any wire breaking change. +// So you can use it directly for passing attributes across different systems. +// +// NOTE: Different system may generate different subset of attributes. Please +// verify the system specification before relying on an attribute generated +// a system. +message AttributeContext { + // This message defines attributes for a node that handles a network request. + // The node can be either a service or an application that sends, forwards, + // or receives the request. Service peers should fill in + // `principal` and `labels` as appropriate. + message Peer { + // The IP address of the peer. + string ip = 1; + + // The network port of the peer. + int64 port = 2; + + // The labels associated with the peer. + map labels = 6; + + // The identity of this peer. Similar to `Request.auth.principal`, but + // relative to the peer instead of the request. For example, the + // identity associated with a load balancer that forwarded the request. + string principal = 7; + + // The CLDR country/region code associated with the above IP address. + // If the IP address is private, the `region_code` should reflect the + // physical location where this peer is running. + string region_code = 8; + } + + // This message defines attributes associated with API operations, such as + // a network API request. The terminology is based on the conventions used + // by Google APIs, Istio, and OpenAPI. + message Api { + // The API service name. It is a logical identifier for a networked API, + // such as "pubsub.googleapis.com". The naming syntax depends on the + // API management system being used for handling the request. + string service = 1; + + // The API operation name. For gRPC requests, it is the fully qualified API + // method name, such as "google.pubsub.v1.Publisher.Publish". For OpenAPI + // requests, it is the `operationId`, such as "getPet". + string operation = 2; + + // The API protocol used for sending the request, such as "http", "https", + // "grpc", or "internal". + string protocol = 3; + + // The API version associated with the API operation above, such as "v1" or + // "v1alpha1". + string version = 4; + } + + // This message defines request authentication attributes. Terminology is + // based on the JSON Web Token (JWT) standard, but the terms also + // correlate to concepts in other standards. + message Auth { + // The authenticated principal. Reflects the issuer (`iss`) and subject + // (`sub`) claims within a JWT. The issuer and subject should be `/` + // delimited, with `/` percent-encoded within the subject fragment. For + // Google accounts, the principal format is: + // "https://accounts.google.com/{id}" + string principal = 1; + + // The intended audience(s) for this authentication information. Reflects + // the audience (`aud`) claim within a JWT. The audience + // value(s) depends on the `issuer`, but typically include one or more of + // the following pieces of information: + // + // * The services intended to receive the credential. For example, + // ["https://pubsub.googleapis.com/", "https://storage.googleapis.com/"]. + // * A set of service-based scopes. For example, + // ["https://www.googleapis.com/auth/cloud-platform"]. + // * The client id of an app, such as the Firebase project id for JWTs + // from Firebase Auth. + // + // Consult the documentation for the credential issuer to determine the + // information provided. + repeated string audiences = 2; + + // The authorized presenter of the credential. Reflects the optional + // Authorized Presenter (`azp`) claim within a JWT or the + // OAuth client id. For example, a Google Cloud Platform client id looks + // as follows: "123456789012.apps.googleusercontent.com". + string presenter = 3; + + // Structured claims presented with the credential. JWTs include + // `{key: value}` pairs for standard and private claims. The following + // is a subset of the standard required and optional claims that would + // typically be presented for a Google-based JWT: + // + // {'iss': 'accounts.google.com', + // 'sub': '113289723416554971153', + // 'aud': ['123456789012', 'pubsub.googleapis.com'], + // 'azp': '123456789012.apps.googleusercontent.com', + // 'email': 'jsmith@example.com', + // 'iat': 1353601026, + // 'exp': 1353604926} + // + // SAML assertions are similarly specified, but with an identity provider + // dependent structure. + google.protobuf.Struct claims = 4; + + // A list of access level resource names that allow resources to be + // accessed by authenticated requester. It is part of Secure GCP processing + // for the incoming request. An access level string has the format: + // "//{api_service_name}/accessPolicies/{policy_id}/accessLevels/{short_name}" + // + // Example: + // "//accesscontextmanager.googleapis.com/accessPolicies/MY_POLICY_ID/accessLevels/MY_LEVEL" + repeated string access_levels = 5; + } + + // This message defines attributes for an HTTP request. If the actual + // request is not an HTTP request, the runtime system should try to map + // the actual request to an equivalent HTTP request. + message Request { + // The unique ID for a request, which can be propagated to downstream + // systems. The ID should have low probability of collision + // within a single day for a specific service. + string id = 1; + + // The HTTP request method, such as `GET`, `POST`. + string method = 2; + + // The HTTP request headers. If multiple headers share the same key, they + // must be merged according to the HTTP spec. All header keys must be + // lowercased, because HTTP header keys are case-insensitive. + map headers = 3; + + // The HTTP URL path, excluding the query parameters. + string path = 4; + + // The HTTP request `Host` header value. + string host = 5; + + // The HTTP URL scheme, such as `http` and `https`. + string scheme = 6; + + // The HTTP URL query in the format of `name1=value1&name2=value2`, as it + // appears in the first line of the HTTP request. No decoding is performed. + string query = 7; + + // The timestamp when the `destination` service receives the last byte of + // the request. + google.protobuf.Timestamp time = 9; + + // The HTTP request size in bytes. If unknown, it must be -1. + int64 size = 10; + + // The network protocol used with the request, such as "http/1.1", + // "spdy/3", "h2", "h2c", "webrtc", "tcp", "udp", "quic". See + // https://www.iana.org/assignments/tls-extensiontype-values/tls-extensiontype-values.xhtml#alpn-protocol-ids + // for details. + string protocol = 11; + + // A special parameter for request reason. It is used by security systems + // to associate auditing information with a request. + string reason = 12; + + // The request authentication. May be absent for unauthenticated requests. + // Derived from the HTTP request `Authorization` header or equivalent. + Auth auth = 13; + + // The values from Origin header from the HTTP request, such as + // "https://console.cloud.google.com". Modern browsers can only have one + // origin. Special browsers and/or HTTP clients may require multiple + // origins. + string origin = 14; + } + + // This message defines attributes for a typical network response. It + // generally models semantics of an HTTP response. + message Response { + // The HTTP response status code, such as `200` and `404`. + int64 code = 1; + + // The HTTP response size in bytes. If unknown, it must be -1. + int64 size = 2; + + // The HTTP response headers. If multiple headers share the same key, they + // must be merged according to HTTP spec. All header keys must be + // lowercased, because HTTP header keys are case-insensitive. + map headers = 3; + + // The timestamp when the `destination` service sends the last byte of + // the response. + google.protobuf.Timestamp time = 4; + + // The amount of time it takes the backend service to fully respond to a + // request. Measured from when the destination service starts to send the + // request to the backend until when the destination service receives the + // complete response from the backend. + google.protobuf.Duration backend_latency = 5; + } + + // This message defines core attributes for a resource. A resource is an + // addressable (named) entity provided by the destination service. For + // example, a file stored on a network storage service. + message Resource { + // The name of the service that this resource belongs to, such as + // `pubsub.googleapis.com`. The service may be different from the DNS + // hostname that actually serves the request. + string service = 1; + + // The stable identifier (name) of a resource on the `service`. A resource + // can be logically identified as "//{resource.service}/{resource.name}". + // The differences between a resource name and a URI are: + // + // * Resource name is a logical identifier, independent of network + // protocol and API version. For example, + // `//pubsub.googleapis.com/projects/123/topics/news-feed`. + // * URI often includes protocol and version information, so it can + // be used directly by applications. For example, + // `https://pubsub.googleapis.com/v1/projects/123/topics/news-feed`. + // + // See https://cloud.google.com/apis/design/resource_names for details. + string name = 2; + + // The type of the resource. The syntax is platform-specific because + // different platforms define their resources differently. + // + // For Google APIs, the type format must be "{service}/{kind}", such as + // "pubsub.googleapis.com/Topic". + string type = 3; + + // The labels or tags on the resource, such as AWS resource tags and + // Kubernetes resource labels. + map labels = 4; + + // The unique identifier of the resource. UID is unique in the time + // and space for this resource within the scope of the service. It is + // typically generated by the server on successful creation of a resource + // and must not be changed. UID is used to uniquely identify resources + // with resource name reuses. This should be a UUID4. + string uid = 5; + + // Annotations is an unstructured key-value map stored with a resource that + // may be set by external tools to store and retrieve arbitrary metadata. + // They are not queryable and should be preserved when modifying objects. + // + // More info: + // https://kubernetes.io/docs/concepts/overview/working-with-objects/annotations/ + map annotations = 6; + + // Mutable. The display name set by clients. Must be <= 63 characters. + string display_name = 7; + + // Output only. The timestamp when the resource was created. This may + // be either the time creation was initiated or when it was completed. + google.protobuf.Timestamp create_time = 8; + + // Output only. The timestamp when the resource was last updated. Any + // change to the resource made by users must refresh this value. + // Changes to a resource made by the service should refresh this value. + google.protobuf.Timestamp update_time = 9; + + // Output only. The timestamp when the resource was deleted. + // If the resource is not deleted, this must be empty. + google.protobuf.Timestamp delete_time = 10; + + // Output only. An opaque value that uniquely identifies a version or + // generation of a resource. It can be used to confirm that the client + // and server agree on the ordering of a resource being written. + string etag = 11; + + // Immutable. The location of the resource. The location encoding is + // specific to the service provider, and new encoding may be introduced + // as the service evolves. + // + // For Google Cloud products, the encoding is what is used by Google Cloud + // APIs, such as `us-east1`, `aws-us-east-1`, and `azure-eastus2`. The + // semantics of `location` is identical to the + // `cloud.googleapis.com/location` label used by some Google Cloud APIs. + string location = 12; + } + + // The origin of a network activity. In a multi hop network activity, + // the origin represents the sender of the first hop. For the first hop, + // the `source` and the `origin` must have the same content. + Peer origin = 7; + + // The source of a network activity, such as starting a TCP connection. + // In a multi hop network activity, the source represents the sender of the + // last hop. + Peer source = 1; + + // The destination of a network activity, such as accepting a TCP connection. + // In a multi hop network activity, the destination represents the receiver of + // the last hop. + Peer destination = 2; + + // Represents a network request, such as an HTTP request. + Request request = 3; + + // Represents a network response, such as an HTTP response. + Response response = 4; + + // Represents a target resource that is involved with a network activity. + // If multiple resources are involved with an activity, this must be the + // primary one. + Resource resource = 5; + + // Represents an API operation that is involved to a network activity. + Api api = 6; + + // Supports extensions for advanced use cases, such as logs and metrics. + repeated google.protobuf.Any extensions = 8; +} diff --git a/python/user_packages/Python313/site-packages/google/rpc/context/attribute_context_pb2.py b/python/user_packages/Python313/site-packages/google/rpc/context/attribute_context_pb2.py new file mode 100644 index 0000000000000000000000000000000000000000..7d1064fb76f61fde3bd9f6260134b408fcc9777f --- /dev/null +++ b/python/user_packages/Python313/site-packages/google/rpc/context/attribute_context_pb2.py @@ -0,0 +1,87 @@ +# -*- coding: utf-8 -*- + +# Copyright 2025 Google LLC +# +# 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. + +# Generated by the protocol buffer compiler. DO NOT EDIT! +# source: google/rpc/context/attribute_context.proto +# Protobuf Python Version: 4.25.3 +"""Generated protocol buffer code.""" + +from google.protobuf import descriptor as _descriptor +from google.protobuf import descriptor_pool as _descriptor_pool +from google.protobuf import symbol_database as _symbol_database +from google.protobuf.internal import builder as _builder + +# @@protoc_insertion_point(imports) + +_sym_db = _symbol_database.Default() + + +from google.protobuf import any_pb2 as google_dot_protobuf_dot_any__pb2 +from google.protobuf import duration_pb2 as google_dot_protobuf_dot_duration__pb2 +from google.protobuf import struct_pb2 as google_dot_protobuf_dot_struct__pb2 +from google.protobuf import timestamp_pb2 as google_dot_protobuf_dot_timestamp__pb2 + +DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile( + b"\n*google/rpc/context/attribute_context.proto\x12\x12google.rpc.context\x1a\x19google/protobuf/any.proto\x1a\x1egoogle/protobuf/duration.proto\x1a\x1cgoogle/protobuf/struct.proto\x1a\x1fgoogle/protobuf/timestamp.proto\"\x93\x10\n\x10\x41ttributeContext\x12\x39\n\x06origin\x18\x07 \x01(\x0b\x32).google.rpc.context.AttributeContext.Peer\x12\x39\n\x06source\x18\x01 \x01(\x0b\x32).google.rpc.context.AttributeContext.Peer\x12>\n\x0b\x64\x65stination\x18\x02 \x01(\x0b\x32).google.rpc.context.AttributeContext.Peer\x12=\n\x07request\x18\x03 \x01(\x0b\x32,.google.rpc.context.AttributeContext.Request\x12?\n\x08response\x18\x04 \x01(\x0b\x32-.google.rpc.context.AttributeContext.Response\x12?\n\x08resource\x18\x05 \x01(\x0b\x32-.google.rpc.context.AttributeContext.Resource\x12\x35\n\x03\x61pi\x18\x06 \x01(\x0b\x32(.google.rpc.context.AttributeContext.Api\x12(\n\nextensions\x18\x08 \x03(\x0b\x32\x14.google.protobuf.Any\x1a\xbe\x01\n\x04Peer\x12\n\n\x02ip\x18\x01 \x01(\t\x12\x0c\n\x04port\x18\x02 \x01(\x03\x12\x45\n\x06labels\x18\x06 \x03(\x0b\x32\x35.google.rpc.context.AttributeContext.Peer.LabelsEntry\x12\x11\n\tprincipal\x18\x07 \x01(\t\x12\x13\n\x0bregion_code\x18\x08 \x01(\t\x1a-\n\x0bLabelsEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12\r\n\x05value\x18\x02 \x01(\t:\x02\x38\x01\x1aL\n\x03\x41pi\x12\x0f\n\x07service\x18\x01 \x01(\t\x12\x11\n\toperation\x18\x02 \x01(\t\x12\x10\n\x08protocol\x18\x03 \x01(\t\x12\x0f\n\x07version\x18\x04 \x01(\t\x1a\x7f\n\x04\x41uth\x12\x11\n\tprincipal\x18\x01 \x01(\t\x12\x11\n\taudiences\x18\x02 \x03(\t\x12\x11\n\tpresenter\x18\x03 \x01(\t\x12'\n\x06\x63laims\x18\x04 \x01(\x0b\x32\x17.google.protobuf.Struct\x12\x15\n\raccess_levels\x18\x05 \x03(\t\x1a\xff\x02\n\x07Request\x12\n\n\x02id\x18\x01 \x01(\t\x12\x0e\n\x06method\x18\x02 \x01(\t\x12J\n\x07headers\x18\x03 \x03(\x0b\x32\x39.google.rpc.context.AttributeContext.Request.HeadersEntry\x12\x0c\n\x04path\x18\x04 \x01(\t\x12\x0c\n\x04host\x18\x05 \x01(\t\x12\x0e\n\x06scheme\x18\x06 \x01(\t\x12\r\n\x05query\x18\x07 \x01(\t\x12(\n\x04time\x18\t \x01(\x0b\x32\x1a.google.protobuf.Timestamp\x12\x0c\n\x04size\x18\n \x01(\x03\x12\x10\n\x08protocol\x18\x0b \x01(\t\x12\x0e\n\x06reason\x18\x0c \x01(\t\x12\x37\n\x04\x61uth\x18\r \x01(\x0b\x32).google.rpc.context.AttributeContext.Auth\x12\x0e\n\x06origin\x18\x0e \x01(\t\x1a.\n\x0cHeadersEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12\r\n\x05value\x18\x02 \x01(\t:\x02\x38\x01\x1a\x81\x02\n\x08Response\x12\x0c\n\x04\x63ode\x18\x01 \x01(\x03\x12\x0c\n\x04size\x18\x02 \x01(\x03\x12K\n\x07headers\x18\x03 \x03(\x0b\x32:.google.rpc.context.AttributeContext.Response.HeadersEntry\x12(\n\x04time\x18\x04 \x01(\x0b\x32\x1a.google.protobuf.Timestamp\x12\x32\n\x0f\x62\x61\x63kend_latency\x18\x05 \x01(\x0b\x32\x19.google.protobuf.Duration\x1a.\n\x0cHeadersEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12\r\n\x05value\x18\x02 \x01(\t:\x02\x38\x01\x1a\x90\x04\n\x08Resource\x12\x0f\n\x07service\x18\x01 \x01(\t\x12\x0c\n\x04name\x18\x02 \x01(\t\x12\x0c\n\x04type\x18\x03 \x01(\t\x12I\n\x06labels\x18\x04 \x03(\x0b\x32\x39.google.rpc.context.AttributeContext.Resource.LabelsEntry\x12\x0b\n\x03uid\x18\x05 \x01(\t\x12S\n\x0b\x61nnotations\x18\x06 \x03(\x0b\x32>.google.rpc.context.AttributeContext.Resource.AnnotationsEntry\x12\x14\n\x0c\x64isplay_name\x18\x07 \x01(\t\x12/\n\x0b\x63reate_time\x18\x08 \x01(\x0b\x32\x1a.google.protobuf.Timestamp\x12/\n\x0bupdate_time\x18\t \x01(\x0b\x32\x1a.google.protobuf.Timestamp\x12/\n\x0b\x64\x65lete_time\x18\n \x01(\x0b\x32\x1a.google.protobuf.Timestamp\x12\x0c\n\x04\x65tag\x18\x0b \x01(\t\x12\x10\n\x08location\x18\x0c \x01(\t\x1a-\n\x0bLabelsEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12\r\n\x05value\x18\x02 \x01(\t:\x02\x38\x01\x1a\x32\n\x10\x41nnotationsEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12\r\n\x05value\x18\x02 \x01(\t:\x02\x38\x01\x42\x88\x01\n\x16\x63om.google.rpc.contextB\x15\x41ttributeContextProtoP\x01ZUgoogle.golang.org/genproto/googleapis/rpc/context/attribute_context;attribute_contextb\x06proto3" +) + +_globals = globals() +_builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, _globals) +_builder.BuildTopDescriptorsAndMessages( + DESCRIPTOR, "google.rpc.context.attribute_context_pb2", _globals +) +if _descriptor._USE_C_DESCRIPTORS == False: + _globals["DESCRIPTOR"]._options = None + _globals[ + "DESCRIPTOR" + ]._serialized_options = b"\n\026com.google.rpc.contextB\025AttributeContextProtoP\001ZUgoogle.golang.org/genproto/googleapis/rpc/context/attribute_context;attribute_context" + _globals["_ATTRIBUTECONTEXT_PEER_LABELSENTRY"]._options = None + _globals["_ATTRIBUTECONTEXT_PEER_LABELSENTRY"]._serialized_options = b"8\001" + _globals["_ATTRIBUTECONTEXT_REQUEST_HEADERSENTRY"]._options = None + _globals["_ATTRIBUTECONTEXT_REQUEST_HEADERSENTRY"]._serialized_options = b"8\001" + _globals["_ATTRIBUTECONTEXT_RESPONSE_HEADERSENTRY"]._options = None + _globals["_ATTRIBUTECONTEXT_RESPONSE_HEADERSENTRY"]._serialized_options = b"8\001" + _globals["_ATTRIBUTECONTEXT_RESOURCE_LABELSENTRY"]._options = None + _globals["_ATTRIBUTECONTEXT_RESOURCE_LABELSENTRY"]._serialized_options = b"8\001" + _globals["_ATTRIBUTECONTEXT_RESOURCE_ANNOTATIONSENTRY"]._options = None + _globals[ + "_ATTRIBUTECONTEXT_RESOURCE_ANNOTATIONSENTRY" + ]._serialized_options = b"8\001" + _globals["_ATTRIBUTECONTEXT"]._serialized_start = 189 + _globals["_ATTRIBUTECONTEXT"]._serialized_end = 2256 + _globals["_ATTRIBUTECONTEXT_PEER"]._serialized_start = 682 + _globals["_ATTRIBUTECONTEXT_PEER"]._serialized_end = 872 + _globals["_ATTRIBUTECONTEXT_PEER_LABELSENTRY"]._serialized_start = 827 + _globals["_ATTRIBUTECONTEXT_PEER_LABELSENTRY"]._serialized_end = 872 + _globals["_ATTRIBUTECONTEXT_API"]._serialized_start = 874 + _globals["_ATTRIBUTECONTEXT_API"]._serialized_end = 950 + _globals["_ATTRIBUTECONTEXT_AUTH"]._serialized_start = 952 + _globals["_ATTRIBUTECONTEXT_AUTH"]._serialized_end = 1079 + _globals["_ATTRIBUTECONTEXT_REQUEST"]._serialized_start = 1082 + _globals["_ATTRIBUTECONTEXT_REQUEST"]._serialized_end = 1465 + _globals["_ATTRIBUTECONTEXT_REQUEST_HEADERSENTRY"]._serialized_start = 1419 + _globals["_ATTRIBUTECONTEXT_REQUEST_HEADERSENTRY"]._serialized_end = 1465 + _globals["_ATTRIBUTECONTEXT_RESPONSE"]._serialized_start = 1468 + _globals["_ATTRIBUTECONTEXT_RESPONSE"]._serialized_end = 1725 + _globals["_ATTRIBUTECONTEXT_RESPONSE_HEADERSENTRY"]._serialized_start = 1419 + _globals["_ATTRIBUTECONTEXT_RESPONSE_HEADERSENTRY"]._serialized_end = 1465 + _globals["_ATTRIBUTECONTEXT_RESOURCE"]._serialized_start = 1728 + _globals["_ATTRIBUTECONTEXT_RESOURCE"]._serialized_end = 2256 + _globals["_ATTRIBUTECONTEXT_RESOURCE_LABELSENTRY"]._serialized_start = 827 + _globals["_ATTRIBUTECONTEXT_RESOURCE_LABELSENTRY"]._serialized_end = 872 + _globals["_ATTRIBUTECONTEXT_RESOURCE_ANNOTATIONSENTRY"]._serialized_start = 2206 + _globals["_ATTRIBUTECONTEXT_RESOURCE_ANNOTATIONSENTRY"]._serialized_end = 2256 +# @@protoc_insertion_point(module_scope) diff --git a/python/user_packages/Python313/site-packages/google/rpc/context/attribute_context_pb2.pyi b/python/user_packages/Python313/site-packages/google/rpc/context/attribute_context_pb2.pyi new file mode 100644 index 0000000000000000000000000000000000000000..a068b06626f7e2fc85513eed6c0d782ac0e00783 --- /dev/null +++ b/python/user_packages/Python313/site-packages/google/rpc/context/attribute_context_pb2.pyi @@ -0,0 +1,313 @@ +# Copyright 2025 Google LLC +# +# 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. + +from typing import ClassVar as _ClassVar +from typing import Iterable as _Iterable +from typing import Mapping as _Mapping +from typing import Optional as _Optional +from typing import Union as _Union + +from google.protobuf import any_pb2 as _any_pb2 +from google.protobuf import descriptor as _descriptor +from google.protobuf import duration_pb2 as _duration_pb2 +from google.protobuf import message as _message +from google.protobuf import struct_pb2 as _struct_pb2 +from google.protobuf import timestamp_pb2 as _timestamp_pb2 +from google.protobuf.internal import containers as _containers + +DESCRIPTOR: _descriptor.FileDescriptor + +class AttributeContext(_message.Message): + __slots__ = ( + "origin", + "source", + "destination", + "request", + "response", + "resource", + "api", + "extensions", + ) + class Peer(_message.Message): + __slots__ = ("ip", "port", "labels", "principal", "region_code") + class LabelsEntry(_message.Message): + __slots__ = ("key", "value") + KEY_FIELD_NUMBER: _ClassVar[int] + VALUE_FIELD_NUMBER: _ClassVar[int] + key: str + value: str + def __init__( + self, key: _Optional[str] = ..., value: _Optional[str] = ... + ) -> None: ... + + IP_FIELD_NUMBER: _ClassVar[int] + PORT_FIELD_NUMBER: _ClassVar[int] + LABELS_FIELD_NUMBER: _ClassVar[int] + PRINCIPAL_FIELD_NUMBER: _ClassVar[int] + REGION_CODE_FIELD_NUMBER: _ClassVar[int] + ip: str + port: int + labels: _containers.ScalarMap[str, str] + principal: str + region_code: str + def __init__( + self, + ip: _Optional[str] = ..., + port: _Optional[int] = ..., + labels: _Optional[_Mapping[str, str]] = ..., + principal: _Optional[str] = ..., + region_code: _Optional[str] = ..., + ) -> None: ... + + class Api(_message.Message): + __slots__ = ("service", "operation", "protocol", "version") + SERVICE_FIELD_NUMBER: _ClassVar[int] + OPERATION_FIELD_NUMBER: _ClassVar[int] + PROTOCOL_FIELD_NUMBER: _ClassVar[int] + VERSION_FIELD_NUMBER: _ClassVar[int] + service: str + operation: str + protocol: str + version: str + def __init__( + self, + service: _Optional[str] = ..., + operation: _Optional[str] = ..., + protocol: _Optional[str] = ..., + version: _Optional[str] = ..., + ) -> None: ... + + class Auth(_message.Message): + __slots__ = ("principal", "audiences", "presenter", "claims", "access_levels") + PRINCIPAL_FIELD_NUMBER: _ClassVar[int] + AUDIENCES_FIELD_NUMBER: _ClassVar[int] + PRESENTER_FIELD_NUMBER: _ClassVar[int] + CLAIMS_FIELD_NUMBER: _ClassVar[int] + ACCESS_LEVELS_FIELD_NUMBER: _ClassVar[int] + principal: str + audiences: _containers.RepeatedScalarFieldContainer[str] + presenter: str + claims: _struct_pb2.Struct + access_levels: _containers.RepeatedScalarFieldContainer[str] + def __init__( + self, + principal: _Optional[str] = ..., + audiences: _Optional[_Iterable[str]] = ..., + presenter: _Optional[str] = ..., + claims: _Optional[_Union[_struct_pb2.Struct, _Mapping]] = ..., + access_levels: _Optional[_Iterable[str]] = ..., + ) -> None: ... + + class Request(_message.Message): + __slots__ = ( + "id", + "method", + "headers", + "path", + "host", + "scheme", + "query", + "time", + "size", + "protocol", + "reason", + "auth", + "origin", + ) + class HeadersEntry(_message.Message): + __slots__ = ("key", "value") + KEY_FIELD_NUMBER: _ClassVar[int] + VALUE_FIELD_NUMBER: _ClassVar[int] + key: str + value: str + def __init__( + self, key: _Optional[str] = ..., value: _Optional[str] = ... + ) -> None: ... + + ID_FIELD_NUMBER: _ClassVar[int] + METHOD_FIELD_NUMBER: _ClassVar[int] + HEADERS_FIELD_NUMBER: _ClassVar[int] + PATH_FIELD_NUMBER: _ClassVar[int] + HOST_FIELD_NUMBER: _ClassVar[int] + SCHEME_FIELD_NUMBER: _ClassVar[int] + QUERY_FIELD_NUMBER: _ClassVar[int] + TIME_FIELD_NUMBER: _ClassVar[int] + SIZE_FIELD_NUMBER: _ClassVar[int] + PROTOCOL_FIELD_NUMBER: _ClassVar[int] + REASON_FIELD_NUMBER: _ClassVar[int] + AUTH_FIELD_NUMBER: _ClassVar[int] + ORIGIN_FIELD_NUMBER: _ClassVar[int] + id: str + method: str + headers: _containers.ScalarMap[str, str] + path: str + host: str + scheme: str + query: str + time: _timestamp_pb2.Timestamp + size: int + protocol: str + reason: str + auth: AttributeContext.Auth + origin: str + def __init__( + self, + id: _Optional[str] = ..., + method: _Optional[str] = ..., + headers: _Optional[_Mapping[str, str]] = ..., + path: _Optional[str] = ..., + host: _Optional[str] = ..., + scheme: _Optional[str] = ..., + query: _Optional[str] = ..., + time: _Optional[_Union[_timestamp_pb2.Timestamp, _Mapping]] = ..., + size: _Optional[int] = ..., + protocol: _Optional[str] = ..., + reason: _Optional[str] = ..., + auth: _Optional[_Union[AttributeContext.Auth, _Mapping]] = ..., + origin: _Optional[str] = ..., + ) -> None: ... + + class Response(_message.Message): + __slots__ = ("code", "size", "headers", "time", "backend_latency") + class HeadersEntry(_message.Message): + __slots__ = ("key", "value") + KEY_FIELD_NUMBER: _ClassVar[int] + VALUE_FIELD_NUMBER: _ClassVar[int] + key: str + value: str + def __init__( + self, key: _Optional[str] = ..., value: _Optional[str] = ... + ) -> None: ... + + CODE_FIELD_NUMBER: _ClassVar[int] + SIZE_FIELD_NUMBER: _ClassVar[int] + HEADERS_FIELD_NUMBER: _ClassVar[int] + TIME_FIELD_NUMBER: _ClassVar[int] + BACKEND_LATENCY_FIELD_NUMBER: _ClassVar[int] + code: int + size: int + headers: _containers.ScalarMap[str, str] + time: _timestamp_pb2.Timestamp + backend_latency: _duration_pb2.Duration + def __init__( + self, + code: _Optional[int] = ..., + size: _Optional[int] = ..., + headers: _Optional[_Mapping[str, str]] = ..., + time: _Optional[_Union[_timestamp_pb2.Timestamp, _Mapping]] = ..., + backend_latency: _Optional[_Union[_duration_pb2.Duration, _Mapping]] = ..., + ) -> None: ... + + class Resource(_message.Message): + __slots__ = ( + "service", + "name", + "type", + "labels", + "uid", + "annotations", + "display_name", + "create_time", + "update_time", + "delete_time", + "etag", + "location", + ) + class LabelsEntry(_message.Message): + __slots__ = ("key", "value") + KEY_FIELD_NUMBER: _ClassVar[int] + VALUE_FIELD_NUMBER: _ClassVar[int] + key: str + value: str + def __init__( + self, key: _Optional[str] = ..., value: _Optional[str] = ... + ) -> None: ... + + class AnnotationsEntry(_message.Message): + __slots__ = ("key", "value") + KEY_FIELD_NUMBER: _ClassVar[int] + VALUE_FIELD_NUMBER: _ClassVar[int] + key: str + value: str + def __init__( + self, key: _Optional[str] = ..., value: _Optional[str] = ... + ) -> None: ... + + SERVICE_FIELD_NUMBER: _ClassVar[int] + NAME_FIELD_NUMBER: _ClassVar[int] + TYPE_FIELD_NUMBER: _ClassVar[int] + LABELS_FIELD_NUMBER: _ClassVar[int] + UID_FIELD_NUMBER: _ClassVar[int] + ANNOTATIONS_FIELD_NUMBER: _ClassVar[int] + DISPLAY_NAME_FIELD_NUMBER: _ClassVar[int] + CREATE_TIME_FIELD_NUMBER: _ClassVar[int] + UPDATE_TIME_FIELD_NUMBER: _ClassVar[int] + DELETE_TIME_FIELD_NUMBER: _ClassVar[int] + ETAG_FIELD_NUMBER: _ClassVar[int] + LOCATION_FIELD_NUMBER: _ClassVar[int] + service: str + name: str + type: str + labels: _containers.ScalarMap[str, str] + uid: str + annotations: _containers.ScalarMap[str, str] + display_name: str + create_time: _timestamp_pb2.Timestamp + update_time: _timestamp_pb2.Timestamp + delete_time: _timestamp_pb2.Timestamp + etag: str + location: str + def __init__( + self, + service: _Optional[str] = ..., + name: _Optional[str] = ..., + type: _Optional[str] = ..., + labels: _Optional[_Mapping[str, str]] = ..., + uid: _Optional[str] = ..., + annotations: _Optional[_Mapping[str, str]] = ..., + display_name: _Optional[str] = ..., + create_time: _Optional[_Union[_timestamp_pb2.Timestamp, _Mapping]] = ..., + update_time: _Optional[_Union[_timestamp_pb2.Timestamp, _Mapping]] = ..., + delete_time: _Optional[_Union[_timestamp_pb2.Timestamp, _Mapping]] = ..., + etag: _Optional[str] = ..., + location: _Optional[str] = ..., + ) -> None: ... + + ORIGIN_FIELD_NUMBER: _ClassVar[int] + SOURCE_FIELD_NUMBER: _ClassVar[int] + DESTINATION_FIELD_NUMBER: _ClassVar[int] + REQUEST_FIELD_NUMBER: _ClassVar[int] + RESPONSE_FIELD_NUMBER: _ClassVar[int] + RESOURCE_FIELD_NUMBER: _ClassVar[int] + API_FIELD_NUMBER: _ClassVar[int] + EXTENSIONS_FIELD_NUMBER: _ClassVar[int] + origin: AttributeContext.Peer + source: AttributeContext.Peer + destination: AttributeContext.Peer + request: AttributeContext.Request + response: AttributeContext.Response + resource: AttributeContext.Resource + api: AttributeContext.Api + extensions: _containers.RepeatedCompositeFieldContainer[_any_pb2.Any] + def __init__( + self, + origin: _Optional[_Union[AttributeContext.Peer, _Mapping]] = ..., + source: _Optional[_Union[AttributeContext.Peer, _Mapping]] = ..., + destination: _Optional[_Union[AttributeContext.Peer, _Mapping]] = ..., + request: _Optional[_Union[AttributeContext.Request, _Mapping]] = ..., + response: _Optional[_Union[AttributeContext.Response, _Mapping]] = ..., + resource: _Optional[_Union[AttributeContext.Resource, _Mapping]] = ..., + api: _Optional[_Union[AttributeContext.Api, _Mapping]] = ..., + extensions: _Optional[_Iterable[_Union[_any_pb2.Any, _Mapping]]] = ..., + ) -> None: ... diff --git a/python/user_packages/Python313/site-packages/google/rpc/context/audit_context.proto b/python/user_packages/Python313/site-packages/google/rpc/context/audit_context.proto new file mode 100644 index 0000000000000000000000000000000000000000..03c5ab9a508659be37500885a137c071f73f565c --- /dev/null +++ b/python/user_packages/Python313/site-packages/google/rpc/context/audit_context.proto @@ -0,0 +1,48 @@ +// Copyright 2026 Google LLC +// +// 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. + +syntax = "proto3"; + +package google.rpc.context; + +import "google/protobuf/struct.proto"; + +option go_package = "google.golang.org/genproto/googleapis/rpc/context;context"; +option java_multiple_files = true; +option java_outer_classname = "AuditContextProto"; +option java_package = "com.google.rpc.context"; + +// `AuditContext` provides information that is needed for audit logging. +message AuditContext { + // Serialized audit log. + bytes audit_log = 1; + + // An API request message that is scrubbed based on the method annotation. + // This field should only be filled if audit_log field is present. + // Service Control will use this to assemble a complete log for Cloud Audit + // Logs and Google internal audit logs. + google.protobuf.Struct scrubbed_request = 2; + + // An API response message that is scrubbed based on the method annotation. + // This field should only be filled if audit_log field is present. + // Service Control will use this to assemble a complete log for Cloud Audit + // Logs and Google internal audit logs. + google.protobuf.Struct scrubbed_response = 3; + + // Number of scrubbed response items. + int32 scrubbed_response_item_count = 4; + + // Audit resource name which is scrubbed. + string target_resource = 5; +} diff --git a/python/user_packages/Python313/site-packages/google/rpc/context/audit_context_pb2.py b/python/user_packages/Python313/site-packages/google/rpc/context/audit_context_pb2.py new file mode 100644 index 0000000000000000000000000000000000000000..8d52ec1220582eeb9d77a0aa7bf52d6c11901045 --- /dev/null +++ b/python/user_packages/Python313/site-packages/google/rpc/context/audit_context_pb2.py @@ -0,0 +1,50 @@ +# -*- coding: utf-8 -*- + +# Copyright 2025 Google LLC +# +# 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. + +# Generated by the protocol buffer compiler. DO NOT EDIT! +# source: google/rpc/context/audit_context.proto +# Protobuf Python Version: 4.25.3 +"""Generated protocol buffer code.""" + +from google.protobuf import descriptor as _descriptor +from google.protobuf import descriptor_pool as _descriptor_pool +from google.protobuf import symbol_database as _symbol_database +from google.protobuf.internal import builder as _builder + +# @@protoc_insertion_point(imports) + +_sym_db = _symbol_database.Default() + + +from google.protobuf import struct_pb2 as google_dot_protobuf_dot_struct__pb2 + +DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile( + b'\n&google/rpc/context/audit_context.proto\x12\x12google.rpc.context\x1a\x1cgoogle/protobuf/struct.proto"\xc7\x01\n\x0c\x41uditContext\x12\x11\n\taudit_log\x18\x01 \x01(\x0c\x12\x31\n\x10scrubbed_request\x18\x02 \x01(\x0b\x32\x17.google.protobuf.Struct\x12\x32\n\x11scrubbed_response\x18\x03 \x01(\x0b\x32\x17.google.protobuf.Struct\x12$\n\x1cscrubbed_response_item_count\x18\x04 \x01(\x05\x12\x17\n\x0ftarget_resource\x18\x05 \x01(\tBh\n\x16\x63om.google.rpc.contextB\x11\x41uditContextProtoP\x01Z9google.golang.org/genproto/googleapis/rpc/context;contextb\x06proto3' +) + +_globals = globals() +_builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, _globals) +_builder.BuildTopDescriptorsAndMessages( + DESCRIPTOR, "google.rpc.context.audit_context_pb2", _globals +) +if _descriptor._USE_C_DESCRIPTORS == False: + _globals["DESCRIPTOR"]._options = None + _globals[ + "DESCRIPTOR" + ]._serialized_options = b"\n\026com.google.rpc.contextB\021AuditContextProtoP\001Z9google.golang.org/genproto/googleapis/rpc/context;context" + _globals["_AUDITCONTEXT"]._serialized_start = 93 + _globals["_AUDITCONTEXT"]._serialized_end = 292 +# @@protoc_insertion_point(module_scope) diff --git a/python/user_packages/Python313/site-packages/google/rpc/context/audit_context_pb2.pyi b/python/user_packages/Python313/site-packages/google/rpc/context/audit_context_pb2.pyi new file mode 100644 index 0000000000000000000000000000000000000000..8583ec169fb2cfc55a23053e4942c9601061a571 --- /dev/null +++ b/python/user_packages/Python313/site-packages/google/rpc/context/audit_context_pb2.pyi @@ -0,0 +1,51 @@ +# Copyright 2025 Google LLC +# +# 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. + +from typing import ClassVar as _ClassVar +from typing import Mapping as _Mapping +from typing import Optional as _Optional +from typing import Union as _Union + +from google.protobuf import descriptor as _descriptor +from google.protobuf import message as _message +from google.protobuf import struct_pb2 as _struct_pb2 + +DESCRIPTOR: _descriptor.FileDescriptor + +class AuditContext(_message.Message): + __slots__ = ( + "audit_log", + "scrubbed_request", + "scrubbed_response", + "scrubbed_response_item_count", + "target_resource", + ) + AUDIT_LOG_FIELD_NUMBER: _ClassVar[int] + SCRUBBED_REQUEST_FIELD_NUMBER: _ClassVar[int] + SCRUBBED_RESPONSE_FIELD_NUMBER: _ClassVar[int] + SCRUBBED_RESPONSE_ITEM_COUNT_FIELD_NUMBER: _ClassVar[int] + TARGET_RESOURCE_FIELD_NUMBER: _ClassVar[int] + audit_log: bytes + scrubbed_request: _struct_pb2.Struct + scrubbed_response: _struct_pb2.Struct + scrubbed_response_item_count: int + target_resource: str + def __init__( + self, + audit_log: _Optional[bytes] = ..., + scrubbed_request: _Optional[_Union[_struct_pb2.Struct, _Mapping]] = ..., + scrubbed_response: _Optional[_Union[_struct_pb2.Struct, _Mapping]] = ..., + scrubbed_response_item_count: _Optional[int] = ..., + target_resource: _Optional[str] = ..., + ) -> None: ... diff --git a/python/user_packages/Python313/site-packages/google/rpc/status_pb2.py b/python/user_packages/Python313/site-packages/google/rpc/status_pb2.py new file mode 100644 index 0000000000000000000000000000000000000000..2c39a81ec757576a5d18de06b8c76bd01f7ce2d4 --- /dev/null +++ b/python/user_packages/Python313/site-packages/google/rpc/status_pb2.py @@ -0,0 +1,48 @@ +# -*- coding: utf-8 -*- + +# Copyright 2025 Google LLC +# +# 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. + +# Generated by the protocol buffer compiler. DO NOT EDIT! +# source: google/rpc/status.proto +# Protobuf Python Version: 4.25.3 +"""Generated protocol buffer code.""" + +from google.protobuf import descriptor as _descriptor +from google.protobuf import descriptor_pool as _descriptor_pool +from google.protobuf import symbol_database as _symbol_database +from google.protobuf.internal import builder as _builder + +# @@protoc_insertion_point(imports) + +_sym_db = _symbol_database.Default() + + +from google.protobuf import any_pb2 as google_dot_protobuf_dot_any__pb2 + +DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile( + b'\n\x17google/rpc/status.proto\x12\ngoogle.rpc\x1a\x19google/protobuf/any.proto"N\n\x06Status\x12\x0c\n\x04\x63ode\x18\x01 \x01(\x05\x12\x0f\n\x07message\x18\x02 \x01(\t\x12%\n\x07\x64\x65tails\x18\x03 \x03(\x0b\x32\x14.google.protobuf.AnyB^\n\x0e\x63om.google.rpcB\x0bStatusProtoP\x01Z7google.golang.org/genproto/googleapis/rpc/status;status\xa2\x02\x03RPCb\x06proto3' +) + +_globals = globals() +_builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, _globals) +_builder.BuildTopDescriptorsAndMessages(DESCRIPTOR, "google.rpc.status_pb2", _globals) +if _descriptor._USE_C_DESCRIPTORS == False: + _globals["DESCRIPTOR"]._options = None + _globals[ + "DESCRIPTOR" + ]._serialized_options = b"\n\016com.google.rpcB\013StatusProtoP\001Z7google.golang.org/genproto/googleapis/rpc/status;status\242\002\003RPC" + _globals["_STATUS"]._serialized_start = 66 + _globals["_STATUS"]._serialized_end = 144 +# @@protoc_insertion_point(module_scope) diff --git a/python/user_packages/Python313/site-packages/google/rpc/status_pb2.pyi b/python/user_packages/Python313/site-packages/google/rpc/status_pb2.pyi new file mode 100644 index 0000000000000000000000000000000000000000..ac386e228feef0c5527c92b14997d3eb03c71b7b --- /dev/null +++ b/python/user_packages/Python313/site-packages/google/rpc/status_pb2.pyi @@ -0,0 +1,41 @@ +# Copyright 2025 Google LLC +# +# 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. + +from typing import ClassVar as _ClassVar +from typing import Iterable as _Iterable +from typing import Mapping as _Mapping +from typing import Optional as _Optional +from typing import Union as _Union + +from google.protobuf import any_pb2 as _any_pb2 +from google.protobuf import descriptor as _descriptor +from google.protobuf import message as _message +from google.protobuf.internal import containers as _containers + +DESCRIPTOR: _descriptor.FileDescriptor + +class Status(_message.Message): + __slots__ = ("code", "message", "details") + CODE_FIELD_NUMBER: _ClassVar[int] + MESSAGE_FIELD_NUMBER: _ClassVar[int] + DETAILS_FIELD_NUMBER: _ClassVar[int] + code: int + message: str + details: _containers.RepeatedCompositeFieldContainer[_any_pb2.Any] + def __init__( + self, + code: _Optional[int] = ..., + message: _Optional[str] = ..., + details: _Optional[_Iterable[_Union[_any_pb2.Any, _Mapping]]] = ..., + ) -> None: ... diff --git a/python/user_packages/Python313/site-packages/google/type/__pycache__/calendar_period_pb2.cpython-313.pyc b/python/user_packages/Python313/site-packages/google/type/__pycache__/calendar_period_pb2.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6041d64b3abcf1173e0ec8dc98c755da4dd1a3a6 Binary files /dev/null and b/python/user_packages/Python313/site-packages/google/type/__pycache__/calendar_period_pb2.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/google/type/__pycache__/color_pb2.cpython-313.pyc b/python/user_packages/Python313/site-packages/google/type/__pycache__/color_pb2.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c991eecf8a854538ac6fb0ffbaacac088943b4cd Binary files /dev/null and b/python/user_packages/Python313/site-packages/google/type/__pycache__/color_pb2.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/google/type/__pycache__/date_pb2.cpython-313.pyc b/python/user_packages/Python313/site-packages/google/type/__pycache__/date_pb2.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1a7a69915f521c7d706bf7ef761841a8d830f0fb Binary files /dev/null and b/python/user_packages/Python313/site-packages/google/type/__pycache__/date_pb2.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/google/type/__pycache__/datetime_pb2.cpython-313.pyc b/python/user_packages/Python313/site-packages/google/type/__pycache__/datetime_pb2.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9ea5a7fb991108a1e0259f0a64e1c3728420e46e Binary files /dev/null and b/python/user_packages/Python313/site-packages/google/type/__pycache__/datetime_pb2.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/google/type/__pycache__/dayofweek_pb2.cpython-313.pyc b/python/user_packages/Python313/site-packages/google/type/__pycache__/dayofweek_pb2.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..41c7aafa57ed001c622a4a44c0f3cef6c32d336f Binary files /dev/null and b/python/user_packages/Python313/site-packages/google/type/__pycache__/dayofweek_pb2.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/google/type/__pycache__/decimal_pb2.cpython-313.pyc b/python/user_packages/Python313/site-packages/google/type/__pycache__/decimal_pb2.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ff6e166847b101910a04d1a846b86c031e7345ad Binary files /dev/null and b/python/user_packages/Python313/site-packages/google/type/__pycache__/decimal_pb2.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/google/type/__pycache__/expr_pb2.cpython-313.pyc b/python/user_packages/Python313/site-packages/google/type/__pycache__/expr_pb2.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b8d9d2b4ca4f689f65cd7906684ae177ba67afca Binary files /dev/null and b/python/user_packages/Python313/site-packages/google/type/__pycache__/expr_pb2.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/google/type/__pycache__/fraction_pb2.cpython-313.pyc b/python/user_packages/Python313/site-packages/google/type/__pycache__/fraction_pb2.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3e878d6a0f7693155af022bea8bd8b8933762a66 Binary files /dev/null and b/python/user_packages/Python313/site-packages/google/type/__pycache__/fraction_pb2.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/google/type/__pycache__/interval_pb2.cpython-313.pyc b/python/user_packages/Python313/site-packages/google/type/__pycache__/interval_pb2.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..beceecba192b7bec20655d3d3cb4b4f05ff17b92 Binary files /dev/null and b/python/user_packages/Python313/site-packages/google/type/__pycache__/interval_pb2.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/google/type/__pycache__/latlng_pb2.cpython-313.pyc b/python/user_packages/Python313/site-packages/google/type/__pycache__/latlng_pb2.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d2b9cedfaf64be8c662b92e4ec2f42629d7b6cc0 Binary files /dev/null and b/python/user_packages/Python313/site-packages/google/type/__pycache__/latlng_pb2.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/google/type/__pycache__/localized_text_pb2.cpython-313.pyc b/python/user_packages/Python313/site-packages/google/type/__pycache__/localized_text_pb2.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f90700b4917e0e2637b8a91f48ae74dede7db598 Binary files /dev/null and b/python/user_packages/Python313/site-packages/google/type/__pycache__/localized_text_pb2.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/google/type/__pycache__/money_pb2.cpython-313.pyc b/python/user_packages/Python313/site-packages/google/type/__pycache__/money_pb2.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..054d8e1060594283d43118fbeaf8725c1703e156 Binary files /dev/null and b/python/user_packages/Python313/site-packages/google/type/__pycache__/money_pb2.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/google/type/__pycache__/month_pb2.cpython-313.pyc b/python/user_packages/Python313/site-packages/google/type/__pycache__/month_pb2.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..76b932e6744c2c6163027364d94744ed5d1df243 Binary files /dev/null and b/python/user_packages/Python313/site-packages/google/type/__pycache__/month_pb2.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/google/type/__pycache__/phone_number_pb2.cpython-313.pyc b/python/user_packages/Python313/site-packages/google/type/__pycache__/phone_number_pb2.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..73b0a4b083e9038ef259151a87a595cc6ca0f598 Binary files /dev/null and b/python/user_packages/Python313/site-packages/google/type/__pycache__/phone_number_pb2.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/google/type/__pycache__/postal_address_pb2.cpython-313.pyc b/python/user_packages/Python313/site-packages/google/type/__pycache__/postal_address_pb2.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0e058f0488822e0b5bcc3474ce406464b8b15260 Binary files /dev/null and b/python/user_packages/Python313/site-packages/google/type/__pycache__/postal_address_pb2.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/google/type/__pycache__/quaternion_pb2.cpython-313.pyc b/python/user_packages/Python313/site-packages/google/type/__pycache__/quaternion_pb2.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c0836579385752b93fcb3cfad52791ee352bae8b Binary files /dev/null and b/python/user_packages/Python313/site-packages/google/type/__pycache__/quaternion_pb2.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/google/type/__pycache__/timeofday_pb2.cpython-313.pyc b/python/user_packages/Python313/site-packages/google/type/__pycache__/timeofday_pb2.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1577f9ee8790e33d348ee77bd510c5e6e6ae52bb Binary files /dev/null and b/python/user_packages/Python313/site-packages/google/type/__pycache__/timeofday_pb2.cpython-313.pyc differ diff --git a/python/user_packages/Python313/site-packages/google/type/calendar_period.proto b/python/user_packages/Python313/site-packages/google/type/calendar_period.proto new file mode 100644 index 0000000000000000000000000000000000000000..ae08aebd677038c965cf667fc596ce0257250ecd --- /dev/null +++ b/python/user_packages/Python313/site-packages/google/type/calendar_period.proto @@ -0,0 +1,56 @@ +// Copyright 2026 Google LLC +// +// 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. + +syntax = "proto3"; + +package google.type; + +option go_package = "google.golang.org/genproto/googleapis/type/calendarperiod;calendarperiod"; +option java_multiple_files = true; +option java_outer_classname = "CalendarPeriodProto"; +option java_package = "com.google.type"; +option objc_class_prefix = "GTP"; + +// A `CalendarPeriod` represents the abstract concept of a time period that has +// a canonical start. Grammatically, "the start of the current +// `CalendarPeriod`." All calendar times begin at midnight UTC. +enum CalendarPeriod { + // Undefined period, raises an error. + CALENDAR_PERIOD_UNSPECIFIED = 0; + + // A day. + DAY = 1; + + // A week. Weeks begin on Monday, following + // [ISO 8601](https://en.wikipedia.org/wiki/ISO_week_date). + WEEK = 2; + + // A fortnight. The first calendar fortnight of the year begins at the start + // of week 1 according to + // [ISO 8601](https://en.wikipedia.org/wiki/ISO_week_date). + FORTNIGHT = 3; + + // A month. + MONTH = 4; + + // A quarter. Quarters start on dates 1-Jan, 1-Apr, 1-Jul, and 1-Oct of each + // year. + QUARTER = 5; + + // A half-year. Half-years start on dates 1-Jan and 1-Jul. + HALF = 6; + + // A year. + YEAR = 7; +} diff --git a/python/user_packages/Python313/site-packages/google/type/calendar_period_pb2.py b/python/user_packages/Python313/site-packages/google/type/calendar_period_pb2.py new file mode 100644 index 0000000000000000000000000000000000000000..bdaa5304f8eaf2232fdab1cd0be3544c23652641 --- /dev/null +++ b/python/user_packages/Python313/site-packages/google/type/calendar_period_pb2.py @@ -0,0 +1,48 @@ +# -*- coding: utf-8 -*- + +# Copyright 2025 Google LLC +# +# 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. + +# Generated by the protocol buffer compiler. DO NOT EDIT! +# source: google/type/calendar_period.proto +# Protobuf Python Version: 4.25.3 +"""Generated protocol buffer code.""" + +from google.protobuf import descriptor as _descriptor +from google.protobuf import descriptor_pool as _descriptor_pool +from google.protobuf import symbol_database as _symbol_database +from google.protobuf.internal import builder as _builder + +# @@protoc_insertion_point(imports) + +_sym_db = _symbol_database.Default() + + +DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile( + b"\n!google/type/calendar_period.proto\x12\x0bgoogle.type*\x7f\n\x0e\x43\x61lendarPeriod\x12\x1f\n\x1b\x43\x41LENDAR_PERIOD_UNSPECIFIED\x10\x00\x12\x07\n\x03\x44\x41Y\x10\x01\x12\x08\n\x04WEEK\x10\x02\x12\r\n\tFORTNIGHT\x10\x03\x12\t\n\x05MONTH\x10\x04\x12\x0b\n\x07QUARTER\x10\x05\x12\x08\n\x04HALF\x10\x06\x12\x08\n\x04YEAR\x10\x07\x42x\n\x0f\x63om.google.typeB\x13\x43\x61lendarPeriodProtoP\x01ZHgoogle.golang.org/genproto/googleapis/type/calendarperiod;calendarperiod\xa2\x02\x03GTPb\x06proto3" +) + +_globals = globals() +_builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, _globals) +_builder.BuildTopDescriptorsAndMessages( + DESCRIPTOR, "google.type.calendar_period_pb2", _globals +) +if _descriptor._USE_C_DESCRIPTORS == False: + _globals["DESCRIPTOR"]._options = None + _globals[ + "DESCRIPTOR" + ]._serialized_options = b"\n\017com.google.typeB\023CalendarPeriodProtoP\001ZHgoogle.golang.org/genproto/googleapis/type/calendarperiod;calendarperiod\242\002\003GTP" + _globals["_CALENDARPERIOD"]._serialized_start = 50 + _globals["_CALENDARPERIOD"]._serialized_end = 177 +# @@protoc_insertion_point(module_scope) diff --git a/python/user_packages/Python313/site-packages/google/type/calendar_period_pb2.pyi b/python/user_packages/Python313/site-packages/google/type/calendar_period_pb2.pyi new file mode 100644 index 0000000000000000000000000000000000000000..2e230b4ed08c6f02448fe8f77ec6c2a356d01cdb --- /dev/null +++ b/python/user_packages/Python313/site-packages/google/type/calendar_period_pb2.pyi @@ -0,0 +1,40 @@ +# Copyright 2025 Google LLC +# +# 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. + +from typing import ClassVar as _ClassVar + +from google.protobuf import descriptor as _descriptor +from google.protobuf.internal import enum_type_wrapper as _enum_type_wrapper + +DESCRIPTOR: _descriptor.FileDescriptor + +class CalendarPeriod(int, metaclass=_enum_type_wrapper.EnumTypeWrapper): + __slots__ = () + CALENDAR_PERIOD_UNSPECIFIED: _ClassVar[CalendarPeriod] + DAY: _ClassVar[CalendarPeriod] + WEEK: _ClassVar[CalendarPeriod] + FORTNIGHT: _ClassVar[CalendarPeriod] + MONTH: _ClassVar[CalendarPeriod] + QUARTER: _ClassVar[CalendarPeriod] + HALF: _ClassVar[CalendarPeriod] + YEAR: _ClassVar[CalendarPeriod] + +CALENDAR_PERIOD_UNSPECIFIED: CalendarPeriod +DAY: CalendarPeriod +WEEK: CalendarPeriod +FORTNIGHT: CalendarPeriod +MONTH: CalendarPeriod +QUARTER: CalendarPeriod +HALF: CalendarPeriod +YEAR: CalendarPeriod diff --git a/python/user_packages/Python313/site-packages/google/type/color.proto b/python/user_packages/Python313/site-packages/google/type/color.proto new file mode 100644 index 0000000000000000000000000000000000000000..c48d0644a70f44fbccaa81421bf918862491553f --- /dev/null +++ b/python/user_packages/Python313/site-packages/google/type/color.proto @@ -0,0 +1,173 @@ +// Copyright 2026 Google LLC +// +// 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. + +syntax = "proto3"; + +package google.type; + +import "google/protobuf/wrappers.proto"; + +option go_package = "google.golang.org/genproto/googleapis/type/color;color"; +option java_multiple_files = true; +option java_outer_classname = "ColorProto"; +option java_package = "com.google.type"; +option objc_class_prefix = "GTP"; + +// Represents a color in the RGBA color space. This representation is designed +// for simplicity of conversion to and from color representations in various +// languages over compactness. For example, the fields of this representation +// can be trivially provided to the constructor of `java.awt.Color` in Java; it +// can also be trivially provided to UIColor's `+colorWithRed:green:blue:alpha` +// method in iOS; and, with just a little work, it can be easily formatted into +// a CSS `rgba()` string in JavaScript. +// +// This reference page doesn't have information about the absolute color +// space that should be used to interpret the RGB value—for example, sRGB, +// Adobe RGB, +// DCI-P3, and BT.2020. By default, applications should assume the sRGB color +// space. +// +// When color equality needs to be decided, implementations, unless documented +// otherwise, treat two colors as equal if all their red, green, blue, and alpha +// values each differ by at most `1e-5`. +// +// Example (Java): +// +// import com.google.type.Color; +// +// // ... +// public static java.awt.Color fromProto(Color protocolor) { +// float alpha = protocolor.hasAlpha() +// ? protocolor.getAlpha().getValue() +// : 1.0; +// +// return new java.awt.Color( +// protocolor.getRed(), +// protocolor.getGreen(), +// protocolor.getBlue(), +// alpha); +// } +// +// public static Color toProto(java.awt.Color color) { +// float red = (float) color.getRed(); +// float green = (float) color.getGreen(); +// float blue = (float) color.getBlue(); +// float denominator = 255.0; +// Color.Builder resultBuilder = +// Color +// .newBuilder() +// .setRed(red / denominator) +// .setGreen(green / denominator) +// .setBlue(blue / denominator); +// int alpha = color.getAlpha(); +// if (alpha != 255) { +// result.setAlpha( +// FloatValue +// .newBuilder() +// .setValue(((float) alpha) / denominator) +// .build()); +// } +// return resultBuilder.build(); +// } +// // ... +// +// Example (iOS / Obj-C): +// +// // ... +// static UIColor* fromProto(Color* protocolor) { +// float red = [protocolor red]; +// float green = [protocolor green]; +// float blue = [protocolor blue]; +// FloatValue* alpha_wrapper = [protocolor alpha]; +// float alpha = 1.0; +// if (alpha_wrapper != nil) { +// alpha = [alpha_wrapper value]; +// } +// return [UIColor colorWithRed:red green:green blue:blue alpha:alpha]; +// } +// +// static Color* toProto(UIColor* color) { +// CGFloat red, green, blue, alpha; +// if (![color getRed:&red green:&green blue:&blue alpha:&alpha]) { +// return nil; +// } +// Color* result = [[Color alloc] init]; +// [result setRed:red]; +// [result setGreen:green]; +// [result setBlue:blue]; +// if (alpha <= 0.9999) { +// [result setAlpha:floatWrapperWithValue(alpha)]; +// } +// [result autorelease]; +// return result; +// } +// // ... +// +// Example (JavaScript): +// +// // ... +// +// var protoToCssColor = function(rgb_color) { +// var redFrac = rgb_color.red || 0.0; +// var greenFrac = rgb_color.green || 0.0; +// var blueFrac = rgb_color.blue || 0.0; +// var red = Math.floor(redFrac * 255); +// var green = Math.floor(greenFrac * 255); +// var blue = Math.floor(blueFrac * 255); +// +// if (!('alpha' in rgb_color)) { +// return rgbToCssColor(red, green, blue); +// } +// +// var alphaFrac = rgb_color.alpha.value || 0.0; +// var rgbParams = [red, green, blue].join(','); +// return ['rgba(', rgbParams, ',', alphaFrac, ')'].join(''); +// }; +// +// var rgbToCssColor = function(red, green, blue) { +// var rgbNumber = new Number((red << 16) | (green << 8) | blue); +// var hexString = rgbNumber.toString(16); +// var missingZeros = 6 - hexString.length; +// var resultBuilder = ['#']; +// for (var i = 0; i < missingZeros; i++) { +// resultBuilder.push('0'); +// } +// resultBuilder.push(hexString); +// return resultBuilder.join(''); +// }; +// +// // ... +message Color { + // The amount of red in the color as a value in the interval [0, 1]. + float red = 1; + + // The amount of green in the color as a value in the interval [0, 1]. + float green = 2; + + // The amount of blue in the color as a value in the interval [0, 1]. + float blue = 3; + + // The fraction of this color that should be applied to the pixel. That is, + // the final pixel color is defined by the equation: + // + // `pixel color = alpha * (this color) + (1.0 - alpha) * (background color)` + // + // This means that a value of 1.0 corresponds to a solid color, whereas + // a value of 0.0 corresponds to a completely transparent color. This + // uses a wrapper message rather than a simple float scalar so that it is + // possible to distinguish between a default value and the value being unset. + // If omitted, this color object is rendered as a solid color + // (as if the alpha value had been explicitly given a value of 1.0). + google.protobuf.FloatValue alpha = 4; +} diff --git a/python/user_packages/Python313/site-packages/google/type/color_pb2.py b/python/user_packages/Python313/site-packages/google/type/color_pb2.py new file mode 100644 index 0000000000000000000000000000000000000000..4c45dd671dc84cc63a758e89150f9fde15164f00 --- /dev/null +++ b/python/user_packages/Python313/site-packages/google/type/color_pb2.py @@ -0,0 +1,48 @@ +# -*- coding: utf-8 -*- + +# Copyright 2025 Google LLC +# +# 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. + +# Generated by the protocol buffer compiler. DO NOT EDIT! +# source: google/type/color.proto +# Protobuf Python Version: 4.25.3 +"""Generated protocol buffer code.""" + +from google.protobuf import descriptor as _descriptor +from google.protobuf import descriptor_pool as _descriptor_pool +from google.protobuf import symbol_database as _symbol_database +from google.protobuf.internal import builder as _builder + +# @@protoc_insertion_point(imports) + +_sym_db = _symbol_database.Default() + + +from google.protobuf import wrappers_pb2 as google_dot_protobuf_dot_wrappers__pb2 + +DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile( + b'\n\x17google/type/color.proto\x12\x0bgoogle.type\x1a\x1egoogle/protobuf/wrappers.proto"]\n\x05\x43olor\x12\x0b\n\x03red\x18\x01 \x01(\x02\x12\r\n\x05green\x18\x02 \x01(\x02\x12\x0c\n\x04\x62lue\x18\x03 \x01(\x02\x12*\n\x05\x61lpha\x18\x04 \x01(\x0b\x32\x1b.google.protobuf.FloatValueB]\n\x0f\x63om.google.typeB\nColorProtoP\x01Z6google.golang.org/genproto/googleapis/type/color;color\xa2\x02\x03GTPb\x06proto3' +) + +_globals = globals() +_builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, _globals) +_builder.BuildTopDescriptorsAndMessages(DESCRIPTOR, "google.type.color_pb2", _globals) +if _descriptor._USE_C_DESCRIPTORS == False: + _globals["DESCRIPTOR"]._options = None + _globals[ + "DESCRIPTOR" + ]._serialized_options = b"\n\017com.google.typeB\nColorProtoP\001Z6google.golang.org/genproto/googleapis/type/color;color\242\002\003GTP" + _globals["_COLOR"]._serialized_start = 72 + _globals["_COLOR"]._serialized_end = 165 +# @@protoc_insertion_point(module_scope) diff --git a/python/user_packages/Python313/site-packages/google/type/color_pb2.pyi b/python/user_packages/Python313/site-packages/google/type/color_pb2.pyi new file mode 100644 index 0000000000000000000000000000000000000000..93a51cd310e7beba71b4ca7f07456e4bf3e944b9 --- /dev/null +++ b/python/user_packages/Python313/site-packages/google/type/color_pb2.pyi @@ -0,0 +1,42 @@ +# Copyright 2025 Google LLC +# +# 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. + +from typing import ClassVar as _ClassVar +from typing import Mapping as _Mapping +from typing import Optional as _Optional +from typing import Union as _Union + +from google.protobuf import descriptor as _descriptor +from google.protobuf import message as _message +from google.protobuf import wrappers_pb2 as _wrappers_pb2 + +DESCRIPTOR: _descriptor.FileDescriptor + +class Color(_message.Message): + __slots__ = ("red", "green", "blue", "alpha") + RED_FIELD_NUMBER: _ClassVar[int] + GREEN_FIELD_NUMBER: _ClassVar[int] + BLUE_FIELD_NUMBER: _ClassVar[int] + ALPHA_FIELD_NUMBER: _ClassVar[int] + red: float + green: float + blue: float + alpha: _wrappers_pb2.FloatValue + def __init__( + self, + red: _Optional[float] = ..., + green: _Optional[float] = ..., + blue: _Optional[float] = ..., + alpha: _Optional[_Union[_wrappers_pb2.FloatValue, _Mapping]] = ..., + ) -> None: ... diff --git a/python/user_packages/Python313/site-packages/google/type/date.proto b/python/user_packages/Python313/site-packages/google/type/date.proto new file mode 100644 index 0000000000000000000000000000000000000000..12be7e16a48bc13784ae27e1fb5f129ad916fcdb --- /dev/null +++ b/python/user_packages/Python313/site-packages/google/type/date.proto @@ -0,0 +1,54 @@ +// Copyright 2026 Google LLC +// +// 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. + +syntax = "proto3"; + +package google.type; + +option go_package = "google.golang.org/genproto/googleapis/type/date;date"; +option java_multiple_files = true; +option java_outer_classname = "DateProto"; +option java_package = "com.google.type"; +option objc_class_prefix = "GTP"; + +// Represents a whole or partial calendar date, such as a birthday. The time of +// day and time zone are either specified elsewhere or are insignificant. The +// date is relative to the Gregorian Calendar. This can represent one of the +// following: +// +// * A full date, with non-zero year, month, and day values. +// * A month and day, with a zero year (for example, an anniversary). +// * A year on its own, with a zero month and a zero day. +// * A year and month, with a zero day (for example, a credit card expiration +// date). +// +// Related types: +// +// * [google.type.TimeOfDay][google.type.TimeOfDay] +// * [google.type.DateTime][google.type.DateTime] +// * [google.protobuf.Timestamp][google.protobuf.Timestamp] +message Date { + // Year of the date. Must be from 1 to 9999, or 0 to specify a date without + // a year. + int32 year = 1; + + // Month of a year. Must be from 1 to 12, or 0 to specify a year without a + // month and day. + int32 month = 2; + + // Day of a month. Must be from 1 to 31 and valid for the year and month, or 0 + // to specify a year by itself or a year and month where the day isn't + // significant. + int32 day = 3; +} diff --git a/python/user_packages/Python313/site-packages/google/type/date_pb2.py b/python/user_packages/Python313/site-packages/google/type/date_pb2.py new file mode 100644 index 0000000000000000000000000000000000000000..3fcad8ffa9a9091e2b1bddcb8628612049e1db73 --- /dev/null +++ b/python/user_packages/Python313/site-packages/google/type/date_pb2.py @@ -0,0 +1,46 @@ +# -*- coding: utf-8 -*- + +# Copyright 2025 Google LLC +# +# 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. + +# Generated by the protocol buffer compiler. DO NOT EDIT! +# source: google/type/date.proto +# Protobuf Python Version: 4.25.3 +"""Generated protocol buffer code.""" + +from google.protobuf import descriptor as _descriptor +from google.protobuf import descriptor_pool as _descriptor_pool +from google.protobuf import symbol_database as _symbol_database +from google.protobuf.internal import builder as _builder + +# @@protoc_insertion_point(imports) + +_sym_db = _symbol_database.Default() + + +DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile( + b'\n\x16google/type/date.proto\x12\x0bgoogle.type"0\n\x04\x44\x61te\x12\x0c\n\x04year\x18\x01 \x01(\x05\x12\r\n\x05month\x18\x02 \x01(\x05\x12\x0b\n\x03\x64\x61y\x18\x03 \x01(\x05\x42Z\n\x0f\x63om.google.typeB\tDateProtoP\x01Z4google.golang.org/genproto/googleapis/type/date;date\xa2\x02\x03GTPb\x06proto3' +) + +_globals = globals() +_builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, _globals) +_builder.BuildTopDescriptorsAndMessages(DESCRIPTOR, "google.type.date_pb2", _globals) +if _descriptor._USE_C_DESCRIPTORS == False: + _globals["DESCRIPTOR"]._options = None + _globals[ + "DESCRIPTOR" + ]._serialized_options = b"\n\017com.google.typeB\tDateProtoP\001Z4google.golang.org/genproto/googleapis/type/date;date\242\002\003GTP" + _globals["_DATE"]._serialized_start = 39 + _globals["_DATE"]._serialized_end = 87 +# @@protoc_insertion_point(module_scope) diff --git a/python/user_packages/Python313/site-packages/google/type/date_pb2.pyi b/python/user_packages/Python313/site-packages/google/type/date_pb2.pyi new file mode 100644 index 0000000000000000000000000000000000000000..fcaf2f9984af7bd0be3f457ccb6936d146c226f8 --- /dev/null +++ b/python/user_packages/Python313/site-packages/google/type/date_pb2.pyi @@ -0,0 +1,36 @@ +# Copyright 2025 Google LLC +# +# 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. + +from typing import ClassVar as _ClassVar +from typing import Optional as _Optional + +from google.protobuf import descriptor as _descriptor +from google.protobuf import message as _message + +DESCRIPTOR: _descriptor.FileDescriptor + +class Date(_message.Message): + __slots__ = ("year", "month", "day") + YEAR_FIELD_NUMBER: _ClassVar[int] + MONTH_FIELD_NUMBER: _ClassVar[int] + DAY_FIELD_NUMBER: _ClassVar[int] + year: int + month: int + day: int + def __init__( + self, + year: _Optional[int] = ..., + month: _Optional[int] = ..., + day: _Optional[int] = ..., + ) -> None: ... diff --git a/python/user_packages/Python313/site-packages/google/type/datetime.proto b/python/user_packages/Python313/site-packages/google/type/datetime.proto new file mode 100644 index 0000000000000000000000000000000000000000..b81e4f472f973802b1484ce1792e45aa393d2688 --- /dev/null +++ b/python/user_packages/Python313/site-packages/google/type/datetime.proto @@ -0,0 +1,104 @@ +// Copyright 2026 Google LLC +// +// 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. + +syntax = "proto3"; + +package google.type; + +import "google/protobuf/duration.proto"; + +option go_package = "google.golang.org/genproto/googleapis/type/datetime;datetime"; +option java_multiple_files = true; +option java_outer_classname = "DateTimeProto"; +option java_package = "com.google.type"; +option objc_class_prefix = "GTP"; + +// Represents civil time (or occasionally physical time). +// +// This type can represent a civil time in one of a few possible ways: +// +// * When utc_offset is set and time_zone is unset: a civil time on a calendar +// day with a particular offset from UTC. +// * When time_zone is set and utc_offset is unset: a civil time on a calendar +// day in a particular time zone. +// * When neither time_zone nor utc_offset is set: a civil time on a calendar +// day in local time. +// +// The date is relative to the Proleptic Gregorian Calendar. +// +// If year, month, or day are 0, the DateTime is considered not to have a +// specific year, month, or day respectively. +// +// This type may also be used to represent a physical time if all the date and +// time fields are set and either case of the `time_offset` oneof is set. +// Consider using `Timestamp` message for physical time instead. If your use +// case also would like to store the user's timezone, that can be done in +// another field. +// +// This type is more flexible than some applications may want. Make sure to +// document and validate your application's limitations. +message DateTime { + // Optional. Year of date. Must be from 1 to 9999, or 0 if specifying a + // datetime without a year. + int32 year = 1; + + // Optional. Month of year. Must be from 1 to 12, or 0 if specifying a + // datetime without a month. + int32 month = 2; + + // Optional. Day of month. Must be from 1 to 31 and valid for the year and + // month, or 0 if specifying a datetime without a day. + int32 day = 3; + + // Optional. Hours of day in 24 hour format. Should be from 0 to 23, defaults + // to 0 (midnight). An API may choose to allow the value "24:00:00" for + // scenarios like business closing time. + int32 hours = 4; + + // Optional. Minutes of hour of day. Must be from 0 to 59, defaults to 0. + int32 minutes = 5; + + // Optional. Seconds of minutes of the time. Must normally be from 0 to 59, + // defaults to 0. An API may allow the value 60 if it allows leap-seconds. + int32 seconds = 6; + + // Optional. Fractions of seconds in nanoseconds. Must be from 0 to + // 999,999,999, defaults to 0. + int32 nanos = 7; + + // Optional. Specifies either the UTC offset or the time zone of the DateTime. + // Choose carefully between them, considering that time zone data may change + // in the future (for example, a country modifies their DST start/end dates, + // and future DateTimes in the affected range had already been stored). + // If omitted, the DateTime is considered to be in local time. + oneof time_offset { + // UTC offset. Must be whole seconds, between -18 hours and +18 hours. + // For example, a UTC offset of -4:00 would be represented as + // { seconds: -14400 }. + google.protobuf.Duration utc_offset = 8; + + // Time zone. + TimeZone time_zone = 9; + } +} + +// Represents a time zone from the +// [IANA Time Zone Database](https://www.iana.org/time-zones). +message TimeZone { + // IANA Time Zone Database time zone. For example "America/New_York". + string id = 1; + + // Optional. IANA Time Zone Database version number. For example "2019a". + string version = 2; +} diff --git a/python/user_packages/Python313/site-packages/google/type/datetime_pb2.py b/python/user_packages/Python313/site-packages/google/type/datetime_pb2.py new file mode 100644 index 0000000000000000000000000000000000000000..f0b66396b46e3a2aedcfe4fb73572e5838187e54 --- /dev/null +++ b/python/user_packages/Python313/site-packages/google/type/datetime_pb2.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- + +# Copyright 2025 Google LLC +# +# 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. + +# Generated by the protocol buffer compiler. DO NOT EDIT! +# source: google/type/datetime.proto +# Protobuf Python Version: 4.25.3 +"""Generated protocol buffer code.""" + +from google.protobuf import descriptor as _descriptor +from google.protobuf import descriptor_pool as _descriptor_pool +from google.protobuf import symbol_database as _symbol_database +from google.protobuf.internal import builder as _builder + +# @@protoc_insertion_point(imports) + +_sym_db = _symbol_database.Default() + + +from google.protobuf import duration_pb2 as google_dot_protobuf_dot_duration__pb2 + +DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile( + b'\n\x1agoogle/type/datetime.proto\x12\x0bgoogle.type\x1a\x1egoogle/protobuf/duration.proto"\xe0\x01\n\x08\x44\x61teTime\x12\x0c\n\x04year\x18\x01 \x01(\x05\x12\r\n\x05month\x18\x02 \x01(\x05\x12\x0b\n\x03\x64\x61y\x18\x03 \x01(\x05\x12\r\n\x05hours\x18\x04 \x01(\x05\x12\x0f\n\x07minutes\x18\x05 \x01(\x05\x12\x0f\n\x07seconds\x18\x06 \x01(\x05\x12\r\n\x05nanos\x18\x07 \x01(\x05\x12/\n\nutc_offset\x18\x08 \x01(\x0b\x32\x19.google.protobuf.DurationH\x00\x12*\n\ttime_zone\x18\t \x01(\x0b\x32\x15.google.type.TimeZoneH\x00\x42\r\n\x0btime_offset"\'\n\x08TimeZone\x12\n\n\x02id\x18\x01 \x01(\t\x12\x0f\n\x07version\x18\x02 \x01(\tBf\n\x0f\x63om.google.typeB\rDateTimeProtoP\x01Z None: ... + +class TimeZone(_message.Message): + __slots__ = ("id", "version") + ID_FIELD_NUMBER: _ClassVar[int] + VERSION_FIELD_NUMBER: _ClassVar[int] + id: str + version: str + def __init__( + self, id: _Optional[str] = ..., version: _Optional[str] = ... + ) -> None: ... diff --git a/python/user_packages/Python313/site-packages/google/type/dayofweek.proto b/python/user_packages/Python313/site-packages/google/type/dayofweek.proto new file mode 100644 index 0000000000000000000000000000000000000000..669d89401c1821b5ea7aa911567f39f543d5b283 --- /dev/null +++ b/python/user_packages/Python313/site-packages/google/type/dayofweek.proto @@ -0,0 +1,50 @@ +// Copyright 2026 Google LLC +// +// 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. + +syntax = "proto3"; + +package google.type; + +option go_package = "google.golang.org/genproto/googleapis/type/dayofweek;dayofweek"; +option java_multiple_files = true; +option java_outer_classname = "DayOfWeekProto"; +option java_package = "com.google.type"; +option objc_class_prefix = "GTP"; + +// Represents a day of the week. +enum DayOfWeek { + // The day of the week is unspecified. + DAY_OF_WEEK_UNSPECIFIED = 0; + + // Monday + MONDAY = 1; + + // Tuesday + TUESDAY = 2; + + // Wednesday + WEDNESDAY = 3; + + // Thursday + THURSDAY = 4; + + // Friday + FRIDAY = 5; + + // Saturday + SATURDAY = 6; + + // Sunday + SUNDAY = 7; +} diff --git a/python/user_packages/Python313/site-packages/google/type/dayofweek_pb2.py b/python/user_packages/Python313/site-packages/google/type/dayofweek_pb2.py new file mode 100644 index 0000000000000000000000000000000000000000..3cbc442d255bdb65df3805c3a566157c77a1a80b --- /dev/null +++ b/python/user_packages/Python313/site-packages/google/type/dayofweek_pb2.py @@ -0,0 +1,48 @@ +# -*- coding: utf-8 -*- + +# Copyright 2025 Google LLC +# +# 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. + +# Generated by the protocol buffer compiler. DO NOT EDIT! +# source: google/type/dayofweek.proto +# Protobuf Python Version: 4.25.3 +"""Generated protocol buffer code.""" + +from google.protobuf import descriptor as _descriptor +from google.protobuf import descriptor_pool as _descriptor_pool +from google.protobuf import symbol_database as _symbol_database +from google.protobuf.internal import builder as _builder + +# @@protoc_insertion_point(imports) + +_sym_db = _symbol_database.Default() + + +DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile( + b"\n\x1bgoogle/type/dayofweek.proto\x12\x0bgoogle.type*\x84\x01\n\tDayOfWeek\x12\x1b\n\x17\x44\x41Y_OF_WEEK_UNSPECIFIED\x10\x00\x12\n\n\x06MONDAY\x10\x01\x12\x0b\n\x07TUESDAY\x10\x02\x12\r\n\tWEDNESDAY\x10\x03\x12\x0c\n\x08THURSDAY\x10\x04\x12\n\n\x06\x46RIDAY\x10\x05\x12\x0c\n\x08SATURDAY\x10\x06\x12\n\n\x06SUNDAY\x10\x07\x42i\n\x0f\x63om.google.typeB\x0e\x44\x61yOfWeekProtoP\x01Z>google.golang.org/genproto/googleapis/type/dayofweek;dayofweek\xa2\x02\x03GTPb\x06proto3" +) + +_globals = globals() +_builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, _globals) +_builder.BuildTopDescriptorsAndMessages( + DESCRIPTOR, "google.type.dayofweek_pb2", _globals +) +if _descriptor._USE_C_DESCRIPTORS == False: + _globals["DESCRIPTOR"]._options = None + _globals[ + "DESCRIPTOR" + ]._serialized_options = b"\n\017com.google.typeB\016DayOfWeekProtoP\001Z>google.golang.org/genproto/googleapis/type/dayofweek;dayofweek\242\002\003GTP" + _globals["_DAYOFWEEK"]._serialized_start = 45 + _globals["_DAYOFWEEK"]._serialized_end = 177 +# @@protoc_insertion_point(module_scope) diff --git a/python/user_packages/Python313/site-packages/google/type/dayofweek_pb2.pyi b/python/user_packages/Python313/site-packages/google/type/dayofweek_pb2.pyi new file mode 100644 index 0000000000000000000000000000000000000000..34c6770654e1760d13500cc78bfcfd2e2f695540 --- /dev/null +++ b/python/user_packages/Python313/site-packages/google/type/dayofweek_pb2.pyi @@ -0,0 +1,40 @@ +# Copyright 2025 Google LLC +# +# 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. + +from typing import ClassVar as _ClassVar + +from google.protobuf import descriptor as _descriptor +from google.protobuf.internal import enum_type_wrapper as _enum_type_wrapper + +DESCRIPTOR: _descriptor.FileDescriptor + +class DayOfWeek(int, metaclass=_enum_type_wrapper.EnumTypeWrapper): + __slots__ = () + DAY_OF_WEEK_UNSPECIFIED: _ClassVar[DayOfWeek] + MONDAY: _ClassVar[DayOfWeek] + TUESDAY: _ClassVar[DayOfWeek] + WEDNESDAY: _ClassVar[DayOfWeek] + THURSDAY: _ClassVar[DayOfWeek] + FRIDAY: _ClassVar[DayOfWeek] + SATURDAY: _ClassVar[DayOfWeek] + SUNDAY: _ClassVar[DayOfWeek] + +DAY_OF_WEEK_UNSPECIFIED: DayOfWeek +MONDAY: DayOfWeek +TUESDAY: DayOfWeek +WEDNESDAY: DayOfWeek +THURSDAY: DayOfWeek +FRIDAY: DayOfWeek +SATURDAY: DayOfWeek +SUNDAY: DayOfWeek diff --git a/python/user_packages/Python313/site-packages/google/type/decimal.proto b/python/user_packages/Python313/site-packages/google/type/decimal.proto new file mode 100644 index 0000000000000000000000000000000000000000..353e14b477a9ed506af2248f221ad6b03b57542c --- /dev/null +++ b/python/user_packages/Python313/site-packages/google/type/decimal.proto @@ -0,0 +1,93 @@ +// Copyright 2026 Google LLC +// +// 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. + +syntax = "proto3"; + +package google.type; + +option go_package = "google.golang.org/genproto/googleapis/type/decimal;decimal"; +option java_multiple_files = true; +option java_outer_classname = "DecimalProto"; +option java_package = "com.google.type"; +option objc_class_prefix = "GTP"; + +// A representation of a decimal value, such as 2.5. Clients may convert values +// into language-native decimal formats, such as Java's +// [BigDecimal](https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/math/BigDecimal.html) +// or Python's +// [decimal.Decimal](https://docs.python.org/3/library/decimal.html). +message Decimal { + // The decimal value, as a string. + // + // The string representation consists of an optional sign, `+` (`U+002B`) + // or `-` (`U+002D`), followed by a sequence of zero or more decimal digits + // ("the integer"), optionally followed by a fraction, optionally followed + // by an exponent. An empty string **should** be interpreted as `0`. + // + // The fraction consists of a decimal point followed by zero or more decimal + // digits. The string must contain at least one digit in either the integer + // or the fraction. The number formed by the sign, the integer and the + // fraction is referred to as the significand. + // + // The exponent consists of the character `e` (`U+0065`) or `E` (`U+0045`) + // followed by one or more decimal digits. + // + // Services **should** normalize decimal values before storing them by: + // + // - Removing an explicitly-provided `+` sign (`+2.5` -> `2.5`). + // - Replacing a zero-length integer value with `0` (`.5` -> `0.5`). + // - Coercing the exponent character to upper-case, with explicit sign + // (`2.5e8` -> `2.5E+8`). + // - Removing an explicitly-provided zero exponent (`2.5E0` -> `2.5`). + // + // Services **may** perform additional normalization based on its own needs + // and the internal decimal implementation selected, such as shifting the + // decimal point and exponent value together (example: `2.5E-1` <-> `0.25`). + // Additionally, services **may** preserve trailing zeroes in the fraction + // to indicate increased precision, but are not required to do so. + // + // Note that only the `.` character is supported to divide the integer + // and the fraction; `,` **should not** be supported regardless of locale. + // Additionally, thousand separators **should not** be supported. If a + // service does support them, values **must** be normalized. + // + // The ENBF grammar is: + // + // DecimalString = + // '' | [Sign] Significand [Exponent]; + // + // Sign = '+' | '-'; + // + // Significand = + // Digits ['.'] [Digits] | [Digits] '.' Digits; + // + // Exponent = ('e' | 'E') [Sign] Digits; + // + // Digits = { '0' | '1' | '2' | '3' | '4' | '5' | '6' | '7' | '8' | '9' }; + // + // Services **should** clearly document the range of supported values, the + // maximum supported precision (total number of digits), and, if applicable, + // the scale (number of digits after the decimal point), as well as how it + // behaves when receiving out-of-bounds values. + // + // Services **may** choose to accept values passed as input even when the + // value has a higher precision or scale than the service supports, and + // **should** round the value to fit the supported scale. Alternatively, the + // service **may** error with `400 Bad Request` (`INVALID_ARGUMENT` in gRPC) + // if precision would be lost. + // + // Services **should** error with `400 Bad Request` (`INVALID_ARGUMENT` in + // gRPC) if the service receives a value outside of the supported range. + string value = 1; +} diff --git a/python/user_packages/Python313/site-packages/google/type/decimal_pb2.py b/python/user_packages/Python313/site-packages/google/type/decimal_pb2.py new file mode 100644 index 0000000000000000000000000000000000000000..1390a03b1fef3030e01c3b6c5e4cb5f7c3b328b5 --- /dev/null +++ b/python/user_packages/Python313/site-packages/google/type/decimal_pb2.py @@ -0,0 +1,46 @@ +# -*- coding: utf-8 -*- + +# Copyright 2025 Google LLC +# +# 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. + +# Generated by the protocol buffer compiler. DO NOT EDIT! +# source: google/type/decimal.proto +# Protobuf Python Version: 4.25.3 +"""Generated protocol buffer code.""" + +from google.protobuf import descriptor as _descriptor +from google.protobuf import descriptor_pool as _descriptor_pool +from google.protobuf import symbol_database as _symbol_database +from google.protobuf.internal import builder as _builder + +# @@protoc_insertion_point(imports) + +_sym_db = _symbol_database.Default() + + +DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile( + b'\n\x19google/type/decimal.proto\x12\x0bgoogle.type"\x18\n\x07\x44\x65\x63imal\x12\r\n\x05value\x18\x01 \x01(\tBc\n\x0f\x63om.google.typeB\x0c\x44\x65\x63imalProtoP\x01Z:google.golang.org/genproto/googleapis/type/decimal;decimal\xa2\x02\x03GTPb\x06proto3' +) + +_globals = globals() +_builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, _globals) +_builder.BuildTopDescriptorsAndMessages(DESCRIPTOR, "google.type.decimal_pb2", _globals) +if _descriptor._USE_C_DESCRIPTORS == False: + _globals["DESCRIPTOR"]._options = None + _globals[ + "DESCRIPTOR" + ]._serialized_options = b"\n\017com.google.typeB\014DecimalProtoP\001Z:google.golang.org/genproto/googleapis/type/decimal;decimal\242\002\003GTP" + _globals["_DECIMAL"]._serialized_start = 42 + _globals["_DECIMAL"]._serialized_end = 66 +# @@protoc_insertion_point(module_scope) diff --git a/python/user_packages/Python313/site-packages/google/type/decimal_pb2.pyi b/python/user_packages/Python313/site-packages/google/type/decimal_pb2.pyi new file mode 100644 index 0000000000000000000000000000000000000000..95f43e305a7d55a9f840c44cfb3fbe95eb193c22 --- /dev/null +++ b/python/user_packages/Python313/site-packages/google/type/decimal_pb2.pyi @@ -0,0 +1,27 @@ +# Copyright 2025 Google LLC +# +# 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. + +from typing import ClassVar as _ClassVar +from typing import Optional as _Optional + +from google.protobuf import descriptor as _descriptor +from google.protobuf import message as _message + +DESCRIPTOR: _descriptor.FileDescriptor + +class Decimal(_message.Message): + __slots__ = ("value",) + VALUE_FIELD_NUMBER: _ClassVar[int] + value: str + def __init__(self, value: _Optional[str] = ...) -> None: ... diff --git a/python/user_packages/Python313/site-packages/google/type/expr.proto b/python/user_packages/Python313/site-packages/google/type/expr.proto new file mode 100644 index 0000000000000000000000000000000000000000..2fca5cda3151c24b3efd6e409d51324749b30261 --- /dev/null +++ b/python/user_packages/Python313/site-packages/google/type/expr.proto @@ -0,0 +1,73 @@ +// Copyright 2026 Google LLC +// +// 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. + +syntax = "proto3"; + +package google.type; + +option go_package = "google.golang.org/genproto/googleapis/type/expr;expr"; +option java_multiple_files = true; +option java_outer_classname = "ExprProto"; +option java_package = "com.google.type"; +option objc_class_prefix = "GTP"; + +// Represents a textual expression in the Common Expression Language (CEL) +// syntax. CEL is a C-like expression language. The syntax and semantics of CEL +// are documented at https://github.com/google/cel-spec. +// +// Example (Comparison): +// +// title: "Summary size limit" +// description: "Determines if a summary is less than 100 chars" +// expression: "document.summary.size() < 100" +// +// Example (Equality): +// +// title: "Requestor is owner" +// description: "Determines if requestor is the document owner" +// expression: "document.owner == request.auth.claims.email" +// +// Example (Logic): +// +// title: "Public documents" +// description: "Determine whether the document should be publicly visible" +// expression: "document.type != 'private' && document.type != 'internal'" +// +// Example (Data Manipulation): +// +// title: "Notification string" +// description: "Create a notification string with a timestamp." +// expression: "'New message received at ' + string(document.create_time)" +// +// The exact variables and functions that may be referenced within an expression +// are determined by the service that evaluates it. See the service +// documentation for additional information. +message Expr { + // Textual representation of an expression in Common Expression Language + // syntax. + string expression = 1; + + // Optional. Title for the expression, i.e. a short string describing + // its purpose. This can be used e.g. in UIs which allow to enter the + // expression. + string title = 2; + + // Optional. Description of the expression. This is a longer text which + // describes the expression, e.g. when hovered over it in a UI. + string description = 3; + + // Optional. String indicating the location of the expression for error + // reporting, e.g. a file name and a position in the file. + string location = 4; +} diff --git a/python/user_packages/Python313/site-packages/google/type/expr_pb2.py b/python/user_packages/Python313/site-packages/google/type/expr_pb2.py new file mode 100644 index 0000000000000000000000000000000000000000..c26d068cd41b488dd26ee5d54dc006e4bb70a3ec --- /dev/null +++ b/python/user_packages/Python313/site-packages/google/type/expr_pb2.py @@ -0,0 +1,46 @@ +# -*- coding: utf-8 -*- + +# Copyright 2025 Google LLC +# +# 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. + +# Generated by the protocol buffer compiler. DO NOT EDIT! +# source: google/type/expr.proto +# Protobuf Python Version: 4.25.3 +"""Generated protocol buffer code.""" + +from google.protobuf import descriptor as _descriptor +from google.protobuf import descriptor_pool as _descriptor_pool +from google.protobuf import symbol_database as _symbol_database +from google.protobuf.internal import builder as _builder + +# @@protoc_insertion_point(imports) + +_sym_db = _symbol_database.Default() + + +DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile( + b'\n\x16google/type/expr.proto\x12\x0bgoogle.type"P\n\x04\x45xpr\x12\x12\n\nexpression\x18\x01 \x01(\t\x12\r\n\x05title\x18\x02 \x01(\t\x12\x13\n\x0b\x64\x65scription\x18\x03 \x01(\t\x12\x10\n\x08location\x18\x04 \x01(\tBZ\n\x0f\x63om.google.typeB\tExprProtoP\x01Z4google.golang.org/genproto/googleapis/type/expr;expr\xa2\x02\x03GTPb\x06proto3' +) + +_globals = globals() +_builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, _globals) +_builder.BuildTopDescriptorsAndMessages(DESCRIPTOR, "google.type.expr_pb2", _globals) +if _descriptor._USE_C_DESCRIPTORS == False: + _globals["DESCRIPTOR"]._options = None + _globals[ + "DESCRIPTOR" + ]._serialized_options = b"\n\017com.google.typeB\tExprProtoP\001Z4google.golang.org/genproto/googleapis/type/expr;expr\242\002\003GTP" + _globals["_EXPR"]._serialized_start = 39 + _globals["_EXPR"]._serialized_end = 119 +# @@protoc_insertion_point(module_scope) diff --git a/python/user_packages/Python313/site-packages/google/type/expr_pb2.pyi b/python/user_packages/Python313/site-packages/google/type/expr_pb2.pyi new file mode 100644 index 0000000000000000000000000000000000000000..a1a55662b924800dbc0bf7913337777f7f0b6203 --- /dev/null +++ b/python/user_packages/Python313/site-packages/google/type/expr_pb2.pyi @@ -0,0 +1,39 @@ +# Copyright 2025 Google LLC +# +# 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. + +from typing import ClassVar as _ClassVar +from typing import Optional as _Optional + +from google.protobuf import descriptor as _descriptor +from google.protobuf import message as _message + +DESCRIPTOR: _descriptor.FileDescriptor + +class Expr(_message.Message): + __slots__ = ("expression", "title", "description", "location") + EXPRESSION_FIELD_NUMBER: _ClassVar[int] + TITLE_FIELD_NUMBER: _ClassVar[int] + DESCRIPTION_FIELD_NUMBER: _ClassVar[int] + LOCATION_FIELD_NUMBER: _ClassVar[int] + expression: str + title: str + description: str + location: str + def __init__( + self, + expression: _Optional[str] = ..., + title: _Optional[str] = ..., + description: _Optional[str] = ..., + location: _Optional[str] = ..., + ) -> None: ... diff --git a/python/user_packages/Python313/site-packages/google/type/fraction.proto b/python/user_packages/Python313/site-packages/google/type/fraction.proto new file mode 100644 index 0000000000000000000000000000000000000000..72f90b3113ebaf46ac293f8aba821f5c970d2133 --- /dev/null +++ b/python/user_packages/Python313/site-packages/google/type/fraction.proto @@ -0,0 +1,33 @@ +// Copyright 2026 Google LLC +// +// 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. + +syntax = "proto3"; + +package google.type; + +option go_package = "google.golang.org/genproto/googleapis/type/fraction;fraction"; +option java_multiple_files = true; +option java_outer_classname = "FractionProto"; +option java_package = "com.google.type"; +option objc_class_prefix = "GTP"; + +// Represents a fraction in terms of a numerator divided by a denominator. +message Fraction { + // The numerator in the fraction, e.g. 2 in 2/3. + int64 numerator = 1; + + // The value by which the numerator is divided, e.g. 3 in 2/3. Must be + // positive. + int64 denominator = 2; +} diff --git a/python/user_packages/Python313/site-packages/google/type/fraction_pb2.py b/python/user_packages/Python313/site-packages/google/type/fraction_pb2.py new file mode 100644 index 0000000000000000000000000000000000000000..c8ef97a75de352950a8a5d9647b2cf65d23c0b56 --- /dev/null +++ b/python/user_packages/Python313/site-packages/google/type/fraction_pb2.py @@ -0,0 +1,48 @@ +# -*- coding: utf-8 -*- + +# Copyright 2025 Google LLC +# +# 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. + +# Generated by the protocol buffer compiler. DO NOT EDIT! +# source: google/type/fraction.proto +# Protobuf Python Version: 4.25.3 +"""Generated protocol buffer code.""" + +from google.protobuf import descriptor as _descriptor +from google.protobuf import descriptor_pool as _descriptor_pool +from google.protobuf import symbol_database as _symbol_database +from google.protobuf.internal import builder as _builder + +# @@protoc_insertion_point(imports) + +_sym_db = _symbol_database.Default() + + +DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile( + b'\n\x1agoogle/type/fraction.proto\x12\x0bgoogle.type"2\n\x08\x46raction\x12\x11\n\tnumerator\x18\x01 \x01(\x03\x12\x13\n\x0b\x64\x65nominator\x18\x02 \x01(\x03\x42\x66\n\x0f\x63om.google.typeB\rFractionProtoP\x01Z None: ... diff --git a/python/user_packages/Python313/site-packages/google/type/interval.proto b/python/user_packages/Python313/site-packages/google/type/interval.proto new file mode 100644 index 0000000000000000000000000000000000000000..8e001282caae5d89a7751c6a441bc68f2ab20418 --- /dev/null +++ b/python/user_packages/Python313/site-packages/google/type/interval.proto @@ -0,0 +1,45 @@ +// Copyright 2026 Google LLC +// +// 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. + +syntax = "proto3"; + +package google.type; + +import "google/protobuf/timestamp.proto"; + +option go_package = "google.golang.org/genproto/googleapis/type/interval;interval"; +option java_multiple_files = true; +option java_outer_classname = "IntervalProto"; +option java_package = "com.google.type"; +option objc_class_prefix = "GTP"; + +// Represents a time interval, encoded as a Timestamp start (inclusive) and a +// Timestamp end (exclusive). +// +// The start must be less than or equal to the end. +// When the start equals the end, the interval is empty (matches no time). +// When both start and end are unspecified, the interval matches any time. +message Interval { + // Optional. Inclusive start of the interval. + // + // If specified, a Timestamp matching this interval will have to be the same + // or after the start. + google.protobuf.Timestamp start_time = 1; + + // Optional. Exclusive end of the interval. + // + // If specified, a Timestamp matching this interval will have to be before the + // end. + google.protobuf.Timestamp end_time = 2; +} diff --git a/python/user_packages/Python313/site-packages/google/type/interval_pb2.py b/python/user_packages/Python313/site-packages/google/type/interval_pb2.py new file mode 100644 index 0000000000000000000000000000000000000000..d662285783727d2cf8c82e4ffa713c34e8f2388d --- /dev/null +++ b/python/user_packages/Python313/site-packages/google/type/interval_pb2.py @@ -0,0 +1,50 @@ +# -*- coding: utf-8 -*- + +# Copyright 2025 Google LLC +# +# 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. + +# Generated by the protocol buffer compiler. DO NOT EDIT! +# source: google/type/interval.proto +# Protobuf Python Version: 4.25.3 +"""Generated protocol buffer code.""" + +from google.protobuf import descriptor as _descriptor +from google.protobuf import descriptor_pool as _descriptor_pool +from google.protobuf import symbol_database as _symbol_database +from google.protobuf.internal import builder as _builder + +# @@protoc_insertion_point(imports) + +_sym_db = _symbol_database.Default() + + +from google.protobuf import timestamp_pb2 as google_dot_protobuf_dot_timestamp__pb2 + +DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile( + b'\n\x1agoogle/type/interval.proto\x12\x0bgoogle.type\x1a\x1fgoogle/protobuf/timestamp.proto"h\n\x08Interval\x12.\n\nstart_time\x18\x01 \x01(\x0b\x32\x1a.google.protobuf.Timestamp\x12,\n\x08\x65nd_time\x18\x02 \x01(\x0b\x32\x1a.google.protobuf.TimestampBf\n\x0f\x63om.google.typeB\rIntervalProtoP\x01Z None: ... diff --git a/python/user_packages/Python313/site-packages/google/type/latlng.proto b/python/user_packages/Python313/site-packages/google/type/latlng.proto new file mode 100644 index 0000000000000000000000000000000000000000..2866058ccf1c8de90269891ae50589fd81c9186d --- /dev/null +++ b/python/user_packages/Python313/site-packages/google/type/latlng.proto @@ -0,0 +1,36 @@ +// Copyright 2026 Google LLC +// +// 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. + +syntax = "proto3"; + +package google.type; + +option go_package = "google.golang.org/genproto/googleapis/type/latlng;latlng"; +option java_multiple_files = true; +option java_outer_classname = "LatLngProto"; +option java_package = "com.google.type"; +option objc_class_prefix = "GTP"; + +// An object that represents a latitude/longitude pair. This is expressed as a +// pair of doubles to represent degrees latitude and degrees longitude. Unless +// specified otherwise, this object must conform to the +// +// WGS84 standard. Values must be within normalized ranges. +message LatLng { + // The latitude in degrees. It must be in the range [-90.0, +90.0]. + double latitude = 1; + + // The longitude in degrees. It must be in the range [-180.0, +180.0]. + double longitude = 2; +} diff --git a/python/user_packages/Python313/site-packages/google/type/latlng_pb2.py b/python/user_packages/Python313/site-packages/google/type/latlng_pb2.py new file mode 100644 index 0000000000000000000000000000000000000000..210e80371709c702eaac49fc01579e2e05427423 --- /dev/null +++ b/python/user_packages/Python313/site-packages/google/type/latlng_pb2.py @@ -0,0 +1,46 @@ +# -*- coding: utf-8 -*- + +# Copyright 2025 Google LLC +# +# 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. + +# Generated by the protocol buffer compiler. DO NOT EDIT! +# source: google/type/latlng.proto +# Protobuf Python Version: 4.25.3 +"""Generated protocol buffer code.""" + +from google.protobuf import descriptor as _descriptor +from google.protobuf import descriptor_pool as _descriptor_pool +from google.protobuf import symbol_database as _symbol_database +from google.protobuf.internal import builder as _builder + +# @@protoc_insertion_point(imports) + +_sym_db = _symbol_database.Default() + + +DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile( + b'\n\x18google/type/latlng.proto\x12\x0bgoogle.type"-\n\x06LatLng\x12\x10\n\x08latitude\x18\x01 \x01(\x01\x12\x11\n\tlongitude\x18\x02 \x01(\x01\x42`\n\x0f\x63om.google.typeB\x0bLatLngProtoP\x01Z8google.golang.org/genproto/googleapis/type/latlng;latlng\xa2\x02\x03GTPb\x06proto3' +) + +_globals = globals() +_builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, _globals) +_builder.BuildTopDescriptorsAndMessages(DESCRIPTOR, "google.type.latlng_pb2", _globals) +if _descriptor._USE_C_DESCRIPTORS == False: + _globals["DESCRIPTOR"]._options = None + _globals[ + "DESCRIPTOR" + ]._serialized_options = b"\n\017com.google.typeB\013LatLngProtoP\001Z8google.golang.org/genproto/googleapis/type/latlng;latlng\242\002\003GTP" + _globals["_LATLNG"]._serialized_start = 41 + _globals["_LATLNG"]._serialized_end = 86 +# @@protoc_insertion_point(module_scope) diff --git a/python/user_packages/Python313/site-packages/google/type/latlng_pb2.pyi b/python/user_packages/Python313/site-packages/google/type/latlng_pb2.pyi new file mode 100644 index 0000000000000000000000000000000000000000..033dd88192491943d6987c0899f69e8f6dfeedf8 --- /dev/null +++ b/python/user_packages/Python313/site-packages/google/type/latlng_pb2.pyi @@ -0,0 +1,31 @@ +# Copyright 2025 Google LLC +# +# 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. + +from typing import ClassVar as _ClassVar +from typing import Optional as _Optional + +from google.protobuf import descriptor as _descriptor +from google.protobuf import message as _message + +DESCRIPTOR: _descriptor.FileDescriptor + +class LatLng(_message.Message): + __slots__ = ("latitude", "longitude") + LATITUDE_FIELD_NUMBER: _ClassVar[int] + LONGITUDE_FIELD_NUMBER: _ClassVar[int] + latitude: float + longitude: float + def __init__( + self, latitude: _Optional[float] = ..., longitude: _Optional[float] = ... + ) -> None: ... diff --git a/python/user_packages/Python313/site-packages/google/type/localized_text.proto b/python/user_packages/Python313/site-packages/google/type/localized_text.proto new file mode 100644 index 0000000000000000000000000000000000000000..d3f2c2c1833b41950c839531b8f489279535ff14 --- /dev/null +++ b/python/user_packages/Python313/site-packages/google/type/localized_text.proto @@ -0,0 +1,36 @@ +// Copyright 2026 Google LLC +// +// 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. + +syntax = "proto3"; + +package google.type; + +option go_package = "google.golang.org/genproto/googleapis/type/localized_text;localized_text"; +option java_multiple_files = true; +option java_outer_classname = "LocalizedTextProto"; +option java_package = "com.google.type"; +option objc_class_prefix = "GTP"; + +// Localized variant of a text in a particular language. +message LocalizedText { + // Localized string in the language corresponding to + // [language_code][google.type.LocalizedText.language_code] below. + string text = 1; + + // The text's BCP-47 language code, such as "en-US" or "sr-Latn". + // + // For more information, see + // http://www.unicode.org/reports/tr35/#Unicode_locale_identifier. + string language_code = 2; +} diff --git a/python/user_packages/Python313/site-packages/google/type/localized_text_pb2.py b/python/user_packages/Python313/site-packages/google/type/localized_text_pb2.py new file mode 100644 index 0000000000000000000000000000000000000000..6c96ffc50b0d840fe5a2fee2bccfdcb0db907525 --- /dev/null +++ b/python/user_packages/Python313/site-packages/google/type/localized_text_pb2.py @@ -0,0 +1,48 @@ +# -*- coding: utf-8 -*- + +# Copyright 2025 Google LLC +# +# 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. + +# Generated by the protocol buffer compiler. DO NOT EDIT! +# source: google/type/localized_text.proto +# Protobuf Python Version: 4.25.3 +"""Generated protocol buffer code.""" + +from google.protobuf import descriptor as _descriptor +from google.protobuf import descriptor_pool as _descriptor_pool +from google.protobuf import symbol_database as _symbol_database +from google.protobuf.internal import builder as _builder + +# @@protoc_insertion_point(imports) + +_sym_db = _symbol_database.Default() + + +DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile( + b'\n google/type/localized_text.proto\x12\x0bgoogle.type"4\n\rLocalizedText\x12\x0c\n\x04text\x18\x01 \x01(\t\x12\x15\n\rlanguage_code\x18\x02 \x01(\tBw\n\x0f\x63om.google.typeB\x12LocalizedTextProtoP\x01ZHgoogle.golang.org/genproto/googleapis/type/localized_text;localized_text\xa2\x02\x03GTPb\x06proto3' +) + +_globals = globals() +_builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, _globals) +_builder.BuildTopDescriptorsAndMessages( + DESCRIPTOR, "google.type.localized_text_pb2", _globals +) +if _descriptor._USE_C_DESCRIPTORS == False: + _globals["DESCRIPTOR"]._options = None + _globals[ + "DESCRIPTOR" + ]._serialized_options = b"\n\017com.google.typeB\022LocalizedTextProtoP\001ZHgoogle.golang.org/genproto/googleapis/type/localized_text;localized_text\242\002\003GTP" + _globals["_LOCALIZEDTEXT"]._serialized_start = 49 + _globals["_LOCALIZEDTEXT"]._serialized_end = 101 +# @@protoc_insertion_point(module_scope) diff --git a/python/user_packages/Python313/site-packages/google/type/localized_text_pb2.pyi b/python/user_packages/Python313/site-packages/google/type/localized_text_pb2.pyi new file mode 100644 index 0000000000000000000000000000000000000000..f67aa6deb76fcd8a3267b962ddbbf88c1e875884 --- /dev/null +++ b/python/user_packages/Python313/site-packages/google/type/localized_text_pb2.pyi @@ -0,0 +1,31 @@ +# Copyright 2025 Google LLC +# +# 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. + +from typing import ClassVar as _ClassVar +from typing import Optional as _Optional + +from google.protobuf import descriptor as _descriptor +from google.protobuf import message as _message + +DESCRIPTOR: _descriptor.FileDescriptor + +class LocalizedText(_message.Message): + __slots__ = ("text", "language_code") + TEXT_FIELD_NUMBER: _ClassVar[int] + LANGUAGE_CODE_FIELD_NUMBER: _ClassVar[int] + text: str + language_code: str + def __init__( + self, text: _Optional[str] = ..., language_code: _Optional[str] = ... + ) -> None: ... diff --git a/python/user_packages/Python313/site-packages/google/type/money.proto b/python/user_packages/Python313/site-packages/google/type/money.proto new file mode 100644 index 0000000000000000000000000000000000000000..ed0d790a33431936c838c01d9105c415b6f0436f --- /dev/null +++ b/python/user_packages/Python313/site-packages/google/type/money.proto @@ -0,0 +1,41 @@ +// Copyright 2026 Google LLC +// +// 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. + +syntax = "proto3"; + +package google.type; + +option go_package = "google.golang.org/genproto/googleapis/type/money;money"; +option java_multiple_files = true; +option java_outer_classname = "MoneyProto"; +option java_package = "com.google.type"; +option objc_class_prefix = "GTP"; + +// Represents an amount of money with its currency type. +message Money { + // The three-letter currency code defined in ISO 4217. + string currency_code = 1; + + // The whole units of the amount. + // For example if `currencyCode` is `"USD"`, then 1 unit is one US dollar. + int64 units = 2; + + // Number of nano (10^-9) units of the amount. + // The value must be between -999,999,999 and +999,999,999 inclusive. + // If `units` is positive, `nanos` must be positive or zero. + // If `units` is zero, `nanos` can be positive, zero, or negative. + // If `units` is negative, `nanos` must be negative or zero. + // For example $-1.75 is represented as `units`=-1 and `nanos`=-750,000,000. + int32 nanos = 3; +} diff --git a/python/user_packages/Python313/site-packages/google/type/money_pb2.py b/python/user_packages/Python313/site-packages/google/type/money_pb2.py new file mode 100644 index 0000000000000000000000000000000000000000..081336d33cbc401021bd19069fde97b649cfe628 --- /dev/null +++ b/python/user_packages/Python313/site-packages/google/type/money_pb2.py @@ -0,0 +1,46 @@ +# -*- coding: utf-8 -*- + +# Copyright 2025 Google LLC +# +# 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. + +# Generated by the protocol buffer compiler. DO NOT EDIT! +# source: google/type/money.proto +# Protobuf Python Version: 4.25.3 +"""Generated protocol buffer code.""" + +from google.protobuf import descriptor as _descriptor +from google.protobuf import descriptor_pool as _descriptor_pool +from google.protobuf import symbol_database as _symbol_database +from google.protobuf.internal import builder as _builder + +# @@protoc_insertion_point(imports) + +_sym_db = _symbol_database.Default() + + +DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile( + b'\n\x17google/type/money.proto\x12\x0bgoogle.type"<\n\x05Money\x12\x15\n\rcurrency_code\x18\x01 \x01(\t\x12\r\n\x05units\x18\x02 \x01(\x03\x12\r\n\x05nanos\x18\x03 \x01(\x05\x42]\n\x0f\x63om.google.typeB\nMoneyProtoP\x01Z6google.golang.org/genproto/googleapis/type/money;money\xa2\x02\x03GTPb\x06proto3' +) + +_globals = globals() +_builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, _globals) +_builder.BuildTopDescriptorsAndMessages(DESCRIPTOR, "google.type.money_pb2", _globals) +if _descriptor._USE_C_DESCRIPTORS == False: + _globals["DESCRIPTOR"]._options = None + _globals[ + "DESCRIPTOR" + ]._serialized_options = b"\n\017com.google.typeB\nMoneyProtoP\001Z6google.golang.org/genproto/googleapis/type/money;money\242\002\003GTP" + _globals["_MONEY"]._serialized_start = 40 + _globals["_MONEY"]._serialized_end = 100 +# @@protoc_insertion_point(module_scope) diff --git a/python/user_packages/Python313/site-packages/google/type/money_pb2.pyi b/python/user_packages/Python313/site-packages/google/type/money_pb2.pyi new file mode 100644 index 0000000000000000000000000000000000000000..dd1c02b32126e6dbfa41ac038e8f944af144d907 --- /dev/null +++ b/python/user_packages/Python313/site-packages/google/type/money_pb2.pyi @@ -0,0 +1,36 @@ +# Copyright 2025 Google LLC +# +# 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. + +from typing import ClassVar as _ClassVar +from typing import Optional as _Optional + +from google.protobuf import descriptor as _descriptor +from google.protobuf import message as _message + +DESCRIPTOR: _descriptor.FileDescriptor + +class Money(_message.Message): + __slots__ = ("currency_code", "units", "nanos") + CURRENCY_CODE_FIELD_NUMBER: _ClassVar[int] + UNITS_FIELD_NUMBER: _ClassVar[int] + NANOS_FIELD_NUMBER: _ClassVar[int] + currency_code: str + units: int + nanos: int + def __init__( + self, + currency_code: _Optional[str] = ..., + units: _Optional[int] = ..., + nanos: _Optional[int] = ..., + ) -> None: ... diff --git a/python/user_packages/Python313/site-packages/google/type/month.proto b/python/user_packages/Python313/site-packages/google/type/month.proto new file mode 100644 index 0000000000000000000000000000000000000000..f8a66305f9b7235f194c6d751b365c79cc7ee215 --- /dev/null +++ b/python/user_packages/Python313/site-packages/google/type/month.proto @@ -0,0 +1,65 @@ +// Copyright 2026 Google LLC +// +// 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. + +syntax = "proto3"; + +package google.type; + +option go_package = "google.golang.org/genproto/googleapis/type/month;month"; +option java_multiple_files = true; +option java_outer_classname = "MonthProto"; +option java_package = "com.google.type"; +option objc_class_prefix = "GTP"; + +// Represents a month in the Gregorian calendar. +enum Month { + // The unspecified month. + MONTH_UNSPECIFIED = 0; + + // The month of January. + JANUARY = 1; + + // The month of February. + FEBRUARY = 2; + + // The month of March. + MARCH = 3; + + // The month of April. + APRIL = 4; + + // The month of May. + MAY = 5; + + // The month of June. + JUNE = 6; + + // The month of July. + JULY = 7; + + // The month of August. + AUGUST = 8; + + // The month of September. + SEPTEMBER = 9; + + // The month of October. + OCTOBER = 10; + + // The month of November. + NOVEMBER = 11; + + // The month of December. + DECEMBER = 12; +} diff --git a/python/user_packages/Python313/site-packages/google/type/month_pb2.py b/python/user_packages/Python313/site-packages/google/type/month_pb2.py new file mode 100644 index 0000000000000000000000000000000000000000..0be12142a6f347962ae1e63615943839ee4073c5 --- /dev/null +++ b/python/user_packages/Python313/site-packages/google/type/month_pb2.py @@ -0,0 +1,46 @@ +# -*- coding: utf-8 -*- + +# Copyright 2025 Google LLC +# +# 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. + +# Generated by the protocol buffer compiler. DO NOT EDIT! +# source: google/type/month.proto +# Protobuf Python Version: 4.25.3 +"""Generated protocol buffer code.""" + +from google.protobuf import descriptor as _descriptor +from google.protobuf import descriptor_pool as _descriptor_pool +from google.protobuf import symbol_database as _symbol_database +from google.protobuf.internal import builder as _builder + +# @@protoc_insertion_point(imports) + +_sym_db = _symbol_database.Default() + + +DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile( + b"\n\x17google/type/month.proto\x12\x0bgoogle.type*\xb0\x01\n\x05Month\x12\x15\n\x11MONTH_UNSPECIFIED\x10\x00\x12\x0b\n\x07JANUARY\x10\x01\x12\x0c\n\x08\x46\x45\x42RUARY\x10\x02\x12\t\n\x05MARCH\x10\x03\x12\t\n\x05\x41PRIL\x10\x04\x12\x07\n\x03MAY\x10\x05\x12\x08\n\x04JUNE\x10\x06\x12\x08\n\x04JULY\x10\x07\x12\n\n\x06\x41UGUST\x10\x08\x12\r\n\tSEPTEMBER\x10\t\x12\x0b\n\x07OCTOBER\x10\n\x12\x0c\n\x08NOVEMBER\x10\x0b\x12\x0c\n\x08\x44\x45\x43\x45MBER\x10\x0c\x42]\n\x0f\x63om.google.typeB\nMonthProtoP\x01Z6google.golang.org/genproto/googleapis/type/month;month\xa2\x02\x03GTPb\x06proto3" +) + +_globals = globals() +_builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, _globals) +_builder.BuildTopDescriptorsAndMessages(DESCRIPTOR, "google.type.month_pb2", _globals) +if _descriptor._USE_C_DESCRIPTORS == False: + _globals["DESCRIPTOR"]._options = None + _globals[ + "DESCRIPTOR" + ]._serialized_options = b"\n\017com.google.typeB\nMonthProtoP\001Z6google.golang.org/genproto/googleapis/type/month;month\242\002\003GTP" + _globals["_MONTH"]._serialized_start = 41 + _globals["_MONTH"]._serialized_end = 217 +# @@protoc_insertion_point(module_scope) diff --git a/python/user_packages/Python313/site-packages/google/type/month_pb2.pyi b/python/user_packages/Python313/site-packages/google/type/month_pb2.pyi new file mode 100644 index 0000000000000000000000000000000000000000..a5634ce225025f4b15808749cb8f93c5b1325c43 --- /dev/null +++ b/python/user_packages/Python313/site-packages/google/type/month_pb2.pyi @@ -0,0 +1,50 @@ +# Copyright 2025 Google LLC +# +# 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. + +from typing import ClassVar as _ClassVar + +from google.protobuf import descriptor as _descriptor +from google.protobuf.internal import enum_type_wrapper as _enum_type_wrapper + +DESCRIPTOR: _descriptor.FileDescriptor + +class Month(int, metaclass=_enum_type_wrapper.EnumTypeWrapper): + __slots__ = () + MONTH_UNSPECIFIED: _ClassVar[Month] + JANUARY: _ClassVar[Month] + FEBRUARY: _ClassVar[Month] + MARCH: _ClassVar[Month] + APRIL: _ClassVar[Month] + MAY: _ClassVar[Month] + JUNE: _ClassVar[Month] + JULY: _ClassVar[Month] + AUGUST: _ClassVar[Month] + SEPTEMBER: _ClassVar[Month] + OCTOBER: _ClassVar[Month] + NOVEMBER: _ClassVar[Month] + DECEMBER: _ClassVar[Month] + +MONTH_UNSPECIFIED: Month +JANUARY: Month +FEBRUARY: Month +MARCH: Month +APRIL: Month +MAY: Month +JUNE: Month +JULY: Month +AUGUST: Month +SEPTEMBER: Month +OCTOBER: Month +NOVEMBER: Month +DECEMBER: Month diff --git a/python/user_packages/Python313/site-packages/google/type/phone_number.proto b/python/user_packages/Python313/site-packages/google/type/phone_number.proto new file mode 100644 index 0000000000000000000000000000000000000000..7c55be07688de034232c66785a3b38b5e962b7c3 --- /dev/null +++ b/python/user_packages/Python313/site-packages/google/type/phone_number.proto @@ -0,0 +1,118 @@ +// Copyright 2026 Google LLC +// +// 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. + +syntax = "proto3"; + +package google.type; + +option go_package = "google.golang.org/genproto/googleapis/type/phone_number;phone_number"; +option java_multiple_files = true; +option java_outer_classname = "PhoneNumberProto"; +option java_package = "com.google.type"; +option objc_class_prefix = "GTP"; + +// An object representing a phone number, suitable as an API wire format. +// +// This representation: +// +// - should not be used for locale-specific formatting of a phone number, such +// as "+1 (650) 253-0000 ext. 123" +// +// - is not designed for efficient storage +// - may not be suitable for dialing - specialized libraries (see references) +// should be used to parse the number for that purpose +// +// To do something meaningful with this number, such as format it for various +// use-cases, convert it to an `i18n.phonenumbers.PhoneNumber` object first. +// +// For instance, in Java this would be: +// +// com.google.type.PhoneNumber wireProto = +// com.google.type.PhoneNumber.newBuilder().build(); +// com.google.i18n.phonenumbers.Phonenumber.PhoneNumber phoneNumber = +// PhoneNumberUtil.getInstance().parse(wireProto.getE164Number(), "ZZ"); +// if (!wireProto.getExtension().isEmpty()) { +// phoneNumber.setExtension(wireProto.getExtension()); +// } +// +// Reference(s): +// - https://github.com/google/libphonenumber +message PhoneNumber { + // An object representing a short code, which is a phone number that is + // typically much shorter than regular phone numbers and can be used to + // address messages in MMS and SMS systems, as well as for abbreviated dialing + // (For example "Text 611 to see how many minutes you have remaining on your + // plan."). + // + // Short codes are restricted to a region and are not internationally + // dialable, which means the same short code can exist in different regions, + // with different usage and pricing, even if those regions share the same + // country calling code (For example: US and CA). + message ShortCode { + // Required. The BCP-47 region code of the location where calls to this + // short code can be made, such as "US" and "BB". + // + // Reference(s): + // - http://www.unicode.org/reports/tr35/#unicode_region_subtag + string region_code = 1; + + // Required. The short code digits, without a leading plus ('+') or country + // calling code. For example "611". + string number = 2; + } + + // Required. Either a regular number, or a short code. New fields may be + // added to the oneof below in the future, so clients should ignore phone + // numbers for which none of the fields they coded against are set. + oneof kind { + // The phone number, represented as a leading plus sign ('+'), followed by a + // phone number that uses a relaxed ITU E.164 format consisting of the + // country calling code (1 to 3 digits) and the subscriber number, with no + // additional spaces or formatting. For example: + // + // - correct: "+15552220123" + // + // - incorrect: "+1 (555) 222-01234 x123" + // + // The ITU E.164 format limits the latter to 12 digits, but in practice not + // all countries respect that, so we relax that restriction here. + // National-only numbers are not allowed. + // + // References: + // + // - https://www.itu.int/rec/T-REC-E.164-201011-I + // + // - https://en.wikipedia.org/wiki/E.164. + // + // - https://en.wikipedia.org/wiki/List_of_country_calling_codes + string e164_number = 1; + + // A short code. + // + // Reference(s): + // - https://wikipedia.org/wiki/Short_code + ShortCode short_code = 2; + } + + // The phone number's extension. The extension is not standardized in ITU + // recommendations, except for being defined as a series of numbers with a + // maximum length of 40 digits. Other than digits, some other dialing + // characters such as ',' (indicating a wait) or '#' may be stored here. + // + // Note that no regions currently use extensions with short codes, so this + // field is normally only set in conjunction with an E.164 number. It is held + // separately from the E.164 number to allow for short code extensions in the + // future. + string extension = 3; +} diff --git a/python/user_packages/Python313/site-packages/google/type/phone_number_pb2.py b/python/user_packages/Python313/site-packages/google/type/phone_number_pb2.py new file mode 100644 index 0000000000000000000000000000000000000000..e5488589ece5f92fe4a58637a219728e82f91a2f --- /dev/null +++ b/python/user_packages/Python313/site-packages/google/type/phone_number_pb2.py @@ -0,0 +1,50 @@ +# -*- coding: utf-8 -*- + +# Copyright 2025 Google LLC +# +# 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. + +# Generated by the protocol buffer compiler. DO NOT EDIT! +# source: google/type/phone_number.proto +# Protobuf Python Version: 4.25.3 +"""Generated protocol buffer code.""" + +from google.protobuf import descriptor as _descriptor +from google.protobuf import descriptor_pool as _descriptor_pool +from google.protobuf import symbol_database as _symbol_database +from google.protobuf.internal import builder as _builder + +# @@protoc_insertion_point(imports) + +_sym_db = _symbol_database.Default() + + +DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile( + b'\n\x1egoogle/type/phone_number.proto\x12\x0bgoogle.type"\xab\x01\n\x0bPhoneNumber\x12\x15\n\x0b\x65\x31\x36\x34_number\x18\x01 \x01(\tH\x00\x12\x38\n\nshort_code\x18\x02 \x01(\x0b\x32".google.type.PhoneNumber.ShortCodeH\x00\x12\x11\n\textension\x18\x03 \x01(\t\x1a\x30\n\tShortCode\x12\x13\n\x0bregion_code\x18\x01 \x01(\t\x12\x0e\n\x06number\x18\x02 \x01(\tB\x06\n\x04kindBq\n\x0f\x63om.google.typeB\x10PhoneNumberProtoP\x01ZDgoogle.golang.org/genproto/googleapis/type/phone_number;phone_number\xa2\x02\x03GTPb\x06proto3' +) + +_globals = globals() +_builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, _globals) +_builder.BuildTopDescriptorsAndMessages( + DESCRIPTOR, "google.type.phone_number_pb2", _globals +) +if _descriptor._USE_C_DESCRIPTORS == False: + _globals["DESCRIPTOR"]._options = None + _globals[ + "DESCRIPTOR" + ]._serialized_options = b"\n\017com.google.typeB\020PhoneNumberProtoP\001ZDgoogle.golang.org/genproto/googleapis/type/phone_number;phone_number\242\002\003GTP" + _globals["_PHONENUMBER"]._serialized_start = 48 + _globals["_PHONENUMBER"]._serialized_end = 219 + _globals["_PHONENUMBER_SHORTCODE"]._serialized_start = 163 + _globals["_PHONENUMBER_SHORTCODE"]._serialized_end = 211 +# @@protoc_insertion_point(module_scope) diff --git a/python/user_packages/Python313/site-packages/google/type/phone_number_pb2.pyi b/python/user_packages/Python313/site-packages/google/type/phone_number_pb2.pyi new file mode 100644 index 0000000000000000000000000000000000000000..12a10dbf83d15541295744696f3d28e1c1943fcc --- /dev/null +++ b/python/user_packages/Python313/site-packages/google/type/phone_number_pb2.pyi @@ -0,0 +1,48 @@ +# Copyright 2025 Google LLC +# +# 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. + +from typing import ClassVar as _ClassVar +from typing import Mapping as _Mapping +from typing import Optional as _Optional +from typing import Union as _Union + +from google.protobuf import descriptor as _descriptor +from google.protobuf import message as _message + +DESCRIPTOR: _descriptor.FileDescriptor + +class PhoneNumber(_message.Message): + __slots__ = ("e164_number", "short_code", "extension") + class ShortCode(_message.Message): + __slots__ = ("region_code", "number") + REGION_CODE_FIELD_NUMBER: _ClassVar[int] + NUMBER_FIELD_NUMBER: _ClassVar[int] + region_code: str + number: str + def __init__( + self, region_code: _Optional[str] = ..., number: _Optional[str] = ... + ) -> None: ... + + E164_NUMBER_FIELD_NUMBER: _ClassVar[int] + SHORT_CODE_FIELD_NUMBER: _ClassVar[int] + EXTENSION_FIELD_NUMBER: _ClassVar[int] + e164_number: str + short_code: PhoneNumber.ShortCode + extension: str + def __init__( + self, + e164_number: _Optional[str] = ..., + short_code: _Optional[_Union[PhoneNumber.ShortCode, _Mapping]] = ..., + extension: _Optional[str] = ..., + ) -> None: ... diff --git a/python/user_packages/Python313/site-packages/google/type/postal_address.proto b/python/user_packages/Python313/site-packages/google/type/postal_address.proto new file mode 100644 index 0000000000000000000000000000000000000000..57059625235909947c85be4fb17137243227f8b9 --- /dev/null +++ b/python/user_packages/Python313/site-packages/google/type/postal_address.proto @@ -0,0 +1,134 @@ +// Copyright 2026 Google LLC +// +// 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. + +syntax = "proto3"; + +package google.type; + +option go_package = "google.golang.org/genproto/googleapis/type/postaladdress;postaladdress"; +option java_multiple_files = true; +option java_outer_classname = "PostalAddressProto"; +option java_package = "com.google.type"; +option objc_class_prefix = "GTP"; + +// Represents a postal address, such as for postal delivery or payments +// addresses. With a postal address, a postal service can deliver items to a +// premise, P.O. box, or similar. A postal address is not intended to model +// geographical locations like roads, towns, or mountains. +// +// In typical usage, an address would be created by user input or from importing +// existing data, depending on the type of process. +// +// Advice on address input or editing: +// +// - Use an internationalization-ready address widget such as +// https://github.com/google/libaddressinput. +// - Users should not be presented with UI elements for input or editing of +// fields outside countries where that field is used. +// +// For more guidance on how to use this schema, see: +// https://support.google.com/business/answer/6397478. +message PostalAddress { + // The schema revision of the `PostalAddress`. This must be set to 0, which is + // the latest revision. + // + // All new revisions **must** be backward compatible with old revisions. + int32 revision = 1; + + // Required. CLDR region code of the country/region of the address. This + // is never inferred and it is up to the user to ensure the value is + // correct. See https://cldr.unicode.org/ and + // https://www.unicode.org/cldr/charts/30/supplemental/territory_information.html + // for details. Example: "CH" for Switzerland. + string region_code = 2; + + // Optional. BCP-47 language code of the contents of this address (if + // known). This is often the UI language of the input form or is expected + // to match one of the languages used in the address' country/region, or their + // transliterated equivalents. + // This can affect formatting in certain countries, but is not critical + // to the correctness of the data and will never affect any validation or + // other non-formatting related operations. + // + // If this value is not known, it should be omitted (rather than specifying a + // possibly incorrect default). + // + // Examples: "zh-Hant", "ja", "ja-Latn", "en". + string language_code = 3; + + // Optional. Postal code of the address. Not all countries use or require + // postal codes to be present, but where they are used, they may trigger + // additional validation with other parts of the address (for example, + // state or zip code validation in the United States). + string postal_code = 4; + + // Optional. Additional, country-specific, sorting code. This is not used + // in most regions. Where it is used, the value is either a string like + // "CEDEX", optionally followed by a number (for example, "CEDEX 7"), or just + // a number alone, representing the "sector code" (Jamaica), "delivery area + // indicator" (Malawi) or "post office indicator" (Côte d'Ivoire). + string sorting_code = 5; + + // Optional. Highest administrative subdivision which is used for postal + // addresses of a country or region. + // For example, this can be a state, a province, an oblast, or a prefecture. + // For Spain, this is the province and not the autonomous + // community (for example, "Barcelona" and not "Catalonia"). + // Many countries don't use an administrative area in postal addresses. For + // example, in Switzerland, this should be left unpopulated. + string administrative_area = 6; + + // Optional. Generally refers to the city or town portion of the address. + // Examples: US city, IT comune, UK post town. + // In regions of the world where localities are not well defined or do not fit + // into this structure well, leave `locality` empty and use `address_lines`. + string locality = 7; + + // Optional. Sublocality of the address. + // For example, this can be a neighborhood, borough, or district. + string sublocality = 8; + + // Unstructured address lines describing the lower levels of an address. + // + // Because values in `address_lines` do not have type information and may + // sometimes contain multiple values in a single field (for example, + // "Austin, TX"), it is important that the line order is clear. The order of + // address lines should be "envelope order" for the country or region of the + // address. In places where this can vary (for example, Japan), + // `address_language` is used to make it explicit (for example, "ja" for + // large-to-small ordering and "ja-Latn" or "en" for small-to-large). In this + // way, the most specific line of an address can be selected based on the + // language. + // + // The minimum permitted structural representation of an address consists + // of a `region_code` with all remaining information placed in the + // `address_lines`. It would be possible to format such an address very + // approximately without geocoding, but no semantic reasoning could be + // made about any of the address components until it was at least + // partially resolved. + // + // Creating an address only containing a `region_code` and `address_lines` and + // then geocoding is the recommended way to handle completely unstructured + // addresses (as opposed to guessing which parts of the address should be + // localities or administrative areas). + repeated string address_lines = 9; + + // Optional. The recipient at the address. + // This field may, under certain circumstances, contain multiline information. + // For example, it might contain "care of" information. + repeated string recipients = 10; + + // Optional. The name of the organization at the address. + string organization = 11; +} diff --git a/python/user_packages/Python313/site-packages/google/type/postal_address_pb2.py b/python/user_packages/Python313/site-packages/google/type/postal_address_pb2.py new file mode 100644 index 0000000000000000000000000000000000000000..487bce9acdc3f63891b926edf876021165b13e7e --- /dev/null +++ b/python/user_packages/Python313/site-packages/google/type/postal_address_pb2.py @@ -0,0 +1,48 @@ +# -*- coding: utf-8 -*- + +# Copyright 2025 Google LLC +# +# 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. + +# Generated by the protocol buffer compiler. DO NOT EDIT! +# source: google/type/postal_address.proto +# Protobuf Python Version: 4.25.3 +"""Generated protocol buffer code.""" + +from google.protobuf import descriptor as _descriptor +from google.protobuf import descriptor_pool as _descriptor_pool +from google.protobuf import symbol_database as _symbol_database +from google.protobuf.internal import builder as _builder + +# @@protoc_insertion_point(imports) + +_sym_db = _symbol_database.Default() + + +DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile( + b'\n google/type/postal_address.proto\x12\x0bgoogle.type"\xfd\x01\n\rPostalAddress\x12\x10\n\x08revision\x18\x01 \x01(\x05\x12\x13\n\x0bregion_code\x18\x02 \x01(\t\x12\x15\n\rlanguage_code\x18\x03 \x01(\t\x12\x13\n\x0bpostal_code\x18\x04 \x01(\t\x12\x14\n\x0csorting_code\x18\x05 \x01(\t\x12\x1b\n\x13\x61\x64ministrative_area\x18\x06 \x01(\t\x12\x10\n\x08locality\x18\x07 \x01(\t\x12\x13\n\x0bsublocality\x18\x08 \x01(\t\x12\x15\n\raddress_lines\x18\t \x03(\t\x12\x12\n\nrecipients\x18\n \x03(\t\x12\x14\n\x0corganization\x18\x0b \x01(\tBu\n\x0f\x63om.google.typeB\x12PostalAddressProtoP\x01ZFgoogle.golang.org/genproto/googleapis/type/postaladdress;postaladdress\xa2\x02\x03GTPb\x06proto3' +) + +_globals = globals() +_builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, _globals) +_builder.BuildTopDescriptorsAndMessages( + DESCRIPTOR, "google.type.postal_address_pb2", _globals +) +if _descriptor._USE_C_DESCRIPTORS == False: + _globals["DESCRIPTOR"]._options = None + _globals[ + "DESCRIPTOR" + ]._serialized_options = b"\n\017com.google.typeB\022PostalAddressProtoP\001ZFgoogle.golang.org/genproto/googleapis/type/postaladdress;postaladdress\242\002\003GTP" + _globals["_POSTALADDRESS"]._serialized_start = 50 + _globals["_POSTALADDRESS"]._serialized_end = 303 +# @@protoc_insertion_point(module_scope) diff --git a/python/user_packages/Python313/site-packages/google/type/postal_address_pb2.pyi b/python/user_packages/Python313/site-packages/google/type/postal_address_pb2.pyi new file mode 100644 index 0000000000000000000000000000000000000000..e31003b6d5bd46ef1338ffa1424b3bbaa6661333 --- /dev/null +++ b/python/user_packages/Python313/site-packages/google/type/postal_address_pb2.pyi @@ -0,0 +1,74 @@ +# Copyright 2025 Google LLC +# +# 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. + +from typing import ClassVar as _ClassVar +from typing import Iterable as _Iterable +from typing import Optional as _Optional + +from google.protobuf import descriptor as _descriptor +from google.protobuf import message as _message +from google.protobuf.internal import containers as _containers + +DESCRIPTOR: _descriptor.FileDescriptor + +class PostalAddress(_message.Message): + __slots__ = ( + "revision", + "region_code", + "language_code", + "postal_code", + "sorting_code", + "administrative_area", + "locality", + "sublocality", + "address_lines", + "recipients", + "organization", + ) + REVISION_FIELD_NUMBER: _ClassVar[int] + REGION_CODE_FIELD_NUMBER: _ClassVar[int] + LANGUAGE_CODE_FIELD_NUMBER: _ClassVar[int] + POSTAL_CODE_FIELD_NUMBER: _ClassVar[int] + SORTING_CODE_FIELD_NUMBER: _ClassVar[int] + ADMINISTRATIVE_AREA_FIELD_NUMBER: _ClassVar[int] + LOCALITY_FIELD_NUMBER: _ClassVar[int] + SUBLOCALITY_FIELD_NUMBER: _ClassVar[int] + ADDRESS_LINES_FIELD_NUMBER: _ClassVar[int] + RECIPIENTS_FIELD_NUMBER: _ClassVar[int] + ORGANIZATION_FIELD_NUMBER: _ClassVar[int] + revision: int + region_code: str + language_code: str + postal_code: str + sorting_code: str + administrative_area: str + locality: str + sublocality: str + address_lines: _containers.RepeatedScalarFieldContainer[str] + recipients: _containers.RepeatedScalarFieldContainer[str] + organization: str + def __init__( + self, + revision: _Optional[int] = ..., + region_code: _Optional[str] = ..., + language_code: _Optional[str] = ..., + postal_code: _Optional[str] = ..., + sorting_code: _Optional[str] = ..., + administrative_area: _Optional[str] = ..., + locality: _Optional[str] = ..., + sublocality: _Optional[str] = ..., + address_lines: _Optional[_Iterable[str]] = ..., + recipients: _Optional[_Iterable[str]] = ..., + organization: _Optional[str] = ..., + ) -> None: ... diff --git a/python/user_packages/Python313/site-packages/google/type/quaternion.proto b/python/user_packages/Python313/site-packages/google/type/quaternion.proto new file mode 100644 index 0000000000000000000000000000000000000000..d24629821ffe18bf3516477f92314bb81aab4679 --- /dev/null +++ b/python/user_packages/Python313/site-packages/google/type/quaternion.proto @@ -0,0 +1,94 @@ +// Copyright 2026 Google LLC +// +// 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. + +syntax = "proto3"; + +package google.type; + +option go_package = "google.golang.org/genproto/googleapis/type/quaternion;quaternion"; +option java_multiple_files = true; +option java_outer_classname = "QuaternionProto"; +option java_package = "com.google.type"; +option objc_class_prefix = "GTP"; + +// A quaternion, represented by four 64-bit floating point values. +// +// A quaternion is defined as the quotient of two directed lines in a +// three-dimensional space or equivalently as the quotient of two Euclidean +// vectors (https://en.wikipedia.org/wiki/Quaternion). +// +// Quaternions are often used in calculations involving three-dimensional +// rotations (https://en.wikipedia.org/wiki/Quaternions_and_spatial_rotation), +// as they provide greater mathematical robustness by avoiding the gimbal lock +// problems that can be encountered when using Euler angles +// (https://en.wikipedia.org/wiki/Gimbal_lock). +// +// Quaternions are generally represented in this form: +// +// w + xi + yj + zk +// +// where x, y, z, and w are real numbers, and i, j, and k are three imaginary +// numbers. +// +// The naming choice `(x, y, z, w)` comes from the desire to avoid confusion for +// those interested in the geometric properties of the quaternion in the 3D +// Cartesian space. Other texts often use alternative names or subscripts, such +// as `(a, b, c, d)`, `(1, i, j, k)`, or `(0, 1, 2, 3)`, which are perhaps +// better suited for mathematical interpretations. +// +// To avoid any confusion, as well as to maintain compatibility with a large +// number of software libraries, the quaternions represented using the protocol +// buffer below *must* follow the Hamilton convention, which defines `ij = k` +// (i.e. a right-handed algebra), and therefore: +// +// i^2 = j^2 = k^2 = ijk = −1 +// ij = −ji = k +// jk = −kj = i +// ki = −ik = j +// +// Please DO NOT use this to represent quaternions that follow the JPL +// convention, or any of the other quaternion flavors out there. +// +// Definitions: +// +// - Quaternion norm (or magnitude): `sqrt(x^2 + y^2 + z^2 + w^2)`. +// - Unit (or normalized) quaternion: a quaternion whose norm is 1. +// - Pure quaternion: a quaternion whose scalar component (`w`) is 0. +// - Rotation quaternion: a unit quaternion used to represent rotation. +// - Orientation quaternion: a unit quaternion used to represent orientation. +// +// A quaternion can be normalized by dividing it by its norm. The resulting +// quaternion maintains the same direction, but has a norm of 1, i.e. it moves +// on the unit sphere. This is generally necessary for rotation and orientation +// quaternions, to avoid rounding errors: +// https://en.wikipedia.org/wiki/Rotation_formalisms_in_three_dimensions +// +// Note that `(x, y, z, w)` and `(-x, -y, -z, -w)` represent the same rotation, +// but normalization would be even more useful, e.g. for comparison purposes, if +// it would produce a unique representation. It is thus recommended that `w` be +// kept positive, which can be achieved by changing all the signs when `w` is +// negative. +message Quaternion { + // The x component. + double x = 1; + + // The y component. + double y = 2; + + // The z component. + double z = 3; + + // The scalar component. + double w = 4; +} diff --git a/python/user_packages/Python313/site-packages/google/type/quaternion_pb2.py b/python/user_packages/Python313/site-packages/google/type/quaternion_pb2.py new file mode 100644 index 0000000000000000000000000000000000000000..7385af524b776bda52b9c6250266cee8fe94b2f7 --- /dev/null +++ b/python/user_packages/Python313/site-packages/google/type/quaternion_pb2.py @@ -0,0 +1,48 @@ +# -*- coding: utf-8 -*- + +# Copyright 2025 Google LLC +# +# 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. + +# Generated by the protocol buffer compiler. DO NOT EDIT! +# source: google/type/quaternion.proto +# Protobuf Python Version: 4.25.3 +"""Generated protocol buffer code.""" + +from google.protobuf import descriptor as _descriptor +from google.protobuf import descriptor_pool as _descriptor_pool +from google.protobuf import symbol_database as _symbol_database +from google.protobuf.internal import builder as _builder + +# @@protoc_insertion_point(imports) + +_sym_db = _symbol_database.Default() + + +DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile( + b'\n\x1cgoogle/type/quaternion.proto\x12\x0bgoogle.type"8\n\nQuaternion\x12\t\n\x01x\x18\x01 \x01(\x01\x12\t\n\x01y\x18\x02 \x01(\x01\x12\t\n\x01z\x18\x03 \x01(\x01\x12\t\n\x01w\x18\x04 \x01(\x01\x42l\n\x0f\x63om.google.typeB\x0fQuaternionProtoP\x01Z@google.golang.org/genproto/googleapis/type/quaternion;quaternion\xa2\x02\x03GTPb\x06proto3' +) + +_globals = globals() +_builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, _globals) +_builder.BuildTopDescriptorsAndMessages( + DESCRIPTOR, "google.type.quaternion_pb2", _globals +) +if _descriptor._USE_C_DESCRIPTORS == False: + _globals["DESCRIPTOR"]._options = None + _globals[ + "DESCRIPTOR" + ]._serialized_options = b"\n\017com.google.typeB\017QuaternionProtoP\001Z@google.golang.org/genproto/googleapis/type/quaternion;quaternion\242\002\003GTP" + _globals["_QUATERNION"]._serialized_start = 45 + _globals["_QUATERNION"]._serialized_end = 101 +# @@protoc_insertion_point(module_scope) diff --git a/python/user_packages/Python313/site-packages/google/type/quaternion_pb2.pyi b/python/user_packages/Python313/site-packages/google/type/quaternion_pb2.pyi new file mode 100644 index 0000000000000000000000000000000000000000..8a7bfbe24c269ef4dd056ea9fd0df1f9699f3653 --- /dev/null +++ b/python/user_packages/Python313/site-packages/google/type/quaternion_pb2.pyi @@ -0,0 +1,39 @@ +# Copyright 2025 Google LLC +# +# 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. + +from typing import ClassVar as _ClassVar +from typing import Optional as _Optional + +from google.protobuf import descriptor as _descriptor +from google.protobuf import message as _message + +DESCRIPTOR: _descriptor.FileDescriptor + +class Quaternion(_message.Message): + __slots__ = ("x", "y", "z", "w") + X_FIELD_NUMBER: _ClassVar[int] + Y_FIELD_NUMBER: _ClassVar[int] + Z_FIELD_NUMBER: _ClassVar[int] + W_FIELD_NUMBER: _ClassVar[int] + x: float + y: float + z: float + w: float + def __init__( + self, + x: _Optional[float] = ..., + y: _Optional[float] = ..., + z: _Optional[float] = ..., + w: _Optional[float] = ..., + ) -> None: ... diff --git a/python/user_packages/Python313/site-packages/google/type/timeofday.proto b/python/user_packages/Python313/site-packages/google/type/timeofday.proto new file mode 100644 index 0000000000000000000000000000000000000000..94090bd085e541b6aee27736660034f88b6700cf --- /dev/null +++ b/python/user_packages/Python313/site-packages/google/type/timeofday.proto @@ -0,0 +1,47 @@ +// Copyright 2026 Google LLC +// +// 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. + +syntax = "proto3"; + +package google.type; + +option go_package = "google.golang.org/genproto/googleapis/type/timeofday;timeofday"; +option java_multiple_files = true; +option java_outer_classname = "TimeOfDayProto"; +option java_package = "com.google.type"; +option objc_class_prefix = "GTP"; + +// Represents a time of day. The date and time zone are either not significant +// or are specified elsewhere. An API may choose to allow leap seconds. Related +// types are [google.type.Date][google.type.Date] and +// `google.protobuf.Timestamp`. +message TimeOfDay { + // Hours of a day in 24 hour format. Must be greater than or equal to 0 and + // typically must be less than or equal to 23. An API may choose to allow the + // value "24:00:00" for scenarios like business closing time. + int32 hours = 1; + + // Minutes of an hour. Must be greater than or equal to 0 and less than or + // equal to 59. + int32 minutes = 2; + + // Seconds of a minute. Must be greater than or equal to 0 and typically must + // be less than or equal to 59. An API may allow the value 60 if it allows + // leap-seconds. + int32 seconds = 3; + + // Fractions of seconds, in nanoseconds. Must be greater than or equal to 0 + // and less than or equal to 999,999,999. + int32 nanos = 4; +} diff --git a/python/user_packages/Python313/site-packages/google/type/timeofday_pb2.py b/python/user_packages/Python313/site-packages/google/type/timeofday_pb2.py new file mode 100644 index 0000000000000000000000000000000000000000..f5d96ac2f7edee0b329271fdb997ba5535265cc8 --- /dev/null +++ b/python/user_packages/Python313/site-packages/google/type/timeofday_pb2.py @@ -0,0 +1,48 @@ +# -*- coding: utf-8 -*- + +# Copyright 2025 Google LLC +# +# 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. + +# Generated by the protocol buffer compiler. DO NOT EDIT! +# source: google/type/timeofday.proto +# Protobuf Python Version: 4.25.3 +"""Generated protocol buffer code.""" + +from google.protobuf import descriptor as _descriptor +from google.protobuf import descriptor_pool as _descriptor_pool +from google.protobuf import symbol_database as _symbol_database +from google.protobuf.internal import builder as _builder + +# @@protoc_insertion_point(imports) + +_sym_db = _symbol_database.Default() + + +DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile( + b'\n\x1bgoogle/type/timeofday.proto\x12\x0bgoogle.type"K\n\tTimeOfDay\x12\r\n\x05hours\x18\x01 \x01(\x05\x12\x0f\n\x07minutes\x18\x02 \x01(\x05\x12\x0f\n\x07seconds\x18\x03 \x01(\x05\x12\r\n\x05nanos\x18\x04 \x01(\x05\x42i\n\x0f\x63om.google.typeB\x0eTimeOfDayProtoP\x01Z>google.golang.org/genproto/googleapis/type/timeofday;timeofday\xa2\x02\x03GTPb\x06proto3' +) + +_globals = globals() +_builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, _globals) +_builder.BuildTopDescriptorsAndMessages( + DESCRIPTOR, "google.type.timeofday_pb2", _globals +) +if _descriptor._USE_C_DESCRIPTORS == False: + _globals["DESCRIPTOR"]._options = None + _globals[ + "DESCRIPTOR" + ]._serialized_options = b"\n\017com.google.typeB\016TimeOfDayProtoP\001Z>google.golang.org/genproto/googleapis/type/timeofday;timeofday\242\002\003GTP" + _globals["_TIMEOFDAY"]._serialized_start = 44 + _globals["_TIMEOFDAY"]._serialized_end = 119 +# @@protoc_insertion_point(module_scope) diff --git a/python/user_packages/Python313/site-packages/google/type/timeofday_pb2.pyi b/python/user_packages/Python313/site-packages/google/type/timeofday_pb2.pyi new file mode 100644 index 0000000000000000000000000000000000000000..1a5e261895693875fd4db69e5717ebd55f17433a --- /dev/null +++ b/python/user_packages/Python313/site-packages/google/type/timeofday_pb2.pyi @@ -0,0 +1,39 @@ +# Copyright 2025 Google LLC +# +# 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. + +from typing import ClassVar as _ClassVar +from typing import Optional as _Optional + +from google.protobuf import descriptor as _descriptor +from google.protobuf import message as _message + +DESCRIPTOR: _descriptor.FileDescriptor + +class TimeOfDay(_message.Message): + __slots__ = ("hours", "minutes", "seconds", "nanos") + HOURS_FIELD_NUMBER: _ClassVar[int] + MINUTES_FIELD_NUMBER: _ClassVar[int] + SECONDS_FIELD_NUMBER: _ClassVar[int] + NANOS_FIELD_NUMBER: _ClassVar[int] + hours: int + minutes: int + seconds: int + nanos: int + def __init__( + self, + hours: _Optional[int] = ..., + minutes: _Optional[int] = ..., + seconds: _Optional[int] = ..., + nanos: _Optional[int] = ..., + ) -> None: ...