diff --git a/micromamba_root/envs/pytorch_env/Lib/idlelib/Icons/README.txt b/micromamba_root/envs/pytorch_env/Lib/idlelib/Icons/README.txt new file mode 100644 index 0000000000000000000000000000000000000000..d91c4d5d8d8cfa20b4994de21605b48f47ba430f --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/idlelib/Icons/README.txt @@ -0,0 +1,13 @@ +The IDLE icons are from https://bugs.python.org/issue1490384 + +Created by Andrew Clover. + +The original sources are available from Andrew's website: +https://www.doxdesk.com/software/py/pyicons.html + +Various different formats and sizes are available at this GitHub Pull Request: +https://github.com/python/cpython/pull/17473 + +The idle.ico file was created with ImageMagick: + + $ convert idle_16.png idle_32.png idle_48.png idle_256.png idle.ico diff --git a/micromamba_root/envs/pytorch_env/Lib/idlelib/Icons/idle.ico b/micromamba_root/envs/pytorch_env/Lib/idlelib/Icons/idle.ico new file mode 100644 index 0000000000000000000000000000000000000000..2aa9a8300d9e29670ecbe585f5ab21579dece9c2 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/idlelib/Icons/idle.ico differ diff --git a/micromamba_root/envs/pytorch_env/Lib/idlelib/idle_test/README.txt b/micromamba_root/envs/pytorch_env/Lib/idlelib/idle_test/README.txt new file mode 100644 index 0000000000000000000000000000000000000000..cacd06db873d039baa144a95fa45914565ca6197 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/idlelib/idle_test/README.txt @@ -0,0 +1,241 @@ +README FOR IDLE TESTS IN IDLELIB.IDLE_TEST + +0. Quick Start + +Automated unit tests were added in 3.3 for Python 3.x. +To run the tests from a command line: + +python -m test.test_idle + +Human-mediated tests were added later in 3.4. + +python -m idlelib.idle_test.htest + + +1. Test Files + +The idle directory, idlelib, has over 60 xyz.py files. The idle_test +subdirectory contains test_xyz.py for each implementation file xyz.py. +To add a test for abc.py, open idle_test/template.py and immediately +Save As test_abc.py. Insert 'abc' on the first line, and replace +'zzdummy' with 'abc. + +Remove the imports of requires and tkinter if not needed. Otherwise, +add to the tkinter imports as needed. + +Add a prefix to 'Test' for the initial test class. The template class +contains code needed or possibly needed for gui tests. See the next +section if doing gui tests. If not, and not needed for further classes, +this code can be removed. + +Add the following at the end of abc.py. If an htest was added first, +insert the import and main lines before the htest lines. + +if __name__ == "__main__": + from unittest import main + main('idlelib.idle_test.test_abc', verbosity=2, exit=False) + +The ', exit=False' is only needed if an htest follows. + + + +2. GUI Tests + +When run as part of the Python test suite, Idle GUI tests need to run +test.support.requires('gui'). A test is a GUI test if it creates a +tkinter.Tk root or master object either directly or indirectly by +instantiating a tkinter or idle class. GUI tests cannot run in test +processes that either have no graphical environment available or are not +allowed to use it. + +To guard a module consisting entirely of GUI tests, start with + +from test.support import requires +requires('gui') + +To guard a test class, put "requires('gui')" in its setUpClass function. +The template.py file does this. + +To avoid interfering with other GUI tests, all GUI objects must be +destroyed and deleted by the end of the test. The Tk root created in a +setUpX function should be destroyed in the corresponding tearDownX and +the module or class attribute deleted. Others widgets should descend +from the single root and the attributes deleted BEFORE root is +destroyed. See https://bugs.python.org/issue20567. + + @classmethod + def setUpClass(cls): + requires('gui') + cls.root = tk.Tk() + cls.text = tk.Text(root) + + @classmethod + def tearDownClass(cls): + del cls.text + cls.root.update_idletasks() + cls.root.destroy() + del cls.root + +The update_idletasks call is sometimes needed to prevent the following +warning either when running a test alone or as part of the test suite +(#27196). It should not hurt if not needed. + + can't invoke "event" command: application has been destroyed + ... + "ttk::ThemeChanged" + +If a test creates instance 'e' of EditorWindow, call 'e._close()' before +or as the first part of teardown. The effect of omitting this depends +on the later shutdown. Then enable the after_cancel loop in the +template. This prevents messages like the following. + +bgerror failed to handle background error. + Original error: invalid command name "106096696timer_event" + Error in bgerror: can't invoke "tk" command: application has been destroyed + +Requires('gui') causes the test(s) it guards to be skipped if any of +these conditions are met: + + - The tests are being run by regrtest.py, and it was started without + enabling the "gui" resource with the "-u" command line option. + + - The tests are being run on Windows by a service that is not allowed + to interact with the graphical environment. + + - The tests are being run on Linux and X Windows is not available. + + - The tests are being run on Mac OSX in a process that cannot make a + window manager connection. + + - tkinter.Tk cannot be successfully instantiated for some reason. + + - test.support.use_resources has been set by something other than + regrtest.py and does not contain "gui". + +Tests of non-GUI operations should avoid creating tk widgets. Incidental +uses of tk variables and messageboxes can be replaced by the mock +classes in idle_test/mock_tk.py. The mock text handles some uses of the +tk Text widget. + + +3. Running Unit Tests + +Assume that xyz.py and test_xyz.py both end with a unittest.main() call. +Running either from an Idle editor runs all tests in the test_xyz file +with the version of Python running Idle. Test output appears in the +Shell window. The 'verbosity=2' option lists all test methods in the +file, which is appropriate when developing tests. The 'exit=False' +option is needed in xyx.py files when an htest follows. + +The following command lines also run all test methods, including +GUI tests, in test_xyz.py. (Both '-m idlelib' and '-m idlelib.idle' +start Idle and so cannot run tests.) + +python -m idlelib.xyz +python -m idlelib.idle_test.test_xyz + +The following runs all idle_test/test_*.py tests interactively. + +>>> import unittest +>>> unittest.main('idlelib.idle_test', verbosity=2) + +The following run all Idle tests at a command line. Option '-v' is the +same as 'verbosity=2'. + +python -m unittest -v idlelib.idle_test +python -m test -v -ugui test_idle +python -m test.test_idle + +IDLE tests are 'discovered' by idlelib.idle_test.__init__.load_tests +when this is imported into test.test_idle. Normally, neither file +should be changed when working on individual test modules. The third +command runs unittest indirectly through regrtest. The same happens when +the entire test suite is run with 'python -m test'. So that command must +work for buildbots to stay green. IDLE tests must not disturb the +environment in a way that makes other tests fail (GH-62281). + +To test subsets of modules, see idlelib.idle_test.__init__. This +can be used to find refleaks or possible sources of "Theme changed" +tcl messages (GH-71383). + +To run an individual Testcase or test method, extend the dotted name +given to unittest on the command line or use the test -m option. The +latter allows use of other regrtest options. When using the latter, +all components of the pattern must be present, but any can be replaced +by '*'. + +python -m unittest -v idlelib.idle_test.test_xyz.Test_case.test_meth +python -m test -m idlelib.idle_test.text_xyz.Test_case.test_meth test_idle + +The test suite can be run in an IDLE user process from Shell. +>>> import test.autotest # Issue 25588, 2017/10/13, 3.6.4, 3.7.0a2. +There are currently failures not usually present, and this does not +work when run from the editor. + + +4. Human-mediated Tests + +Human-mediated tests are widget tests that cannot be automated but need +human verification. They are contained in idlelib/idle_test/htest.py, +which has instructions. (Some modules need an auxiliary function, +identified with "# htest # on the header line.) The set is about +complete, though some tests need improvement. To run all htests, run the +htest file from an editor or from the command line with: + +python -m idlelib.idle_test.htest + + +5. Test Coverage + +Install the coverage package into your Python 3.6 site-packages +directory. (Its exact location depends on the OS). +> python3 -m pip install coverage +(On Windows, replace 'python3 with 'py -3.6' or perhaps just 'python'.) + +The problem with running coverage with repository python is that +coverage uses absolute imports for its submodules, hence it needs to be +in a directory in sys.path. One solution: copy the package to the +directory containing the cpython repository. Call it 'dev'. Then run +coverage either directly or from a script in that directory so that +'dev' is prepended to sys.path. + +Either edit or add dev/.coveragerc so it looks something like this. +--- +# .coveragerc sets coverage options. +[run] +branch = True + +[report] +# Regexes for lines to exclude from consideration +exclude_lines = + # Don't complain if non-runnable code isn't run: + if 0: + if __name__ == .__main__.: + + .*# htest # + if not _utest: + if _htest: +--- +The additions for IDLE are 'branch = True', to test coverage both ways, +and the last three exclude lines, to exclude things peculiar to IDLE +that are not executed during tests. + +A script like the following cover.bat (for Windows) is very handy. +--- +@echo off +rem Usage: cover filename [test_ suffix] # proper case required by coverage +rem filename without .py, 2nd parameter if test is not test_filename +setlocal +set py=f:\dev\3x\pcbuild\win32\python_d.exe +set src=idlelib.%1 +if "%2" EQU "" set tst=f:/dev/3x/Lib/idlelib/idle_test/test_%1.py +if "%2" NEQ "" set tst=f:/dev/ex/Lib/idlelib/idle_test/test_%2.py + +%py% -m coverage run --pylib --source=%src% %tst% +%py% -m coverage report --show-missing +%py% -m coverage html +start htmlcov\3x_Lib_idlelib_%1_py.html +rem Above opens new report; htmlcov\index.html displays report index +--- +The second parameter was added for tests of module x not named test_x. +(There were several before modules were renamed, now only one is left.) diff --git a/micromamba_root/envs/pytorch_env/Lib/idlelib/idle_test/example_noext b/micromamba_root/envs/pytorch_env/Lib/idlelib/idle_test/example_noext new file mode 100644 index 0000000000000000000000000000000000000000..7d2510e30bc0ae41fde1a2e2fa30cdbb55318893 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/idlelib/idle_test/example_noext @@ -0,0 +1,4 @@ +#!usr/bin/env python + +def example_function(some_argument): + pass diff --git a/micromamba_root/envs/pytorch_env/Lib/idlelib/idle_test/example_stub.pyi b/micromamba_root/envs/pytorch_env/Lib/idlelib/idle_test/example_stub.pyi new file mode 100644 index 0000000000000000000000000000000000000000..17b58010a9d8de8f6737998d6277dc51c823841e --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/idlelib/idle_test/example_stub.pyi @@ -0,0 +1,4 @@ +" Example to test recognition of .pyi file as Python source code. + +class Example: + def method(self, argument1: str, argument2: list[int]) -> None: ... diff --git a/micromamba_root/envs/pytorch_env/Lib/idlelib/idle_test/htest.py b/micromamba_root/envs/pytorch_env/Lib/idlelib/idle_test/htest.py new file mode 100644 index 0000000000000000000000000000000000000000..a7293774eecaeb957314578baaad65f024b40387 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/idlelib/idle_test/htest.py @@ -0,0 +1,442 @@ +"""Run human tests of Idle's window, dialog, and popup widgets. + +run(*tests) Create a master Tk() htest window. Within that, run each +callable in tests after finding the matching test spec in this file. If +tests is empty, run an htest for each spec dict in this file after +finding the matching callable in the module named in the spec. Close +the master window to end testing. + +In a tested module, let X be a global name bound to a callable (class or +function) whose .__name__ attribute is also X (the usual situation). The +first parameter of X must be 'parent' or 'master'. When called, the +first argument will be the root window. X must create a child +Toplevel(parent/master) (or subclass thereof). The Toplevel may be a +test widget or dialog, in which case the callable is the corresponding +class. Or the Toplevel may contain the widget to be tested or set up a +context in which a test widget is invoked. In this latter case, the +callable is a wrapper function that sets up the Toplevel and other +objects. Wrapper function names, such as _editor_window', should start +with '_' and be lowercase. + + +End the module with + +if __name__ == '__main__': + + from idlelib.idle_test.htest import run + run(callable) # There could be multiple comma-separated callables. + +To have wrapper functions ignored by coverage reports, tag the def +header like so: "def _wrapper(parent): # htest #". Use the same tag +for htest lines in widget code. Make sure that the 'if __name__' line +matches the above. Then have make sure that .coveragerc includes the +following: + +[report] +exclude_lines = + .*# htest # + if __name__ == .__main__.: + +(The "." instead of "'" is intentional and necessary.) + + +To run any X, this file must contain a matching instance of the +following template, with X.__name__ prepended to '_spec'. +When all tests are run, the prefix is use to get X. + +callable_spec = { + 'file': '', + 'kwds': {'title': ''}, + 'msg': "" + } + +file (no .py): run() imports file.py. +kwds: augmented with {'parent':root} and passed to X as **kwds. +title: an example kwd; some widgets need this, delete line if not. +msg: master window hints about testing the widget. + + +TODO test these modules and classes: + autocomplete_w.AutoCompleteWindow + debugger.Debugger + outwin.OutputWindow (indirectly being tested with grep test) + pyshell.PyShellEditorWindow +""" + +import idlelib.pyshell # Set Windows DPI awareness before Tk(). +from importlib import import_module +import textwrap +import tkinter as tk +from tkinter.ttk import Scrollbar +tk.NoDefaultRoot() + +AboutDialog_spec = { + 'file': 'help_about', + 'kwds': {'title': 'help_about test', + '_htest': True, + }, + 'msg': "Click on URL to open in default browser.\n" + "Verify x.y.z versions and test each button, including Close.\n " + } + +# TODO implement ^\; adding '' to function does not work. +_calltip_window_spec = { + 'file': 'calltip_w', + 'kwds': {}, + 'msg': "Typing '(' should display a calltip.\n" + "Typing ') should hide the calltip.\n" + "So should moving cursor out of argument area.\n" + "Force-open-calltip does not work here.\n" + } + +_color_delegator_spec = { + 'file': 'colorizer', + 'kwds': {}, + 'msg': "The text is sample Python code.\n" + "Ensure components like comments, keywords, builtins,\n" + "string, definitions, and break are correctly colored.\n" + "The default color scheme is in idlelib/config-highlight.def" + } + +ConfigDialog_spec = { + 'file': 'configdialog', + 'kwds': {'title': 'ConfigDialogTest', + '_htest': True,}, + 'msg': "IDLE preferences dialog.\n" + "In the 'Fonts/Tabs' tab, changing font face, should update the " + "font face of the text in the area below it.\nIn the " + "'Highlighting' tab, try different color schemes. Clicking " + "items in the sample program should update the choices above it." + "\nIn the 'Keys', 'General' and 'Extensions' tabs, test settings " + "of interest." + "\n[Ok] to close the dialog.[Apply] to apply the settings and " + "and [Cancel] to revert all changes.\nRe-run the test to ensure " + "changes made have persisted." + } + +CustomRun_spec = { + 'file': 'query', + 'kwds': {'title': 'Customize query.py Run', + '_htest': True}, + 'msg': "Enter with or [OK]. Print valid entry to Shell\n" + "Arguments are parsed into a list\n" + "Mode is currently restart True or False\n" + "Close dialog with valid entry, , [Cancel], [X]" + } + +_debug_object_browser_spec = { + 'file': 'debugobj', + 'kwds': {}, + 'msg': "Double click on items up to the lowest level.\n" + "Attributes of the objects and related information " + "will be displayed side-by-side at each level." + } + +# TODO Improve message +_dyn_option_menu_spec = { + 'file': 'dynoption', + 'kwds': {}, + 'msg': "Select one of the many options in the 'old option set'.\n" + "Click the button to change the option set.\n" + "Select one of the many options in the 'new option set'." + } + +# TODO edit wrapper +_editor_window_spec = { + 'file': 'editor', + 'kwds': {}, + 'msg': "Test editor functions of interest.\n" + "Best to close editor first." + } + +GetKeysWindow_spec = { + 'file': 'config_key', + 'kwds': {'title': 'Test keybindings', + 'action': 'find-again', + 'current_key_sequences': [['', '', '']], + '_htest': True, + }, + 'msg': "Test for different key modifier sequences.\n" + " is invalid.\n" + "No modifier key is invalid.\n" + "Shift key with [a-z],[0-9], function key, move key, tab, space " + "is invalid.\nNo validity checking if advanced key binding " + "entry is used." + } + +_grep_dialog_spec = { + 'file': 'grep', + 'kwds': {}, + 'msg': "Click the 'Show GrepDialog' button.\n" + "Test the various 'Find-in-files' functions.\n" + "The results should be displayed in a new '*Output*' window.\n" + "'Right-click'->'Go to file/line' in the search results\n " + "should open that file in a new EditorWindow." + } + +HelpSource_spec = { + 'file': 'query', + 'kwds': {'title': 'Help name and source', + 'menuitem': 'test', + 'filepath': __file__, + 'used_names': {'abc'}, + '_htest': True}, + 'msg': "Enter menu item name and help file path\n" + "'', > than 30 chars, and 'abc' are invalid menu item names.\n" + "'' and file does not exist are invalid path items.\n" + "Any url ('www...', 'http...') is accepted.\n" + "Test Browse with and without path, as cannot unittest.\n" + "[Ok] or prints valid entry to shell\n" + ", [Cancel], or [X] prints None to shell" + } + +_io_binding_spec = { + 'file': 'iomenu', + 'kwds': {}, + 'msg': "Test the following bindings.\n" + " to open file from dialog.\n" + "Edit the file.\n" + " to print the file.\n" + " to save the file.\n" + " to save-as another file.\n" + " to save-copy-as another file.\n" + "Check that changes were saved by opening the file elsewhere." + } + +_multi_call_spec = { + 'file': 'multicall', + 'kwds': {}, + 'msg': "The following should trigger a print to console or IDLE Shell.\n" + "Entering and leaving the text area, key entry, ,\n" + ", , , \n" + ", and focusing elsewhere." + } + +_module_browser_spec = { + 'file': 'browser', + 'kwds': {}, + 'msg': textwrap.dedent(""" + "Inspect names of module, class(with superclass if applicable), + "methods and functions. Toggle nested items. Double clicking + "on items prints a traceback for an exception that is ignored.""") + } + +_multistatus_bar_spec = { + 'file': 'statusbar', + 'kwds': {}, + 'msg': "Ensure presence of multi-status bar below text area.\n" + "Click 'Update Status' to change the status text" + } + +PathBrowser_spec = { + 'file': 'pathbrowser', + 'kwds': {'_htest': True}, + 'msg': "Test for correct display of all paths in sys.path.\n" + "Toggle nested items out to the lowest level.\n" + "Double clicking on an item prints a traceback\n" + "for an exception that is ignored." + } + +_percolator_spec = { + 'file': 'percolator', + 'kwds': {}, + 'msg': "There are two tracers which can be toggled using a checkbox.\n" + "Toggling a tracer 'on' by checking it should print tracer " + "output to the console or to the IDLE shell.\n" + "If both the tracers are 'on', the output from the tracer which " + "was switched 'on' later, should be printed first\n" + "Test for actions like text entry, and removal." + } + +Query_spec = { + 'file': 'query', + 'kwds': {'title': 'Query', + 'message': 'Enter something', + 'text0': 'Go', + '_htest': True}, + 'msg': "Enter with or [Ok]. Print valid entry to Shell\n" + "Blank line, after stripping, is ignored\n" + "Close dialog with valid entry, , [Cancel], [X]" + } + + +_replace_dialog_spec = { + 'file': 'replace', + 'kwds': {}, + 'msg': "Click the 'Replace' button.\n" + "Test various replace options in the 'Replace dialog'.\n" + "Click [Close] or [X] to close the 'Replace Dialog'." + } + +_scrolled_list_spec = { + 'file': 'scrolledlist', + 'kwds': {}, + 'msg': "You should see a scrollable list of items\n" + "Selecting (clicking) or double clicking an item " + "prints the name to the console or Idle shell.\n" + "Right clicking an item will display a popup." + } + +_search_dialog_spec = { + 'file': 'search', + 'kwds': {}, + 'msg': "Click the 'Search' button.\n" + "Test various search options in the 'Search dialog'.\n" + "Click [Close] or [X] to close the 'Search Dialog'." + } + +_searchbase_spec = { + 'file': 'searchbase', + 'kwds': {}, + 'msg': "Check the appearance of the base search dialog\n" + "Its only action is to close." + } + +show_idlehelp_spec = { + 'file': 'help', + 'kwds': {}, + 'msg': "If the help text displays, this works.\n" + "Text is selectable. Window is scrollable." + } + +_sidebar_number_scrolling_spec = { + 'file': 'sidebar', + 'kwds': {}, + 'msg': textwrap.dedent("""\ + 1. Click on the line numbers and drag down below the edge of the + window, moving the mouse a bit and then leaving it there for a + while. The text and line numbers should gradually scroll down, + with the selection updated continuously. + + 2. With the lines still selected, click on a line number above + or below the selected lines. Only the line whose number was + clicked should be selected. + + 3. Repeat step #1, dragging to above the window. The text and + line numbers should gradually scroll up, with the selection + updated continuously. + + 4. Repeat step #2, clicking a line number below the selection."""), + } + +_stackbrowser_spec = { + 'file': 'stackviewer', + 'kwds': {}, + 'msg': "A stacktrace for a NameError exception.\n" + "Should have NameError and 1 traceback line." + } + +_tooltip_spec = { + 'file': 'tooltip', + 'kwds': {}, + 'msg': "Place mouse cursor over both the buttons\n" + "A tooltip should appear with some text." + } + +_tree_widget_spec = { + 'file': 'tree', + 'kwds': {}, + 'msg': "The canvas is scrollable.\n" + "Click on folders up to to the lowest level." + } + +_undo_delegator_spec = { + 'file': 'undo', + 'kwds': {}, + 'msg': "Click [Undo] to undo any action.\n" + "Click [Redo] to redo any action.\n" + "Click [Dump] to dump the current state " + "by printing to the console or the IDLE shell.\n" + } + +ViewWindow_spec = { + 'file': 'textview', + 'kwds': {'title': 'Test textview', + 'contents': 'The quick brown fox jumps over the lazy dog.\n'*35, + '_htest': True}, + 'msg': "Test for read-only property of text.\n" + "Select text, scroll window, close" + } + +_widget_redirector_spec = { + 'file': 'redirector', + 'kwds': {}, + 'msg': "Every text insert should be printed to the console " + "or the IDLE shell." + } + +def run(*tests): + "Run callables in tests." + root = tk.Tk() + root.title('IDLE htest') + root.resizable(0, 0) + + # A scrollable Label-like constant width text widget. + frameLabel = tk.Frame(root, padx=10) + frameLabel.pack() + text = tk.Text(frameLabel, wrap='word') + text.configure(bg=root.cget('bg'), relief='flat', height=4, width=70) + scrollbar = Scrollbar(frameLabel, command=text.yview) + text.config(yscrollcommand=scrollbar.set) + scrollbar.pack(side='right', fill='y', expand=False) + text.pack(side='left', fill='both', expand=True) + + test_list = [] # Make list of (spec, callable) tuples. + if tests: + for test in tests: + test_spec = globals()[test.__name__ + '_spec'] + test_spec['name'] = test.__name__ + test_list.append((test_spec, test)) + else: + for key, dic in globals().items(): + if key.endswith('_spec'): + test_name = key[:-5] + test_spec = dic + test_spec['name'] = test_name + mod = import_module('idlelib.' + test_spec['file']) + test = getattr(mod, test_name) + test_list.append((test_spec, test)) + test_list.reverse() # So can pop in proper order in next_test. + + test_name = tk.StringVar(root) + callable_object = None + test_kwds = None + + def next_test(): + nonlocal test_name, callable_object, test_kwds + if len(test_list) == 1: + next_button.pack_forget() + test_spec, callable_object = test_list.pop() + test_kwds = test_spec['kwds'] + test_name.set('Test ' + test_spec['name']) + + text['state'] = 'normal' # Enable text replacement. + text.delete('1.0', 'end') + text.insert("1.0", test_spec['msg']) + text['state'] = 'disabled' # Restore read-only property. + + def run_test(_=None): + widget = callable_object(root, **test_kwds) + try: + print(widget.result) # Only true for query classes(?). + except AttributeError: + pass + + def close(_=None): + root.destroy() + + button = tk.Button(root, textvariable=test_name, + default='active', command=run_test) + next_button = tk.Button(root, text="Next", command=next_test) + button.pack() + next_button.pack() + next_button.focus_set() + root.bind('', run_test) + root.bind('', close) + + next_test() + root.mainloop() + + +if __name__ == '__main__': + run() diff --git a/micromamba_root/envs/pytorch_env/Lib/idlelib/idle_test/mock_idle.py b/micromamba_root/envs/pytorch_env/Lib/idlelib/idle_test/mock_idle.py new file mode 100644 index 0000000000000000000000000000000000000000..71fa480ce4d05c1d4bcb32fb1cf2d10f8695a2e5 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/idlelib/idle_test/mock_idle.py @@ -0,0 +1,61 @@ +'''Mock classes that imitate idlelib modules or classes. + +Attributes and methods will be added as needed for tests. +''' + +from idlelib.idle_test.mock_tk import Text + +class Func: + '''Record call, capture args, return/raise result set by test. + + When mock function is called, set or use attributes: + self.called - increment call number even if no args, kwds passed. + self.args - capture positional arguments. + self.kwds - capture keyword arguments. + self.result - return or raise value set in __init__. + self.return_self - return self instead, to mock query class return. + + Most common use will probably be to mock instance methods. + Given class instance, can set and delete as instance attribute. + Mock_tk.Var and Mbox_func are special variants of this. + ''' + def __init__(self, result=None, return_self=False): + self.called = 0 + self.result = result + self.return_self = return_self + self.args = None + self.kwds = None + def __call__(self, *args, **kwds): + self.called += 1 + self.args = args + self.kwds = kwds + if isinstance(self.result, BaseException): + raise self.result + elif self.return_self: + return self + else: + return self.result + + +class Editor: + '''Minimally imitate editor.EditorWindow class. + ''' + def __init__(self, flist=None, filename=None, key=None, root=None, + text=None): # Allow real Text with mock Editor. + self.text = text or Text() + self.undo = UndoDelegator() + + def get_selection_indices(self): + first = self.text.index('1.0') + last = self.text.index('end') + return first, last + + +class UndoDelegator: + '''Minimally imitate undo.UndoDelegator class. + ''' + # A real undo block is only needed for user interaction. + def undo_block_start(*args): + pass + def undo_block_stop(*args): + pass diff --git a/micromamba_root/envs/pytorch_env/Lib/idlelib/idle_test/mock_tk.py b/micromamba_root/envs/pytorch_env/Lib/idlelib/idle_test/mock_tk.py new file mode 100644 index 0000000000000000000000000000000000000000..8304734b847a835e5ad17227a66a0ff3b21eeaf7 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/idlelib/idle_test/mock_tk.py @@ -0,0 +1,307 @@ +"""Classes that replace tkinter gui objects used by an object being tested. + +A gui object is anything with a master or parent parameter, which is +typically required in spite of what the doc strings say. +""" +import re +from _tkinter import TclError + + +class Event: + '''Minimal mock with attributes for testing event handlers. + + This is not a gui object, but is used as an argument for callbacks + that access attributes of the event passed. If a callback ignores + the event, other than the fact that is happened, pass 'event'. + + Keyboard, mouse, window, and other sources generate Event instances. + Event instances have the following attributes: serial (number of + event), time (of event), type (of event as number), widget (in which + event occurred), and x,y (position of mouse). There are other + attributes for specific events, such as keycode for key events. + tkinter.Event.__doc__ has more but is still not complete. + ''' + def __init__(self, **kwds): + "Create event with attributes needed for test" + self.__dict__.update(kwds) + + +class Var: + "Use for String/Int/BooleanVar: incomplete" + def __init__(self, master=None, value=None, name=None): + self.master = master + self.value = value + self.name = name + def set(self, value): + self.value = value + def get(self): + return self.value + + +class Mbox_func: + """Generic mock for messagebox functions, which all have the same signature. + + Instead of displaying a message box, the mock's call method saves the + arguments as instance attributes, which test functions can then examine. + The test can set the result returned to ask function + """ + def __init__(self, result=None): + self.result = result # Return None for all show funcs + def __call__(self, title, message, *args, **kwds): + # Save all args for possible examination by tester + self.title = title + self.message = message + self.args = args + self.kwds = kwds + return self.result # Set by tester for ask functions + + +class Mbox: + """Mock for tkinter.messagebox with an Mbox_func for each function. + + Example usage in test_module.py for testing functions in module.py: + --- +from idlelib.idle_test.mock_tk import Mbox +import module + +orig_mbox = module.messagebox +showerror = Mbox.showerror # example, for attribute access in test methods + +class Test(unittest.TestCase): + + @classmethod + def setUpClass(cls): + module.messagebox = Mbox + + @classmethod + def tearDownClass(cls): + module.messagebox = orig_mbox + --- + For 'ask' functions, set func.result return value before calling the method + that uses the message function. When messagebox functions are the + only GUI calls in a method, this replacement makes the method GUI-free, + """ + askokcancel = Mbox_func() # True or False + askquestion = Mbox_func() # 'yes' or 'no' + askretrycancel = Mbox_func() # True or False + askyesno = Mbox_func() # True or False + askyesnocancel = Mbox_func() # True, False, or None + showerror = Mbox_func() # None + showinfo = Mbox_func() # None + showwarning = Mbox_func() # None + + +class Text: + """A semi-functional non-gui replacement for tkinter.Text text editors. + + The mock's data model is that a text is a list of \n-terminated lines. + The mock adds an empty string at the beginning of the list so that the + index of actual lines start at 1, as with Tk. The methods never see this. + Tk initializes files with a terminal \n that cannot be deleted. It is + invisible in the sense that one cannot move the cursor beyond it. + + This class is only tested (and valid) with strings of ascii chars. + For testing, we are not concerned with Tk Text's treatment of, + for instance, 0-width characters or character + accent. + """ + def __init__(self, master=None, cnf={}, **kw): + '''Initialize mock, non-gui, text-only Text widget. + + At present, all args are ignored. Almost all affect visual behavior. + There are just a few Text-only options that affect text behavior. + ''' + self.data = ['', '\n'] + + def index(self, index): + "Return string version of index decoded according to current text." + return "%s.%s" % self._decode(index, endflag=1) + + def _decode(self, index, endflag=0): + """Return a (line, char) tuple of int indexes into self.data. + + This implements .index without converting the result back to a string. + The result is constrained by the number of lines and linelengths of + self.data. For many indexes, the result is initially (1, 0). + + The input index may have any of several possible forms: + * line.char float: converted to 'line.char' string; + * 'line.char' string, where line and char are decimal integers; + * 'line.char lineend', where lineend='lineend' (and char is ignored); + * 'line.end', where end='end' (same as above); + * 'insert', the positions before terminal \n; + * 'end', whose meaning depends on the endflag passed to ._endex. + * 'sel.first' or 'sel.last', where sel is a tag -- not implemented. + """ + if isinstance(index, (float, bytes)): + index = str(index) + try: + index=index.lower() + except AttributeError: + raise TclError('bad text index "%s"' % index) from None + + lastline = len(self.data) - 1 # same as number of text lines + if index == 'insert': + return lastline, len(self.data[lastline]) - 1 + elif index == 'end': + return self._endex(endflag) + + line, char = index.split('.') + line = int(line) + + # Out of bounds line becomes first or last ('end') index + if line < 1: + return 1, 0 + elif line > lastline: + return self._endex(endflag) + + linelength = len(self.data[line]) -1 # position before/at \n + if char.endswith(' lineend') or char == 'end': + return line, linelength + # Tk requires that ignored chars before ' lineend' be valid int + if m := re.fullmatch(r'end-(\d*)c', char, re.A): # Used by hyperparser. + return line, linelength - int(m.group(1)) + + # Out of bounds char becomes first or last index of line + char = int(char) + if char < 0: + char = 0 + elif char > linelength: + char = linelength + return line, char + + def _endex(self, endflag): + '''Return position for 'end' or line overflow corresponding to endflag. + + -1: position before terminal \n; for .insert(), .delete + 0: position after terminal \n; for .get, .delete index 1 + 1: same viewed as beginning of non-existent next line (for .index) + ''' + n = len(self.data) + if endflag == 1: + return n, 0 + else: + n -= 1 + return n, len(self.data[n]) + endflag + + def insert(self, index, chars): + "Insert chars before the character at index." + + if not chars: # ''.splitlines() is [], not [''] + return + chars = chars.splitlines(True) + if chars[-1][-1] == '\n': + chars.append('') + line, char = self._decode(index, -1) + before = self.data[line][:char] + after = self.data[line][char:] + self.data[line] = before + chars[0] + self.data[line+1:line+1] = chars[1:] + self.data[line+len(chars)-1] += after + + def get(self, index1, index2=None): + "Return slice from index1 to index2 (default is 'index1+1')." + + startline, startchar = self._decode(index1) + if index2 is None: + endline, endchar = startline, startchar+1 + else: + endline, endchar = self._decode(index2) + + if startline == endline: + return self.data[startline][startchar:endchar] + else: + lines = [self.data[startline][startchar:]] + for i in range(startline+1, endline): + lines.append(self.data[i]) + lines.append(self.data[endline][:endchar]) + return ''.join(lines) + + def delete(self, index1, index2=None): + '''Delete slice from index1 to index2 (default is 'index1+1'). + + Adjust default index2 ('index+1) for line ends. + Do not delete the terminal \n at the very end of self.data ([-1][-1]). + ''' + startline, startchar = self._decode(index1, -1) + if index2 is None: + if startchar < len(self.data[startline])-1: + # not deleting \n + endline, endchar = startline, startchar+1 + elif startline < len(self.data) - 1: + # deleting non-terminal \n, convert 'index1+1 to start of next line + endline, endchar = startline+1, 0 + else: + # do not delete terminal \n if index1 == 'insert' + return + else: + endline, endchar = self._decode(index2, -1) + # restricting end position to insert position excludes terminal \n + + if startline == endline and startchar < endchar: + self.data[startline] = self.data[startline][:startchar] + \ + self.data[startline][endchar:] + elif startline < endline: + self.data[startline] = self.data[startline][:startchar] + \ + self.data[endline][endchar:] + startline += 1 + for i in range(startline, endline+1): + del self.data[startline] + + def compare(self, index1, op, index2): + line1, char1 = self._decode(index1) + line2, char2 = self._decode(index2) + if op == '<': + return line1 < line2 or line1 == line2 and char1 < char2 + elif op == '<=': + return line1 < line2 or line1 == line2 and char1 <= char2 + elif op == '>': + return line1 > line2 or line1 == line2 and char1 > char2 + elif op == '>=': + return line1 > line2 or line1 == line2 and char1 >= char2 + elif op == '==': + return line1 == line2 and char1 == char2 + elif op == '!=': + return line1 != line2 or char1 != char2 + else: + raise TclError('''bad comparison operator "%s": ''' + '''must be <, <=, ==, >=, >, or !=''' % op) + + # The following Text methods normally do something and return None. + # Whether doing nothing is sufficient for a test will depend on the test. + + def mark_set(self, name, index): + "Set mark *name* before the character at index." + pass + + def mark_unset(self, *markNames): + "Delete all marks in markNames." + + def tag_remove(self, tagName, index1, index2=None): + "Remove tag tagName from all characters between index1 and index2." + pass + + # The following Text methods affect the graphics screen and return None. + # Doing nothing should always be sufficient for tests. + + def scan_dragto(self, x, y): + "Adjust the view of the text according to scan_mark" + + def scan_mark(self, x, y): + "Remember the current X, Y coordinates." + + def see(self, index): + "Scroll screen to make the character at INDEX is visible." + pass + + # The following is a Misc method inherited by Text. + # It should properly go in a Misc mock, but is included here for now. + + def bind(sequence=None, func=None, add=None): + "Bind to this widget at event sequence a call to function func." + pass + + +class Entry: + "Mock for tkinter.Entry." + def focus_set(self): + pass diff --git a/micromamba_root/envs/pytorch_env/Lib/idlelib/idle_test/template.py b/micromamba_root/envs/pytorch_env/Lib/idlelib/idle_test/template.py new file mode 100644 index 0000000000000000000000000000000000000000..725a55b9c47230c32c63b3e6cd036f0319173046 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/idlelib/idle_test/template.py @@ -0,0 +1,30 @@ +"Test , coverage %." + +from idlelib import zzdummy +import unittest +from test.support import requires +from tkinter import Tk + + +class Test(unittest.TestCase): + + @classmethod + def setUpClass(cls): + requires('gui') + cls.root = Tk() + cls.root.withdraw() + + @classmethod + def tearDownClass(cls): + cls.root.update_idletasks() +## for id in cls.root.tk.call('after', 'info'): +## cls.root.after_cancel(id) # Need for EditorWindow. + cls.root.destroy() + del cls.root + + def test_init(self): + self.assertTrue(True) + + +if __name__ == '__main__': + unittest.main(verbosity=2) diff --git a/micromamba_root/envs/pytorch_env/Lib/idlelib/idle_test/test_autocomplete.py b/micromamba_root/envs/pytorch_env/Lib/idlelib/idle_test/test_autocomplete.py new file mode 100644 index 0000000000000000000000000000000000000000..a811363c18d04e5770ec7071e08f0273dd04f0bf --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/idlelib/idle_test/test_autocomplete.py @@ -0,0 +1,305 @@ +"Test autocomplete, coverage 93%." + +import unittest +from unittest.mock import Mock, patch +from test.support import requires +from tkinter import Tk, Text +import os +import __main__ + +import idlelib.autocomplete as ac +import idlelib.autocomplete_w as acw +from idlelib.idle_test.mock_idle import Func +from idlelib.idle_test.mock_tk import Event + + +class DummyEditwin: + def __init__(self, root, text): + self.root = root + self.text = text + self.indentwidth = 8 + self.tabwidth = 8 + self.prompt_last_line = '>>>' # Currently not used by autocomplete. + + +class AutoCompleteTest(unittest.TestCase): + + @classmethod + def setUpClass(cls): + requires('gui') + cls.root = Tk() + cls.root.withdraw() + cls.text = Text(cls.root) + cls.editor = DummyEditwin(cls.root, cls.text) + + @classmethod + def tearDownClass(cls): + del cls.editor, cls.text + cls.root.update_idletasks() + cls.root.destroy() + del cls.root + + def setUp(self): + self.text.delete('1.0', 'end') + self.autocomplete = ac.AutoComplete(self.editor) + + def test_init(self): + self.assertEqual(self.autocomplete.editwin, self.editor) + self.assertEqual(self.autocomplete.text, self.text) + + def test_make_autocomplete_window(self): + testwin = self.autocomplete._make_autocomplete_window() + self.assertIsInstance(testwin, acw.AutoCompleteWindow) + + def test_remove_autocomplete_window(self): + acp = self.autocomplete + acp.autocompletewindow = m = Mock() + acp._remove_autocomplete_window() + m.hide_window.assert_called_once() + self.assertIsNone(acp.autocompletewindow) + + def test_force_open_completions_event(self): + # Call _open_completions and break. + acp = self.autocomplete + open_c = Func() + acp.open_completions = open_c + self.assertEqual(acp.force_open_completions_event('event'), 'break') + self.assertEqual(open_c.args[0], ac.FORCE) + + def test_autocomplete_event(self): + Equal = self.assertEqual + acp = self.autocomplete + + # Result of autocomplete event: If modified tab, None. + ev = Event(mc_state=True) + self.assertIsNone(acp.autocomplete_event(ev)) + del ev.mc_state + + # If tab after whitespace, None. + self.text.insert('1.0', ' """Docstring.\n ') + self.assertIsNone(acp.autocomplete_event(ev)) + self.text.delete('1.0', 'end') + + # If active autocomplete window, complete() and 'break'. + self.text.insert('1.0', 're.') + acp.autocompletewindow = mock = Mock() + mock.is_active = Mock(return_value=True) + Equal(acp.autocomplete_event(ev), 'break') + mock.complete.assert_called_once() + acp.autocompletewindow = None + + # If no active autocomplete window, open_completions(), None/break. + open_c = Func(result=False) + acp.open_completions = open_c + Equal(acp.autocomplete_event(ev), None) + Equal(open_c.args[0], ac.TAB) + open_c.result = True + Equal(acp.autocomplete_event(ev), 'break') + Equal(open_c.args[0], ac.TAB) + + def test_try_open_completions_event(self): + Equal = self.assertEqual + text = self.text + acp = self.autocomplete + trycompletions = acp.try_open_completions_event + after = Func(result='after1') + acp.text.after = after + + # If no text or trigger, after not called. + trycompletions() + Equal(after.called, 0) + text.insert('1.0', 're') + trycompletions() + Equal(after.called, 0) + + # Attribute needed, no existing callback. + text.insert('insert', ' re.') + acp._delayed_completion_id = None + trycompletions() + Equal(acp._delayed_completion_index, text.index('insert')) + Equal(after.args, + (acp.popupwait, acp._delayed_open_completions, ac.TRY_A)) + cb1 = acp._delayed_completion_id + Equal(cb1, 'after1') + + # File needed, existing callback cancelled. + text.insert('insert', ' "./Lib/') + after.result = 'after2' + cancel = Func() + acp.text.after_cancel = cancel + trycompletions() + Equal(acp._delayed_completion_index, text.index('insert')) + Equal(cancel.args, (cb1,)) + Equal(after.args, + (acp.popupwait, acp._delayed_open_completions, ac.TRY_F)) + Equal(acp._delayed_completion_id, 'after2') + + def test_delayed_open_completions(self): + Equal = self.assertEqual + acp = self.autocomplete + open_c = Func() + acp.open_completions = open_c + self.text.insert('1.0', '"dict.') + + # Set autocomplete._delayed_completion_id to None. + # Text index changed, don't call open_completions. + acp._delayed_completion_id = 'after' + acp._delayed_completion_index = self.text.index('insert+1c') + acp._delayed_open_completions('dummy') + self.assertIsNone(acp._delayed_completion_id) + Equal(open_c.called, 0) + + # Text index unchanged, call open_completions. + acp._delayed_completion_index = self.text.index('insert') + acp._delayed_open_completions((1, 2, 3, ac.FILES)) + self.assertEqual(open_c.args[0], (1, 2, 3, ac.FILES)) + + def test_oc_cancel_comment(self): + none = self.assertIsNone + acp = self.autocomplete + + # Comment is in neither code or string. + acp._delayed_completion_id = 'after' + after = Func(result='after') + acp.text.after_cancel = after + self.text.insert(1.0, '# comment') + none(acp.open_completions(ac.TAB)) # From 'else' after 'elif'. + none(acp._delayed_completion_id) + + def test_oc_no_list(self): + acp = self.autocomplete + fetch = Func(result=([],[])) + acp.fetch_completions = fetch + self.text.insert('1.0', 'object') + self.assertIsNone(acp.open_completions(ac.TAB)) + self.text.insert('insert', '.') + self.assertIsNone(acp.open_completions(ac.TAB)) + self.assertEqual(fetch.called, 2) + + + def test_open_completions_none(self): + # Test other two None returns. + none = self.assertIsNone + acp = self.autocomplete + + # No object for attributes or need call not allowed. + self.text.insert(1.0, '.') + none(acp.open_completions(ac.TAB)) + self.text.insert('insert', ' int().') + none(acp.open_completions(ac.TAB)) + + # Blank or quote trigger 'if complete ...'. + self.text.delete(1.0, 'end') + self.assertFalse(acp.open_completions(ac.TAB)) + self.text.insert('1.0', '"') + self.assertFalse(acp.open_completions(ac.TAB)) + self.text.delete('1.0', 'end') + + class dummy_acw: + __init__ = Func() + show_window = Func(result=False) + hide_window = Func() + + def test_open_completions(self): + # Test completions of files and attributes. + acp = self.autocomplete + fetch = Func(result=(['tem'],['tem', '_tem'])) + acp.fetch_completions = fetch + def make_acw(): return self.dummy_acw() + acp._make_autocomplete_window = make_acw + + self.text.insert('1.0', 'int.') + acp.open_completions(ac.TAB) + self.assertIsInstance(acp.autocompletewindow, self.dummy_acw) + self.text.delete('1.0', 'end') + + # Test files. + self.text.insert('1.0', '"t') + self.assertTrue(acp.open_completions(ac.TAB)) + self.text.delete('1.0', 'end') + + def test_completion_kwds(self): + self.assertIn('and', ac.completion_kwds) + self.assertIn('case', ac.completion_kwds) + self.assertNotIn('None', ac.completion_kwds) + + def test_fetch_completions(self): + # Test that fetch_completions returns 2 lists: + # For attribute completion, a large list containing all variables, and + # a small list containing non-private variables. + # For file completion, a large list containing all files in the path, + # and a small list containing files that do not start with '.'. + acp = self.autocomplete + small, large = acp.fetch_completions( + '', ac.ATTRS) + if hasattr(__main__, '__file__') and __main__.__file__ != ac.__file__: + self.assertNotIn('AutoComplete', small) # See issue 36405. + + # Test attributes + s, b = acp.fetch_completions('', ac.ATTRS) + self.assertLess(len(small), len(large)) + self.assertTrue(all(filter(lambda x: x.startswith('_'), s))) + self.assertTrue(any(filter(lambda x: x.startswith('_'), b))) + + # Test smalll should respect to __all__. + with patch.dict('__main__.__dict__', {'__all__': ['a', 'b']}): + s, b = acp.fetch_completions('', ac.ATTRS) + self.assertEqual(s, ['a', 'b']) + self.assertIn('__name__', b) # From __main__.__dict__. + self.assertIn('sum', b) # From __main__.__builtins__.__dict__. + self.assertIn('nonlocal', b) # From keyword.kwlist. + pos = b.index('False') # Test False not included twice. + self.assertNotEqual(b[pos+1], 'False') + + # Test attributes with name entity. + mock = Mock() + mock._private = Mock() + with patch.dict('__main__.__dict__', {'foo': mock}): + s, b = acp.fetch_completions('foo', ac.ATTRS) + self.assertNotIn('_private', s) + self.assertIn('_private', b) + self.assertEqual(s, [i for i in sorted(dir(mock)) if i[:1] != '_']) + self.assertEqual(b, sorted(dir(mock))) + + # Test files + def _listdir(path): + # This will be patch and used in fetch_completions. + if path == '.': + return ['foo', 'bar', '.hidden'] + return ['monty', 'python', '.hidden'] + + with patch.object(os, 'listdir', _listdir): + s, b = acp.fetch_completions('', ac.FILES) + self.assertEqual(s, ['bar', 'foo']) + self.assertEqual(b, ['.hidden', 'bar', 'foo']) + + s, b = acp.fetch_completions('~', ac.FILES) + self.assertEqual(s, ['monty', 'python']) + self.assertEqual(b, ['.hidden', 'monty', 'python']) + + def test_get_entity(self): + # Test that a name is in the namespace of sys.modules and + # __main__.__dict__. + acp = self.autocomplete + Equal = self.assertEqual + + Equal(acp.get_entity('int'), int) + + # Test name from sys.modules. + mock = Mock() + with patch.dict('sys.modules', {'tempfile': mock}): + Equal(acp.get_entity('tempfile'), mock) + + # Test name from __main__.__dict__. + di = {'foo': 10, 'bar': 20} + with patch.dict('__main__.__dict__', {'d': di}): + Equal(acp.get_entity('d'), di) + + # Test name not in namespace. + with patch.dict('__main__.__dict__', {}): + with self.assertRaises(NameError): + acp.get_entity('not_exist') + + +if __name__ == '__main__': + unittest.main(verbosity=2) diff --git a/micromamba_root/envs/pytorch_env/Lib/idlelib/idle_test/test_autocomplete_w.py b/micromamba_root/envs/pytorch_env/Lib/idlelib/idle_test/test_autocomplete_w.py new file mode 100644 index 0000000000000000000000000000000000000000..a59a375c90fd807e1d3219cde60b3f2612d24fac --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/idlelib/idle_test/test_autocomplete_w.py @@ -0,0 +1,32 @@ +"Test autocomplete_w, coverage 11%." + +import unittest +from test.support import requires +from tkinter import Tk, Text + +import idlelib.autocomplete_w as acw + + +class AutoCompleteWindowTest(unittest.TestCase): + + @classmethod + def setUpClass(cls): + requires('gui') + cls.root = Tk() + cls.root.withdraw() + cls.text = Text(cls.root) + cls.acw = acw.AutoCompleteWindow(cls.text, tags=None) + + @classmethod + def tearDownClass(cls): + del cls.text, cls.acw + cls.root.update_idletasks() + cls.root.destroy() + del cls.root + + def test_init(self): + self.assertEqual(self.acw.widget, self.text) + + +if __name__ == '__main__': + unittest.main(verbosity=2) diff --git a/micromamba_root/envs/pytorch_env/Lib/idlelib/idle_test/test_autoexpand.py b/micromamba_root/envs/pytorch_env/Lib/idlelib/idle_test/test_autoexpand.py new file mode 100644 index 0000000000000000000000000000000000000000..e734a8be714a2adc3ea1a6fca6957cac2815309e --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/idlelib/idle_test/test_autoexpand.py @@ -0,0 +1,155 @@ +"Test autoexpand, coverage 100%." + +from idlelib.autoexpand import AutoExpand +import unittest +from test.support import requires +from tkinter import Text, Tk + + +class DummyEditwin: + # AutoExpand.__init__ only needs .text + def __init__(self, text): + self.text = text + +class AutoExpandTest(unittest.TestCase): + + @classmethod + def setUpClass(cls): + requires('gui') + cls.tk = Tk() + cls.text = Text(cls.tk) + cls.auto_expand = AutoExpand(DummyEditwin(cls.text)) + cls.auto_expand.bell = lambda: None + +# If mock_tk.Text._decode understood indexes 'insert' with suffixed 'linestart', +# 'wordstart', and 'lineend', used by autoexpand, we could use the following +# to run these test on non-gui machines (but check bell). +## try: +## requires('gui') +## #raise ResourceDenied() # Uncomment to test mock. +## except ResourceDenied: +## from idlelib.idle_test.mock_tk import Text +## cls.text = Text() +## cls.text.bell = lambda: None +## else: +## from tkinter import Tk, Text +## cls.tk = Tk() +## cls.text = Text(cls.tk) + + @classmethod + def tearDownClass(cls): + del cls.text, cls.auto_expand + if hasattr(cls, 'tk'): + cls.tk.destroy() + del cls.tk + + def tearDown(self): + self.text.delete('1.0', 'end') + + def test_get_prevword(self): + text = self.text + previous = self.auto_expand.getprevword + equal = self.assertEqual + + equal(previous(), '') + + text.insert('insert', 't') + equal(previous(), 't') + + text.insert('insert', 'his') + equal(previous(), 'this') + + text.insert('insert', ' ') + equal(previous(), '') + + text.insert('insert', 'is') + equal(previous(), 'is') + + text.insert('insert', '\nsample\nstring') + equal(previous(), 'string') + + text.delete('3.0', 'insert') + equal(previous(), '') + + text.delete('1.0', 'end') + equal(previous(), '') + + def test_before_only(self): + previous = self.auto_expand.getprevword + expand = self.auto_expand.expand_word_event + equal = self.assertEqual + + self.text.insert('insert', 'ab ac bx ad ab a') + equal(self.auto_expand.getwords(), ['ab', 'ad', 'ac', 'a']) + expand('event') + equal(previous(), 'ab') + expand('event') + equal(previous(), 'ad') + expand('event') + equal(previous(), 'ac') + expand('event') + equal(previous(), 'a') + + def test_after_only(self): + # Also add punctuation 'noise' that should be ignored. + text = self.text + previous = self.auto_expand.getprevword + expand = self.auto_expand.expand_word_event + equal = self.assertEqual + + text.insert('insert', 'a, [ab] ac: () bx"" cd ac= ad ya') + text.mark_set('insert', '1.1') + equal(self.auto_expand.getwords(), ['ab', 'ac', 'ad', 'a']) + expand('event') + equal(previous(), 'ab') + expand('event') + equal(previous(), 'ac') + expand('event') + equal(previous(), 'ad') + expand('event') + equal(previous(), 'a') + + def test_both_before_after(self): + text = self.text + previous = self.auto_expand.getprevword + expand = self.auto_expand.expand_word_event + equal = self.assertEqual + + text.insert('insert', 'ab xy yz\n') + text.insert('insert', 'a ac by ac') + + text.mark_set('insert', '2.1') + equal(self.auto_expand.getwords(), ['ab', 'ac', 'a']) + expand('event') + equal(previous(), 'ab') + expand('event') + equal(previous(), 'ac') + expand('event') + equal(previous(), 'a') + + def test_other_expand_cases(self): + text = self.text + expand = self.auto_expand.expand_word_event + equal = self.assertEqual + + # no expansion candidate found + equal(self.auto_expand.getwords(), []) + equal(expand('event'), 'break') + + text.insert('insert', 'bx cy dz a') + equal(self.auto_expand.getwords(), []) + + # reset state by successfully expanding once + # move cursor to another position and expand again + text.insert('insert', 'ac xy a ac ad a') + text.mark_set('insert', '1.7') + expand('event') + initial_state = self.auto_expand.state + text.mark_set('insert', '1.end') + expand('event') + new_state = self.auto_expand.state + self.assertNotEqual(initial_state, new_state) + + +if __name__ == '__main__': + unittest.main(verbosity=2) diff --git a/micromamba_root/envs/pytorch_env/Lib/idlelib/idle_test/test_browser.py b/micromamba_root/envs/pytorch_env/Lib/idlelib/idle_test/test_browser.py new file mode 100644 index 0000000000000000000000000000000000000000..6cfea3888cd6a9064be1b9b5f5c13febdc701b96 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/idlelib/idle_test/test_browser.py @@ -0,0 +1,257 @@ +"Test browser, coverage 90%." + +from idlelib import browser +from test.support import requires +import unittest +from unittest import mock +from idlelib.idle_test.mock_idle import Func +from idlelib.util import py_extensions + +from collections import deque +import os.path +import pyclbr +from tkinter import Tk + +from idlelib.tree import TreeNode + + +class ModuleBrowserTest(unittest.TestCase): + + @classmethod + def setUpClass(cls): + requires('gui') + cls.root = Tk() + cls.root.withdraw() + cls.mb = browser.ModuleBrowser(cls.root, __file__, _utest=True) + + @classmethod + def tearDownClass(cls): + cls.mb.close() + cls.root.update_idletasks() + cls.root.destroy() + del cls.root, cls.mb + + def test_init(self): + mb = self.mb + eq = self.assertEqual + eq(mb.path, __file__) + eq(pyclbr._modules, {}) + self.assertIsInstance(mb.node, TreeNode) + self.assertIsNotNone(browser.file_open) + + def test_settitle(self): + mb = self.mb + self.assertIn(os.path.basename(__file__), mb.top.title()) + self.assertEqual(mb.top.iconname(), 'Module Browser') + + def test_rootnode(self): + mb = self.mb + rn = mb.rootnode() + self.assertIsInstance(rn, browser.ModuleBrowserTreeItem) + + def test_close(self): + mb = self.mb + mb.top.destroy = Func() + mb.node.destroy = Func() + mb.close() + self.assertTrue(mb.top.destroy.called) + self.assertTrue(mb.node.destroy.called) + del mb.top.destroy, mb.node.destroy + + def test_is_browseable_extension(self): + path = "/path/to/file" + for ext in py_extensions: + with self.subTest(ext=ext): + filename = f'{path}{ext}' + actual = browser.is_browseable_extension(filename) + expected = ext not in browser.browseable_extension_blocklist + self.assertEqual(actual, expected) + + +# Nested tree same as in test_pyclbr.py except for supers on C0. C1. +mb = pyclbr +module, fname = 'test', 'test.py' +C0 = mb.Class(module, 'C0', ['base'], fname, 1, end_lineno=9) +F1 = mb._nest_function(C0, 'F1', 3, 5) +C1 = mb._nest_class(C0, 'C1', 6, 9, ['']) +C2 = mb._nest_class(C1, 'C2', 7, 9) +F3 = mb._nest_function(C2, 'F3', 9, 9) +f0 = mb.Function(module, 'f0', fname, 11, end_lineno=15) +f1 = mb._nest_function(f0, 'f1', 12, 14) +f2 = mb._nest_function(f1, 'f2', 13, 13) +c1 = mb._nest_class(f0, 'c1', 15, 15) +mock_pyclbr_tree = {'C0': C0, 'f0': f0} + +# Adjust C0.name, C1.name so tests do not depend on order. +browser.transform_children(mock_pyclbr_tree, 'test') # C0(base) +browser.transform_children(C0.children) # C1() + +# The class below checks that the calls above are correct +# and that duplicate calls have no effect. + + +class TransformChildrenTest(unittest.TestCase): + + def test_transform_module_children(self): + eq = self.assertEqual + transform = browser.transform_children + # Parameter matches tree module. + tcl = list(transform(mock_pyclbr_tree, 'test')) + eq(tcl, [C0, f0]) + eq(tcl[0].name, 'C0(base)') + eq(tcl[1].name, 'f0') + # Check that second call does not change suffix. + tcl = list(transform(mock_pyclbr_tree, 'test')) + eq(tcl[0].name, 'C0(base)') + # Nothing to traverse if parameter name isn't same as tree module. + tcl = list(transform(mock_pyclbr_tree, 'different name')) + eq(tcl, []) + + def test_transform_node_children(self): + eq = self.assertEqual + transform = browser.transform_children + # Class with two children, one name altered. + tcl = list(transform(C0.children)) + eq(tcl, [F1, C1]) + eq(tcl[0].name, 'F1') + eq(tcl[1].name, 'C1()') + tcl = list(transform(C0.children)) + eq(tcl[1].name, 'C1()') + # Function with two children. + eq(list(transform(f0.children)), [f1, c1]) + + +class ModuleBrowserTreeItemTest(unittest.TestCase): + + @classmethod + def setUpClass(cls): + cls.mbt = browser.ModuleBrowserTreeItem(fname) + + def test_init(self): + self.assertEqual(self.mbt.file, fname) + + def test_gettext(self): + self.assertEqual(self.mbt.GetText(), fname) + + def test_geticonname(self): + self.assertEqual(self.mbt.GetIconName(), 'python') + + def test_isexpandable(self): + self.assertTrue(self.mbt.IsExpandable()) + + def test_listchildren(self): + save_rex = browser.pyclbr.readmodule_ex + save_tc = browser.transform_children + browser.pyclbr.readmodule_ex = Func(result=mock_pyclbr_tree) + browser.transform_children = Func(result=[f0, C0]) + try: + self.assertEqual(self.mbt.listchildren(), [f0, C0]) + finally: + browser.pyclbr.readmodule_ex = save_rex + browser.transform_children = save_tc + + def test_getsublist(self): + mbt = self.mbt + mbt.listchildren = Func(result=[f0, C0]) + sub0, sub1 = mbt.GetSubList() + del mbt.listchildren + self.assertIsInstance(sub0, browser.ChildBrowserTreeItem) + self.assertIsInstance(sub1, browser.ChildBrowserTreeItem) + self.assertEqual(sub0.name, 'f0') + self.assertEqual(sub1.name, 'C0(base)') + + @mock.patch('idlelib.browser.file_open') + def test_ondoubleclick(self, fopen): + mbt = self.mbt + + with mock.patch('os.path.exists', return_value=False): + mbt.OnDoubleClick() + fopen.assert_not_called() + + with mock.patch('os.path.exists', return_value=True): + mbt.OnDoubleClick() + fopen.assert_called_once_with(fname) + + +class ChildBrowserTreeItemTest(unittest.TestCase): + + @classmethod + def setUpClass(cls): + CBT = browser.ChildBrowserTreeItem + cls.cbt_f1 = CBT(f1) + cls.cbt_C1 = CBT(C1) + cls.cbt_F1 = CBT(F1) + + @classmethod + def tearDownClass(cls): + del cls.cbt_C1, cls.cbt_f1, cls.cbt_F1 + + def test_init(self): + eq = self.assertEqual + eq(self.cbt_C1.name, 'C1()') + self.assertFalse(self.cbt_C1.isfunction) + eq(self.cbt_f1.name, 'f1') + self.assertTrue(self.cbt_f1.isfunction) + + def test_gettext(self): + self.assertEqual(self.cbt_C1.GetText(), 'class C1()') + self.assertEqual(self.cbt_f1.GetText(), 'def f1(...)') + + def test_geticonname(self): + self.assertEqual(self.cbt_C1.GetIconName(), 'folder') + self.assertEqual(self.cbt_f1.GetIconName(), 'python') + + def test_isexpandable(self): + self.assertTrue(self.cbt_C1.IsExpandable()) + self.assertTrue(self.cbt_f1.IsExpandable()) + self.assertFalse(self.cbt_F1.IsExpandable()) + + def test_getsublist(self): + eq = self.assertEqual + CBT = browser.ChildBrowserTreeItem + + f1sublist = self.cbt_f1.GetSubList() + self.assertIsInstance(f1sublist[0], CBT) + eq(len(f1sublist), 1) + eq(f1sublist[0].name, 'f2') + + eq(self.cbt_F1.GetSubList(), []) + + @mock.patch('idlelib.browser.file_open') + def test_ondoubleclick(self, fopen): + goto = fopen.return_value.gotoline = mock.Mock() + self.cbt_F1.OnDoubleClick() + fopen.assert_called() + goto.assert_called() + goto.assert_called_with(self.cbt_F1.obj.lineno) + # Failure test would have to raise OSError or AttributeError. + + +class NestedChildrenTest(unittest.TestCase): + "Test that all the nodes in a nested tree are added to the BrowserTree." + + def test_nested(self): + queue = deque() + actual_names = [] + # The tree items are processed in breadth first order. + # Verify that processing each sublist hits every node and + # in the right order. + expected_names = ['f0', 'C0(base)', + 'f1', 'c1', 'F1', 'C1()', + 'f2', 'C2', + 'F3'] + CBT = browser.ChildBrowserTreeItem + queue.extend((CBT(f0), CBT(C0))) + while queue: + cb = queue.popleft() + sublist = cb.GetSubList() + queue.extend(sublist) + self.assertIn(cb.name, cb.GetText()) + self.assertIn(cb.GetIconName(), ('python', 'folder')) + self.assertIs(cb.IsExpandable(), sublist != []) + actual_names.append(cb.name) + self.assertEqual(actual_names, expected_names) + + +if __name__ == '__main__': + unittest.main(verbosity=2) diff --git a/micromamba_root/envs/pytorch_env/Lib/idlelib/idle_test/test_calltip.py b/micromamba_root/envs/pytorch_env/Lib/idlelib/idle_test/test_calltip.py new file mode 100644 index 0000000000000000000000000000000000000000..28c196a42672fcd2b025753341a7aac656926a6a --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/idlelib/idle_test/test_calltip.py @@ -0,0 +1,372 @@ +"Test calltip, coverage 76%" + +from idlelib import calltip +import unittest +from unittest.mock import Mock +import textwrap +import types +import re +from idlelib.idle_test.mock_tk import Text +from test.support import MISSING_C_DOCSTRINGS + + +# Test Class TC is used in multiple get_argspec test methods +class TC: + 'doc' + tip = "(ai=None, *b)" + def __init__(self, ai=None, *b): 'doc' + __init__.tip = "(self, ai=None, *b)" + def t1(self): 'doc' + t1.tip = "(self)" + def t2(self, ai, b=None): 'doc' + t2.tip = "(self, ai, b=None)" + def t3(self, ai, *args): 'doc' + t3.tip = "(self, ai, *args)" + def t4(self, *args): 'doc' + t4.tip = "(self, *args)" + def t5(self, ai, b=None, *args, **kw): 'doc' + t5.tip = "(self, ai, b=None, *args, **kw)" + def t6(no, self): 'doc' + t6.tip = "(no, self)" + def __call__(self, ci): 'doc' + __call__.tip = "(self, ci)" + def nd(self): pass # No doc. + # attaching .tip to wrapped methods does not work + @classmethod + def cm(cls, a): 'doc' + @staticmethod + def sm(b): 'doc' + + +tc = TC() +default_tip = calltip._default_callable_argspec +get_spec = calltip.get_argspec + + +class Get_argspecTest(unittest.TestCase): + # The get_spec function must return a string, even if blank. + # Test a variety of objects to be sure that none cause it to raise + # (quite aside from getting as correct an answer as possible). + # The tests of builtins may break if inspect or the docstrings change, + # but a red buildbot is better than a user crash (as has happened). + # For a simple mismatch, change the expected output to the actual. + + @unittest.skipIf(MISSING_C_DOCSTRINGS, + "Signature information for builtins requires docstrings") + def test_builtins(self): + + def tiptest(obj, out): + self.assertEqual(get_spec(obj), out) + + # Python class that inherits builtin methods + class List(list): "List() doc" + + # Simulate builtin with no docstring for default tip test + class SB: __call__ = None + + if List.__doc__ is not None: + tiptest(List, + f'(iterable=(), /)' + f'\n{List.__doc__}') + tiptest(list.__new__, + '(*args, **kwargs)\n' + 'Create and return a new object. ' + 'See help(type) for accurate signature.') + tiptest(list.__init__, + '(self, /, *args, **kwargs)\n' + 'Initialize self. See help(type(self)) for accurate signature.') + append_doc = "\nAppend object to the end of the list." + tiptest(list.append, '(self, object, /)' + append_doc) + tiptest(List.append, '(self, object, /)' + append_doc) + tiptest([].append, '(object, /)' + append_doc) + # The use of 'object' above matches the signature text. + + tiptest(types.MethodType, + '(function, instance, /)\n' + 'Create a bound instance method object.') + tiptest(SB(), default_tip) + + p = re.compile('') + tiptest(re.sub, '''\ +(pattern, repl, string, count=0, flags=0) +Return the string obtained by replacing the leftmost +non-overlapping occurrences of the pattern in string by the +replacement repl. repl can be either a string or a callable; +if a string, backslash escapes in it are processed. If it is +a callable, it's passed the Match object and must return''') + tiptest(p.sub, '''\ +(repl, string, count=0) +Return the string obtained by replacing the leftmost \ +non-overlapping occurrences o...''') + + def test_signature_wrap(self): + if textwrap.TextWrapper.__doc__ is not None: + self.assertEqual(get_spec(textwrap.TextWrapper), '''\ +(width=70, initial_indent='', subsequent_indent='', expand_tabs=True, + replace_whitespace=True, fix_sentence_endings=False, break_long_words=True, + drop_whitespace=True, break_on_hyphens=True, tabsize=8, *, max_lines=None, + placeholder=' [...]') +Object for wrapping/filling text. The public interface consists of +the wrap() and fill() methods; the other methods are just there for +subclasses to override in order to tweak the default behaviour. +If you want to completely replace the main wrapping algorithm, +you\'ll probably have to override _wrap_chunks().''') + + def test_properly_formatted(self): + + def foo(s='a'*100): + pass + + def bar(s='a'*100): + """Hello Guido""" + pass + + def baz(s='a'*100, z='b'*100): + pass + + indent = calltip._INDENT + + sfoo = "(s='aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"\ + "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" + indent + "aaaaaaaaa"\ + "aaaaaaaaaa')" + sbar = "(s='aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"\ + "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" + indent + "aaaaaaaaa"\ + "aaaaaaaaaa')\nHello Guido" + sbaz = "(s='aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"\ + "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" + indent + "aaaaaaaaa"\ + "aaaaaaaaaa', z='bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb"\ + "bbbbbbbbbbbbbbbbb\n" + indent + "bbbbbbbbbbbbbbbbbbbbbb"\ + "bbbbbbbbbbbbbbbbbbbbbb')" + + for func,doc in [(foo, sfoo), (bar, sbar), (baz, sbaz)]: + with self.subTest(func=func, doc=doc): + self.assertEqual(get_spec(func), doc) + + def test_docline_truncation(self): + def f(): pass + f.__doc__ = 'a'*300 + self.assertEqual(get_spec(f), f"()\n{'a'*(calltip._MAX_COLS-3) + '...'}") + + @unittest.skipIf(MISSING_C_DOCSTRINGS, + "Signature information for builtins requires docstrings") + def test_multiline_docstring(self): + # Test fewer lines than max. + self.assertEqual(get_spec(range), + "range(stop) -> range object\n" + "range(start, stop[, step]) -> range object") + + # Test max lines + self.assertEqual(get_spec(bytes), '''\ +bytes(iterable_of_ints) -> bytes +bytes(string, encoding[, errors]) -> bytes +bytes(bytes_or_buffer) -> immutable copy of bytes_or_buffer +bytes(int) -> bytes object of size given by the parameter initialized with null bytes +bytes() -> empty bytes object''') + + def test_multiline_docstring_2(self): + # Test more than max lines + def f(): pass + f.__doc__ = 'a\n' * 15 + self.assertEqual(get_spec(f), '()' + '\na' * calltip._MAX_LINES) + + def test_functions(self): + def t1(): 'doc' + t1.tip = "()" + def t2(a, b=None): 'doc' + t2.tip = "(a, b=None)" + def t3(a, *args): 'doc' + t3.tip = "(a, *args)" + def t4(*args): 'doc' + t4.tip = "(*args)" + def t5(a, b=None, *args, **kw): 'doc' + t5.tip = "(a, b=None, *args, **kw)" + + doc = '\ndoc' if t1.__doc__ is not None else '' + for func in (t1, t2, t3, t4, t5, TC): + with self.subTest(func=func): + self.assertEqual(get_spec(func), func.tip + doc) + + def test_methods(self): + doc = '\ndoc' if TC.__doc__ is not None else '' + for meth in (TC.t1, TC.t2, TC.t3, TC.t4, TC.t5, TC.t6, TC.__call__): + with self.subTest(meth=meth): + self.assertEqual(get_spec(meth), meth.tip + doc) + self.assertEqual(get_spec(TC.cm), "(a)" + doc) + self.assertEqual(get_spec(TC.sm), "(b)" + doc) + + def test_bound_methods(self): + # test that first parameter is correctly removed from argspec + doc = '\ndoc' if TC.__doc__ is not None else '' + for meth, mtip in ((tc.t1, "()"), (tc.t4, "(*args)"), + (tc.t6, "(self)"), (tc.__call__, '(ci)'), + (tc, '(ci)'), (TC.cm, "(a)"),): + with self.subTest(meth=meth, mtip=mtip): + self.assertEqual(get_spec(meth), mtip + doc) + + def test_starred_parameter(self): + # test that starred first parameter is *not* removed from argspec + class C: + def m1(*args): pass + c = C() + for meth, mtip in ((C.m1, '(*args)'), (c.m1, "(*args)"),): + with self.subTest(meth=meth, mtip=mtip): + self.assertEqual(get_spec(meth), mtip) + + def test_invalid_method_get_spec(self): + class C: + def m2(**kwargs): pass + class Test: + def __call__(*, a): pass + + mtip = calltip._invalid_method + self.assertEqual(get_spec(C().m2), mtip) + self.assertEqual(get_spec(Test()), mtip) + + def test_non_ascii_name(self): + # test that re works to delete a first parameter name that + # includes non-ascii chars, such as various forms of A. + uni = "(A\u0391\u0410\u05d0\u0627\u0905\u1e00\u3042, a)" + assert calltip._first_param.sub('', uni) == '(a)' + + def test_no_docstring(self): + for meth, mtip in ((TC.nd, "(self)"), (tc.nd, "()")): + with self.subTest(meth=meth, mtip=mtip): + self.assertEqual(get_spec(meth), mtip) + + def test_buggy_getattr_class(self): + class NoCall: + def __getattr__(self, name): # Not invoked for class attribute. + raise IndexError # Bug. + class CallA(NoCall): + def __call__(self, ci): # Bug does not matter. + pass + class CallB(NoCall): + def __call__(oui, a, b, c): # Non-standard 'self'. + pass + + for meth, mtip in ((NoCall, default_tip), (CallA, default_tip), + (NoCall(), ''), (CallA(), '(ci)'), + (CallB(), '(a, b, c)')): + with self.subTest(meth=meth, mtip=mtip): + self.assertEqual(get_spec(meth), mtip) + + def test_metaclass_class(self): # Failure case for issue 38689. + class Type(type): # Type() requires 3 type args, returns class. + __class__ = property({}.__getitem__, {}.__setitem__) + class Object(metaclass=Type): + __slots__ = '__class__' + for meth, mtip in ((Type, get_spec(type)), (Object, default_tip), + (Object(), '')): + with self.subTest(meth=meth, mtip=mtip): + self.assertEqual(get_spec(meth), mtip) + + def test_non_callables(self): + for obj in (0, 0.0, '0', b'0', [], {}): + with self.subTest(obj=obj): + self.assertEqual(get_spec(obj), '') + + +class Get_entityTest(unittest.TestCase): + def test_bad_entity(self): + self.assertIsNone(calltip.get_entity('1/0')) + def test_good_entity(self): + self.assertIs(calltip.get_entity('int'), int) + + +# Test the 9 Calltip methods. +# open_calltip is about half the code; the others are fairly trivial. +# The default mocks are what are needed for open_calltip. + +class mock_Shell: + "Return mock sufficient to pass to hyperparser." + def __init__(self, text): + text.tag_prevrange = Mock(return_value=None) + self.text = text + self.prompt_last_line = ">>> " + self.indentwidth = 4 + self.tabwidth = 8 + + +class mock_TipWindow: + def __init__(self): + pass + + def showtip(self, text, parenleft, parenright): + self.args = parenleft, parenright + self.parenline, self.parencol = map(int, parenleft.split('.')) + + +class WrappedCalltip(calltip.Calltip): + def _make_tk_calltip_window(self): + return mock_TipWindow() + + def remove_calltip_window(self, event=None): + if self.active_calltip: # Setup to None. + self.active_calltip = None + self.tips_removed += 1 # Setup to 0. + + def fetch_tip(self, expression): + return 'tip' + + +class CalltipTest(unittest.TestCase): + + @classmethod + def setUpClass(cls): + cls.text = Text() + cls.ct = WrappedCalltip(mock_Shell(cls.text)) + + def setUp(self): + self.text.delete('1.0', 'end') # Insert and call + self.ct.active_calltip = None + # Test .active_calltip, +args + self.ct.tips_removed = 0 + + def open_close(self, testfunc): + # Open-close template with testfunc called in between. + opentip = self.ct.open_calltip + self.text.insert(1.0, 'f(') + opentip(False) + self.tip = self.ct.active_calltip + testfunc(self) ### + self.text.insert('insert', ')') + opentip(False) + self.assertIsNone(self.ct.active_calltip, None) + + def test_open_close(self): + def args(self): + self.assertEqual(self.tip.args, ('1.1', '1.end')) + self.open_close(args) + + def test_repeated_force(self): + def force(self): + for char in 'abc': + self.text.insert('insert', 'a') + self.ct.open_calltip(True) + self.ct.open_calltip(True) + self.assertIs(self.ct.active_calltip, self.tip) + self.open_close(force) + + def test_repeated_parens(self): + def parens(self): + for context in "a", "'": + with self.subTest(context=context): + self.text.insert('insert', context) + for char in '(()())': + self.text.insert('insert', char) + self.assertIs(self.ct.active_calltip, self.tip) + self.text.insert('insert', "'") + self.open_close(parens) + + def test_comment_parens(self): + def comment(self): + self.text.insert('insert', "# ") + for char in '(()())': + self.text.insert('insert', char) + self.assertIs(self.ct.active_calltip, self.tip) + self.text.insert('insert', "\n") + self.open_close(comment) + + +if __name__ == '__main__': + unittest.main(verbosity=2) diff --git a/micromamba_root/envs/pytorch_env/Lib/idlelib/idle_test/test_calltip_w.py b/micromamba_root/envs/pytorch_env/Lib/idlelib/idle_test/test_calltip_w.py new file mode 100644 index 0000000000000000000000000000000000000000..a5ec76e15ffdf3ed8c4259dd3c9435ca9e0ec3a4 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/idlelib/idle_test/test_calltip_w.py @@ -0,0 +1,29 @@ +"Test calltip_w, coverage 18%." + +from idlelib import calltip_w +import unittest +from test.support import requires +from tkinter import Tk, Text + + +class CallTipWindowTest(unittest.TestCase): + + @classmethod + def setUpClass(cls): + requires('gui') + cls.root = Tk() + cls.root.withdraw() + cls.text = Text(cls.root) + cls.calltip = calltip_w.CalltipWindow(cls.text) + + @classmethod + def tearDownClass(cls): + cls.root.update_idletasks() + cls.root.destroy() + del cls.text, cls.root + + def test_init(self): + self.assertEqual(self.calltip.anchor_widget, self.text) + +if __name__ == '__main__': + unittest.main(verbosity=2) diff --git a/micromamba_root/envs/pytorch_env/Lib/idlelib/idle_test/test_codecontext.py b/micromamba_root/envs/pytorch_env/Lib/idlelib/idle_test/test_codecontext.py new file mode 100644 index 0000000000000000000000000000000000000000..6969ad73b01a81a7ec896a2c1991905e26e7a564 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/idlelib/idle_test/test_codecontext.py @@ -0,0 +1,455 @@ +"Test codecontext, coverage 100%" + +from idlelib import codecontext +import unittest +import unittest.mock +from test.support import requires +from tkinter import NSEW, Tk, Frame, Text, TclError + +from unittest import mock +import re +from idlelib import config + + +usercfg = codecontext.idleConf.userCfg +testcfg = { + 'main': config.IdleUserConfParser(''), + 'highlight': config.IdleUserConfParser(''), + 'keys': config.IdleUserConfParser(''), + 'extensions': config.IdleUserConfParser(''), +} +code_sample = """\ + +class C1: + # Class comment. + def __init__(self, a, b): + self.a = a + self.b = b + def compare(self): + if a > b: + return a + elif a < b: + return b + else: + return None +""" + + +class DummyEditwin: + def __init__(self, root, frame, text): + self.root = root + self.top = root + self.text_frame = frame + self.text = text + self.label = '' + + def getlineno(self, index): + return int(float(self.text.index(index))) + + def update_menu_label(self, **kwargs): + self.label = kwargs['label'] + + +class CodeContextTest(unittest.TestCase): + + @classmethod + def setUpClass(cls): + requires('gui') + root = cls.root = Tk() + root.withdraw() + frame = cls.frame = Frame(root) + text = cls.text = Text(frame) + text.insert('1.0', code_sample) + # Need to pack for creation of code context text widget. + frame.pack(side='left', fill='both', expand=1) + text.grid(row=1, column=1, sticky=NSEW) + cls.editor = DummyEditwin(root, frame, text) + codecontext.idleConf.userCfg = testcfg + + @classmethod + def tearDownClass(cls): + codecontext.idleConf.userCfg = usercfg + cls.editor.text.delete('1.0', 'end') + del cls.editor, cls.frame, cls.text + cls.root.update_idletasks() + cls.root.destroy() + del cls.root + + def setUp(self): + self.text.yview(0) + self.text['font'] = 'TkFixedFont' + self.cc = codecontext.CodeContext(self.editor) + + self.highlight_cfg = {"background": '#abcdef', + "foreground": '#123456'} + orig_idleConf_GetHighlight = codecontext.idleConf.GetHighlight + def mock_idleconf_GetHighlight(theme, element): + if element == 'context': + return self.highlight_cfg + return orig_idleConf_GetHighlight(theme, element) + GetHighlight_patcher = unittest.mock.patch.object( + codecontext.idleConf, 'GetHighlight', mock_idleconf_GetHighlight) + GetHighlight_patcher.start() + self.addCleanup(GetHighlight_patcher.stop) + + self.font_override = 'TkFixedFont' + def mock_idleconf_GetFont(root, configType, section): + return self.font_override + GetFont_patcher = unittest.mock.patch.object( + codecontext.idleConf, 'GetFont', mock_idleconf_GetFont) + GetFont_patcher.start() + self.addCleanup(GetFont_patcher.stop) + + def tearDown(self): + if self.cc.context: + self.cc.context.destroy() + # Explicitly call __del__ to remove scheduled scripts. + self.cc.__del__() + del self.cc.context, self.cc + + def test_init(self): + eq = self.assertEqual + ed = self.editor + cc = self.cc + + eq(cc.editwin, ed) + eq(cc.text, ed.text) + eq(cc.text['font'], ed.text['font']) + self.assertIsNone(cc.context) + eq(cc.info, [(0, -1, '', False)]) + eq(cc.topvisible, 1) + self.assertIsNone(self.cc.t1) + + def test_del(self): + self.cc.__del__() + + def test_del_with_timer(self): + timer = self.cc.t1 = self.text.after(10000, lambda: None) + self.cc.__del__() + with self.assertRaises(TclError) as cm: + self.root.tk.call('after', 'info', timer) + self.assertIn("doesn't exist", str(cm.exception)) + + def test_reload(self): + codecontext.CodeContext.reload() + self.assertEqual(self.cc.context_depth, 15) + + def test_toggle_code_context_event(self): + eq = self.assertEqual + cc = self.cc + toggle = cc.toggle_code_context_event + + # Make sure code context is off. + if cc.context: + toggle() + + # Toggle on. + toggle() + self.assertIsNotNone(cc.context) + eq(cc.context['font'], self.text['font']) + eq(cc.context['fg'], self.highlight_cfg['foreground']) + eq(cc.context['bg'], self.highlight_cfg['background']) + eq(cc.context.get('1.0', 'end-1c'), '') + eq(cc.editwin.label, 'Hide Code Context') + eq(self.root.tk.call('after', 'info', self.cc.t1)[1], 'timer') + + # Toggle off. + toggle() + self.assertIsNone(cc.context) + eq(cc.editwin.label, 'Show Code Context') + self.assertIsNone(self.cc.t1) + + # Scroll down and toggle back on. + line11_context = '\n'.join(x[2] for x in cc.get_context(11)[0]) + cc.text.yview(11) + toggle() + eq(cc.context.get('1.0', 'end-1c'), line11_context) + + # Toggle off and on again. + toggle() + toggle() + eq(cc.context.get('1.0', 'end-1c'), line11_context) + + def test_get_context(self): + eq = self.assertEqual + gc = self.cc.get_context + + # stopline must be greater than 0. + with self.assertRaises(AssertionError): + gc(1, stopline=0) + + eq(gc(3), ([(2, 0, 'class C1:', 'class')], 0)) + + # Don't return comment. + eq(gc(4), ([(2, 0, 'class C1:', 'class')], 0)) + + # Two indentation levels and no comment. + eq(gc(5), ([(2, 0, 'class C1:', 'class'), + (4, 4, ' def __init__(self, a, b):', 'def')], 0)) + + # Only one 'def' is returned, not both at the same indent level. + eq(gc(10), ([(2, 0, 'class C1:', 'class'), + (7, 4, ' def compare(self):', 'def'), + (8, 8, ' if a > b:', 'if')], 0)) + + # With 'elif', also show the 'if' even though it's at the same level. + eq(gc(11), ([(2, 0, 'class C1:', 'class'), + (7, 4, ' def compare(self):', 'def'), + (8, 8, ' if a > b:', 'if'), + (10, 8, ' elif a < b:', 'elif')], 0)) + + # Set stop_line to not go back to first line in source code. + # Return includes stop_line. + eq(gc(11, stopline=2), ([(2, 0, 'class C1:', 'class'), + (7, 4, ' def compare(self):', 'def'), + (8, 8, ' if a > b:', 'if'), + (10, 8, ' elif a < b:', 'elif')], 0)) + eq(gc(11, stopline=3), ([(7, 4, ' def compare(self):', 'def'), + (8, 8, ' if a > b:', 'if'), + (10, 8, ' elif a < b:', 'elif')], 4)) + eq(gc(11, stopline=8), ([(8, 8, ' if a > b:', 'if'), + (10, 8, ' elif a < b:', 'elif')], 8)) + + # Set stop_indent to test indent level to stop at. + eq(gc(11, stopindent=4), ([(7, 4, ' def compare(self):', 'def'), + (8, 8, ' if a > b:', 'if'), + (10, 8, ' elif a < b:', 'elif')], 4)) + # Check that the 'if' is included. + eq(gc(11, stopindent=8), ([(8, 8, ' if a > b:', 'if'), + (10, 8, ' elif a < b:', 'elif')], 8)) + + def test_update_code_context(self): + eq = self.assertEqual + cc = self.cc + # Ensure code context is active. + if not cc.context: + cc.toggle_code_context_event() + + # Invoke update_code_context without scrolling - nothing happens. + self.assertIsNone(cc.update_code_context()) + eq(cc.info, [(0, -1, '', False)]) + eq(cc.topvisible, 1) + + # Scroll down to line 1. + cc.text.yview(1) + cc.update_code_context() + eq(cc.info, [(0, -1, '', False)]) + eq(cc.topvisible, 2) + eq(cc.context.get('1.0', 'end-1c'), '') + + # Scroll down to line 2. + cc.text.yview(2) + cc.update_code_context() + eq(cc.info, [(0, -1, '', False), (2, 0, 'class C1:', 'class')]) + eq(cc.topvisible, 3) + eq(cc.context.get('1.0', 'end-1c'), 'class C1:') + + # Scroll down to line 3. Since it's a comment, nothing changes. + cc.text.yview(3) + cc.update_code_context() + eq(cc.info, [(0, -1, '', False), (2, 0, 'class C1:', 'class')]) + eq(cc.topvisible, 4) + eq(cc.context.get('1.0', 'end-1c'), 'class C1:') + + # Scroll down to line 4. + cc.text.yview(4) + cc.update_code_context() + eq(cc.info, [(0, -1, '', False), + (2, 0, 'class C1:', 'class'), + (4, 4, ' def __init__(self, a, b):', 'def')]) + eq(cc.topvisible, 5) + eq(cc.context.get('1.0', 'end-1c'), 'class C1:\n' + ' def __init__(self, a, b):') + + # Scroll down to line 11. Last 'def' is removed. + cc.text.yview(11) + cc.update_code_context() + eq(cc.info, [(0, -1, '', False), + (2, 0, 'class C1:', 'class'), + (7, 4, ' def compare(self):', 'def'), + (8, 8, ' if a > b:', 'if'), + (10, 8, ' elif a < b:', 'elif')]) + eq(cc.topvisible, 12) + eq(cc.context.get('1.0', 'end-1c'), 'class C1:\n' + ' def compare(self):\n' + ' if a > b:\n' + ' elif a < b:') + + # No scroll. No update, even though context_depth changed. + cc.update_code_context() + cc.context_depth = 1 + eq(cc.info, [(0, -1, '', False), + (2, 0, 'class C1:', 'class'), + (7, 4, ' def compare(self):', 'def'), + (8, 8, ' if a > b:', 'if'), + (10, 8, ' elif a < b:', 'elif')]) + eq(cc.topvisible, 12) + eq(cc.context.get('1.0', 'end-1c'), 'class C1:\n' + ' def compare(self):\n' + ' if a > b:\n' + ' elif a < b:') + + # Scroll up. + cc.text.yview(5) + cc.update_code_context() + eq(cc.info, [(0, -1, '', False), + (2, 0, 'class C1:', 'class'), + (4, 4, ' def __init__(self, a, b):', 'def')]) + eq(cc.topvisible, 6) + # context_depth is 1. + eq(cc.context.get('1.0', 'end-1c'), ' def __init__(self, a, b):') + + def test_jumptoline(self): + eq = self.assertEqual + cc = self.cc + jump = cc.jumptoline + + if not cc.context: + cc.toggle_code_context_event() + + # Empty context. + cc.text.yview('2.0') + cc.update_code_context() + eq(cc.topvisible, 2) + cc.context.mark_set('insert', '1.5') + jump() + eq(cc.topvisible, 1) + + # 4 lines of context showing. + cc.text.yview('12.0') + cc.update_code_context() + eq(cc.topvisible, 12) + cc.context.mark_set('insert', '3.0') + jump() + eq(cc.topvisible, 8) + + # More context lines than limit. + cc.context_depth = 2 + cc.text.yview('12.0') + cc.update_code_context() + eq(cc.topvisible, 12) + cc.context.mark_set('insert', '1.0') + jump() + eq(cc.topvisible, 8) + + # Context selection stops jump. + cc.text.yview('5.0') + cc.update_code_context() + cc.context.tag_add('sel', '1.0', '2.0') + cc.context.mark_set('insert', '1.0') + jump() # Without selection, to line 2. + eq(cc.topvisible, 5) + + @mock.patch.object(codecontext.CodeContext, 'update_code_context') + def test_timer_event(self, mock_update): + # Ensure code context is not active. + if self.cc.context: + self.cc.toggle_code_context_event() + self.cc.timer_event() + mock_update.assert_not_called() + + # Activate code context. + self.cc.toggle_code_context_event() + self.cc.timer_event() + mock_update.assert_called() + + def test_font(self): + eq = self.assertEqual + cc = self.cc + + orig_font = cc.text['font'] + test_font = 'TkTextFont' + self.assertNotEqual(orig_font, test_font) + + # Ensure code context is not active. + if cc.context is not None: + cc.toggle_code_context_event() + + self.font_override = test_font + # Nothing breaks or changes with inactive code context. + cc.update_font() + + # Activate code context, previous font change is immediately effective. + cc.toggle_code_context_event() + eq(cc.context['font'], test_font) + + # Call the font update, change is picked up. + self.font_override = orig_font + cc.update_font() + eq(cc.context['font'], orig_font) + + def test_highlight_colors(self): + eq = self.assertEqual + cc = self.cc + + orig_colors = dict(self.highlight_cfg) + test_colors = {'background': '#222222', 'foreground': '#ffff00'} + + def assert_colors_are_equal(colors): + eq(cc.context['background'], colors['background']) + eq(cc.context['foreground'], colors['foreground']) + + # Ensure code context is not active. + if cc.context: + cc.toggle_code_context_event() + + self.highlight_cfg = test_colors + # Nothing breaks with inactive code context. + cc.update_highlight_colors() + + # Activate code context, previous colors change is immediately effective. + cc.toggle_code_context_event() + assert_colors_are_equal(test_colors) + + # Call colors update with no change to the configured colors. + cc.update_highlight_colors() + assert_colors_are_equal(test_colors) + + # Call the colors update with code context active, change is picked up. + self.highlight_cfg = orig_colors + cc.update_highlight_colors() + assert_colors_are_equal(orig_colors) + + +class HelperFunctionText(unittest.TestCase): + + def test_get_spaces_firstword(self): + get = codecontext.get_spaces_firstword + test_lines = ( + (' first word', (' ', 'first')), + ('\tfirst word', ('\t', 'first')), + (' \u19D4\u19D2: ', (' ', '\u19D4\u19D2')), + ('no spaces', ('', 'no')), + ('', ('', '')), + ('# TEST COMMENT', ('', '')), + (' (continuation)', (' ', '')) + ) + for line, expected_output in test_lines: + self.assertEqual(get(line), expected_output) + + # Send the pattern in the call. + self.assertEqual(get(' (continuation)', + c=re.compile(r'^(\s*)([^\s]*)')), + (' ', '(continuation)')) + + def test_get_line_info(self): + eq = self.assertEqual + gli = codecontext.get_line_info + lines = code_sample.splitlines() + + # Line 1 is not a BLOCKOPENER. + eq(gli(lines[0]), (codecontext.INFINITY, '', False)) + # Line 2 is a BLOCKOPENER without an indent. + eq(gli(lines[1]), (0, 'class C1:', 'class')) + # Line 3 is not a BLOCKOPENER and does not return the indent level. + eq(gli(lines[2]), (codecontext.INFINITY, ' # Class comment.', False)) + # Line 4 is a BLOCKOPENER and is indented. + eq(gli(lines[3]), (4, ' def __init__(self, a, b):', 'def')) + # Line 8 is a different BLOCKOPENER and is indented. + eq(gli(lines[7]), (8, ' if a > b:', 'if')) + # Test tab. + eq(gli('\tif a == b:'), (1, '\tif a == b:', 'if')) + + +if __name__ == '__main__': + unittest.main(verbosity=2) diff --git a/micromamba_root/envs/pytorch_env/Lib/idlelib/idle_test/test_colorizer.py b/micromamba_root/envs/pytorch_env/Lib/idlelib/idle_test/test_colorizer.py new file mode 100644 index 0000000000000000000000000000000000000000..308bc389384d33dc8d4bb473b06dc5b5b127c0b6 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/idlelib/idle_test/test_colorizer.py @@ -0,0 +1,622 @@ +"Test colorizer, coverage 99%." +from idlelib import colorizer +from test.support import requires +import unittest +from unittest import mock +from idlelib.idle_test.tkinter_testing_utils import run_in_tk_mainloop + +from functools import partial +import textwrap +from tkinter import Tk, Text +from idlelib import config +from idlelib.percolator import Percolator + + +usercfg = colorizer.idleConf.userCfg +testcfg = { + 'main': config.IdleUserConfParser(''), + 'highlight': config.IdleUserConfParser(''), + 'keys': config.IdleUserConfParser(''), + 'extensions': config.IdleUserConfParser(''), +} + +source = textwrap.dedent("""\ + if True: int ('1') # keyword, builtin, string, comment + elif False: print(0) # 'string' in comment + else: float(None) # if in comment + if iF + If + IF: 'keyword matching must respect case' + if'': x or'' # valid keyword-string no-space combinations + async def f(): await g() + # Strings should be entirely colored, including quotes. + 'x', '''x''', "x", \"""x\""" + 'abc\\ + def' + '''abc\\ + def''' + # All valid prefixes for unicode and byte strings should be colored. + r'x', u'x', R'x', U'x', f'x', F'x' + fr'x', Fr'x', fR'x', FR'x', rf'x', rF'x', Rf'x', RF'x' + b'x',B'x', br'x',Br'x',bR'x',BR'x', rb'x', rB'x',Rb'x',RB'x' + # Invalid combinations of legal characters should be half colored. + ur'x', ru'x', uf'x', fu'x', UR'x', ufr'x', rfu'x', xf'x', fx'x' + match point: + case (x, 0) as _: + print(f"X={x}") + case [_, [_], "_", + _]: + pass + case _ if ("a" if _ else set()): pass + case _: + raise ValueError("Not a point _") + ''' + case _:''' + "match x:" + """) + + +def setUpModule(): + colorizer.idleConf.userCfg = testcfg + + +def tearDownModule(): + colorizer.idleConf.userCfg = usercfg + + +class FunctionTest(unittest.TestCase): + + def test_any(self): + self.assertEqual(colorizer.any('test', ('a', 'b', 'cd')), + '(?Pa|b|cd)') + + def test_make_pat(self): + # Tested in more detail by testing prog. + self.assertTrue(colorizer.make_pat()) + + def test_prog(self): + prog = colorizer.prog + eq = self.assertEqual + line = 'def f():\n print("hello")\n' + m = prog.search(line) + eq(m.groupdict()['KEYWORD'], 'def') + m = prog.search(line, m.end()) + eq(m.groupdict()['SYNC'], '\n') + m = prog.search(line, m.end()) + eq(m.groupdict()['BUILTIN'], 'print') + m = prog.search(line, m.end()) + eq(m.groupdict()['STRING'], '"hello"') + m = prog.search(line, m.end()) + eq(m.groupdict()['SYNC'], '\n') + + def test_idprog(self): + idprog = colorizer.idprog + m = idprog.match('nospace') + self.assertIsNone(m) + m = idprog.match(' space') + self.assertEqual(m.group(0), ' space') + + +class ColorConfigTest(unittest.TestCase): + + @classmethod + def setUpClass(cls): + requires('gui') + root = cls.root = Tk() + root.withdraw() + cls.text = Text(root) + + @classmethod + def tearDownClass(cls): + del cls.text + cls.root.update_idletasks() + cls.root.destroy() + del cls.root + + def test_color_config(self): + text = self.text + eq = self.assertEqual + colorizer.color_config(text) + # Uses IDLE Classic theme as default. + eq(text['background'], '#ffffff') + eq(text['foreground'], '#000000') + eq(text['selectbackground'], 'gray') + eq(text['selectforeground'], '#000000') + eq(text['insertbackground'], 'black') + eq(text['inactiveselectbackground'], 'gray') + + +class ColorDelegatorInstantiationTest(unittest.TestCase): + + @classmethod + def setUpClass(cls): + requires('gui') + root = cls.root = Tk() + root.withdraw() + cls.text = Text(root) + + @classmethod + def tearDownClass(cls): + del cls.text + cls.root.update_idletasks() + cls.root.destroy() + del cls.root + + def setUp(self): + self.color = colorizer.ColorDelegator() + + def tearDown(self): + self.color.close() + self.text.delete('1.0', 'end') + self.color.resetcache() + del self.color + + def test_init(self): + color = self.color + self.assertIsInstance(color, colorizer.ColorDelegator) + + def test_init_state(self): + # init_state() is called during the instantiation of + # ColorDelegator in setUp(). + color = self.color + self.assertIsNone(color.after_id) + self.assertTrue(color.allow_colorizing) + self.assertFalse(color.colorizing) + self.assertFalse(color.stop_colorizing) + + +class ColorDelegatorTest(unittest.TestCase): + + @classmethod + def setUpClass(cls): + requires('gui') + root = cls.root = Tk() + root.withdraw() + text = cls.text = Text(root) + cls.percolator = Percolator(text) + # Delegator stack = [Delegator(text)] + + @classmethod + def tearDownClass(cls): + cls.percolator.close() + del cls.percolator, cls.text + cls.root.update_idletasks() + cls.root.destroy() + del cls.root + + def setUp(self): + self.color = colorizer.ColorDelegator() + self.percolator.insertfilter(self.color) + # Calls color.setdelegate(Delegator(text)). + + def tearDown(self): + self.color.close() + self.percolator.removefilter(self.color) + self.text.delete('1.0', 'end') + self.color.resetcache() + del self.color + + def test_setdelegate(self): + # Called in setUp when filter is attached to percolator. + color = self.color + self.assertIsInstance(color.delegate, colorizer.Delegator) + # It is too late to mock notify_range, so test side effect. + self.assertEqual(self.root.tk.call( + 'after', 'info', color.after_id)[1], 'timer') + + def test_LoadTagDefs(self): + highlight = partial(config.idleConf.GetHighlight, theme='IDLE Classic') + for tag, colors in self.color.tagdefs.items(): + with self.subTest(tag=tag): + self.assertIn('background', colors) + self.assertIn('foreground', colors) + if tag not in ('SYNC', 'TODO'): + self.assertEqual(colors, highlight(element=tag.lower())) + + def test_config_colors(self): + text = self.text + highlight = partial(config.idleConf.GetHighlight, theme='IDLE Classic') + for tag in self.color.tagdefs: + for plane in ('background', 'foreground'): + with self.subTest(tag=tag, plane=plane): + if tag in ('SYNC', 'TODO'): + self.assertEqual(text.tag_cget(tag, plane), '') + else: + self.assertEqual(text.tag_cget(tag, plane), + highlight(element=tag.lower())[plane]) + # 'sel' is marked as the highest priority. + self.assertEqual(text.tag_names()[-1], 'sel') + + @mock.patch.object(colorizer.ColorDelegator, 'notify_range') + def test_insert(self, mock_notify): + text = self.text + # Initial text. + text.insert('insert', 'foo') + self.assertEqual(text.get('1.0', 'end'), 'foo\n') + mock_notify.assert_called_with('1.0', '1.0+3c') + # Additional text. + text.insert('insert', 'barbaz') + self.assertEqual(text.get('1.0', 'end'), 'foobarbaz\n') + mock_notify.assert_called_with('1.3', '1.3+6c') + + @mock.patch.object(colorizer.ColorDelegator, 'notify_range') + def test_delete(self, mock_notify): + text = self.text + # Initialize text. + text.insert('insert', 'abcdefghi') + self.assertEqual(text.get('1.0', 'end'), 'abcdefghi\n') + # Delete single character. + text.delete('1.7') + self.assertEqual(text.get('1.0', 'end'), 'abcdefgi\n') + mock_notify.assert_called_with('1.7') + # Delete multiple characters. + text.delete('1.3', '1.6') + self.assertEqual(text.get('1.0', 'end'), 'abcgi\n') + mock_notify.assert_called_with('1.3') + + def test_notify_range(self): + text = self.text + color = self.color + eq = self.assertEqual + + # Colorizing already scheduled. + save_id = color.after_id + eq(self.root.tk.call('after', 'info', save_id)[1], 'timer') + self.assertFalse(color.colorizing) + self.assertFalse(color.stop_colorizing) + self.assertTrue(color.allow_colorizing) + + # Coloring scheduled and colorizing in progress. + color.colorizing = True + color.notify_range('1.0', 'end') + self.assertFalse(color.stop_colorizing) + eq(color.after_id, save_id) + + # No colorizing scheduled and colorizing in progress. + text.after_cancel(save_id) + color.after_id = None + color.notify_range('1.0', '1.0+3c') + self.assertTrue(color.stop_colorizing) + self.assertIsNotNone(color.after_id) + eq(self.root.tk.call('after', 'info', color.after_id)[1], 'timer') + # New event scheduled. + self.assertNotEqual(color.after_id, save_id) + + # No colorizing scheduled and colorizing off. + text.after_cancel(color.after_id) + color.after_id = None + color.allow_colorizing = False + color.notify_range('1.4', '1.4+10c') + # Nothing scheduled when colorizing is off. + self.assertIsNone(color.after_id) + + def test_toggle_colorize_event(self): + color = self.color + eq = self.assertEqual + + # Starts with colorizing allowed and scheduled. + self.assertFalse(color.colorizing) + self.assertFalse(color.stop_colorizing) + self.assertTrue(color.allow_colorizing) + eq(self.root.tk.call('after', 'info', color.after_id)[1], 'timer') + + # Toggle colorizing off. + color.toggle_colorize_event() + self.assertIsNone(color.after_id) + self.assertFalse(color.colorizing) + self.assertFalse(color.stop_colorizing) + self.assertFalse(color.allow_colorizing) + + # Toggle on while colorizing in progress (doesn't add timer). + color.colorizing = True + color.toggle_colorize_event() + self.assertIsNone(color.after_id) + self.assertTrue(color.colorizing) + self.assertFalse(color.stop_colorizing) + self.assertTrue(color.allow_colorizing) + + # Toggle off while colorizing in progress. + color.toggle_colorize_event() + self.assertIsNone(color.after_id) + self.assertTrue(color.colorizing) + self.assertTrue(color.stop_colorizing) + self.assertFalse(color.allow_colorizing) + + # Toggle on while colorizing not in progress. + color.colorizing = False + color.toggle_colorize_event() + eq(self.root.tk.call('after', 'info', color.after_id)[1], 'timer') + self.assertFalse(color.colorizing) + self.assertTrue(color.stop_colorizing) + self.assertTrue(color.allow_colorizing) + + @mock.patch.object(colorizer.ColorDelegator, 'recolorize_main') + def test_recolorize(self, mock_recmain): + text = self.text + color = self.color + eq = self.assertEqual + # Call recolorize manually and not scheduled. + text.after_cancel(color.after_id) + + # No delegate. + save_delegate = color.delegate + color.delegate = None + color.recolorize() + mock_recmain.assert_not_called() + color.delegate = save_delegate + + # Toggle off colorizing. + color.allow_colorizing = False + color.recolorize() + mock_recmain.assert_not_called() + color.allow_colorizing = True + + # Colorizing in progress. + color.colorizing = True + color.recolorize() + mock_recmain.assert_not_called() + color.colorizing = False + + # Colorizing is done, but not completed, so rescheduled. + color.recolorize() + self.assertFalse(color.stop_colorizing) + self.assertFalse(color.colorizing) + mock_recmain.assert_called() + eq(mock_recmain.call_count, 1) + # Rescheduled when TODO tag still exists. + eq(self.root.tk.call('after', 'info', color.after_id)[1], 'timer') + + # No changes to text, so no scheduling added. + text.tag_remove('TODO', '1.0', 'end') + color.recolorize() + self.assertFalse(color.stop_colorizing) + self.assertFalse(color.colorizing) + mock_recmain.assert_called() + eq(mock_recmain.call_count, 2) + self.assertIsNone(color.after_id) + + @mock.patch.object(colorizer.ColorDelegator, 'notify_range') + def test_recolorize_main(self, mock_notify): + text = self.text + color = self.color + eq = self.assertEqual + + text.insert('insert', source) + expected = (('1.0', ('KEYWORD',)), ('1.2', ()), ('1.3', ('KEYWORD',)), + ('1.7', ()), ('1.9', ('BUILTIN',)), ('1.14', ('STRING',)), + ('1.19', ('COMMENT',)), + ('2.1', ('KEYWORD',)), ('2.18', ()), ('2.25', ('COMMENT',)), + ('3.6', ('BUILTIN',)), ('3.12', ('KEYWORD',)), ('3.21', ('COMMENT',)), + ('4.0', ('KEYWORD',)), ('4.3', ()), ('4.6', ()), + ('5.2', ('STRING',)), ('5.8', ('KEYWORD',)), ('5.10', ('STRING',)), + ('6.0', ('KEYWORD',)), ('6.10', ('DEFINITION',)), ('6.11', ()), + ('8.0', ('STRING',)), ('8.4', ()), ('8.5', ('STRING',)), + ('8.12', ()), ('8.14', ('STRING',)), + ('19.0', ('KEYWORD',)), + ('20.4', ('KEYWORD',)), ('20.16', ('KEYWORD',)),# ('20.19', ('KEYWORD',)), + #('22.4', ('KEYWORD',)), ('22.10', ('KEYWORD',)), ('22.14', ('KEYWORD',)), ('22.19', ('STRING',)), + #('23.12', ('KEYWORD',)), + ('24.8', ('KEYWORD',)), + ('25.4', ('KEYWORD',)), ('25.9', ('KEYWORD',)), + ('25.11', ('KEYWORD',)), ('25.15', ('STRING',)), + ('25.19', ('KEYWORD',)), ('25.22', ()), + ('25.24', ('KEYWORD',)), ('25.29', ('BUILTIN',)), ('25.37', ('KEYWORD',)), + ('26.4', ('KEYWORD',)), ('26.9', ('KEYWORD',)),# ('26.11', ('KEYWORD',)), ('26.14', (),), + ('27.25', ('STRING',)), ('27.38', ('STRING',)), + ('29.0', ('STRING',)), + ('30.1', ('STRING',)), + # SYNC at the end of every line. + ('1.55', ('SYNC',)), ('2.50', ('SYNC',)), ('3.34', ('SYNC',)), + ) + + # Nothing marked to do therefore no tags in text. + text.tag_remove('TODO', '1.0', 'end') + color.recolorize_main() + for tag in text.tag_names(): + with self.subTest(tag=tag): + eq(text.tag_ranges(tag), ()) + + # Source marked for processing. + text.tag_add('TODO', '1.0', 'end') + # Check some indexes. + color.recolorize_main() + for index, expected_tags in expected: + with self.subTest(index=index): + eq(text.tag_names(index), expected_tags) + + # Check for some tags for ranges. + eq(text.tag_nextrange('TODO', '1.0'), ()) + eq(text.tag_nextrange('KEYWORD', '1.0'), ('1.0', '1.2')) + eq(text.tag_nextrange('COMMENT', '2.0'), ('2.22', '2.43')) + eq(text.tag_nextrange('SYNC', '2.0'), ('2.43', '3.0')) + eq(text.tag_nextrange('STRING', '2.0'), ('4.17', '4.53')) + eq(text.tag_nextrange('STRING', '8.0'), ('8.0', '8.3')) + eq(text.tag_nextrange('STRING', '8.3'), ('8.5', '8.12')) + eq(text.tag_nextrange('STRING', '8.12'), ('8.14', '8.17')) + eq(text.tag_nextrange('STRING', '8.17'), ('8.19', '8.26')) + eq(text.tag_nextrange('SYNC', '8.0'), ('8.26', '9.0')) + eq(text.tag_nextrange('SYNC', '30.0'), ('30.10', '32.0')) + + def _assert_highlighting(self, source, tag_ranges): + """Check highlighting of a given piece of code. + + This inserts just this code into the Text widget. It will then + check that the resulting highlighting tag ranges exactly match + those described in the given `tag_ranges` dict. + + Note that the irrelevant tags 'sel', 'TODO' and 'SYNC' are + ignored. + """ + text = self.text + + with mock.patch.object(colorizer.ColorDelegator, 'notify_range'): + text.delete('1.0', 'end-1c') + text.insert('insert', source) + text.tag_add('TODO', '1.0', 'end-1c') + self.color.recolorize_main() + + # Make a dict with highlighting tag ranges in the Text widget. + text_tag_ranges = {} + for tag in set(text.tag_names()) - {'sel', 'TODO', 'SYNC'}: + indexes = [rng.string for rng in text.tag_ranges(tag)] + for index_pair in zip(indexes[::2], indexes[1::2]): + text_tag_ranges.setdefault(tag, []).append(index_pair) + + self.assertEqual(text_tag_ranges, tag_ranges) + + with mock.patch.object(colorizer.ColorDelegator, 'notify_range'): + text.delete('1.0', 'end-1c') + + def test_def_statement(self): + # empty def + self._assert_highlighting('def', {'KEYWORD': [('1.0', '1.3')]}) + + # def followed by identifier + self._assert_highlighting('def foo:', {'KEYWORD': [('1.0', '1.3')], + 'DEFINITION': [('1.4', '1.7')]}) + + # def followed by partial identifier + self._assert_highlighting('def fo', {'KEYWORD': [('1.0', '1.3')], + 'DEFINITION': [('1.4', '1.6')]}) + + # def followed by non-keyword + self._assert_highlighting('def ++', {'KEYWORD': [('1.0', '1.3')]}) + + def test_match_soft_keyword(self): + # empty match + self._assert_highlighting('match', {'KEYWORD': [('1.0', '1.5')]}) + + # match followed by partial identifier + self._assert_highlighting('match fo', {'KEYWORD': [('1.0', '1.5')]}) + + # match followed by identifier and colon + self._assert_highlighting('match foo:', {'KEYWORD': [('1.0', '1.5')]}) + + # match followed by keyword + self._assert_highlighting('match and', {'KEYWORD': [('1.6', '1.9')]}) + + # match followed by builtin with keyword prefix + self._assert_highlighting('match int:', {'KEYWORD': [('1.0', '1.5')], + 'BUILTIN': [('1.6', '1.9')]}) + + # match followed by non-text operator + self._assert_highlighting('match^', {}) + self._assert_highlighting('match @', {}) + + # match followed by colon + self._assert_highlighting('match :', {}) + + # match followed by comma + self._assert_highlighting('match\t,', {}) + + # match followed by a lone underscore + self._assert_highlighting('match _:', {'KEYWORD': [('1.0', '1.5')]}) + + def test_case_soft_keyword(self): + # empty case + self._assert_highlighting('case', {'KEYWORD': [('1.0', '1.4')]}) + + # case followed by partial identifier + self._assert_highlighting('case fo', {'KEYWORD': [('1.0', '1.4')]}) + + # case followed by identifier and colon + self._assert_highlighting('case foo:', {'KEYWORD': [('1.0', '1.4')]}) + + # case followed by keyword + self._assert_highlighting('case and', {'KEYWORD': [('1.5', '1.8')]}) + + # case followed by builtin with keyword prefix + self._assert_highlighting('case int:', {'KEYWORD': [('1.0', '1.4')], + 'BUILTIN': [('1.5', '1.8')]}) + + # case followed by non-text operator + self._assert_highlighting('case^', {}) + self._assert_highlighting('case @', {}) + + # case followed by colon + self._assert_highlighting('case :', {}) + + # case followed by comma + self._assert_highlighting('case\t,', {}) + + # case followed by a lone underscore + self._assert_highlighting('case _:', {'KEYWORD': [('1.0', '1.4'), + ('1.5', '1.6')]}) + + def test_long_multiline_string(self): + source = textwrap.dedent('''\ + """a + b + c + d + e""" + ''') + self._assert_highlighting(source, {'STRING': [('1.0', '5.4')]}) + + @run_in_tk_mainloop(delay=50) + def test_incremental_editing(self): + text = self.text + eq = self.assertEqual + + # Simulate typing 'inte'. During this, the highlighting should + # change from normal to keyword to builtin to normal. + text.insert('insert', 'i') + yield + eq(text.tag_nextrange('BUILTIN', '1.0'), ()) + eq(text.tag_nextrange('KEYWORD', '1.0'), ()) + + text.insert('insert', 'n') + yield + eq(text.tag_nextrange('BUILTIN', '1.0'), ()) + eq(text.tag_nextrange('KEYWORD', '1.0'), ('1.0', '1.2')) + + text.insert('insert', 't') + yield + eq(text.tag_nextrange('BUILTIN', '1.0'), ('1.0', '1.3')) + eq(text.tag_nextrange('KEYWORD', '1.0'), ()) + + text.insert('insert', 'e') + yield + eq(text.tag_nextrange('BUILTIN', '1.0'), ()) + eq(text.tag_nextrange('KEYWORD', '1.0'), ()) + + # Simulate deleting three characters from the end of 'inte'. + # During this, the highlighting should change from normal to + # builtin to keyword to normal. + text.delete('insert-1c', 'insert') + yield + eq(text.tag_nextrange('BUILTIN', '1.0'), ('1.0', '1.3')) + eq(text.tag_nextrange('KEYWORD', '1.0'), ()) + + text.delete('insert-1c', 'insert') + yield + eq(text.tag_nextrange('BUILTIN', '1.0'), ()) + eq(text.tag_nextrange('KEYWORD', '1.0'), ('1.0', '1.2')) + + text.delete('insert-1c', 'insert') + yield + eq(text.tag_nextrange('BUILTIN', '1.0'), ()) + eq(text.tag_nextrange('KEYWORD', '1.0'), ()) + + @mock.patch.object(colorizer.ColorDelegator, 'recolorize') + @mock.patch.object(colorizer.ColorDelegator, 'notify_range') + def test_removecolors(self, mock_notify, mock_recolorize): + text = self.text + color = self.color + text.insert('insert', source) + + color.recolorize_main() + # recolorize_main doesn't add these tags. + text.tag_add("ERROR", "1.0") + text.tag_add("TODO", "1.0") + text.tag_add("hit", "1.0") + for tag in color.tagdefs: + with self.subTest(tag=tag): + self.assertNotEqual(text.tag_ranges(tag), ()) + + color.removecolors() + for tag in color.tagdefs: + with self.subTest(tag=tag): + self.assertEqual(text.tag_ranges(tag), ()) + + +if __name__ == '__main__': + unittest.main(verbosity=2) diff --git a/micromamba_root/envs/pytorch_env/Lib/idlelib/idle_test/test_config.py b/micromamba_root/envs/pytorch_env/Lib/idlelib/idle_test/test_config.py new file mode 100644 index 0000000000000000000000000000000000000000..6d75cf7aa67dcce3b9bc49cc54cb4d5fd24cc103 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/idlelib/idle_test/test_config.py @@ -0,0 +1,805 @@ +"""Test config, coverage 93%. +(100% for IdleConfParser, IdleUserConfParser*, ConfigChanges). +* Exception is OSError clause in Save method. +Much of IdleConf is also exercised by ConfigDialog and test_configdialog. +""" +from idlelib import config +import sys +import os +import tempfile +from test.support import captured_stderr, findfile +import unittest +from unittest import mock +import idlelib +from idlelib.idle_test.mock_idle import Func + +# Tests should not depend on fortuitous user configurations. +# They must not affect actual user .cfg files. +# Replace user parsers with empty parsers that cannot be saved +# due to getting '' as the filename when created. + +idleConf = config.idleConf +usercfg = idleConf.userCfg +testcfg = {} +usermain = testcfg['main'] = config.IdleUserConfParser('') +userhigh = testcfg['highlight'] = config.IdleUserConfParser('') +userkeys = testcfg['keys'] = config.IdleUserConfParser('') +userextn = testcfg['extensions'] = config.IdleUserConfParser('') + +def setUpModule(): + idleConf.userCfg = testcfg + idlelib.testing = True + +def tearDownModule(): + idleConf.userCfg = usercfg + idlelib.testing = False + + +class IdleConfParserTest(unittest.TestCase): + """Test that IdleConfParser works""" + + config = """ + [one] + one = false + two = true + three = 10 + + [two] + one = a string + two = true + three = false + """ + + def test_get(self): + parser = config.IdleConfParser('') + parser.read_string(self.config) + eq = self.assertEqual + + # Test with type argument. + self.assertIs(parser.Get('one', 'one', type='bool'), False) + self.assertIs(parser.Get('one', 'two', type='bool'), True) + eq(parser.Get('one', 'three', type='int'), 10) + eq(parser.Get('two', 'one'), 'a string') + self.assertIs(parser.Get('two', 'two', type='bool'), True) + self.assertIs(parser.Get('two', 'three', type='bool'), False) + + # Test without type should fallback to string. + eq(parser.Get('two', 'two'), 'true') + eq(parser.Get('two', 'three'), 'false') + + # If option not exist, should return None, or default. + self.assertIsNone(parser.Get('not', 'exist')) + eq(parser.Get('not', 'exist', default='DEFAULT'), 'DEFAULT') + + def test_get_option_list(self): + parser = config.IdleConfParser('') + parser.read_string(self.config) + get_list = parser.GetOptionList + self.assertCountEqual(get_list('one'), ['one', 'two', 'three']) + self.assertCountEqual(get_list('two'), ['one', 'two', 'three']) + self.assertEqual(get_list('not exist'), []) + + def test_load_nothing(self): + parser = config.IdleConfParser('') + parser.Load() + self.assertEqual(parser.sections(), []) + + def test_load_file(self): + # Borrow test/configdata/cfgparser.1 from test_configparser. + config_path = findfile('cfgparser.1', subdir='configdata') + parser = config.IdleConfParser(config_path) + parser.Load() + + self.assertEqual(parser.Get('Foo Bar', 'foo'), 'newbar') + self.assertEqual(parser.GetOptionList('Foo Bar'), ['foo']) + + +class IdleUserConfParserTest(unittest.TestCase): + """Test that IdleUserConfParser works""" + + def new_parser(self, path=''): + return config.IdleUserConfParser(path) + + def test_set_option(self): + parser = self.new_parser() + parser.add_section('Foo') + # Setting new option in existing section should return True. + self.assertTrue(parser.SetOption('Foo', 'bar', 'true')) + # Setting existing option with same value should return False. + self.assertFalse(parser.SetOption('Foo', 'bar', 'true')) + # Setting exiting option with new value should return True. + self.assertTrue(parser.SetOption('Foo', 'bar', 'false')) + self.assertEqual(parser.Get('Foo', 'bar'), 'false') + + # Setting option in new section should create section and return True. + self.assertTrue(parser.SetOption('Bar', 'bar', 'true')) + self.assertCountEqual(parser.sections(), ['Bar', 'Foo']) + self.assertEqual(parser.Get('Bar', 'bar'), 'true') + + def test_remove_option(self): + parser = self.new_parser() + parser.AddSection('Foo') + parser.SetOption('Foo', 'bar', 'true') + + self.assertTrue(parser.RemoveOption('Foo', 'bar')) + self.assertFalse(parser.RemoveOption('Foo', 'bar')) + self.assertFalse(parser.RemoveOption('Not', 'Exist')) + + def test_add_section(self): + parser = self.new_parser() + self.assertEqual(parser.sections(), []) + + # Should not add duplicate section. + # Configparser raises DuplicateError, IdleParser not. + parser.AddSection('Foo') + parser.AddSection('Foo') + parser.AddSection('Bar') + self.assertCountEqual(parser.sections(), ['Bar', 'Foo']) + + def test_remove_empty_sections(self): + parser = self.new_parser() + + parser.AddSection('Foo') + parser.AddSection('Bar') + parser.SetOption('Idle', 'name', 'val') + self.assertCountEqual(parser.sections(), ['Bar', 'Foo', 'Idle']) + parser.RemoveEmptySections() + self.assertEqual(parser.sections(), ['Idle']) + + def test_is_empty(self): + parser = self.new_parser() + + parser.AddSection('Foo') + parser.AddSection('Bar') + self.assertTrue(parser.IsEmpty()) + self.assertEqual(parser.sections(), []) + + parser.SetOption('Foo', 'bar', 'false') + parser.AddSection('Bar') + self.assertFalse(parser.IsEmpty()) + self.assertCountEqual(parser.sections(), ['Foo']) + + def test_save(self): + with tempfile.TemporaryDirectory() as tdir: + path = os.path.join(tdir, 'test.cfg') + parser = self.new_parser(path) + parser.AddSection('Foo') + parser.SetOption('Foo', 'bar', 'true') + + # Should save to path when config is not empty. + self.assertFalse(os.path.exists(path)) + parser.Save() + self.assertTrue(os.path.exists(path)) + + # Should remove the file from disk when config is empty. + parser.remove_section('Foo') + parser.Save() + self.assertFalse(os.path.exists(path)) + + +class IdleConfTest(unittest.TestCase): + """Test for idleConf""" + + @classmethod + def setUpClass(cls): + cls.config_string = {} + + conf = config.IdleConf(_utest=True) + if __name__ != '__main__': + idle_dir = os.path.dirname(__file__) + else: + idle_dir = os.path.abspath(sys.path[0]) + for ctype in conf.config_types: + config_path = os.path.join(idle_dir, '../config-%s.def' % ctype) + with open(config_path) as f: + cls.config_string[ctype] = f.read() + + cls.orig_warn = config._warn + config._warn = Func() + + @classmethod + def tearDownClass(cls): + config._warn = cls.orig_warn + + def new_config(self, _utest=False): + return config.IdleConf(_utest=_utest) + + def mock_config(self): + """Return a mocked idleConf + + Both default and user config used the same config-*.def + """ + conf = config.IdleConf(_utest=True) + for ctype in conf.config_types: + conf.defaultCfg[ctype] = config.IdleConfParser('') + conf.defaultCfg[ctype].read_string(self.config_string[ctype]) + conf.userCfg[ctype] = config.IdleUserConfParser('') + conf.userCfg[ctype].read_string(self.config_string[ctype]) + + return conf + + @unittest.skipIf(sys.platform.startswith('win'), 'this is test for unix system') + def test_get_user_cfg_dir_unix(self): + # Test to get user config directory under unix. + conf = self.new_config(_utest=True) + + # Check normal way should success + with mock.patch('os.path.expanduser', return_value='/home/foo'): + with mock.patch('os.path.exists', return_value=True): + self.assertEqual(conf.GetUserCfgDir(), '/home/foo/.idlerc') + + # Check os.getcwd should success + with mock.patch('os.path.expanduser', return_value='~'): + with mock.patch('os.getcwd', return_value='/home/foo/cpython'): + with mock.patch('os.mkdir'): + self.assertEqual(conf.GetUserCfgDir(), + '/home/foo/cpython/.idlerc') + + # Check user dir not exists and created failed should raise SystemExit + with mock.patch('os.path.join', return_value='/path/not/exists'): + with self.assertRaises(SystemExit): + with self.assertRaises(FileNotFoundError): + conf.GetUserCfgDir() + + @unittest.skipIf(not sys.platform.startswith('win'), 'this is test for Windows system') + def test_get_user_cfg_dir_windows(self): + # Test to get user config directory under Windows. + conf = self.new_config(_utest=True) + + # Check normal way should success + with mock.patch('os.path.expanduser', return_value='C:\\foo'): + with mock.patch('os.path.exists', return_value=True): + self.assertEqual(conf.GetUserCfgDir(), 'C:\\foo\\.idlerc') + + # Check os.getcwd should success + with mock.patch('os.path.expanduser', return_value='~'): + with mock.patch('os.getcwd', return_value='C:\\foo\\cpython'): + with mock.patch('os.mkdir'): + self.assertEqual(conf.GetUserCfgDir(), + 'C:\\foo\\cpython\\.idlerc') + + # Check user dir not exists and created failed should raise SystemExit + with mock.patch('os.path.join', return_value='/path/not/exists'): + with self.assertRaises(SystemExit): + with self.assertRaises(FileNotFoundError): + conf.GetUserCfgDir() + + def test_create_config_handlers(self): + conf = self.new_config(_utest=True) + + # Mock out idle_dir + idle_dir = '/home/foo' + with mock.patch.dict({'__name__': '__foo__'}): + with mock.patch('os.path.dirname', return_value=idle_dir): + conf.CreateConfigHandlers() + + # Check keys are equal + self.assertCountEqual(conf.defaultCfg, conf.config_types) + self.assertCountEqual(conf.userCfg, conf.config_types) + + # Check conf parser are correct type + for default_parser in conf.defaultCfg.values(): + self.assertIsInstance(default_parser, config.IdleConfParser) + for user_parser in conf.userCfg.values(): + self.assertIsInstance(user_parser, config.IdleUserConfParser) + + # Check config path are correct + for cfg_type, parser in conf.defaultCfg.items(): + self.assertEqual(parser.file, + os.path.join(idle_dir, f'config-{cfg_type}.def')) + for cfg_type, parser in conf.userCfg.items(): + self.assertEqual(parser.file, + os.path.join(conf.userdir or '#', f'config-{cfg_type}.cfg')) + + def test_load_cfg_files(self): + conf = self.new_config(_utest=True) + + # Borrow test/configdata/cfgparser.1 from test_configparser. + config_path = findfile('cfgparser.1', subdir='configdata') + conf.defaultCfg['foo'] = config.IdleConfParser(config_path) + conf.userCfg['foo'] = config.IdleUserConfParser(config_path) + + # Load all config from path + conf.LoadCfgFiles() + + eq = self.assertEqual + + # Check defaultCfg is loaded + eq(conf.defaultCfg['foo'].Get('Foo Bar', 'foo'), 'newbar') + eq(conf.defaultCfg['foo'].GetOptionList('Foo Bar'), ['foo']) + + # Check userCfg is loaded + eq(conf.userCfg['foo'].Get('Foo Bar', 'foo'), 'newbar') + eq(conf.userCfg['foo'].GetOptionList('Foo Bar'), ['foo']) + + def test_save_user_cfg_files(self): + conf = self.mock_config() + + with mock.patch('idlelib.config.IdleUserConfParser.Save') as m: + conf.SaveUserCfgFiles() + self.assertEqual(m.call_count, len(conf.userCfg)) + + def test_get_option(self): + conf = self.mock_config() + + eq = self.assertEqual + eq(conf.GetOption('main', 'EditorWindow', 'width'), '80') + eq(conf.GetOption('main', 'EditorWindow', 'width', type='int'), 80) + with mock.patch('idlelib.config._warn') as _warn: + eq(conf.GetOption('main', 'EditorWindow', 'font', type='int'), None) + eq(conf.GetOption('main', 'EditorWindow', 'NotExists'), None) + eq(conf.GetOption('main', 'EditorWindow', 'NotExists', default='NE'), 'NE') + eq(_warn.call_count, 4) + + def test_set_option(self): + conf = self.mock_config() + + conf.SetOption('main', 'Foo', 'bar', 'newbar') + self.assertEqual(conf.GetOption('main', 'Foo', 'bar'), 'newbar') + + def test_get_section_list(self): + conf = self.mock_config() + + self.assertCountEqual( + conf.GetSectionList('default', 'main'), + ['General', 'EditorWindow', 'PyShell', 'Indent', 'Theme', + 'Keys', 'History', 'HelpFiles']) + self.assertCountEqual( + conf.GetSectionList('user', 'main'), + ['General', 'EditorWindow', 'PyShell', 'Indent', 'Theme', + 'Keys', 'History', 'HelpFiles']) + + with self.assertRaises(config.InvalidConfigSet): + conf.GetSectionList('foobar', 'main') + with self.assertRaises(config.InvalidConfigType): + conf.GetSectionList('default', 'notexists') + + def test_get_highlight(self): + conf = self.mock_config() + + eq = self.assertEqual + eq(conf.GetHighlight('IDLE Classic', 'normal'), {'foreground': '#000000', + 'background': '#ffffff'}) + + # Test cursor (this background should be normal-background) + eq(conf.GetHighlight('IDLE Classic', 'cursor'), {'foreground': 'black', + 'background': '#ffffff'}) + + # Test get user themes + conf.SetOption('highlight', 'Foobar', 'normal-foreground', '#747474') + conf.SetOption('highlight', 'Foobar', 'normal-background', '#171717') + with mock.patch('idlelib.config._warn'): + eq(conf.GetHighlight('Foobar', 'normal'), {'foreground': '#747474', + 'background': '#171717'}) + + def test_get_theme_dict(self): + # TODO: finish. + conf = self.mock_config() + + # These two should be the same + self.assertEqual( + conf.GetThemeDict('default', 'IDLE Classic'), + conf.GetThemeDict('user', 'IDLE Classic')) + + with self.assertRaises(config.InvalidTheme): + conf.GetThemeDict('bad', 'IDLE Classic') + + def test_get_current_theme_and_keys(self): + conf = self.mock_config() + + self.assertEqual(conf.CurrentTheme(), conf.current_colors_and_keys('Theme')) + self.assertEqual(conf.CurrentKeys(), conf.current_colors_and_keys('Keys')) + + def test_current_colors_and_keys(self): + conf = self.mock_config() + + self.assertEqual(conf.current_colors_and_keys('Theme'), 'IDLE Classic') + + def test_default_keys(self): + current_platform = sys.platform + conf = self.new_config(_utest=True) + + sys.platform = 'win32' + self.assertEqual(conf.default_keys(), 'IDLE Classic Windows') + + sys.platform = 'darwin' + self.assertEqual(conf.default_keys(), 'IDLE Classic OSX') + + sys.platform = 'some-linux' + self.assertEqual(conf.default_keys(), 'IDLE Modern Unix') + + # Restore platform + sys.platform = current_platform + + def test_get_extensions(self): + userextn.read_string(''' + [ZzDummy] + enable = True + [DISABLE] + enable = False + ''') + eq = self.assertEqual + iGE = idleConf.GetExtensions + eq(iGE(shell_only=True), []) + eq(iGE(), ['ZzDummy']) + eq(iGE(editor_only=True), ['ZzDummy']) + eq(iGE(active_only=False), ['ZzDummy', 'DISABLE']) + eq(iGE(active_only=False, editor_only=True), ['ZzDummy', 'DISABLE']) + userextn.remove_section('ZzDummy') + userextn.remove_section('DISABLE') + + + def test_remove_key_bind_names(self): + conf = self.mock_config() + + self.assertCountEqual( + conf.RemoveKeyBindNames(conf.GetSectionList('default', 'extensions')), + ['AutoComplete', 'CodeContext', 'FormatParagraph', 'ParenMatch', 'ZzDummy']) + + def test_get_extn_name_for_event(self): + userextn.read_string(''' + [ZzDummy] + enable = True + ''') + eq = self.assertEqual + eq(idleConf.GetExtnNameForEvent('z-in'), 'ZzDummy') + eq(idleConf.GetExtnNameForEvent('z-out'), None) + userextn.remove_section('ZzDummy') + + def test_get_extension_keys(self): + userextn.read_string(''' + [ZzDummy] + enable = True + ''') + self.assertEqual(idleConf.GetExtensionKeys('ZzDummy'), + {'<>': ['']}) + userextn.remove_section('ZzDummy') +# need option key test +## key = [''] if sys.platform == 'darwin' else [''] +## eq(conf.GetExtensionKeys('ZoomHeight'), {'<>': key}) + + def test_get_extension_bindings(self): + userextn.read_string(''' + [ZzDummy] + enable = True + ''') + eq = self.assertEqual + iGEB = idleConf.GetExtensionBindings + eq(iGEB('NotExists'), {}) + expect = {'<>': [''], + '<>': ['']} + eq(iGEB('ZzDummy'), expect) + userextn.remove_section('ZzDummy') + + def test_get_keybinding(self): + conf = self.mock_config() + + eq = self.assertEqual + eq(conf.GetKeyBinding('IDLE Modern Unix', '<>'), + ['', '']) + eq(conf.GetKeyBinding('IDLE Classic Unix', '<>'), + ['', '']) + eq(conf.GetKeyBinding('IDLE Classic Windows', '<>'), + ['', '']) + eq(conf.GetKeyBinding('IDLE Classic Mac', '<>'), ['']) + eq(conf.GetKeyBinding('IDLE Classic OSX', '<>'), ['']) + + # Test keybinding not exists + eq(conf.GetKeyBinding('NOT EXISTS', '<>'), []) + eq(conf.GetKeyBinding('IDLE Modern Unix', 'NOT EXISTS'), []) + + def test_get_current_keyset(self): + current_platform = sys.platform + conf = self.mock_config() + + # Ensure that platform isn't darwin + sys.platform = 'some-linux' + self.assertEqual(conf.GetCurrentKeySet(), conf.GetKeySet(conf.CurrentKeys())) + + # This should not be the same, since replace ') + self.assertEqual(conf.GetKeySet('IDLE Modern Unix')['<>'], '') + + def test_is_core_binding(self): + # XXX: Should move out the core keys to config file or other place + conf = self.mock_config() + + self.assertTrue(conf.IsCoreBinding('copy')) + self.assertTrue(conf.IsCoreBinding('cut')) + self.assertTrue(conf.IsCoreBinding('del-word-right')) + self.assertFalse(conf.IsCoreBinding('not-exists')) + + def test_extra_help_source_list(self): + # Test GetExtraHelpSourceList and GetAllExtraHelpSourcesList in same + # place to prevent prepare input data twice. + conf = self.mock_config() + + # Test default with no extra help source + self.assertEqual(conf.GetExtraHelpSourceList('default'), []) + self.assertEqual(conf.GetExtraHelpSourceList('user'), []) + with self.assertRaises(config.InvalidConfigSet): + self.assertEqual(conf.GetExtraHelpSourceList('bad'), []) + self.assertCountEqual( + conf.GetAllExtraHelpSourcesList(), + conf.GetExtraHelpSourceList('default') + conf.GetExtraHelpSourceList('user')) + + # Add help source to user config + conf.userCfg['main'].SetOption('HelpFiles', '4', 'Python;https://python.org') # This is bad input + conf.userCfg['main'].SetOption('HelpFiles', '3', 'Python:https://python.org') # This is bad input + conf.userCfg['main'].SetOption('HelpFiles', '2', 'Pillow;https://pillow.readthedocs.io/en/latest/') + conf.userCfg['main'].SetOption('HelpFiles', '1', 'IDLE;C:/Programs/Python36/Lib/idlelib/help.html') + self.assertEqual(conf.GetExtraHelpSourceList('user'), + [('IDLE', 'C:/Programs/Python36/Lib/idlelib/help.html', '1'), + ('Pillow', 'https://pillow.readthedocs.io/en/latest/', '2'), + ('Python', 'https://python.org', '4')]) + self.assertCountEqual( + conf.GetAllExtraHelpSourcesList(), + conf.GetExtraHelpSourceList('default') + conf.GetExtraHelpSourceList('user')) + + def test_get_font(self): + from test.support import requires + from tkinter import Tk + from tkinter.font import Font + conf = self.mock_config() + + requires('gui') + root = Tk() + root.withdraw() + + f = Font.actual(Font(name='TkFixedFont', exists=True, root=root)) + self.assertEqual( + conf.GetFont(root, 'main', 'EditorWindow'), + (f['family'], 10 if f['size'] <= 0 else f['size'], f['weight'])) + + # Cleanup root + root.destroy() + del root + + def test_get_core_keys(self): + conf = self.mock_config() + + eq = self.assertEqual + eq(conf.GetCoreKeys()['<>'], ['']) + eq(conf.GetCoreKeys()['<>'], ['', '']) + eq(conf.GetCoreKeys()['<>'], ['']) + eq(conf.GetCoreKeys('IDLE Classic Windows')['<>'], + ['', '']) + eq(conf.GetCoreKeys('IDLE Classic OSX')['<>'], ['']) + eq(conf.GetCoreKeys('IDLE Classic Unix')['<>'], + ['', '']) + eq(conf.GetCoreKeys('IDLE Modern Unix')['<>'], + ['', '']) + + +class CurrentColorKeysTest(unittest.TestCase): + """ Test colorkeys function with user config [Theme] and [Keys] patterns. + + colorkeys = config.IdleConf.current_colors_and_keys + Test all patterns written by IDLE and some errors + Item 'default' should really be 'builtin' (versus 'custom). + """ + colorkeys = idleConf.current_colors_and_keys + default_theme = 'IDLE Classic' + default_keys = idleConf.default_keys() + + def test_old_builtin_theme(self): + # On initial installation, user main is blank. + self.assertEqual(self.colorkeys('Theme'), self.default_theme) + # For old default, name2 must be blank. + usermain.read_string(''' + [Theme] + default = True + ''') + # IDLE omits 'name' for default old builtin theme. + self.assertEqual(self.colorkeys('Theme'), self.default_theme) + # IDLE adds 'name' for non-default old builtin theme. + usermain['Theme']['name'] = 'IDLE New' + self.assertEqual(self.colorkeys('Theme'), 'IDLE New') + # Erroneous non-default old builtin reverts to default. + usermain['Theme']['name'] = 'non-existent' + self.assertEqual(self.colorkeys('Theme'), self.default_theme) + usermain.remove_section('Theme') + + def test_new_builtin_theme(self): + # IDLE writes name2 for new builtins. + usermain.read_string(''' + [Theme] + default = True + name2 = IDLE Dark + ''') + self.assertEqual(self.colorkeys('Theme'), 'IDLE Dark') + # Leftover 'name', not removed, is ignored. + usermain['Theme']['name'] = 'IDLE New' + self.assertEqual(self.colorkeys('Theme'), 'IDLE Dark') + # Erroneous non-default new builtin reverts to default. + usermain['Theme']['name2'] = 'non-existent' + self.assertEqual(self.colorkeys('Theme'), self.default_theme) + usermain.remove_section('Theme') + + def test_user_override_theme(self): + # Erroneous custom name (no definition) reverts to default. + usermain.read_string(''' + [Theme] + default = False + name = Custom Dark + ''') + self.assertEqual(self.colorkeys('Theme'), self.default_theme) + # Custom name is valid with matching Section name. + userhigh.read_string('[Custom Dark]\na=b') + self.assertEqual(self.colorkeys('Theme'), 'Custom Dark') + # Name2 is ignored. + usermain['Theme']['name2'] = 'non-existent' + self.assertEqual(self.colorkeys('Theme'), 'Custom Dark') + usermain.remove_section('Theme') + userhigh.remove_section('Custom Dark') + + def test_old_builtin_keys(self): + # On initial installation, user main is blank. + self.assertEqual(self.colorkeys('Keys'), self.default_keys) + # For old default, name2 must be blank, name is always used. + usermain.read_string(''' + [Keys] + default = True + name = IDLE Classic Unix + ''') + self.assertEqual(self.colorkeys('Keys'), 'IDLE Classic Unix') + # Erroneous non-default old builtin reverts to default. + usermain['Keys']['name'] = 'non-existent' + self.assertEqual(self.colorkeys('Keys'), self.default_keys) + usermain.remove_section('Keys') + + def test_new_builtin_keys(self): + # IDLE writes name2 for new builtins. + usermain.read_string(''' + [Keys] + default = True + name2 = IDLE Modern Unix + ''') + self.assertEqual(self.colorkeys('Keys'), 'IDLE Modern Unix') + # Leftover 'name', not removed, is ignored. + usermain['Keys']['name'] = 'IDLE Classic Unix' + self.assertEqual(self.colorkeys('Keys'), 'IDLE Modern Unix') + # Erroneous non-default new builtin reverts to default. + usermain['Keys']['name2'] = 'non-existent' + self.assertEqual(self.colorkeys('Keys'), self.default_keys) + usermain.remove_section('Keys') + + def test_user_override_keys(self): + # Erroneous custom name (no definition) reverts to default. + usermain.read_string(''' + [Keys] + default = False + name = Custom Keys + ''') + self.assertEqual(self.colorkeys('Keys'), self.default_keys) + # Custom name is valid with matching Section name. + userkeys.read_string('[Custom Keys]\na=b') + self.assertEqual(self.colorkeys('Keys'), 'Custom Keys') + # Name2 is ignored. + usermain['Keys']['name2'] = 'non-existent' + self.assertEqual(self.colorkeys('Keys'), 'Custom Keys') + usermain.remove_section('Keys') + userkeys.remove_section('Custom Keys') + + +class ChangesTest(unittest.TestCase): + + empty = {'main':{}, 'highlight':{}, 'keys':{}, 'extensions':{}} + + def load(self): # Test_add_option verifies that this works. + changes = self.changes + changes.add_option('main', 'Msec', 'mitem', 'mval') + changes.add_option('highlight', 'Hsec', 'hitem', 'hval') + changes.add_option('keys', 'Ksec', 'kitem', 'kval') + return changes + + loaded = {'main': {'Msec': {'mitem': 'mval'}}, + 'highlight': {'Hsec': {'hitem': 'hval'}}, + 'keys': {'Ksec': {'kitem':'kval'}}, + 'extensions': {}} + + def setUp(self): + self.changes = config.ConfigChanges() + + def test_init(self): + self.assertEqual(self.changes, self.empty) + + def test_add_option(self): + changes = self.load() + self.assertEqual(changes, self.loaded) + changes.add_option('main', 'Msec', 'mitem', 'mval') + self.assertEqual(changes, self.loaded) + + def test_save_option(self): # Static function does not touch changes. + save_option = self.changes.save_option + self.assertTrue(save_option('main', 'Indent', 'what', '0')) + self.assertFalse(save_option('main', 'Indent', 'what', '0')) + self.assertEqual(usermain['Indent']['what'], '0') + + self.assertTrue(save_option('main', 'Indent', 'use-spaces', '0')) + self.assertEqual(usermain['Indent']['use-spaces'], '0') + self.assertTrue(save_option('main', 'Indent', 'use-spaces', '1')) + self.assertFalse(usermain.has_option('Indent', 'use-spaces')) + usermain.remove_section('Indent') + + def test_save_added(self): + changes = self.load() + self.assertTrue(changes.save_all()) + self.assertEqual(usermain['Msec']['mitem'], 'mval') + self.assertEqual(userhigh['Hsec']['hitem'], 'hval') + self.assertEqual(userkeys['Ksec']['kitem'], 'kval') + changes.add_option('main', 'Msec', 'mitem', 'mval') + self.assertFalse(changes.save_all()) + usermain.remove_section('Msec') + userhigh.remove_section('Hsec') + userkeys.remove_section('Ksec') + + def test_save_help(self): + # Any change to HelpFiles overwrites entire section. + changes = self.changes + changes.save_option('main', 'HelpFiles', 'IDLE', 'idledoc') + changes.add_option('main', 'HelpFiles', 'ELDI', 'codeldi') + changes.save_all() + self.assertFalse(usermain.has_option('HelpFiles', 'IDLE')) + self.assertTrue(usermain.has_option('HelpFiles', 'ELDI')) + + def test_save_default(self): # Cover 2nd and 3rd false branches. + changes = self.changes + changes.add_option('main', 'Indent', 'use-spaces', '1') + # save_option returns False; cfg_type_changed remains False. + + # TODO: test that save_all calls usercfg Saves. + + def test_delete_section(self): + changes = self.load() + changes.delete_section('main', 'fake') # Test no exception. + self.assertEqual(changes, self.loaded) # Test nothing deleted. + for cfgtype, section in (('main', 'Msec'), ('keys', 'Ksec')): + testcfg[cfgtype].SetOption(section, 'name', 'value') + changes.delete_section(cfgtype, section) + with self.assertRaises(KeyError): + changes[cfgtype][section] # Test section gone from changes + testcfg[cfgtype][section] # and from mock userCfg. + # TODO test for save call. + + def test_clear(self): + changes = self.load() + changes.clear() + self.assertEqual(changes, self.empty) + + +class WarningTest(unittest.TestCase): + + def test_warn(self): + Equal = self.assertEqual + config._warned = set() + with captured_stderr() as stderr: + config._warn('warning', 'key') + Equal(config._warned, {('warning','key')}) + Equal(stderr.getvalue(), 'warning'+'\n') + with captured_stderr() as stderr: + config._warn('warning', 'key') + Equal(stderr.getvalue(), '') + with captured_stderr() as stderr: + config._warn('warn2', 'yek') + Equal(config._warned, {('warning','key'), ('warn2','yek')}) + Equal(stderr.getvalue(), 'warn2'+'\n') + + +if __name__ == '__main__': + unittest.main(verbosity=2) diff --git a/micromamba_root/envs/pytorch_env/Lib/idlelib/idle_test/test_config_key.py b/micromamba_root/envs/pytorch_env/Lib/idlelib/idle_test/test_config_key.py new file mode 100644 index 0000000000000000000000000000000000000000..32f878b842b276dc892c0606503d4fb8abde2180 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/idlelib/idle_test/test_config_key.py @@ -0,0 +1,356 @@ +"""Test config_key, coverage 98%. + +Coverage is effectively 100%. Tkinter dialog is mocked, Mac-only line +may be skipped, and dummy function in bind test should not be called. +Not tested: exit with 'self.advanced or self.keys_ok(keys) ...' False. +""" + +from idlelib import config_key +from test.support import requires +import unittest +from unittest import mock +from tkinter import Tk, TclError +from idlelib.idle_test.mock_idle import Func +from idlelib.idle_test.mock_tk import Mbox_func + + +class ValidationTest(unittest.TestCase): + "Test validation methods: ok, keys_ok, bind_ok." + + class Validator(config_key.GetKeysFrame): + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + class list_keys_final: + get = Func() + self.list_keys_final = list_keys_final + get_modifiers = Func() + showerror = Mbox_func() + + @classmethod + def setUpClass(cls): + requires('gui') + cls.root = Tk() + cls.root.withdraw() + keylist = [[''], ['', '']] + cls.dialog = cls.Validator(cls.root, '<>', keylist) + + @classmethod + def tearDownClass(cls): + del cls.dialog + cls.root.update_idletasks() + cls.root.destroy() + del cls.root + + def setUp(self): + self.dialog.showerror.message = '' + # A test that needs a particular final key value should set it. + # A test that sets a non-blank modifier list should reset it to []. + + def test_ok_empty(self): + self.dialog.key_string.set(' ') + self.dialog.ok() + self.assertEqual(self.dialog.result, '') + self.assertEqual(self.dialog.showerror.message, 'No key specified.') + + def test_ok_good(self): + self.dialog.key_string.set('') + self.dialog.list_keys_final.get.result = 'F11' + self.dialog.ok() + self.assertEqual(self.dialog.result, '') + self.assertEqual(self.dialog.showerror.message, '') + + def test_keys_no_ending(self): + self.assertFalse(self.dialog.keys_ok('')) + self.assertIn('No modifier', self.dialog.showerror.message) + + def test_keys_no_modifier_ok(self): + self.dialog.list_keys_final.get.result = 'F11' + self.assertTrue(self.dialog.keys_ok('')) + self.assertEqual(self.dialog.showerror.message, '') + + def test_keys_shift_bad(self): + self.dialog.list_keys_final.get.result = 'a' + self.dialog.get_modifiers.result = ['Shift'] + self.assertFalse(self.dialog.keys_ok('')) + self.assertIn('shift modifier', self.dialog.showerror.message) + self.dialog.get_modifiers.result = [] + + def test_keys_dup(self): + for mods, final, seq in (([], 'F12', ''), + (['Control'], 'x', ''), + (['Control'], 'X', '')): + with self.subTest(m=mods, f=final, s=seq): + self.dialog.list_keys_final.get.result = final + self.dialog.get_modifiers.result = mods + self.assertFalse(self.dialog.keys_ok(seq)) + self.assertIn('already in use', self.dialog.showerror.message) + self.dialog.get_modifiers.result = [] + + def test_bind_ok(self): + self.assertTrue(self.dialog.bind_ok('')) + self.assertEqual(self.dialog.showerror.message, '') + + def test_bind_not_ok(self): + self.assertFalse(self.dialog.bind_ok('')) + self.assertIn('not accepted', self.dialog.showerror.message) + + +class ToggleLevelTest(unittest.TestCase): + "Test toggle between Basic and Advanced frames." + + @classmethod + def setUpClass(cls): + requires('gui') + cls.root = Tk() + cls.root.withdraw() + cls.dialog = config_key.GetKeysFrame(cls.root, '<>', []) + + @classmethod + def tearDownClass(cls): + del cls.dialog + cls.root.update_idletasks() + cls.root.destroy() + del cls.root + + def test_toggle_level(self): + dialog = self.dialog + + def stackorder(): + """Get the stack order of the children of the frame. + + winfo_children() stores the children in stack order, so + this can be used to check whether a frame is above or + below another one. + """ + for index, child in enumerate(dialog.winfo_children()): + if child._name == 'keyseq_basic': + basic = index + if child._name == 'keyseq_advanced': + advanced = index + return basic, advanced + + # New window starts at basic level. + self.assertFalse(dialog.advanced) + self.assertIn('Advanced', dialog.button_level['text']) + basic, advanced = stackorder() + self.assertGreater(basic, advanced) + + # Toggle to advanced. + dialog.toggle_level() + self.assertTrue(dialog.advanced) + self.assertIn('Basic', dialog.button_level['text']) + basic, advanced = stackorder() + self.assertGreater(advanced, basic) + + # Toggle to basic. + dialog.button_level.invoke() + self.assertFalse(dialog.advanced) + self.assertIn('Advanced', dialog.button_level['text']) + basic, advanced = stackorder() + self.assertGreater(basic, advanced) + + +class KeySelectionTest(unittest.TestCase): + "Test selecting key on Basic frames." + + class Basic(config_key.GetKeysFrame): + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + class list_keys_final: + get = Func() + select_clear = Func() + yview = Func() + self.list_keys_final = list_keys_final + def set_modifiers_for_platform(self): + self.modifiers = ['foo', 'bar', 'BAZ'] + self.modifier_label = {'BAZ': 'ZZZ'} + showerror = Mbox_func() + + @classmethod + def setUpClass(cls): + requires('gui') + cls.root = Tk() + cls.root.withdraw() + cls.dialog = cls.Basic(cls.root, '<>', []) + + @classmethod + def tearDownClass(cls): + del cls.dialog + cls.root.update_idletasks() + cls.root.destroy() + del cls.root + + def setUp(self): + self.dialog.clear_key_seq() + + def test_get_modifiers(self): + dialog = self.dialog + gm = dialog.get_modifiers + eq = self.assertEqual + + # Modifiers are set on/off by invoking the checkbutton. + dialog.modifier_checkbuttons['foo'].invoke() + eq(gm(), ['foo']) + + dialog.modifier_checkbuttons['BAZ'].invoke() + eq(gm(), ['foo', 'BAZ']) + + dialog.modifier_checkbuttons['foo'].invoke() + eq(gm(), ['BAZ']) + + @mock.patch.object(config_key.GetKeysFrame, 'get_modifiers') + def test_build_key_string(self, mock_modifiers): + dialog = self.dialog + key = dialog.list_keys_final + string = dialog.key_string.get + eq = self.assertEqual + + key.get.result = 'a' + mock_modifiers.return_value = [] + dialog.build_key_string() + eq(string(), '') + + mock_modifiers.return_value = ['mymod'] + dialog.build_key_string() + eq(string(), '') + + key.get.result = '' + mock_modifiers.return_value = ['mymod', 'test'] + dialog.build_key_string() + eq(string(), '') + + @mock.patch.object(config_key.GetKeysFrame, 'get_modifiers') + def test_final_key_selected(self, mock_modifiers): + dialog = self.dialog + key = dialog.list_keys_final + string = dialog.key_string.get + eq = self.assertEqual + + mock_modifiers.return_value = ['Shift'] + key.get.result = '{' + dialog.final_key_selected() + eq(string(), '') + + +class CancelWindowTest(unittest.TestCase): + "Simulate user clicking [Cancel] button." + + @classmethod + def setUpClass(cls): + requires('gui') + cls.root = Tk() + cls.root.withdraw() + cls.dialog = config_key.GetKeysWindow( + cls.root, 'Title', '<>', [], _utest=True) + + @classmethod + def tearDownClass(cls): + cls.dialog.cancel() + del cls.dialog + cls.root.update_idletasks() + cls.root.destroy() + del cls.root + + @mock.patch.object(config_key.GetKeysFrame, 'ok') + def test_cancel(self, mock_frame_ok): + self.assertEqual(self.dialog.winfo_class(), 'Toplevel') + self.dialog.button_cancel.invoke() + with self.assertRaises(TclError): + self.dialog.winfo_class() + self.assertEqual(self.dialog.result, '') + mock_frame_ok.assert_not_called() + + +class OKWindowTest(unittest.TestCase): + "Simulate user clicking [OK] button." + + @classmethod + def setUpClass(cls): + requires('gui') + cls.root = Tk() + cls.root.withdraw() + cls.dialog = config_key.GetKeysWindow( + cls.root, 'Title', '<>', [], _utest=True) + + @classmethod + def tearDownClass(cls): + cls.dialog.cancel() + del cls.dialog + cls.root.update_idletasks() + cls.root.destroy() + del cls.root + + @mock.patch.object(config_key.GetKeysFrame, 'ok') + def test_ok(self, mock_frame_ok): + self.assertEqual(self.dialog.winfo_class(), 'Toplevel') + self.dialog.button_ok.invoke() + with self.assertRaises(TclError): + self.dialog.winfo_class() + mock_frame_ok.assert_called() + + +class WindowResultTest(unittest.TestCase): + "Test window result get and set." + + @classmethod + def setUpClass(cls): + requires('gui') + cls.root = Tk() + cls.root.withdraw() + cls.dialog = config_key.GetKeysWindow( + cls.root, 'Title', '<>', [], _utest=True) + + @classmethod + def tearDownClass(cls): + cls.dialog.cancel() + del cls.dialog + cls.root.update_idletasks() + cls.root.destroy() + del cls.root + + def test_result(self): + dialog = self.dialog + eq = self.assertEqual + + dialog.result = '' + eq(dialog.result, '') + eq(dialog.frame.result,'') + + dialog.result = 'bar' + eq(dialog.result,'bar') + eq(dialog.frame.result,'bar') + + dialog.frame.result = 'foo' + eq(dialog.result, 'foo') + eq(dialog.frame.result,'foo') + + +class HelperTest(unittest.TestCase): + "Test module level helper functions." + + def test_translate_key(self): + tr = config_key.translate_key + eq = self.assertEqual + + # Letters return unchanged with no 'Shift'. + eq(tr('q', []), 'Key-q') + eq(tr('q', ['Control', 'Alt']), 'Key-q') + + # 'Shift' uppercases single lowercase letters. + eq(tr('q', ['Shift']), 'Key-Q') + eq(tr('q', ['Control', 'Shift']), 'Key-Q') + eq(tr('q', ['Control', 'Alt', 'Shift']), 'Key-Q') + + # Convert key name to keysym. + eq(tr('Page Up', []), 'Key-Prior') + # 'Shift' doesn't change case when it's not a single char. + eq(tr('*', ['Shift']), 'Key-asterisk') + + +if __name__ == '__main__': + unittest.main(verbosity=2) diff --git a/micromamba_root/envs/pytorch_env/Lib/idlelib/idle_test/test_configdialog.py b/micromamba_root/envs/pytorch_env/Lib/idlelib/idle_test/test_configdialog.py new file mode 100644 index 0000000000000000000000000000000000000000..5099d0933824453c32ca0ec9582721db840db566 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/idlelib/idle_test/test_configdialog.py @@ -0,0 +1,1580 @@ +"""Test configdialog, coverage 94%. + +Half the class creates dialog, half works with user customizations. +""" +from idlelib import configdialog +from test.support import requires +requires('gui') +import unittest +from unittest import mock +from idlelib.idle_test.mock_idle import Func +from tkinter import (Tk, StringVar, IntVar, BooleanVar, DISABLED, NORMAL) +from idlelib import config +from idlelib.configdialog import idleConf, changes, tracers + +# Tests should not depend on fortuitous user configurations. +# They must not affect actual user .cfg files. +# Use solution from test_config: empty parsers with no filename. +usercfg = idleConf.userCfg +testcfg = { + 'main': config.IdleUserConfParser(''), + 'highlight': config.IdleUserConfParser(''), + 'keys': config.IdleUserConfParser(''), + 'extensions': config.IdleUserConfParser(''), +} + +root = None +dialog = None +mainpage = changes['main'] +highpage = changes['highlight'] +keyspage = changes['keys'] +extpage = changes['extensions'] + + +def setUpModule(): + global root, dialog + idleConf.userCfg = testcfg + root = Tk() + # root.withdraw() # Comment out, see issue 30870 + dialog = configdialog.ConfigDialog(root, 'Test', _utest=True) + + +def tearDownModule(): + global root, dialog + idleConf.userCfg = usercfg + tracers.detach() + tracers.clear() + changes.clear() + root.update_idletasks() + root.destroy() + root = dialog = None + + +class ConfigDialogTest(unittest.TestCase): + + def test_deactivate_current_config(self): + pass + + def activate_config_changes(self): + pass + + +class ButtonTest(unittest.TestCase): + + def test_click_ok(self): + d = dialog + apply = d.apply = mock.Mock() + destroy = d.destroy = mock.Mock() + d.buttons['Ok'].invoke() + apply.assert_called_once() + destroy.assert_called_once() + del d.destroy, d.apply + + def test_click_apply(self): + d = dialog + deactivate = d.deactivate_current_config = mock.Mock() + save_ext = d.extpage.save_all_changed_extensions = mock.Mock() + activate = d.activate_config_changes = mock.Mock() + d.buttons['Apply'].invoke() + deactivate.assert_called_once() + save_ext.assert_called_once() + activate.assert_called_once() + del d.extpage.save_all_changed_extensions + del d.activate_config_changes, d.deactivate_current_config + + def test_click_cancel(self): + d = dialog + d.destroy = Func() + changes['main']['something'] = 1 + d.buttons['Cancel'].invoke() + self.assertEqual(changes['main'], {}) + self.assertEqual(d.destroy.called, 1) + del d.destroy + + def test_click_help(self): + dialog.note.select(dialog.keyspage) + with mock.patch.object(configdialog, 'view_text', + new_callable=Func) as view: + dialog.buttons['Help'].invoke() + title, contents = view.kwds['title'], view.kwds['contents'] + self.assertEqual(title, 'Help for IDLE preferences') + self.assertTrue(contents.startswith('When you click') and + contents.endswith('a different name.\n')) + + +class FontPageTest(unittest.TestCase): + """Test that font widgets enable users to make font changes. + + Test that widget actions set vars, that var changes add three + options to changes and call set_samples, and that set_samples + changes the font of both sample boxes. + """ + @classmethod + def setUpClass(cls): + page = cls.page = dialog.fontpage + dialog.note.select(page) + page.set_samples = Func() # Mask instance method. + page.update() + + @classmethod + def tearDownClass(cls): + del cls.page.set_samples # Unmask instance method. + + def setUp(self): + changes.clear() + + def test_load_font_cfg(self): + # Leave widget load test to human visual check. + # TODO Improve checks when add IdleConf.get_font_values. + tracers.detach() + d = self.page + d.font_name.set('Fake') + d.font_size.set('1') + d.font_bold.set(True) + d.set_samples.called = 0 + d.load_font_cfg() + self.assertNotEqual(d.font_name.get(), 'Fake') + self.assertNotEqual(d.font_size.get(), '1') + self.assertFalse(d.font_bold.get()) + self.assertEqual(d.set_samples.called, 1) + tracers.attach() + + def test_fontlist_key(self): + # Up and Down keys should select a new font. + d = self.page + if d.fontlist.size() < 2: + self.skipTest('need at least 2 fonts') + fontlist = d.fontlist + fontlist.activate(0) + font = d.fontlist.get('active') + + # Test Down key. + fontlist.focus_force() + fontlist.update() + fontlist.event_generate('') + fontlist.event_generate('') + + down_font = fontlist.get('active') + self.assertNotEqual(down_font, font) + self.assertIn(d.font_name.get(), down_font.lower()) + + # Test Up key. + fontlist.focus_force() + fontlist.update() + fontlist.event_generate('') + fontlist.event_generate('') + + up_font = fontlist.get('active') + self.assertEqual(up_font, font) + self.assertIn(d.font_name.get(), up_font.lower()) + + def test_fontlist_mouse(self): + # Click on item should select that item. + d = self.page + if d.fontlist.size() < 2: + self.skipTest('need at least 2 fonts') + fontlist = d.fontlist + fontlist.activate(0) + + # Select next item in listbox + fontlist.focus_force() + fontlist.see(1) + fontlist.update() + x, y, dx, dy = fontlist.bbox(1) + x += dx // 2 + y += dy // 2 + fontlist.event_generate('', x=x, y=y) + fontlist.event_generate('', x=x, y=y) + + font1 = fontlist.get(1) + select_font = fontlist.get('anchor') + self.assertEqual(select_font, font1) + self.assertIn(d.font_name.get(), font1.lower()) + + def test_sizelist(self): + # Click on number should select that number + d = self.page + d.sizelist.variable.set(40) + self.assertEqual(d.font_size.get(), '40') + + def test_bold_toggle(self): + # Click on checkbutton should invert it. + d = self.page + d.font_bold.set(False) + d.bold_toggle.invoke() + self.assertTrue(d.font_bold.get()) + d.bold_toggle.invoke() + self.assertFalse(d.font_bold.get()) + + def test_font_set(self): + # Test that setting a font Variable results in 3 provisional + # change entries and a call to set_samples. Use values sure to + # not be defaults. + + default_font = idleConf.GetFont(root, 'main', 'EditorWindow') + default_size = str(default_font[1]) + default_bold = default_font[2] == 'bold' + d = self.page + d.font_size.set(default_size) + d.font_bold.set(default_bold) + d.set_samples.called = 0 + + d.font_name.set('Test Font') + expected = {'EditorWindow': {'font': 'Test Font', + 'font-size': default_size, + 'font-bold': str(default_bold)}} + self.assertEqual(mainpage, expected) + self.assertEqual(d.set_samples.called, 1) + changes.clear() + + d.font_size.set('20') + expected = {'EditorWindow': {'font': 'Test Font', + 'font-size': '20', + 'font-bold': str(default_bold)}} + self.assertEqual(mainpage, expected) + self.assertEqual(d.set_samples.called, 2) + changes.clear() + + d.font_bold.set(not default_bold) + expected = {'EditorWindow': {'font': 'Test Font', + 'font-size': '20', + 'font-bold': str(not default_bold)}} + self.assertEqual(mainpage, expected) + self.assertEqual(d.set_samples.called, 3) + + def test_set_samples(self): + d = self.page + del d.set_samples # Unmask method for test + orig_samples = d.font_sample, d.highlight_sample + d.font_sample, d.highlight_sample = {}, {} + d.font_name.set('test') + d.font_size.set('5') + d.font_bold.set(1) + expected = {'font': ('test', '5', 'bold')} + + # Test set_samples. + d.set_samples() + self.assertTrue(d.font_sample == d.highlight_sample == expected) + + d.font_sample, d.highlight_sample = orig_samples + d.set_samples = Func() # Re-mask for other tests. + + +class HighPageTest(unittest.TestCase): + """Test that highlight tab widgets enable users to make changes. + + Test that widget actions set vars, that var changes add + options to changes and that themes work correctly. + """ + + @classmethod + def setUpClass(cls): + page = cls.page = dialog.highpage + dialog.note.select(page) + page.set_theme_type = Func() + page.paint_theme_sample = Func() + page.set_highlight_target = Func() + page.set_color_sample = Func() + page.update() + + @classmethod + def tearDownClass(cls): + d = cls.page + del d.set_theme_type, d.paint_theme_sample + del d.set_highlight_target, d.set_color_sample + + def setUp(self): + d = self.page + # The following is needed for test_load_key_cfg, _delete_custom_keys. + # This may indicate a defect in some test or function. + for section in idleConf.GetSectionList('user', 'highlight'): + idleConf.userCfg['highlight'].remove_section(section) + changes.clear() + d.set_theme_type.called = 0 + d.paint_theme_sample.called = 0 + d.set_highlight_target.called = 0 + d.set_color_sample.called = 0 + + def test_load_theme_cfg(self): + tracers.detach() + d = self.page + eq = self.assertEqual + + # Use builtin theme with no user themes created. + idleConf.CurrentTheme = mock.Mock(return_value='IDLE Classic') + d.load_theme_cfg() + self.assertTrue(d.theme_source.get()) + # builtinlist sets variable builtin_name to the CurrentTheme default. + eq(d.builtin_name.get(), 'IDLE Classic') + eq(d.custom_name.get(), '- no custom themes -') + eq(d.custom_theme_on.state(), ('disabled',)) + eq(d.set_theme_type.called, 1) + eq(d.paint_theme_sample.called, 1) + eq(d.set_highlight_target.called, 1) + + # Builtin theme with non-empty user theme list. + idleConf.SetOption('highlight', 'test1', 'option', 'value') + idleConf.SetOption('highlight', 'test2', 'option2', 'value2') + d.load_theme_cfg() + eq(d.builtin_name.get(), 'IDLE Classic') + eq(d.custom_name.get(), 'test1') + eq(d.set_theme_type.called, 2) + eq(d.paint_theme_sample.called, 2) + eq(d.set_highlight_target.called, 2) + + # Use custom theme. + idleConf.CurrentTheme = mock.Mock(return_value='test2') + idleConf.SetOption('main', 'Theme', 'default', '0') + d.load_theme_cfg() + self.assertFalse(d.theme_source.get()) + eq(d.builtin_name.get(), 'IDLE Classic') + eq(d.custom_name.get(), 'test2') + eq(d.set_theme_type.called, 3) + eq(d.paint_theme_sample.called, 3) + eq(d.set_highlight_target.called, 3) + + del idleConf.CurrentTheme + tracers.attach() + + def test_theme_source(self): + eq = self.assertEqual + d = self.page + # Test these separately. + d.var_changed_builtin_name = Func() + d.var_changed_custom_name = Func() + # Builtin selected. + d.builtin_theme_on.invoke() + eq(mainpage, {'Theme': {'default': 'True'}}) + eq(d.var_changed_builtin_name.called, 1) + eq(d.var_changed_custom_name.called, 0) + changes.clear() + + # Custom selected. + d.custom_theme_on.state(('!disabled',)) + d.custom_theme_on.invoke() + self.assertEqual(mainpage, {'Theme': {'default': 'False'}}) + eq(d.var_changed_builtin_name.called, 1) + eq(d.var_changed_custom_name.called, 1) + del d.var_changed_builtin_name, d.var_changed_custom_name + + def test_builtin_name(self): + eq = self.assertEqual + d = self.page + item_list = ['IDLE Classic', 'IDLE Dark', 'IDLE New'] + + # Not in old_themes, defaults name to first item. + idleConf.SetOption('main', 'Theme', 'name', 'spam') + d.builtinlist.SetMenu(item_list, 'IDLE Dark') + eq(mainpage, {'Theme': {'name': 'IDLE Classic', + 'name2': 'IDLE Dark'}}) + eq(d.theme_message['text'], 'New theme, see Help') + eq(d.paint_theme_sample.called, 1) + + # Not in old themes - uses name2. + changes.clear() + idleConf.SetOption('main', 'Theme', 'name', 'IDLE New') + d.builtinlist.SetMenu(item_list, 'IDLE Dark') + eq(mainpage, {'Theme': {'name2': 'IDLE Dark'}}) + eq(d.theme_message['text'], 'New theme, see Help') + eq(d.paint_theme_sample.called, 2) + + # Builtin name in old_themes. + changes.clear() + d.builtinlist.SetMenu(item_list, 'IDLE Classic') + eq(mainpage, {'Theme': {'name': 'IDLE Classic', 'name2': ''}}) + eq(d.theme_message['text'], '') + eq(d.paint_theme_sample.called, 3) + + def test_custom_name(self): + d = self.page + + # If no selections, doesn't get added. + d.customlist.SetMenu([], '- no custom themes -') + self.assertNotIn('Theme', mainpage) + self.assertEqual(d.paint_theme_sample.called, 0) + + # Custom name selected. + changes.clear() + d.customlist.SetMenu(['a', 'b', 'c'], 'c') + self.assertEqual(mainpage, {'Theme': {'name': 'c'}}) + self.assertEqual(d.paint_theme_sample.called, 1) + + def test_color(self): + d = self.page + d.on_new_color_set = Func() + # self.color is only set in get_color through colorchooser. + d.color.set('green') + self.assertEqual(d.on_new_color_set.called, 1) + del d.on_new_color_set + + def test_highlight_target_list_mouse(self): + # Set highlight_target through targetlist. + eq = self.assertEqual + d = self.page + + d.targetlist.SetMenu(['a', 'b', 'c'], 'c') + eq(d.highlight_target.get(), 'c') + eq(d.set_highlight_target.called, 1) + + def test_highlight_target_text_mouse(self): + # Set highlight_target through clicking highlight_sample. + eq = self.assertEqual + d = self.page + hs = d.highlight_sample + hs.focus_force() + + def click_char(index): + "Simulate click on character at *index*." + hs.see(index) + hs.update_idletasks() + x, y, dx, dy = hs.bbox(index) + x += dx // 2 + y += dy // 2 + hs.event_generate('', x=0, y=0) + hs.event_generate('', x=x, y=y) + hs.event_generate('', x=x, y=y) + hs.event_generate('', x=x, y=y) + + # Reverse theme_elements to make the tag the key. + elem = {tag: element for element, tag in d.theme_elements.items()} + + # If highlight_sample has a tag that isn't in theme_elements, there + # will be a KeyError in the test run. + count = 0 + for tag in hs.tag_names(): + try: + click_char(hs.tag_nextrange(tag, "1.0")[0]) + eq(d.highlight_target.get(), elem[tag]) + count += 1 + eq(d.set_highlight_target.called, count) + except IndexError: + pass # Skip unused theme_elements tag, like 'sel'. + + def test_highlight_sample_double_click(self): + # Test double click on highlight_sample. + eq = self.assertEqual + d = self.page + + hs = d.highlight_sample + hs.focus_force() + hs.see(1.0) + hs.update_idletasks() + + # Test binding from configdialog. + hs.event_generate('', x=0, y=0) + hs.event_generate('', x=0, y=0) + # Double click is a sequence of two clicks in a row. + for _ in range(2): + hs.event_generate('', x=0, y=0) + hs.event_generate('', x=0, y=0) + + eq(hs.tag_ranges('sel'), ()) + + def test_highlight_sample_b1_motion(self): + # Test button motion on highlight_sample. + eq = self.assertEqual + d = self.page + + hs = d.highlight_sample + hs.focus_force() + hs.see(1.0) + hs.update_idletasks() + + x, y, dx, dy, offset = hs.dlineinfo('1.0') + + # Test binding from configdialog. + hs.event_generate('') + hs.event_generate('') + hs.event_generate('', x=x, y=y) + hs.event_generate('', x=x, y=y) + hs.event_generate('', x=dx, y=dy) + hs.event_generate('', x=dx, y=dy) + + eq(hs.tag_ranges('sel'), ()) + + def test_set_theme_type(self): + eq = self.assertEqual + d = self.page + del d.set_theme_type + + # Builtin theme selected. + d.theme_source.set(True) + d.set_theme_type() + eq(d.builtinlist['state'], NORMAL) + eq(d.customlist['state'], DISABLED) + eq(d.button_delete_custom.state(), ('disabled',)) + + # Custom theme selected. + d.theme_source.set(False) + d.set_theme_type() + eq(d.builtinlist['state'], DISABLED) + eq(d.custom_theme_on.state(), ('selected',)) + eq(d.customlist['state'], NORMAL) + eq(d.button_delete_custom.state(), ()) + d.set_theme_type = Func() + + def test_get_color(self): + eq = self.assertEqual + d = self.page + orig_chooser = configdialog.colorchooser.askcolor + chooser = configdialog.colorchooser.askcolor = Func() + gntn = d.get_new_theme_name = Func() + + d.highlight_target.set('Editor Breakpoint') + d.color.set('#ffffff') + + # Nothing selected. + chooser.result = (None, None) + d.button_set_color.invoke() + eq(d.color.get(), '#ffffff') + + # Selection same as previous color. + chooser.result = ('', d.style.lookup(d.frame_color_set['style'], 'background')) + d.button_set_color.invoke() + eq(d.color.get(), '#ffffff') + + # Select different color. + chooser.result = ((222.8671875, 0.0, 0.0), '#de0000') + + # Default theme. + d.color.set('#ffffff') + d.theme_source.set(True) + + # No theme name selected therefore color not saved. + gntn.result = '' + d.button_set_color.invoke() + eq(gntn.called, 1) + eq(d.color.get(), '#ffffff') + # Theme name selected. + gntn.result = 'My New Theme' + d.button_set_color.invoke() + eq(d.custom_name.get(), gntn.result) + eq(d.color.get(), '#de0000') + + # Custom theme. + d.color.set('#ffffff') + d.theme_source.set(False) + d.button_set_color.invoke() + eq(d.color.get(), '#de0000') + + del d.get_new_theme_name + configdialog.colorchooser.askcolor = orig_chooser + + def test_on_new_color_set(self): + d = self.page + color = '#3f7cae' + d.custom_name.set('Python') + d.highlight_target.set('Selected Text') + d.fg_bg_toggle.set(True) + + d.color.set(color) + self.assertEqual(d.style.lookup(d.frame_color_set['style'], 'background'), color) + self.assertEqual(d.highlight_sample.tag_cget('hilite', 'foreground'), color) + self.assertEqual(highpage, + {'Python': {'hilite-foreground': color}}) + + def test_get_new_theme_name(self): + orig_sectionname = configdialog.SectionName + sn = configdialog.SectionName = Func(return_self=True) + d = self.page + + sn.result = 'New Theme' + self.assertEqual(d.get_new_theme_name(''), 'New Theme') + + configdialog.SectionName = orig_sectionname + + def test_save_as_new_theme(self): + d = self.page + gntn = d.get_new_theme_name = Func() + d.theme_source.set(True) + + # No name entered. + gntn.result = '' + d.button_save_custom.invoke() + self.assertNotIn(gntn.result, idleConf.userCfg['highlight']) + + # Name entered. + gntn.result = 'my new theme' + gntn.called = 0 + self.assertNotIn(gntn.result, idleConf.userCfg['highlight']) + d.button_save_custom.invoke() + self.assertIn(gntn.result, idleConf.userCfg['highlight']) + + del d.get_new_theme_name + + def test_create_new_and_save_new(self): + eq = self.assertEqual + d = self.page + + # Use default as previously active theme. + d.theme_source.set(True) + d.builtin_name.set('IDLE Classic') + first_new = 'my new custom theme' + second_new = 'my second custom theme' + + # No changes, so themes are an exact copy. + self.assertNotIn(first_new, idleConf.userCfg) + d.create_new(first_new) + eq(idleConf.GetSectionList('user', 'highlight'), [first_new]) + eq(idleConf.GetThemeDict('default', 'IDLE Classic'), + idleConf.GetThemeDict('user', first_new)) + eq(d.custom_name.get(), first_new) + self.assertFalse(d.theme_source.get()) # Use custom set. + eq(d.set_theme_type.called, 1) + + # Test that changed targets are in new theme. + changes.add_option('highlight', first_new, 'hit-background', 'yellow') + self.assertNotIn(second_new, idleConf.userCfg) + d.create_new(second_new) + eq(idleConf.GetSectionList('user', 'highlight'), [first_new, second_new]) + self.assertNotEqual(idleConf.GetThemeDict('user', first_new), + idleConf.GetThemeDict('user', second_new)) + # Check that difference in themes was in `hit-background` from `changes`. + idleConf.SetOption('highlight', first_new, 'hit-background', 'yellow') + eq(idleConf.GetThemeDict('user', first_new), + idleConf.GetThemeDict('user', second_new)) + + def test_set_highlight_target(self): + eq = self.assertEqual + d = self.page + del d.set_highlight_target + + # Target is cursor. + d.highlight_target.set('Cursor') + eq(d.fg_on.state(), ('disabled', 'selected')) + eq(d.bg_on.state(), ('disabled',)) + self.assertTrue(d.fg_bg_toggle) + eq(d.set_color_sample.called, 1) + + # Target is not cursor. + d.highlight_target.set('Comment') + eq(d.fg_on.state(), ('selected',)) + eq(d.bg_on.state(), ()) + self.assertTrue(d.fg_bg_toggle) + eq(d.set_color_sample.called, 2) + + d.set_highlight_target = Func() + + def test_set_color_sample_binding(self): + d = self.page + scs = d.set_color_sample + + d.fg_on.invoke() + self.assertEqual(scs.called, 1) + + d.bg_on.invoke() + self.assertEqual(scs.called, 2) + + def test_set_color_sample(self): + d = self.page + del d.set_color_sample + d.highlight_target.set('Selected Text') + d.fg_bg_toggle.set(True) + d.set_color_sample() + self.assertEqual( + d.style.lookup(d.frame_color_set['style'], 'background'), + d.highlight_sample.tag_cget('hilite', 'foreground')) + d.set_color_sample = Func() + + def test_paint_theme_sample(self): + eq = self.assertEqual + page = self.page + del page.paint_theme_sample # Delete masking mock. + hs_tag = page.highlight_sample.tag_cget + gh = idleConf.GetHighlight + + # Create custom theme based on IDLE Dark. + page.theme_source.set(True) + page.builtin_name.set('IDLE Dark') + theme = 'IDLE Test' + page.create_new(theme) + page.set_color_sample.called = 0 + + # Base theme with nothing in `changes`. + page.paint_theme_sample() + new_console = {'foreground': 'blue', + 'background': 'yellow',} + for key, value in new_console.items(): + self.assertNotEqual(hs_tag('console', key), value) + eq(page.set_color_sample.called, 1) + + # Apply changes. + for key, value in new_console.items(): + changes.add_option('highlight', theme, 'console-'+key, value) + page.paint_theme_sample() + for key, value in new_console.items(): + eq(hs_tag('console', key), value) + eq(page.set_color_sample.called, 2) + + page.paint_theme_sample = Func() + + def test_delete_custom(self): + eq = self.assertEqual + d = self.page + d.button_delete_custom.state(('!disabled',)) + yesno = d.askyesno = Func() + dialog.deactivate_current_config = Func() + dialog.activate_config_changes = Func() + + theme_name = 'spam theme' + idleConf.userCfg['highlight'].SetOption(theme_name, 'name', 'value') + highpage[theme_name] = {'option': 'True'} + + theme_name2 = 'other theme' + idleConf.userCfg['highlight'].SetOption(theme_name2, 'name', 'value') + highpage[theme_name2] = {'option': 'False'} + + # Force custom theme. + d.custom_theme_on.state(('!disabled',)) + d.custom_theme_on.invoke() + d.custom_name.set(theme_name) + + # Cancel deletion. + yesno.result = False + d.button_delete_custom.invoke() + eq(yesno.called, 1) + eq(highpage[theme_name], {'option': 'True'}) + eq(idleConf.GetSectionList('user', 'highlight'), [theme_name, theme_name2]) + eq(dialog.deactivate_current_config.called, 0) + eq(dialog.activate_config_changes.called, 0) + eq(d.set_theme_type.called, 0) + + # Confirm deletion. + yesno.result = True + d.button_delete_custom.invoke() + eq(yesno.called, 2) + self.assertNotIn(theme_name, highpage) + eq(idleConf.GetSectionList('user', 'highlight'), [theme_name2]) + eq(d.custom_theme_on.state(), ()) + eq(d.custom_name.get(), theme_name2) + eq(dialog.deactivate_current_config.called, 1) + eq(dialog.activate_config_changes.called, 1) + eq(d.set_theme_type.called, 1) + + # Confirm deletion of second theme - empties list. + d.custom_name.set(theme_name2) + yesno.result = True + d.button_delete_custom.invoke() + eq(yesno.called, 3) + self.assertNotIn(theme_name, highpage) + eq(idleConf.GetSectionList('user', 'highlight'), []) + eq(d.custom_theme_on.state(), ('disabled',)) + eq(d.custom_name.get(), '- no custom themes -') + eq(dialog.deactivate_current_config.called, 2) + eq(dialog.activate_config_changes.called, 2) + eq(d.set_theme_type.called, 2) + + del dialog.activate_config_changes, dialog.deactivate_current_config + del d.askyesno + + +class KeysPageTest(unittest.TestCase): + """Test that keys tab widgets enable users to make changes. + + Test that widget actions set vars, that var changes add + options to changes and that key sets works correctly. + """ + + @classmethod + def setUpClass(cls): + page = cls.page = dialog.keyspage + dialog.note.select(page) + page.set_keys_type = Func() + page.load_keys_list = Func() + + @classmethod + def tearDownClass(cls): + page = cls.page + del page.set_keys_type, page.load_keys_list + + def setUp(self): + d = self.page + # The following is needed for test_load_key_cfg, _delete_custom_keys. + # This may indicate a defect in some test or function. + for section in idleConf.GetSectionList('user', 'keys'): + idleConf.userCfg['keys'].remove_section(section) + changes.clear() + d.set_keys_type.called = 0 + d.load_keys_list.called = 0 + + def test_load_key_cfg(self): + tracers.detach() + d = self.page + eq = self.assertEqual + + # Use builtin keyset with no user keysets created. + idleConf.CurrentKeys = mock.Mock(return_value='IDLE Classic OSX') + d.load_key_cfg() + self.assertTrue(d.keyset_source.get()) + # builtinlist sets variable builtin_name to the CurrentKeys default. + eq(d.builtin_name.get(), 'IDLE Classic OSX') + eq(d.custom_name.get(), '- no custom keys -') + eq(d.custom_keyset_on.state(), ('disabled',)) + eq(d.set_keys_type.called, 1) + eq(d.load_keys_list.called, 1) + eq(d.load_keys_list.args, ('IDLE Classic OSX', )) + + # Builtin keyset with non-empty user keyset list. + idleConf.SetOption('keys', 'test1', 'option', 'value') + idleConf.SetOption('keys', 'test2', 'option2', 'value2') + d.load_key_cfg() + eq(d.builtin_name.get(), 'IDLE Classic OSX') + eq(d.custom_name.get(), 'test1') + eq(d.set_keys_type.called, 2) + eq(d.load_keys_list.called, 2) + eq(d.load_keys_list.args, ('IDLE Classic OSX', )) + + # Use custom keyset. + idleConf.CurrentKeys = mock.Mock(return_value='test2') + idleConf.default_keys = mock.Mock(return_value='IDLE Modern Unix') + idleConf.SetOption('main', 'Keys', 'default', '0') + d.load_key_cfg() + self.assertFalse(d.keyset_source.get()) + eq(d.builtin_name.get(), 'IDLE Modern Unix') + eq(d.custom_name.get(), 'test2') + eq(d.set_keys_type.called, 3) + eq(d.load_keys_list.called, 3) + eq(d.load_keys_list.args, ('test2', )) + + del idleConf.CurrentKeys, idleConf.default_keys + tracers.attach() + + def test_keyset_source(self): + eq = self.assertEqual + d = self.page + # Test these separately. + d.var_changed_builtin_name = Func() + d.var_changed_custom_name = Func() + # Builtin selected. + d.builtin_keyset_on.invoke() + eq(mainpage, {'Keys': {'default': 'True'}}) + eq(d.var_changed_builtin_name.called, 1) + eq(d.var_changed_custom_name.called, 0) + changes.clear() + + # Custom selected. + d.custom_keyset_on.state(('!disabled',)) + d.custom_keyset_on.invoke() + self.assertEqual(mainpage, {'Keys': {'default': 'False'}}) + eq(d.var_changed_builtin_name.called, 1) + eq(d.var_changed_custom_name.called, 1) + del d.var_changed_builtin_name, d.var_changed_custom_name + + def test_builtin_name(self): + eq = self.assertEqual + d = self.page + idleConf.userCfg['main'].remove_section('Keys') + item_list = ['IDLE Classic Windows', 'IDLE Classic OSX', + 'IDLE Modern UNIX'] + + # Not in old_keys, defaults name to first item. + d.builtinlist.SetMenu(item_list, 'IDLE Modern UNIX') + eq(mainpage, {'Keys': {'name': 'IDLE Classic Windows', + 'name2': 'IDLE Modern UNIX'}}) + eq(d.keys_message['text'], 'New key set, see Help') + eq(d.load_keys_list.called, 1) + eq(d.load_keys_list.args, ('IDLE Modern UNIX', )) + + # Not in old keys - uses name2. + changes.clear() + idleConf.SetOption('main', 'Keys', 'name', 'IDLE Classic Unix') + d.builtinlist.SetMenu(item_list, 'IDLE Modern UNIX') + eq(mainpage, {'Keys': {'name2': 'IDLE Modern UNIX'}}) + eq(d.keys_message['text'], 'New key set, see Help') + eq(d.load_keys_list.called, 2) + eq(d.load_keys_list.args, ('IDLE Modern UNIX', )) + + # Builtin name in old_keys. + changes.clear() + d.builtinlist.SetMenu(item_list, 'IDLE Classic OSX') + eq(mainpage, {'Keys': {'name': 'IDLE Classic OSX', 'name2': ''}}) + eq(d.keys_message['text'], '') + eq(d.load_keys_list.called, 3) + eq(d.load_keys_list.args, ('IDLE Classic OSX', )) + + def test_custom_name(self): + d = self.page + + # If no selections, doesn't get added. + d.customlist.SetMenu([], '- no custom keys -') + self.assertNotIn('Keys', mainpage) + self.assertEqual(d.load_keys_list.called, 0) + + # Custom name selected. + changes.clear() + d.customlist.SetMenu(['a', 'b', 'c'], 'c') + self.assertEqual(mainpage, {'Keys': {'name': 'c'}}) + self.assertEqual(d.load_keys_list.called, 1) + + def test_keybinding(self): + idleConf.SetOption('extensions', 'ZzDummy', 'enable', 'True') + d = self.page + d.custom_name.set('my custom keys') + d.bindingslist.delete(0, 'end') + d.bindingslist.insert(0, 'copy') + d.bindingslist.insert(1, 'z-in') + d.bindingslist.selection_set(0) + d.bindingslist.selection_anchor(0) + # Core binding - adds to keys. + d.keybinding.set('') + self.assertEqual(keyspage, + {'my custom keys': {'copy': ''}}) + + # Not a core binding - adds to extensions. + d.bindingslist.selection_set(1) + d.bindingslist.selection_anchor(1) + d.keybinding.set('') + self.assertEqual(extpage, + {'ZzDummy_cfgBindings': {'z-in': ''}}) + + def test_set_keys_type(self): + eq = self.assertEqual + d = self.page + del d.set_keys_type + + # Builtin keyset selected. + d.keyset_source.set(True) + d.set_keys_type() + eq(d.builtinlist['state'], NORMAL) + eq(d.customlist['state'], DISABLED) + eq(d.button_delete_custom_keys.state(), ('disabled',)) + + # Custom keyset selected. + d.keyset_source.set(False) + d.set_keys_type() + eq(d.builtinlist['state'], DISABLED) + eq(d.custom_keyset_on.state(), ('selected',)) + eq(d.customlist['state'], NORMAL) + eq(d.button_delete_custom_keys.state(), ()) + d.set_keys_type = Func() + + def test_get_new_keys(self): + eq = self.assertEqual + d = self.page + orig_getkeysdialog = configdialog.GetKeysWindow + gkd = configdialog.GetKeysWindow = Func(return_self=True) + gnkn = d.get_new_keys_name = Func() + + d.button_new_keys.state(('!disabled',)) + d.bindingslist.delete(0, 'end') + d.bindingslist.insert(0, 'copy - ') + d.bindingslist.selection_set(0) + d.bindingslist.selection_anchor(0) + d.keybinding.set('Key-a') + d.keyset_source.set(True) # Default keyset. + + # Default keyset; no change to binding. + gkd.result = '' + d.button_new_keys.invoke() + eq(d.bindingslist.get('anchor'), 'copy - ') + # Keybinding isn't changed when there isn't a change entered. + eq(d.keybinding.get(), 'Key-a') + + # Default keyset; binding changed. + gkd.result = '' + # No keyset name selected therefore binding not saved. + gnkn.result = '' + d.button_new_keys.invoke() + eq(gnkn.called, 1) + eq(d.bindingslist.get('anchor'), 'copy - ') + # Keyset name selected. + gnkn.result = 'My New Key Set' + d.button_new_keys.invoke() + eq(d.custom_name.get(), gnkn.result) + eq(d.bindingslist.get('anchor'), 'copy - ') + eq(d.keybinding.get(), '') + + # User keyset; binding changed. + d.keyset_source.set(False) # Custom keyset. + gnkn.called = 0 + gkd.result = '' + d.button_new_keys.invoke() + eq(gnkn.called, 0) + eq(d.bindingslist.get('anchor'), 'copy - ') + eq(d.keybinding.get(), '') + + del d.get_new_keys_name + configdialog.GetKeysWindow = orig_getkeysdialog + + def test_get_new_keys_name(self): + orig_sectionname = configdialog.SectionName + sn = configdialog.SectionName = Func(return_self=True) + d = self.page + + sn.result = 'New Keys' + self.assertEqual(d.get_new_keys_name(''), 'New Keys') + + configdialog.SectionName = orig_sectionname + + def test_save_as_new_key_set(self): + d = self.page + gnkn = d.get_new_keys_name = Func() + d.keyset_source.set(True) + + # No name entered. + gnkn.result = '' + d.button_save_custom_keys.invoke() + + # Name entered. + gnkn.result = 'my new key set' + gnkn.called = 0 + self.assertNotIn(gnkn.result, idleConf.userCfg['keys']) + d.button_save_custom_keys.invoke() + self.assertIn(gnkn.result, idleConf.userCfg['keys']) + + del d.get_new_keys_name + + def test_on_bindingslist_select(self): + d = self.page + b = d.bindingslist + b.delete(0, 'end') + b.insert(0, 'copy') + b.insert(1, 'find') + b.activate(0) + + b.focus_force() + b.see(1) + b.update() + x, y, dx, dy = b.bbox(1) + x += dx // 2 + y += dy // 2 + b.event_generate('', x=0, y=0) + b.event_generate('', x=x, y=y) + b.event_generate('', x=x, y=y) + b.event_generate('', x=x, y=y) + self.assertEqual(b.get('anchor'), 'find') + self.assertEqual(d.button_new_keys.state(), ()) + + def test_create_new_key_set_and_save_new_key_set(self): + eq = self.assertEqual + d = self.page + + # Use default as previously active keyset. + d.keyset_source.set(True) + d.builtin_name.set('IDLE Classic Windows') + first_new = 'my new custom key set' + second_new = 'my second custom keyset' + + # No changes, so keysets are an exact copy. + self.assertNotIn(first_new, idleConf.userCfg) + d.create_new_key_set(first_new) + eq(idleConf.GetSectionList('user', 'keys'), [first_new]) + eq(idleConf.GetKeySet('IDLE Classic Windows'), + idleConf.GetKeySet(first_new)) + eq(d.custom_name.get(), first_new) + self.assertFalse(d.keyset_source.get()) # Use custom set. + eq(d.set_keys_type.called, 1) + + # Test that changed keybindings are in new keyset. + changes.add_option('keys', first_new, 'copy', '') + self.assertNotIn(second_new, idleConf.userCfg) + d.create_new_key_set(second_new) + eq(idleConf.GetSectionList('user', 'keys'), [first_new, second_new]) + self.assertNotEqual(idleConf.GetKeySet(first_new), + idleConf.GetKeySet(second_new)) + # Check that difference in keysets was in option `copy` from `changes`. + idleConf.SetOption('keys', first_new, 'copy', '') + eq(idleConf.GetKeySet(first_new), idleConf.GetKeySet(second_new)) + + def test_load_keys_list(self): + eq = self.assertEqual + d = self.page + gks = idleConf.GetKeySet = Func() + del d.load_keys_list + b = d.bindingslist + + b.delete(0, 'end') + b.insert(0, '<>') + b.insert(1, '<>') + gks.result = {'<>': ['', ''], + '<>': [''], + '<>': ['']} + changes.add_option('keys', 'my keys', 'spam', '') + expected = ('copy - ', + 'force-open-completions - ', + 'spam - ') + + # No current selection. + d.load_keys_list('my keys') + eq(b.get(0, 'end'), expected) + eq(b.get('anchor'), '') + eq(b.curselection(), ()) + + # Check selection. + b.selection_set(1) + b.selection_anchor(1) + d.load_keys_list('my keys') + eq(b.get(0, 'end'), expected) + eq(b.get('anchor'), 'force-open-completions - ') + eq(b.curselection(), (1, )) + + # Change selection. + b.selection_set(2) + b.selection_anchor(2) + d.load_keys_list('my keys') + eq(b.get(0, 'end'), expected) + eq(b.get('anchor'), 'spam - ') + eq(b.curselection(), (2, )) + d.load_keys_list = Func() + + del idleConf.GetKeySet + + def test_delete_custom_keys(self): + eq = self.assertEqual + d = self.page + d.button_delete_custom_keys.state(('!disabled',)) + yesno = d.askyesno = Func() + dialog.deactivate_current_config = Func() + dialog.activate_config_changes = Func() + + keyset_name = 'spam key set' + idleConf.userCfg['keys'].SetOption(keyset_name, 'name', 'value') + keyspage[keyset_name] = {'option': 'True'} + + keyset_name2 = 'other key set' + idleConf.userCfg['keys'].SetOption(keyset_name2, 'name', 'value') + keyspage[keyset_name2] = {'option': 'False'} + + # Force custom keyset. + d.custom_keyset_on.state(('!disabled',)) + d.custom_keyset_on.invoke() + d.custom_name.set(keyset_name) + + # Cancel deletion. + yesno.result = False + d.button_delete_custom_keys.invoke() + eq(yesno.called, 1) + eq(keyspage[keyset_name], {'option': 'True'}) + eq(idleConf.GetSectionList('user', 'keys'), [keyset_name, keyset_name2]) + eq(dialog.deactivate_current_config.called, 0) + eq(dialog.activate_config_changes.called, 0) + eq(d.set_keys_type.called, 0) + + # Confirm deletion. + yesno.result = True + d.button_delete_custom_keys.invoke() + eq(yesno.called, 2) + self.assertNotIn(keyset_name, keyspage) + eq(idleConf.GetSectionList('user', 'keys'), [keyset_name2]) + eq(d.custom_keyset_on.state(), ()) + eq(d.custom_name.get(), keyset_name2) + eq(dialog.deactivate_current_config.called, 1) + eq(dialog.activate_config_changes.called, 1) + eq(d.set_keys_type.called, 1) + + # Confirm deletion of second keyset - empties list. + d.custom_name.set(keyset_name2) + yesno.result = True + d.button_delete_custom_keys.invoke() + eq(yesno.called, 3) + self.assertNotIn(keyset_name, keyspage) + eq(idleConf.GetSectionList('user', 'keys'), []) + eq(d.custom_keyset_on.state(), ('disabled',)) + eq(d.custom_name.get(), '- no custom keys -') + eq(dialog.deactivate_current_config.called, 2) + eq(dialog.activate_config_changes.called, 2) + eq(d.set_keys_type.called, 2) + + del dialog.activate_config_changes, dialog.deactivate_current_config + del d.askyesno + + +class WinPageTest(unittest.TestCase): + """Test that general tab widgets enable users to make changes. + + Test that widget actions set vars, that var changes add + options to changes. + """ + @classmethod + def setUpClass(cls): + page = cls.page = dialog.winpage + dialog.note.select(page) + page.update() + + def setUp(self): + changes.clear() + + def test_load_windows_cfg(self): + # Set to wrong values, load, check right values. + eq = self.assertEqual + d = self.page + d.startup_edit.set(1) + d.win_width.set(1) + d.win_height.set(1) + d.load_windows_cfg() + eq(d.startup_edit.get(), 0) + eq(d.win_width.get(), '80') + eq(d.win_height.get(), '40') + + def test_startup(self): + d = self.page + d.startup_editor_on.invoke() + self.assertEqual(mainpage, + {'General': {'editor-on-startup': '1'}}) + changes.clear() + d.startup_shell_on.invoke() + self.assertEqual(mainpage, + {'General': {'editor-on-startup': '0'}}) + + def test_editor_size(self): + d = self.page + d.win_height_int.delete(0, 'end') + d.win_height_int.insert(0, '11') + self.assertEqual(mainpage, {'EditorWindow': {'height': '11'}}) + changes.clear() + d.win_width_int.delete(0, 'end') + d.win_width_int.insert(0, '11') + self.assertEqual(mainpage, {'EditorWindow': {'width': '11'}}) + + def test_indent_spaces(self): + d = self.page + d.indent_chooser.set(6) + self.assertEqual(d.indent_spaces.get(), '6') + self.assertEqual(mainpage, {'Indent': {'num-spaces': '6'}}) + + def test_cursor_blink(self): + self.page.cursor_blink_bool.invoke() + self.assertEqual(mainpage, {'EditorWindow': {'cursor-blink': 'False'}}) + + def test_autocomplete_wait(self): + self.page.auto_wait_int.delete(0, 'end') + self.page.auto_wait_int.insert(0, '11') + self.assertEqual(extpage, {'AutoComplete': {'popupwait': '11'}}) + + def test_parenmatch(self): + d = self.page + eq = self.assertEqual + d.paren_style_type['menu'].invoke(0) + eq(extpage, {'ParenMatch': {'style': 'opener'}}) + changes.clear() + d.paren_flash_time.delete(0, 'end') + d.paren_flash_time.insert(0, '11') + eq(extpage, {'ParenMatch': {'flash-delay': '11'}}) + changes.clear() + d.bell_on.invoke() + eq(extpage, {'ParenMatch': {'bell': 'False'}}) + + def test_paragraph(self): + self.page.format_width_int.delete(0, 'end') + self.page.format_width_int.insert(0, '11') + self.assertEqual(extpage, {'FormatParagraph': {'max-width': '11'}}) + + +class ShedPageTest(unittest.TestCase): + """Test that shed tab widgets enable users to make changes. + + Test that widget actions set vars, that var changes add + options to changes. + """ + @classmethod + def setUpClass(cls): + page = cls.page = dialog.shedpage + dialog.note.select(page) + page.update() + + def setUp(self): + changes.clear() + + def test_load_shelled_cfg(self): + # Set to wrong values, load, check right values. + eq = self.assertEqual + d = self.page + d.autosave.set(1) + d.load_shelled_cfg() + eq(d.autosave.get(), 0) + + def test_autosave(self): + d = self.page + d.save_auto_on.invoke() + self.assertEqual(mainpage, {'General': {'autosave': '1'}}) + d.save_ask_on.invoke() + self.assertEqual(mainpage, {'General': {'autosave': '0'}}) + + def test_context(self): + self.page.context_int.delete(0, 'end') + self.page.context_int.insert(0, '1') + self.assertEqual(extpage, {'CodeContext': {'maxlines': '1'}}) + + +#unittest.skip("Nothing here yet TODO") +class ExtPageTest(unittest.TestCase): + """Test that the help source list works correctly.""" + @classmethod + def setUpClass(cls): + page = dialog.extpage + dialog.note.select(page) + + +class HelpSourceTest(unittest.TestCase): + """Test that the help source list works correctly.""" + @classmethod + def setUpClass(cls): + page = dialog.extpage + dialog.note.select(page) + frame = cls.frame = page.frame_help + frame.set = frame.set_add_delete_state = Func() + frame.upc = frame.update_help_changes = Func() + frame.update() + + @classmethod + def tearDownClass(cls): + frame = cls.frame + del frame.set, frame.set_add_delete_state + del frame.upc, frame.update_help_changes + frame.helplist.delete(0, 'end') + frame.user_helplist.clear() + + def setUp(self): + changes.clear() + + def test_load_helplist(self): + eq = self.assertEqual + fr = self.frame + fr.helplist.insert('end', 'bad') + fr.user_helplist = ['bad', 'worse'] + idleConf.SetOption('main', 'HelpFiles', '1', 'name;file') + fr.load_helplist() + eq(fr.helplist.get(0, 'end'), ('name',)) + eq(fr.user_helplist, [('name', 'file', '1')]) + + def test_source_selected(self): + fr = self.frame + fr.set = fr.set_add_delete_state + fr.upc = fr.update_help_changes + helplist = fr.helplist + dex = 'end' + helplist.insert(dex, 'source') + helplist.activate(dex) + + helplist.focus_force() + helplist.see(dex) + helplist.update() + x, y, dx, dy = helplist.bbox(dex) + x += dx // 2 + y += dy // 2 + fr.set.called = fr.upc.called = 0 + helplist.event_generate('', x=0, y=0) + helplist.event_generate('', x=x, y=y) + helplist.event_generate('', x=x, y=y) + helplist.event_generate('', x=x, y=y) + self.assertEqual(helplist.get('anchor'), 'source') + self.assertTrue(fr.set.called) + self.assertFalse(fr.upc.called) + + def test_set_add_delete_state(self): + # Call with 0 items, 1 unselected item, 1 selected item. + eq = self.assertEqual + fr = self.frame + del fr.set_add_delete_state # Unmask method. + sad = fr.set_add_delete_state + h = fr.helplist + + h.delete(0, 'end') + sad() + eq(fr.button_helplist_edit.state(), ('disabled',)) + eq(fr.button_helplist_remove.state(), ('disabled',)) + + h.insert(0, 'source') + sad() + eq(fr.button_helplist_edit.state(), ('disabled',)) + eq(fr.button_helplist_remove.state(), ('disabled',)) + + h.selection_set(0) + sad() + eq(fr.button_helplist_edit.state(), ()) + eq(fr.button_helplist_remove.state(), ()) + fr.set_add_delete_state = Func() # Mask method. + + def test_helplist_item_add(self): + # Call without and twice with HelpSource result. + # Double call enables check on order. + eq = self.assertEqual + orig_helpsource = configdialog.HelpSource + hs = configdialog.HelpSource = Func(return_self=True) + fr = self.frame + fr.helplist.delete(0, 'end') + fr.user_helplist.clear() + fr.set.called = fr.upc.called = 0 + + hs.result = '' + fr.helplist_item_add() + self.assertTrue(list(fr.helplist.get(0, 'end')) == + fr.user_helplist == []) + self.assertFalse(fr.upc.called) + + hs.result = ('name1', 'file1') + fr.helplist_item_add() + hs.result = ('name2', 'file2') + fr.helplist_item_add() + eq(fr.helplist.get(0, 'end'), ('name1', 'name2')) + eq(fr.user_helplist, [('name1', 'file1'), ('name2', 'file2')]) + eq(fr.upc.called, 2) + self.assertFalse(fr.set.called) + + configdialog.HelpSource = orig_helpsource + + def test_helplist_item_edit(self): + # Call without and with HelpSource change. + eq = self.assertEqual + orig_helpsource = configdialog.HelpSource + hs = configdialog.HelpSource = Func(return_self=True) + fr = self.frame + fr.helplist.delete(0, 'end') + fr.helplist.insert(0, 'name1') + fr.helplist.selection_set(0) + fr.helplist.selection_anchor(0) + fr.user_helplist.clear() + fr.user_helplist.append(('name1', 'file1')) + fr.set.called = fr.upc.called = 0 + + hs.result = '' + fr.helplist_item_edit() + hs.result = ('name1', 'file1') + fr.helplist_item_edit() + eq(fr.helplist.get(0, 'end'), ('name1',)) + eq(fr.user_helplist, [('name1', 'file1')]) + self.assertFalse(fr.upc.called) + + hs.result = ('name2', 'file2') + fr.helplist_item_edit() + eq(fr.helplist.get(0, 'end'), ('name2',)) + eq(fr.user_helplist, [('name2', 'file2')]) + self.assertTrue(fr.upc.called == fr.set.called == 1) + + configdialog.HelpSource = orig_helpsource + + def test_helplist_item_remove(self): + eq = self.assertEqual + fr = self.frame + fr.helplist.delete(0, 'end') + fr.helplist.insert(0, 'name1') + fr.helplist.selection_set(0) + fr.helplist.selection_anchor(0) + fr.user_helplist.clear() + fr.user_helplist.append(('name1', 'file1')) + fr.set.called = fr.upc.called = 0 + + fr.helplist_item_remove() + eq(fr.helplist.get(0, 'end'), ()) + eq(fr.user_helplist, []) + self.assertTrue(fr.upc.called == fr.set.called == 1) + + def test_update_help_changes(self): + fr = self.frame + del fr.update_help_changes + fr.user_helplist.clear() + fr.user_helplist.append(('name1', 'file1')) + fr.user_helplist.append(('name2', 'file2')) + + fr.update_help_changes() + self.assertEqual(mainpage['HelpFiles'], + {'1': 'name1;file1', '2': 'name2;file2'}) + fr.update_help_changes = Func() + + +class VarTraceTest(unittest.TestCase): + + @classmethod + def setUpClass(cls): + cls.tracers = configdialog.VarTrace() + cls.iv = IntVar(root) + cls.bv = BooleanVar(root) + + @classmethod + def tearDownClass(cls): + del cls.tracers, cls.iv, cls.bv + + def setUp(self): + self.tracers.clear() + self.called = 0 + + def var_changed_increment(self, *params): + self.called += 13 + + def var_changed_boolean(self, *params): + pass + + def test_init(self): + tr = self.tracers + tr.__init__() + self.assertEqual(tr.untraced, []) + self.assertEqual(tr.traced, []) + + def test_clear(self): + tr = self.tracers + tr.untraced.append(0) + tr.traced.append(1) + tr.clear() + self.assertEqual(tr.untraced, []) + self.assertEqual(tr.traced, []) + + def test_add(self): + tr = self.tracers + func = Func() + cb = tr.make_callback = mock.Mock(return_value=func) + + iv = tr.add(self.iv, self.var_changed_increment) + self.assertIs(iv, self.iv) + bv = tr.add(self.bv, self.var_changed_boolean) + self.assertIs(bv, self.bv) + + sv = StringVar(root) + sv2 = tr.add(sv, ('main', 'section', 'option')) + self.assertIs(sv2, sv) + cb.assert_called_once() + cb.assert_called_with(sv, ('main', 'section', 'option')) + + expected = [(iv, self.var_changed_increment), + (bv, self.var_changed_boolean), + (sv, func)] + self.assertEqual(tr.traced, []) + self.assertEqual(tr.untraced, expected) + + del tr.make_callback + + def test_make_callback(self): + cb = self.tracers.make_callback(self.iv, ('main', 'section', 'option')) + self.assertTrue(callable(cb)) + self.iv.set(42) + # Not attached, so set didn't invoke the callback. + self.assertNotIn('section', changes['main']) + # Invoke callback manually. + cb() + self.assertIn('section', changes['main']) + self.assertEqual(changes['main']['section']['option'], '42') + changes.clear() + + def test_attach_detach(self): + tr = self.tracers + iv = tr.add(self.iv, self.var_changed_increment) + bv = tr.add(self.bv, self.var_changed_boolean) + expected = [(iv, self.var_changed_increment), + (bv, self.var_changed_boolean)] + + # Attach callbacks and test call increment. + tr.attach() + self.assertEqual(tr.untraced, []) + self.assertCountEqual(tr.traced, expected) + iv.set(1) + self.assertEqual(iv.get(), 1) + self.assertEqual(self.called, 13) + + # Check that only one callback is attached to a variable. + # If more than one callback were attached, then var_changed_increment + # would be called twice and the counter would be 2. + self.called = 0 + tr.attach() + iv.set(1) + self.assertEqual(self.called, 13) + + # Detach callbacks. + self.called = 0 + tr.detach() + self.assertEqual(tr.traced, []) + self.assertCountEqual(tr.untraced, expected) + iv.set(1) + self.assertEqual(self.called, 0) + + +if __name__ == '__main__': + unittest.main(verbosity=2) diff --git a/micromamba_root/envs/pytorch_env/Lib/idlelib/idle_test/test_debugger.py b/micromamba_root/envs/pytorch_env/Lib/idlelib/idle_test/test_debugger.py new file mode 100644 index 0000000000000000000000000000000000000000..d1c9638dd5d711e39b13522d1e2a74cac136a85a --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/idlelib/idle_test/test_debugger.py @@ -0,0 +1,297 @@ +"""Test debugger, coverage 66% + +Try to make tests pass with draft bdbx, which may replace bdb in 3.13+. +""" + +from idlelib import debugger +from collections import namedtuple +from textwrap import dedent +from tkinter import Tk + +from test.support import requires +import unittest +from unittest import mock +from unittest.mock import Mock, patch + +"""A test python script for the debug tests.""" +TEST_CODE = dedent(""" + i = 1 + i += 2 + if i == 3: + print(i) + """) + + +class MockFrame: + "Minimal mock frame." + + def __init__(self, code, lineno): + self.f_code = code + self.f_lineno = lineno + + +class IdbTest(unittest.TestCase): + + @classmethod + def setUpClass(cls): + cls.gui = Mock() + cls.idb = debugger.Idb(cls.gui) + + # Create test and code objects to simulate a debug session. + code_obj = compile(TEST_CODE, 'idlelib/file.py', mode='exec') + frame1 = MockFrame(code_obj, 1) + frame1.f_back = None + frame2 = MockFrame(code_obj, 2) + frame2.f_back = frame1 + cls.frame = frame2 + cls.msg = 'file.py:2: ()' + + def test_init(self): + self.assertIs(self.idb.gui, self.gui) + # Won't test super call since two Bdbs are very different. + + def test_user_line(self): + # Test that .user_line() creates a string message for a frame. + self.gui.interaction = Mock() + self.idb.user_line(self.frame) + self.gui.interaction.assert_called_once_with(self.msg, self.frame) + + def test_user_exception(self): + # Test that .user_exception() creates a string message for a frame. + exc_info = (type(ValueError), ValueError(), None) + self.gui.interaction = Mock() + self.idb.user_exception(self.frame, exc_info) + self.gui.interaction.assert_called_once_with( + self.msg, self.frame, exc_info) + + +class FunctionTest(unittest.TestCase): + # Test module functions together. + + def test_functions(self): + rpc_obj = compile(TEST_CODE,'rpc.py', mode='exec') + rpc_frame = MockFrame(rpc_obj, 2) + rpc_frame.f_back = rpc_frame + self.assertTrue(debugger._in_rpc_code(rpc_frame)) + self.assertEqual(debugger._frame2message(rpc_frame), + 'rpc.py:2: ()') + + code_obj = compile(TEST_CODE, 'idlelib/debugger.py', mode='exec') + code_frame = MockFrame(code_obj, 1) + code_frame.f_back = None + self.assertFalse(debugger._in_rpc_code(code_frame)) + self.assertEqual(debugger._frame2message(code_frame), + 'debugger.py:1: ()') + + code_frame.f_back = code_frame + self.assertFalse(debugger._in_rpc_code(code_frame)) + code_frame.f_back = rpc_frame + self.assertTrue(debugger._in_rpc_code(code_frame)) + + +class DebuggerTest(unittest.TestCase): + "Tests for Debugger that do not need a real root." + + @classmethod + def setUpClass(cls): + cls.pyshell = Mock() + cls.pyshell.root = Mock() + cls.idb = Mock() + with patch.object(debugger.Debugger, 'make_gui'): + cls.debugger = debugger.Debugger(cls.pyshell, cls.idb) + cls.debugger.root = Mock() + + def test_cont(self): + self.debugger.cont() + self.idb.set_continue.assert_called_once() + + def test_step(self): + self.debugger.step() + self.idb.set_step.assert_called_once() + + def test_quit(self): + self.debugger.quit() + self.idb.set_quit.assert_called_once() + + def test_next(self): + with patch.object(self.debugger, 'frame') as frame: + self.debugger.next() + self.idb.set_next.assert_called_once_with(frame) + + def test_ret(self): + with patch.object(self.debugger, 'frame') as frame: + self.debugger.ret() + self.idb.set_return.assert_called_once_with(frame) + + def test_clear_breakpoint(self): + self.debugger.clear_breakpoint('test.py', 4) + self.idb.clear_break.assert_called_once_with('test.py', 4) + + def test_clear_file_breaks(self): + self.debugger.clear_file_breaks('test.py') + self.idb.clear_all_file_breaks.assert_called_once_with('test.py') + + def test_set_load_breakpoints(self): + # Test the .load_breakpoints() method calls idb. + FileIO = namedtuple('FileIO', 'filename') + + class MockEditWindow(object): + def __init__(self, fn, breakpoints): + self.io = FileIO(fn) + self.breakpoints = breakpoints + + self.pyshell.flist = Mock() + self.pyshell.flist.inversedict = ( + MockEditWindow('test1.py', [4, 4]), + MockEditWindow('test2.py', [13, 44, 45]), + ) + self.debugger.set_breakpoint('test0.py', 1) + self.idb.set_break.assert_called_once_with('test0.py', 1) + self.debugger.load_breakpoints() # Call set_breakpoint 5 times. + self.idb.set_break.assert_has_calls( + [mock.call('test0.py', 1), + mock.call('test1.py', 4), + mock.call('test1.py', 4), + mock.call('test2.py', 13), + mock.call('test2.py', 44), + mock.call('test2.py', 45)]) + + def test_sync_source_line(self): + # Test that .sync_source_line() will set the flist.gotofileline with fixed frame. + test_code = compile(TEST_CODE, 'test_sync.py', 'exec') + test_frame = MockFrame(test_code, 1) + self.debugger.frame = test_frame + + self.debugger.flist = Mock() + with patch('idlelib.debugger.os.path.exists', return_value=True): + self.debugger.sync_source_line() + self.debugger.flist.gotofileline.assert_called_once_with('test_sync.py', 1) + + +class DebuggerGuiTest(unittest.TestCase): + """Tests for debugger.Debugger that need tk root. + + close needs debugger.top set in make_gui. + """ + + @classmethod + def setUpClass(cls): + requires('gui') + cls.root = root = Tk() + root.withdraw() + cls.pyshell = Mock() + cls.pyshell.root = root + cls.idb = Mock() +# stack tests fail with debugger here. +## cls.debugger = debugger.Debugger(cls.pyshell, cls.idb) +## cls.debugger.root = root +## # real root needed for real make_gui +## # run, interacting, abort_loop + + @classmethod + def tearDownClass(cls): + cls.root.destroy() + del cls.root + + def setUp(self): + self.debugger = debugger.Debugger(self.pyshell, self.idb) + self.debugger.root = self.root + # real root needed for real make_gui + # run, interacting, abort_loop + + def test_run_debugger(self): + self.debugger.run(1, 'two') + self.idb.run.assert_called_once_with(1, 'two') + self.assertEqual(self.debugger.interacting, 0) + + def test_close(self): + # Test closing the window in an idle state. + self.debugger.close() + self.pyshell.close_debugger.assert_called_once() + + def test_show_stack(self): + self.debugger.show_stack() + self.assertEqual(self.debugger.stackviewer.gui, self.debugger) + + def test_show_stack_with_frame(self): + test_frame = MockFrame(None, None) + self.debugger.frame = test_frame + + # Reset the stackviewer to force it to be recreated. + self.debugger.stackviewer = None + self.idb.get_stack.return_value = ([], 0) + self.debugger.show_stack() + + # Check that the newly created stackviewer has the test gui as a field. + self.assertEqual(self.debugger.stackviewer.gui, self.debugger) + self.idb.get_stack.assert_called_once_with(test_frame, None) + + +class StackViewerTest(unittest.TestCase): + + @classmethod + def setUpClass(cls): + requires('gui') + cls.root = Tk() + cls.root.withdraw() + + @classmethod + def tearDownClass(cls): + cls.root.destroy() + del cls.root + + def setUp(self): + self.code = compile(TEST_CODE, 'test_stackviewer.py', 'exec') + self.stack = [ + (MockFrame(self.code, 1), 1), + (MockFrame(self.code, 2), 2) + ] + # Create a stackviewer and load the test stack. + self.sv = debugger.StackViewer(self.root, None, None) + self.sv.load_stack(self.stack) + + def test_init(self): + # Test creation of StackViewer. + gui = None + flist = None + master_window = self.root + sv = debugger.StackViewer(master_window, flist, gui) + self.assertTrue(hasattr(sv, 'stack')) + + def test_load_stack(self): + # Test the .load_stack() method against a fixed test stack. + # Check the test stack is assigned and the list contains the repr of them. + self.assertEqual(self.sv.stack, self.stack) + self.assertTrue('?.(), line 1:' in self.sv.get(0)) + self.assertEqual(self.sv.get(1), '?.(), line 2: ') + + def test_show_source(self): + # Test the .show_source() method against a fixed test stack. + # Patch out the file list to monitor it + self.sv.flist = Mock() + # Patch out isfile to pretend file exists. + with patch('idlelib.debugger.os.path.isfile', return_value=True) as isfile: + self.sv.show_source(1) + isfile.assert_called_once_with('test_stackviewer.py') + self.sv.flist.open.assert_called_once_with('test_stackviewer.py') + + +class NameSpaceTest(unittest.TestCase): + + @classmethod + def setUpClass(cls): + requires('gui') + cls.root = Tk() + cls.root.withdraw() + + @classmethod + def tearDownClass(cls): + cls.root.destroy() + del cls.root + + def test_init(self): + debugger.NamespaceViewer(self.root, 'Test') + + +if __name__ == '__main__': + unittest.main(verbosity=2) diff --git a/micromamba_root/envs/pytorch_env/Lib/idlelib/idle_test/test_debugger_r.py b/micromamba_root/envs/pytorch_env/Lib/idlelib/idle_test/test_debugger_r.py new file mode 100644 index 0000000000000000000000000000000000000000..cf8af05fe27e77b7a4ec17c2bd9dfcd163a4750e --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/idlelib/idle_test/test_debugger_r.py @@ -0,0 +1,36 @@ +"Test debugger_r, coverage 30%." + +from idlelib import debugger_r +import unittest + +# Boilerplate likely to be needed for future test classes. +##from test.support import requires +##from tkinter import Tk +##class Test(unittest.TestCase): +## @classmethod +## def setUpClass(cls): +## requires('gui') +## cls.root = Tk() +## @classmethod +## def tearDownClass(cls): +## cls.root.destroy() + +# GUIProxy, IdbAdapter, FrameProxy, CodeProxy, DictProxy, +# GUIAdapter, IdbProxy, and 7 functions still need tests. + +class IdbAdapterTest(unittest.TestCase): + + def test_dict_item_noattr(self): # Issue 33065. + + class BinData: + def __repr__(self): + return self.length + + debugger_r.dicttable[0] = {'BinData': BinData()} + idb = debugger_r.IdbAdapter(None) + self.assertTrue(idb.dict_item(0, 'BinData')) + debugger_r.dicttable.clear() + + +if __name__ == '__main__': + unittest.main(verbosity=2) diff --git a/micromamba_root/envs/pytorch_env/Lib/idlelib/idle_test/test_debugobj.py b/micromamba_root/envs/pytorch_env/Lib/idlelib/idle_test/test_debugobj.py new file mode 100644 index 0000000000000000000000000000000000000000..90ace4e1bc4f9ef8ca24028c4c01b985412fdc6d --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/idlelib/idle_test/test_debugobj.py @@ -0,0 +1,57 @@ +"Test debugobj, coverage 40%." + +from idlelib import debugobj +import unittest + + +class ObjectTreeItemTest(unittest.TestCase): + + def test_init(self): + ti = debugobj.ObjectTreeItem('label', 22) + self.assertEqual(ti.labeltext, 'label') + self.assertEqual(ti.object, 22) + self.assertEqual(ti.setfunction, None) + + +class ClassTreeItemTest(unittest.TestCase): + + def test_isexpandable(self): + ti = debugobj.ClassTreeItem('label', 0) + self.assertTrue(ti.IsExpandable()) + + +class AtomicObjectTreeItemTest(unittest.TestCase): + + def test_isexpandable(self): + ti = debugobj.AtomicObjectTreeItem('label', 0) + self.assertFalse(ti.IsExpandable()) + + +class SequenceTreeItemTest(unittest.TestCase): + + def test_isexpandable(self): + ti = debugobj.SequenceTreeItem('label', ()) + self.assertFalse(ti.IsExpandable()) + ti = debugobj.SequenceTreeItem('label', (1,)) + self.assertTrue(ti.IsExpandable()) + + def test_keys(self): + ti = debugobj.SequenceTreeItem('label', 'abc') + self.assertEqual(list(ti.keys()), [0, 1, 2]) # keys() is a range. + + +class DictTreeItemTest(unittest.TestCase): + + def test_isexpandable(self): + ti = debugobj.DictTreeItem('label', {}) + self.assertFalse(ti.IsExpandable()) + ti = debugobj.DictTreeItem('label', {1:1}) + self.assertTrue(ti.IsExpandable()) + + def test_keys(self): + ti = debugobj.DictTreeItem('label', {1:1, 0:0, 2:2}) + self.assertEqual(ti.keys(), [0, 1, 2]) # keys() is a sorted list. + + +if __name__ == '__main__': + unittest.main(verbosity=2) diff --git a/micromamba_root/envs/pytorch_env/Lib/idlelib/idle_test/test_debugobj_r.py b/micromamba_root/envs/pytorch_env/Lib/idlelib/idle_test/test_debugobj_r.py new file mode 100644 index 0000000000000000000000000000000000000000..86e51b6cb2cb22d31aa9c4a1d8cc5b713b8eec34 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/idlelib/idle_test/test_debugobj_r.py @@ -0,0 +1,22 @@ +"Test debugobj_r, coverage 56%." + +from idlelib import debugobj_r +import unittest + + +class WrappedObjectTreeItemTest(unittest.TestCase): + + def test_getattr(self): + ti = debugobj_r.WrappedObjectTreeItem(list) + self.assertEqual(ti.append, list.append) + +class StubObjectTreeItemTest(unittest.TestCase): + + def test_init(self): + ti = debugobj_r.StubObjectTreeItem('socket', 1111) + self.assertEqual(ti.sockio, 'socket') + self.assertEqual(ti.oid, 1111) + + +if __name__ == '__main__': + unittest.main(verbosity=2) diff --git a/micromamba_root/envs/pytorch_env/Lib/idlelib/idle_test/test_delegator.py b/micromamba_root/envs/pytorch_env/Lib/idlelib/idle_test/test_delegator.py new file mode 100644 index 0000000000000000000000000000000000000000..922416297a42e028bc0db33fb1f5195190b29f6e --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/idlelib/idle_test/test_delegator.py @@ -0,0 +1,44 @@ +"Test delegator, coverage 100%." + +from idlelib.delegator import Delegator +import unittest + + +class DelegatorTest(unittest.TestCase): + + def test_mydel(self): + # Test a simple use scenario. + + # Initialize an int delegator. + mydel = Delegator(int) + self.assertIs(mydel.delegate, int) + self.assertEqual(mydel._Delegator__cache, set()) + # Trying to access a non-attribute of int fails. + self.assertRaises(AttributeError, mydel.__getattr__, 'xyz') + + # Add real int attribute 'bit_length' by accessing it. + bl = mydel.bit_length + self.assertIs(bl, int.bit_length) + self.assertIs(mydel.__dict__['bit_length'], int.bit_length) + self.assertEqual(mydel._Delegator__cache, {'bit_length'}) + + # Add attribute 'numerator'. + mydel.numerator + self.assertEqual(mydel._Delegator__cache, {'bit_length', 'numerator'}) + + # Delete 'numerator'. + del mydel.numerator + self.assertNotIn('numerator', mydel.__dict__) + # The current implementation leaves it in the name cache. + # self.assertIn('numerator', mydel._Delegator__cache) + # However, this is not required and not part of the specification + + # Change delegate to float, first resetting the attributes. + mydel.setdelegate(float) # calls resetcache + self.assertNotIn('bit_length', mydel.__dict__) + self.assertEqual(mydel._Delegator__cache, set()) + self.assertIs(mydel.delegate, float) + + +if __name__ == '__main__': + unittest.main(verbosity=2, exit=2) diff --git a/micromamba_root/envs/pytorch_env/Lib/idlelib/idle_test/test_editmenu.py b/micromamba_root/envs/pytorch_env/Lib/idlelib/idle_test/test_editmenu.py new file mode 100644 index 0000000000000000000000000000000000000000..17478473a3d1b2711fd8e1ffa7f6076c540c4386 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/idlelib/idle_test/test_editmenu.py @@ -0,0 +1,74 @@ +'''Test (selected) IDLE Edit menu items. + +Edit modules have their own test files +''' +from test.support import requires +requires('gui') +import tkinter as tk +from tkinter import ttk +import unittest +from idlelib import pyshell + +class PasteTest(unittest.TestCase): + '''Test pasting into widgets that allow pasting. + + On X11, replacing selections requires tk fix. + ''' + @classmethod + def setUpClass(cls): + cls.root = root = tk.Tk() + cls.root.withdraw() + pyshell.fix_x11_paste(root) + cls.text = tk.Text(root) + cls.entry = tk.Entry(root) + cls.tentry = ttk.Entry(root) + cls.spin = tk.Spinbox(root) + root.clipboard_clear() + root.clipboard_append('two') + + @classmethod + def tearDownClass(cls): + del cls.text, cls.entry, cls.tentry + cls.root.clipboard_clear() + cls.root.update_idletasks() + cls.root.destroy() + del cls.root + + def test_paste_text(self): + "Test pasting into text with and without a selection." + text = self.text + for tag, ans in ('', 'onetwo\n'), ('sel', 'two\n'): + with self.subTest(tag=tag, ans=ans): + text.delete('1.0', 'end') + text.insert('1.0', 'one', tag) + text.event_generate('<>') + self.assertEqual(text.get('1.0', 'end'), ans) + + def test_paste_entry(self): + "Test pasting into an entry with and without a selection." + # Generated <> fails for tk entry without empty select + # range for 'no selection'. Live widget works fine. + for entry in self.entry, self.tentry: + for end, ans in (0, 'onetwo'), ('end', 'two'): + with self.subTest(entry=entry, end=end, ans=ans): + entry.delete(0, 'end') + entry.insert(0, 'one') + entry.select_range(0, end) + entry.event_generate('<>') + self.assertEqual(entry.get(), ans) + + def test_paste_spin(self): + "Test pasting into a spinbox with and without a selection." + # See note above for entry. + spin = self.spin + for end, ans in (0, 'onetwo'), ('end', 'two'): + with self.subTest(end=end, ans=ans): + spin.delete(0, 'end') + spin.insert(0, 'one') + spin.selection('range', 0, end) # see note + spin.event_generate('<>') + self.assertEqual(spin.get(), ans) + + +if __name__ == '__main__': + unittest.main(verbosity=2) diff --git a/micromamba_root/envs/pytorch_env/Lib/idlelib/idle_test/test_editor.py b/micromamba_root/envs/pytorch_env/Lib/idlelib/idle_test/test_editor.py new file mode 100644 index 0000000000000000000000000000000000000000..0dfe2f3c58befadd0e85765cac1c1f29083d26fc --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/idlelib/idle_test/test_editor.py @@ -0,0 +1,241 @@ +"Test editor, coverage 53%." + +from idlelib import editor +import unittest +from collections import namedtuple +from test.support import requires +from tkinter import Tk, Text + +Editor = editor.EditorWindow + + +class EditorWindowTest(unittest.TestCase): + + @classmethod + def setUpClass(cls): + requires('gui') + cls.root = Tk() + cls.root.withdraw() + + @classmethod + def tearDownClass(cls): + cls.root.update_idletasks() + for id in cls.root.tk.call('after', 'info'): + cls.root.after_cancel(id) + cls.root.destroy() + del cls.root + + def test_init(self): + e = Editor(root=self.root) + self.assertEqual(e.root, self.root) + e._close() + + +class GetLineIndentTest(unittest.TestCase): + def test_empty_lines(self): + for tabwidth in [1, 2, 4, 6, 8]: + for line in ['', '\n']: + with self.subTest(line=line, tabwidth=tabwidth): + self.assertEqual( + editor.get_line_indent(line, tabwidth=tabwidth), + (0, 0), + ) + + def test_tabwidth_4(self): + # (line, (raw, effective)) + tests = (('no spaces', (0, 0)), + # Internal space isn't counted. + (' space test', (4, 4)), + ('\ttab test', (1, 4)), + ('\t\tdouble tabs test', (2, 8)), + # Different results when mixing tabs and spaces. + (' \tmixed test', (5, 8)), + (' \t mixed test', (5, 6)), + ('\t mixed test', (5, 8)), + # Spaces not divisible by tabwidth. + (' \tmixed test', (3, 4)), + (' \t mixed test', (3, 5)), + ('\t mixed test', (3, 6)), + # Only checks spaces and tabs. + ('\nnewline test', (0, 0))) + + for line, expected in tests: + with self.subTest(line=line): + self.assertEqual( + editor.get_line_indent(line, tabwidth=4), + expected, + ) + + def test_tabwidth_8(self): + # (line, (raw, effective)) + tests = (('no spaces', (0, 0)), + # Internal space isn't counted. + (' space test', (8, 8)), + ('\ttab test', (1, 8)), + ('\t\tdouble tabs test', (2, 16)), + # Different results when mixing tabs and spaces. + (' \tmixed test', (9, 16)), + (' \t mixed test', (9, 10)), + ('\t mixed test', (9, 16)), + # Spaces not divisible by tabwidth. + (' \tmixed test', (3, 8)), + (' \t mixed test', (3, 9)), + ('\t mixed test', (3, 10)), + # Only checks spaces and tabs. + ('\nnewline test', (0, 0))) + + for line, expected in tests: + with self.subTest(line=line): + self.assertEqual( + editor.get_line_indent(line, tabwidth=8), + expected, + ) + + +def insert(text, string): + text.delete('1.0', 'end') + text.insert('end', string) + text.update_idletasks() # Force update for colorizer to finish. + + +class IndentAndNewlineTest(unittest.TestCase): + + @classmethod + def setUpClass(cls): + requires('gui') + cls.root = Tk() + cls.root.withdraw() + cls.window = Editor(root=cls.root) + cls.window.indentwidth = 2 + cls.window.tabwidth = 2 + + @classmethod + def tearDownClass(cls): + cls.window._close() + del cls.window + cls.root.update_idletasks() + for id in cls.root.tk.call('after', 'info'): + cls.root.after_cancel(id) + cls.root.destroy() + del cls.root + + def test_indent_and_newline_event(self): + eq = self.assertEqual + w = self.window + text = w.text + get = text.get + nl = w.newline_and_indent_event + + TestInfo = namedtuple('Tests', ['label', 'text', 'expected', 'mark']) + + tests = (TestInfo('Empty line inserts with no indent.', + ' \n def __init__(self):', + '\n \n def __init__(self):\n', + '1.end'), + TestInfo('Inside bracket before space, deletes space.', + ' def f1(self, a, b):', + ' def f1(self,\n a, b):\n', + '1.14'), + TestInfo('Inside bracket after space, deletes space.', + ' def f1(self, a, b):', + ' def f1(self,\n a, b):\n', + '1.15'), + TestInfo('Inside string with one line - no indent.', + ' """Docstring."""', + ' """Docstring.\n"""\n', + '1.15'), + TestInfo('Inside string with more than one line.', + ' """Docstring.\n Docstring Line 2"""', + ' """Docstring.\n Docstring Line 2\n """\n', + '2.18'), + TestInfo('Backslash with one line.', + 'a =\\', + 'a =\\\n \n', + '1.end'), + TestInfo('Backslash with more than one line.', + 'a =\\\n multiline\\', + 'a =\\\n multiline\\\n \n', + '2.end'), + TestInfo('Block opener - indents +1 level.', + ' def f1(self):\n pass', + ' def f1(self):\n \n pass\n', + '1.end'), + TestInfo('Block closer - dedents -1 level.', + ' def f1(self):\n pass', + ' def f1(self):\n pass\n \n', + '2.end'), + ) + + for test in tests: + with self.subTest(label=test.label): + insert(text, test.text) + text.mark_set('insert', test.mark) + nl(event=None) + eq(get('1.0', 'end'), test.expected) + + # Selected text. + insert(text, ' def f1(self, a, b):\n return a + b') + text.tag_add('sel', '1.17', '1.end') + nl(None) + # Deletes selected text before adding new line. + eq(get('1.0', 'end'), ' def f1(self, a,\n \n return a + b\n') + + +class IndentSearcherTest(unittest.TestCase): + + @classmethod + def setUpClass(cls): + requires('gui') + cls.root = Tk() + cls.root.withdraw() + cls.text = Text(cls.root) + + @classmethod + def tearDownClass(cls): + cls.root.destroy() + del cls.root + + def test_searcher(self): + text = self.text + searcher = (self.text) + test_info = (# text, (block, indent)) + ("", (None, None)), + ("[1,", (None, None)), # TokenError + ("if 1:\n", ('if 1:\n', None)), + ("if 1:\n 2\n 3\n", ('if 1:\n', ' 2\n')), + ) + for code, expected_pair in test_info: + with self.subTest(code=code): + insert(text, code) + actual_pair = editor.IndentSearcher(text).run() + self.assertEqual(actual_pair, expected_pair) + + +class RMenuTest(unittest.TestCase): + + @classmethod + def setUpClass(cls): + requires('gui') + cls.root = Tk() + cls.root.withdraw() + cls.window = Editor(root=cls.root) + + @classmethod + def tearDownClass(cls): + cls.window._close() + del cls.window + cls.root.update_idletasks() + for id in cls.root.tk.call('after', 'info'): + cls.root.after_cancel(id) + cls.root.destroy() + del cls.root + + class DummyRMenu: + def tk_popup(x, y): pass + + def test_rclick(self): + pass + + +if __name__ == '__main__': + unittest.main(verbosity=2) diff --git a/micromamba_root/envs/pytorch_env/Lib/idlelib/idle_test/test_filelist.py b/micromamba_root/envs/pytorch_env/Lib/idlelib/idle_test/test_filelist.py new file mode 100644 index 0000000000000000000000000000000000000000..731f1975e50e23907f60764c0c149f101c6fe898 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/idlelib/idle_test/test_filelist.py @@ -0,0 +1,33 @@ +"Test filelist, coverage 19%." + +from idlelib import filelist +import unittest +from test.support import requires +from tkinter import Tk + +class FileListTest(unittest.TestCase): + + @classmethod + def setUpClass(cls): + requires('gui') + cls.root = Tk() + cls.root.withdraw() + + @classmethod + def tearDownClass(cls): + cls.root.update_idletasks() + for id in cls.root.tk.call('after', 'info'): + cls.root.after_cancel(id) + cls.root.destroy() + del cls.root + + def test_new_empty(self): + flist = filelist.FileList(self.root) + self.assertEqual(flist.root, self.root) + e = flist.new() + self.assertEqual(type(e), flist.EditorWindow) + e._close() + + +if __name__ == '__main__': + unittest.main(verbosity=2) diff --git a/micromamba_root/envs/pytorch_env/Lib/idlelib/idle_test/test_format.py b/micromamba_root/envs/pytorch_env/Lib/idlelib/idle_test/test_format.py new file mode 100644 index 0000000000000000000000000000000000000000..e5e903688597aa770452f15102f9ee7850ace49e --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/idlelib/idle_test/test_format.py @@ -0,0 +1,668 @@ +"Test format, coverage 99%." + +from idlelib import format as ft +import unittest +from unittest import mock +from test.support import requires +from tkinter import Tk, Text +from idlelib.editor import EditorWindow +from idlelib.idle_test.mock_idle import Editor as MockEditor + + +class Is_Get_Test(unittest.TestCase): + """Test the is_ and get_ functions""" + test_comment = '# This is a comment' + test_nocomment = 'This is not a comment' + trailingws_comment = '# This is a comment ' + leadingws_comment = ' # This is a comment' + leadingws_nocomment = ' This is not a comment' + + def test_is_all_white(self): + self.assertTrue(ft.is_all_white('')) + self.assertTrue(ft.is_all_white('\t\n\r\f\v')) + self.assertFalse(ft.is_all_white(self.test_comment)) + + def test_get_indent(self): + Equal = self.assertEqual + Equal(ft.get_indent(self.test_comment), '') + Equal(ft.get_indent(self.trailingws_comment), '') + Equal(ft.get_indent(self.leadingws_comment), ' ') + Equal(ft.get_indent(self.leadingws_nocomment), ' ') + + def test_get_comment_header(self): + Equal = self.assertEqual + # Test comment strings + Equal(ft.get_comment_header(self.test_comment), '#') + Equal(ft.get_comment_header(self.trailingws_comment), '#') + Equal(ft.get_comment_header(self.leadingws_comment), ' #') + # Test non-comment strings + Equal(ft.get_comment_header(self.leadingws_nocomment), ' ') + Equal(ft.get_comment_header(self.test_nocomment), '') + + +class FindTest(unittest.TestCase): + """Test the find_paragraph function in paragraph module. + + Using the runcase() function, find_paragraph() is called with 'mark' set at + multiple indexes before and inside the test paragraph. + + It appears that code with the same indentation as a quoted string is grouped + as part of the same paragraph, which is probably incorrect behavior. + """ + + @classmethod + def setUpClass(cls): + from idlelib.idle_test.mock_tk import Text + cls.text = Text() + + def runcase(self, inserttext, stopline, expected): + # Check that find_paragraph returns the expected paragraph when + # the mark index is set to beginning, middle, end of each line + # up to but not including the stop line + text = self.text + text.insert('1.0', inserttext) + for line in range(1, stopline): + linelength = int(text.index("%d.end" % line).split('.')[1]) + for col in (0, linelength//2, linelength): + tempindex = "%d.%d" % (line, col) + self.assertEqual(ft.find_paragraph(text, tempindex), expected) + text.delete('1.0', 'end') + + def test_find_comment(self): + comment = ( + "# Comment block with no blank lines before\n" + "# Comment line\n" + "\n") + self.runcase(comment, 3, ('1.0', '3.0', '#', comment[0:58])) + + comment = ( + "\n" + "# Comment block with whitespace line before and after\n" + "# Comment line\n" + "\n") + self.runcase(comment, 4, ('2.0', '4.0', '#', comment[1:70])) + + comment = ( + "\n" + " # Indented comment block with whitespace before and after\n" + " # Comment line\n" + "\n") + self.runcase(comment, 4, ('2.0', '4.0', ' #', comment[1:82])) + + comment = ( + "\n" + "# Single line comment\n" + "\n") + self.runcase(comment, 3, ('2.0', '3.0', '#', comment[1:23])) + + comment = ( + "\n" + " # Single line comment with leading whitespace\n" + "\n") + self.runcase(comment, 3, ('2.0', '3.0', ' #', comment[1:51])) + + comment = ( + "\n" + "# Comment immediately followed by code\n" + "x = 42\n" + "\n") + self.runcase(comment, 3, ('2.0', '3.0', '#', comment[1:40])) + + comment = ( + "\n" + " # Indented comment immediately followed by code\n" + "x = 42\n" + "\n") + self.runcase(comment, 3, ('2.0', '3.0', ' #', comment[1:53])) + + comment = ( + "\n" + "# Comment immediately followed by indented code\n" + " x = 42\n" + "\n") + self.runcase(comment, 3, ('2.0', '3.0', '#', comment[1:49])) + + def test_find_paragraph(self): + teststring = ( + '"""String with no blank lines before\n' + 'String line\n' + '"""\n' + '\n') + self.runcase(teststring, 4, ('1.0', '4.0', '', teststring[0:53])) + + teststring = ( + "\n" + '"""String with whitespace line before and after\n' + 'String line.\n' + '"""\n' + '\n') + self.runcase(teststring, 5, ('2.0', '5.0', '', teststring[1:66])) + + teststring = ( + '\n' + ' """Indented string with whitespace before and after\n' + ' Comment string.\n' + ' """\n' + '\n') + self.runcase(teststring, 5, ('2.0', '5.0', ' ', teststring[1:85])) + + teststring = ( + '\n' + '"""Single line string."""\n' + '\n') + self.runcase(teststring, 3, ('2.0', '3.0', '', teststring[1:27])) + + teststring = ( + '\n' + ' """Single line string with leading whitespace."""\n' + '\n') + self.runcase(teststring, 3, ('2.0', '3.0', ' ', teststring[1:55])) + + +class ReformatFunctionTest(unittest.TestCase): + """Test the reformat_paragraph function without the editor window.""" + + def test_reformat_paragraph(self): + Equal = self.assertEqual + reform = ft.reformat_paragraph + hw = "O hello world" + Equal(reform(' ', 1), ' ') + Equal(reform("Hello world", 20), "Hello world") + + # Test without leading newline + Equal(reform(hw, 1), "O\nhello\nworld") + Equal(reform(hw, 6), "O\nhello\nworld") + Equal(reform(hw, 7), "O hello\nworld") + Equal(reform(hw, 12), "O hello\nworld") + Equal(reform(hw, 13), "O hello world") + + # Test with leading newline + hw = "\nO hello world" + Equal(reform(hw, 1), "\nO\nhello\nworld") + Equal(reform(hw, 6), "\nO\nhello\nworld") + Equal(reform(hw, 7), "\nO hello\nworld") + Equal(reform(hw, 12), "\nO hello\nworld") + Equal(reform(hw, 13), "\nO hello world") + + +class ReformatCommentTest(unittest.TestCase): + """Test the reformat_comment function without the editor window.""" + + def test_reformat_comment(self): + Equal = self.assertEqual + + # reformat_comment formats to a minimum of 20 characters + test_string = ( + " \"\"\"this is a test of a reformat for a triple quoted string" + " will it reformat to less than 70 characters for me?\"\"\"") + result = ft.reformat_comment(test_string, 70, " ") + expected = ( + " \"\"\"this is a test of a reformat for a triple quoted string will it\n" + " reformat to less than 70 characters for me?\"\"\"") + Equal(result, expected) + + test_comment = ( + "# this is a test of a reformat for a triple quoted string will " + "it reformat to less than 70 characters for me?") + result = ft.reformat_comment(test_comment, 70, "#") + expected = ( + "# this is a test of a reformat for a triple quoted string will it\n" + "# reformat to less than 70 characters for me?") + Equal(result, expected) + + +class FormatClassTest(unittest.TestCase): + def test_init_close(self): + instance = ft.FormatParagraph('editor') + self.assertEqual(instance.editwin, 'editor') + instance.close() + self.assertEqual(instance.editwin, None) + + +# For testing format_paragraph_event, Initialize FormatParagraph with +# a mock Editor with .text and .get_selection_indices. The text must +# be a Text wrapper that adds two methods + +# A real EditorWindow creates unneeded, time-consuming baggage and +# sometimes emits shutdown warnings like this: +# "warning: callback failed in WindowList +# : invalid command name ".55131368.windows". +# Calling EditorWindow._close in tearDownClass prevents this but causes +# other problems (windows left open). + +class TextWrapper: + def __init__(self, master): + self.text = Text(master=master) + def __getattr__(self, name): + return getattr(self.text, name) + def undo_block_start(self): pass + def undo_block_stop(self): pass + +class Editor: + def __init__(self, root): + self.text = TextWrapper(root) + get_selection_indices = EditorWindow. get_selection_indices + +class FormatEventTest(unittest.TestCase): + """Test the formatting of text inside a Text widget. + + This is done with FormatParagraph.format.paragraph_event, + which calls functions in the module as appropriate. + """ + test_string = ( + " '''this is a test of a reformat for a triple " + "quoted string will it reformat to less than 70 " + "characters for me?'''\n") + multiline_test_string = ( + " '''The first line is under the max width.\n" + " The second line's length is way over the max width. It goes " + "on and on until it is over 100 characters long.\n" + " Same thing with the third line. It is also way over the max " + "width, but FormatParagraph will fix it.\n" + " '''\n") + multiline_test_comment = ( + "# The first line is under the max width.\n" + "# The second line's length is way over the max width. It goes on " + "and on until it is over 100 characters long.\n" + "# Same thing with the third line. It is also way over the max " + "width, but FormatParagraph will fix it.\n" + "# The fourth line is short like the first line.") + + @classmethod + def setUpClass(cls): + requires('gui') + cls.root = Tk() + cls.root.withdraw() + editor = Editor(root=cls.root) + cls.text = editor.text.text # Test code does not need the wrapper. + cls.formatter = ft.FormatParagraph(editor).format_paragraph_event + # Sets the insert mark just after the re-wrapped and inserted text. + + @classmethod + def tearDownClass(cls): + del cls.text, cls.formatter + cls.root.update_idletasks() + cls.root.destroy() + del cls.root + + def test_short_line(self): + self.text.insert('1.0', "Short line\n") + self.formatter("Dummy") + self.assertEqual(self.text.get('1.0', 'insert'), "Short line\n" ) + self.text.delete('1.0', 'end') + + def test_long_line(self): + text = self.text + + # Set cursor ('insert' mark) to '1.0', within text. + text.insert('1.0', self.test_string) + text.mark_set('insert', '1.0') + self.formatter('ParameterDoesNothing', limit=70) + result = text.get('1.0', 'insert') + # find function includes \n + expected = ( +" '''this is a test of a reformat for a triple quoted string will it\n" +" reformat to less than 70 characters for me?'''\n") # yes + self.assertEqual(result, expected) + text.delete('1.0', 'end') + + # Select from 1.11 to line end. + text.insert('1.0', self.test_string) + text.tag_add('sel', '1.11', '1.end') + self.formatter('ParameterDoesNothing', limit=70) + result = text.get('1.0', 'insert') + # selection excludes \n + expected = ( +" '''this is a test of a reformat for a triple quoted string will it reformat\n" +" to less than 70 characters for me?'''") # no + self.assertEqual(result, expected) + text.delete('1.0', 'end') + + def test_multiple_lines(self): + text = self.text + # Select 2 long lines. + text.insert('1.0', self.multiline_test_string) + text.tag_add('sel', '2.0', '4.0') + self.formatter('ParameterDoesNothing', limit=70) + result = text.get('2.0', 'insert') + expected = ( +" The second line's length is way over the max width. It goes on and\n" +" on until it is over 100 characters long. Same thing with the third\n" +" line. It is also way over the max width, but FormatParagraph will\n" +" fix it.\n") + self.assertEqual(result, expected) + text.delete('1.0', 'end') + + def test_comment_block(self): + text = self.text + + # Set cursor ('insert') to '1.0', within block. + text.insert('1.0', self.multiline_test_comment) + self.formatter('ParameterDoesNothing', limit=70) + result = text.get('1.0', 'insert') + expected = ( +"# The first line is under the max width. The second line's length is\n" +"# way over the max width. It goes on and on until it is over 100\n" +"# characters long. Same thing with the third line. It is also way over\n" +"# the max width, but FormatParagraph will fix it. The fourth line is\n" +"# short like the first line.\n") + self.assertEqual(result, expected) + text.delete('1.0', 'end') + + # Select line 2, verify line 1 unaffected. + text.insert('1.0', self.multiline_test_comment) + text.tag_add('sel', '2.0', '3.0') + self.formatter('ParameterDoesNothing', limit=70) + result = text.get('1.0', 'insert') + expected = ( +"# The first line is under the max width.\n" +"# The second line's length is way over the max width. It goes on and\n" +"# on until it is over 100 characters long.\n") + self.assertEqual(result, expected) + text.delete('1.0', 'end') + +# The following block worked with EditorWindow but fails with the mock. +# Lines 2 and 3 get pasted together even though the previous block left +# the previous line alone. More investigation is needed. +## # Select lines 3 and 4 +## text.insert('1.0', self.multiline_test_comment) +## text.tag_add('sel', '3.0', '5.0') +## self.formatter('ParameterDoesNothing') +## result = text.get('3.0', 'insert') +## expected = ( +##"# Same thing with the third line. It is also way over the max width,\n" +##"# but FormatParagraph will fix it. The fourth line is short like the\n" +##"# first line.\n") +## self.assertEqual(result, expected) +## text.delete('1.0', 'end') + + +class DummyEditwin: + def __init__(self, root, text): + self.root = root + self.text = text + self.indentwidth = 4 + self.tabwidth = 4 + self.usetabs = False + self.context_use_ps1 = True + + _make_blanks = EditorWindow._make_blanks + get_selection_indices = EditorWindow.get_selection_indices + + +class FormatRegionTest(unittest.TestCase): + + @classmethod + def setUpClass(cls): + requires('gui') + cls.root = Tk() + cls.root.withdraw() + cls.text = Text(cls.root) + cls.text.undo_block_start = mock.Mock() + cls.text.undo_block_stop = mock.Mock() + cls.editor = DummyEditwin(cls.root, cls.text) + cls.formatter = ft.FormatRegion(cls.editor) + + @classmethod + def tearDownClass(cls): + del cls.text, cls.formatter, cls.editor + cls.root.update_idletasks() + cls.root.destroy() + del cls.root + + def setUp(self): + self.text.insert('1.0', self.code_sample) + + def tearDown(self): + self.text.delete('1.0', 'end') + + code_sample = """\ +# WS line needed for test. +class C1: + # Class comment. + def __init__(self, a, b): + self.a = a + self.b = b + + def compare(self): + if a > b: + return a + elif a < b: + return b + else: + return None +""" + + def test_get_region(self): + get = self.formatter.get_region + text = self.text + eq = self.assertEqual + + # Add selection. + text.tag_add('sel', '7.0', '10.0') + expected_lines = ['', + ' def compare(self):', + ' if a > b:', + ''] + eq(get(), ('7.0', '10.0', '\n'.join(expected_lines), expected_lines)) + + # Remove selection. + text.tag_remove('sel', '1.0', 'end') + eq(get(), ('15.0', '16.0', '\n', ['', ''])) + + def test_set_region(self): + set_ = self.formatter.set_region + text = self.text + eq = self.assertEqual + + save_bell = text.bell + text.bell = mock.Mock() + line6 = self.code_sample.splitlines()[5] + line10 = self.code_sample.splitlines()[9] + + text.tag_add('sel', '6.0', '11.0') + head, tail, chars, lines = self.formatter.get_region() + + # No changes. + set_(head, tail, chars, lines) + text.bell.assert_called_once() + eq(text.get('6.0', '11.0'), chars) + eq(text.get('sel.first', 'sel.last'), chars) + text.tag_remove('sel', '1.0', 'end') + + # Alter selected lines by changing lines and adding a newline. + newstring = 'added line 1\n\n\n\n' + newlines = newstring.split('\n') + set_('7.0', '10.0', chars, newlines) + # Selection changed. + eq(text.get('sel.first', 'sel.last'), newstring) + # Additional line added, so last index is changed. + eq(text.get('7.0', '11.0'), newstring) + # Before and after lines unchanged. + eq(text.get('6.0', '7.0-1c'), line6) + eq(text.get('11.0', '12.0-1c'), line10) + text.tag_remove('sel', '1.0', 'end') + + text.bell = save_bell + + def test_indent_region_event(self): + indent = self.formatter.indent_region_event + text = self.text + eq = self.assertEqual + + text.tag_add('sel', '7.0', '10.0') + indent() + # Blank lines aren't affected by indent. + eq(text.get('7.0', '10.0'), ('\n def compare(self):\n if a > b:\n')) + + def test_dedent_region_event(self): + dedent = self.formatter.dedent_region_event + text = self.text + eq = self.assertEqual + + text.tag_add('sel', '7.0', '10.0') + dedent() + # Blank lines aren't affected by dedent. + eq(text.get('7.0', '10.0'), ('\ndef compare(self):\n if a > b:\n')) + + def test_comment_region_event(self): + comment = self.formatter.comment_region_event + text = self.text + eq = self.assertEqual + + text.tag_add('sel', '7.0', '10.0') + comment() + eq(text.get('7.0', '10.0'), ('##\n## def compare(self):\n## if a > b:\n')) + + def test_uncomment_region_event(self): + comment = self.formatter.comment_region_event + uncomment = self.formatter.uncomment_region_event + text = self.text + eq = self.assertEqual + + text.tag_add('sel', '7.0', '10.0') + comment() + uncomment() + eq(text.get('7.0', '10.0'), ('\n def compare(self):\n if a > b:\n')) + + # Only remove comments at the beginning of a line. + text.tag_remove('sel', '1.0', 'end') + text.tag_add('sel', '3.0', '4.0') + uncomment() + eq(text.get('3.0', '3.end'), (' # Class comment.')) + + self.formatter.set_region('3.0', '4.0', '', ['# Class comment.', '']) + uncomment() + eq(text.get('3.0', '3.end'), (' Class comment.')) + + @mock.patch.object(ft.FormatRegion, "_asktabwidth") + def test_tabify_region_event(self, _asktabwidth): + tabify = self.formatter.tabify_region_event + text = self.text + eq = self.assertEqual + + text.tag_add('sel', '7.0', '10.0') + # No tabwidth selected. + _asktabwidth.return_value = None + self.assertIsNone(tabify()) + + _asktabwidth.return_value = 3 + self.assertIsNotNone(tabify()) + eq(text.get('7.0', '10.0'), ('\n\t def compare(self):\n\t\t if a > b:\n')) + + @mock.patch.object(ft.FormatRegion, "_asktabwidth") + def test_untabify_region_event(self, _asktabwidth): + untabify = self.formatter.untabify_region_event + text = self.text + eq = self.assertEqual + + text.tag_add('sel', '7.0', '10.0') + # No tabwidth selected. + _asktabwidth.return_value = None + self.assertIsNone(untabify()) + + _asktabwidth.return_value = 2 + self.formatter.tabify_region_event() + _asktabwidth.return_value = 3 + self.assertIsNotNone(untabify()) + eq(text.get('7.0', '10.0'), ('\n def compare(self):\n if a > b:\n')) + + @mock.patch.object(ft, "askinteger") + def test_ask_tabwidth(self, askinteger): + ask = self.formatter._asktabwidth + askinteger.return_value = 10 + self.assertEqual(ask(), 10) + + +class IndentsTest(unittest.TestCase): + + @mock.patch.object(ft, "askyesno") + def test_toggle_tabs(self, askyesno): + editor = DummyEditwin(None, None) # usetabs == False. + indents = ft.Indents(editor) + askyesno.return_value = True + + indents.toggle_tabs_event(None) + self.assertEqual(editor.usetabs, True) + self.assertEqual(editor.indentwidth, 8) + + indents.toggle_tabs_event(None) + self.assertEqual(editor.usetabs, False) + self.assertEqual(editor.indentwidth, 8) + + @mock.patch.object(ft, "askinteger") + def test_change_indentwidth(self, askinteger): + editor = DummyEditwin(None, None) # indentwidth == 4. + indents = ft.Indents(editor) + + askinteger.return_value = None + indents.change_indentwidth_event(None) + self.assertEqual(editor.indentwidth, 4) + + askinteger.return_value = 3 + indents.change_indentwidth_event(None) + self.assertEqual(editor.indentwidth, 3) + + askinteger.return_value = 5 + editor.usetabs = True + indents.change_indentwidth_event(None) + self.assertEqual(editor.indentwidth, 3) + + +class RstripTest(unittest.TestCase): + + @classmethod + def setUpClass(cls): + requires('gui') + cls.root = Tk() + cls.root.withdraw() + cls.text = Text(cls.root) + cls.editor = MockEditor(text=cls.text) + cls.do_rstrip = ft.Rstrip(cls.editor).do_rstrip + + @classmethod + def tearDownClass(cls): + del cls.text, cls.do_rstrip, cls.editor + cls.root.update_idletasks() + cls.root.destroy() + del cls.root + + def tearDown(self): + self.text.delete('1.0', 'end-1c') + + def test_rstrip_lines(self): + original = ( + "Line with an ending tab \n" + "Line ending in 5 spaces \n" + "Linewithnospaces\n" + " indented line\n" + " indented line with trailing space \n" + " \n") + stripped = ( + "Line with an ending tab\n" + "Line ending in 5 spaces\n" + "Linewithnospaces\n" + " indented line\n" + " indented line with trailing space\n") + + self.text.insert('1.0', original) + self.do_rstrip() + self.assertEqual(self.text.get('1.0', 'insert'), stripped) + + def test_rstrip_end(self): + text = self.text + for code in ('', '\n', '\n\n\n'): + with self.subTest(code=code): + text.insert('1.0', code) + self.do_rstrip() + self.assertEqual(text.get('1.0','end-1c'), '') + for code in ('a\n', 'a\n\n', 'a\n\n\n'): + with self.subTest(code=code): + text.delete('1.0', 'end-1c') + text.insert('1.0', code) + self.do_rstrip() + self.assertEqual(text.get('1.0','end-1c'), 'a\n') + + +if __name__ == '__main__': + unittest.main(verbosity=2, exit=2) diff --git a/micromamba_root/envs/pytorch_env/Lib/idlelib/idle_test/test_grep.py b/micromamba_root/envs/pytorch_env/Lib/idlelib/idle_test/test_grep.py new file mode 100644 index 0000000000000000000000000000000000000000..a0b5b69171879c0042d7ac3fe3f049e86ba7b0c0 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/idlelib/idle_test/test_grep.py @@ -0,0 +1,156 @@ +""" !Changing this line will break Test_findfile.test_found! +Non-gui unit tests for grep.GrepDialog methods. +dummy_command calls grep_it calls findfiles. +An exception raised in one method will fail callers. +Otherwise, tests are mostly independent. +Currently only test grep_it, coverage 51%. +""" +from idlelib import grep +import unittest +from test.support import captured_stdout +from idlelib.idle_test.mock_tk import Var +import os +import re + + +class Dummy_searchengine: + '''GrepDialog.__init__ calls parent SearchDiabolBase which attaches the + passed in SearchEngine instance as attribute 'engine'. Only a few of the + many possible self.engine.x attributes are needed here. + ''' + def getpat(self): + return self._pat + +searchengine = Dummy_searchengine() + + +class Dummy_grep: + # Methods tested + #default_command = GrepDialog.default_command + grep_it = grep.GrepDialog.grep_it + # Other stuff needed + recvar = Var(False) + engine = searchengine + def close(self): # gui method + pass + +_grep = Dummy_grep() + + +class FindfilesTest(unittest.TestCase): + + @classmethod + def setUpClass(cls): + cls.realpath = os.path.realpath(__file__) + cls.path = os.path.dirname(cls.realpath) + + @classmethod + def tearDownClass(cls): + del cls.realpath, cls.path + + def test_invaliddir(self): + with captured_stdout() as s: + filelist = list(grep.findfiles('invaliddir', '*.*', False)) + self.assertEqual(filelist, []) + self.assertIn('invalid', s.getvalue()) + + def test_curdir(self): + # Test os.curdir. + ff = grep.findfiles + save_cwd = os.getcwd() + os.chdir(self.path) + filename = 'test_grep.py' + filelist = list(ff(os.curdir, filename, False)) + self.assertIn(os.path.join(os.curdir, filename), filelist) + os.chdir(save_cwd) + + def test_base(self): + ff = grep.findfiles + readme = os.path.join(self.path, 'README.txt') + + # Check for Python files in path where this file lives. + filelist = list(ff(self.path, '*.py', False)) + # This directory has many Python files. + self.assertGreater(len(filelist), 10) + self.assertIn(self.realpath, filelist) + self.assertNotIn(readme, filelist) + + # Look for .txt files in path where this file lives. + filelist = list(ff(self.path, '*.txt', False)) + self.assertNotEqual(len(filelist), 0) + self.assertNotIn(self.realpath, filelist) + self.assertIn(readme, filelist) + + # Look for non-matching pattern. + filelist = list(ff(self.path, 'grep.*', False)) + self.assertEqual(len(filelist), 0) + self.assertNotIn(self.realpath, filelist) + + def test_recurse(self): + ff = grep.findfiles + parent = os.path.dirname(self.path) + grepfile = os.path.join(parent, 'grep.py') + pat = '*.py' + + # Get Python files only in parent directory. + filelist = list(ff(parent, pat, False)) + parent_size = len(filelist) + # Lots of Python files in idlelib. + self.assertGreater(parent_size, 20) + self.assertIn(grepfile, filelist) + # Without subdirectories, this file isn't returned. + self.assertNotIn(self.realpath, filelist) + + # Include subdirectories. + filelist = list(ff(parent, pat, True)) + # More files found now. + self.assertGreater(len(filelist), parent_size) + self.assertIn(grepfile, filelist) + # This file exists in list now. + self.assertIn(self.realpath, filelist) + + # Check another level up the tree. + parent = os.path.dirname(parent) + filelist = list(ff(parent, '*.py', True)) + self.assertIn(self.realpath, filelist) + + +class Grep_itTest(unittest.TestCase): + # Test captured reports with 0 and some hits. + # Should test file names, but Windows reports have mixed / and \ separators + # from incomplete replacement, so 'later'. + + def report(self, pat): + _grep.engine._pat = pat + with captured_stdout() as s: + _grep.grep_it(re.compile(pat), __file__) + lines = s.getvalue().split('\n') + lines.pop() # remove bogus '' after last \n + return lines + + def test_unfound(self): + pat = 'xyz*'*7 + lines = self.report(pat) + self.assertEqual(len(lines), 2) + self.assertIn(pat, lines[0]) + self.assertEqual(lines[1], 'No hits.') + + def test_found(self): + + pat = '""" !Changing this line will break Test_findfile.test_found!' + lines = self.report(pat) + self.assertEqual(len(lines), 5) + self.assertIn(pat, lines[0]) + self.assertIn('py: 1:', lines[1]) # line number 1 + self.assertIn('2', lines[3]) # hits found 2 + self.assertTrue(lines[4].startswith('(Hint:')) + + +class Default_commandTest(unittest.TestCase): + # To write this, move outwin import to top of GrepDialog + # so it can be replaced by captured_stdout in class setup/teardown. + pass + + +if __name__ == '__main__': + unittest.main(verbosity=2) diff --git a/micromamba_root/envs/pytorch_env/Lib/idlelib/idle_test/test_help.py b/micromamba_root/envs/pytorch_env/Lib/idlelib/idle_test/test_help.py new file mode 100644 index 0000000000000000000000000000000000000000..c528d4e77f8ca7c32aca8e66d5c0183966661546 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/idlelib/idle_test/test_help.py @@ -0,0 +1,36 @@ +"Test help, coverage 94%." + +from idlelib import help +import unittest +from test.support import requires +requires('gui') +from os.path import abspath, dirname, join +from tkinter import Tk + + +class IdleDocTest(unittest.TestCase): + + @classmethod + def setUpClass(cls): + "By itself, this tests that file parsed without exception." + cls.root = root = Tk() + root.withdraw() + cls.window = help.show_idlehelp(root) + + @classmethod + def tearDownClass(cls): + del cls.window + cls.root.update_idletasks() + cls.root.destroy() + del cls.root + + def test_1window(self): + self.assertIn('IDLE Doc', self.window.wm_title()) + + def test_4text(self): + text = self.window.frame.text + self.assertEqual(text.get('1.0', '1.end'), ' IDLE ') + + +if __name__ == '__main__': + unittest.main(verbosity=2) diff --git a/micromamba_root/envs/pytorch_env/Lib/idlelib/idle_test/test_help_about.py b/micromamba_root/envs/pytorch_env/Lib/idlelib/idle_test/test_help_about.py new file mode 100644 index 0000000000000000000000000000000000000000..7e16abdb7c9f96f1a939ec0d27f0cb426922f6d9 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/idlelib/idle_test/test_help_about.py @@ -0,0 +1,182 @@ +"""Test help_about, coverage 100%. +help_about.build_bits branches on sys.platform='darwin'. +'100% combines coverage on Mac and others. +""" + +from idlelib import help_about +import unittest +from test.support import requires, findfile +from tkinter import Tk, TclError +from idlelib.idle_test.mock_idle import Func +from idlelib.idle_test.mock_tk import Mbox_func +from idlelib import textview +import os.path +from platform import python_version + +About = help_about.AboutDialog + + +class LiveDialogTest(unittest.TestCase): + """Simulate user clicking buttons other than [Close]. + + Test that invoked textview has text from source. + """ + @classmethod + def setUpClass(cls): + requires('gui') + cls.root = Tk() + cls.root.withdraw() + cls.dialog = About(cls.root, 'About IDLE', _utest=True) + + @classmethod + def tearDownClass(cls): + del cls.dialog + cls.root.update_idletasks() + cls.root.destroy() + del cls.root + + def test_build_bits(self): + self.assertIn(help_about.bits, ('32', '64')) + + def test_dialog_title(self): + """Test about dialog title""" + self.assertEqual(self.dialog.title(), 'About IDLE') + + def test_dialog_logo(self): + """Test about dialog logo.""" + path, file = os.path.split(self.dialog.icon_image['file']) + fn, ext = os.path.splitext(file) + self.assertEqual(fn, 'idle_48') + + def test_printer_buttons(self): + """Test buttons whose commands use printer function.""" + dialog = self.dialog + button_sources = [(dialog.py_license, license, 'license'), + (dialog.py_copyright, copyright, 'copyright'), + (dialog.py_credits, credits, 'credits')] + + for button, printer, name in button_sources: + with self.subTest(name=name): + printer._Printer__setup() + button.invoke() + get = dialog._current_textview.viewframe.textframe.text.get + lines = printer._Printer__lines + if len(lines) < 2: + self.fail(name + ' full text was not found') + self.assertEqual(lines[0], get('1.0', '1.end')) + self.assertEqual(lines[1], get('2.0', '2.end')) + dialog._current_textview.destroy() + + def test_file_buttons(self): + """Test buttons that display files.""" + dialog = self.dialog + button_sources = [(self.dialog.readme, 'README.txt', 'readme'), + (self.dialog.idle_news, 'News3.txt', 'news'), + (self.dialog.idle_credits, 'CREDITS.txt', 'credits')] + + for button, filename, name in button_sources: + with self.subTest(name=name): + button.invoke() + fn = findfile(filename, subdir='idlelib') + get = dialog._current_textview.viewframe.textframe.text.get + with open(fn, encoding='utf-8') as f: + self.assertEqual(f.readline().strip(), get('1.0', '1.end')) + f.readline() + self.assertEqual(f.readline().strip(), get('3.0', '3.end')) + dialog._current_textview.destroy() + + +class DefaultTitleTest(unittest.TestCase): + "Test default title." + + @classmethod + def setUpClass(cls): + requires('gui') + cls.root = Tk() + cls.root.withdraw() + cls.dialog = About(cls.root, _utest=True) + + @classmethod + def tearDownClass(cls): + del cls.dialog + cls.root.update_idletasks() + cls.root.destroy() + del cls.root + + def test_dialog_title(self): + """Test about dialog title""" + self.assertEqual(self.dialog.title(), + f'About IDLE {python_version()}' + f' ({help_about.bits} bit)') + + +class CloseTest(unittest.TestCase): + """Simulate user clicking [Close] button""" + + @classmethod + def setUpClass(cls): + requires('gui') + cls.root = Tk() + cls.root.withdraw() + cls.dialog = About(cls.root, 'About IDLE', _utest=True) + + @classmethod + def tearDownClass(cls): + del cls.dialog + cls.root.update_idletasks() + cls.root.destroy() + del cls.root + + def test_close(self): + self.assertEqual(self.dialog.winfo_class(), 'Toplevel') + self.dialog.button_ok.invoke() + with self.assertRaises(TclError): + self.dialog.winfo_class() + + +class Dummy_about_dialog: + # Dummy class for testing file display functions. + idle_credits = About.show_idle_credits + idle_readme = About.show_readme + idle_news = About.show_idle_news + # Called by the above + display_file_text = About.display_file_text + _utest = True + + +class DisplayFileTest(unittest.TestCase): + """Test functions that display files. + + While somewhat redundant with gui-based test_file_dialog, + these unit tests run on all buildbots, not just a few. + """ + dialog = Dummy_about_dialog() + + @classmethod + def setUpClass(cls): + cls.orig_error = textview.showerror + cls.orig_view = textview.view_text + cls.error = Mbox_func() + cls.view = Func() + textview.showerror = cls.error + textview.view_text = cls.view + + @classmethod + def tearDownClass(cls): + textview.showerror = cls.orig_error + textview.view_text = cls.orig_view + + def test_file_display(self): + for handler in (self.dialog.idle_credits, + self.dialog.idle_readme, + self.dialog.idle_news): + self.error.message = '' + self.view.called = False + with self.subTest(handler=handler): + handler() + self.assertEqual(self.error.message, '') + self.assertEqual(self.view.called, True) + + +if __name__ == '__main__': + unittest.main(verbosity=2) diff --git a/micromamba_root/envs/pytorch_env/Lib/idlelib/idle_test/test_history.py b/micromamba_root/envs/pytorch_env/Lib/idlelib/idle_test/test_history.py new file mode 100644 index 0000000000000000000000000000000000000000..675396514447514ff9c6811d095fe054fef589b0 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/idlelib/idle_test/test_history.py @@ -0,0 +1,172 @@ +" Test history, coverage 100%." + +from idlelib.history import History +import unittest +from test.support import requires + +import tkinter as tk +from tkinter import Text as tkText +from idlelib.idle_test.mock_tk import Text as mkText +from idlelib.config import idleConf + +line1 = 'a = 7' +line2 = 'b = a' + + +class StoreTest(unittest.TestCase): + '''Tests History.__init__ and History.store with mock Text''' + + @classmethod + def setUpClass(cls): + cls.text = mkText() + cls.history = History(cls.text) + + def tearDown(self): + self.text.delete('1.0', 'end') + self.history.history = [] + + def test_init(self): + self.assertIs(self.history.text, self.text) + self.assertEqual(self.history.history, []) + self.assertIsNone(self.history.prefix) + self.assertIsNone(self.history.pointer) + self.assertEqual(self.history.cyclic, + idleConf.GetOption("main", "History", "cyclic", 1, "bool")) + + def test_store_short(self): + self.history.store('a') + self.assertEqual(self.history.history, []) + self.history.store(' a ') + self.assertEqual(self.history.history, []) + + def test_store_dup(self): + self.history.store(line1) + self.assertEqual(self.history.history, [line1]) + self.history.store(line2) + self.assertEqual(self.history.history, [line1, line2]) + self.history.store(line1) + self.assertEqual(self.history.history, [line2, line1]) + + def test_store_reset(self): + self.history.prefix = line1 + self.history.pointer = 0 + self.history.store(line2) + self.assertIsNone(self.history.prefix) + self.assertIsNone(self.history.pointer) + + +class TextWrapper: + def __init__(self, master): + self.text = tkText(master=master) + self._bell = False + def __getattr__(self, name): + return getattr(self.text, name) + def bell(self): + self._bell = True + + +class FetchTest(unittest.TestCase): + '''Test History.fetch with wrapped tk.Text. + ''' + @classmethod + def setUpClass(cls): + requires('gui') + cls.root = tk.Tk() + cls.root.withdraw() + + def setUp(self): + self.text = text = TextWrapper(self.root) + text.insert('1.0', ">>> ") + text.mark_set('iomark', '1.4') + text.mark_gravity('iomark', 'left') + self.history = History(text) + self.history.history = [line1, line2] + + @classmethod + def tearDownClass(cls): + cls.root.destroy() + del cls.root + + def fetch_test(self, reverse, line, prefix, index, *, bell=False): + # Perform one fetch as invoked by Alt-N or Alt-P + # Test the result. The line test is the most important. + # The last two are diagnostic of fetch internals. + History = self.history + History.fetch(reverse) + + Equal = self.assertEqual + Equal(self.text.get('iomark', 'end-1c'), line) + Equal(self.text._bell, bell) + if bell: + self.text._bell = False + Equal(History.prefix, prefix) + Equal(History.pointer, index) + Equal(self.text.compare("insert", '==', "end-1c"), 1) + + def test_fetch_prev_cyclic(self): + prefix = '' + test = self.fetch_test + test(True, line2, prefix, 1) + test(True, line1, prefix, 0) + test(True, prefix, None, None, bell=True) + + def test_fetch_next_cyclic(self): + prefix = '' + test = self.fetch_test + test(False, line1, prefix, 0) + test(False, line2, prefix, 1) + test(False, prefix, None, None, bell=True) + + # Prefix 'a' tests skip line2, which starts with 'b' + def test_fetch_prev_prefix(self): + prefix = 'a' + self.text.insert('iomark', prefix) + self.fetch_test(True, line1, prefix, 0) + self.fetch_test(True, prefix, None, None, bell=True) + + def test_fetch_next_prefix(self): + prefix = 'a' + self.text.insert('iomark', prefix) + self.fetch_test(False, line1, prefix, 0) + self.fetch_test(False, prefix, None, None, bell=True) + + def test_fetch_prev_noncyclic(self): + prefix = '' + self.history.cyclic = False + test = self.fetch_test + test(True, line2, prefix, 1) + test(True, line1, prefix, 0) + test(True, line1, prefix, 0, bell=True) + + def test_fetch_next_noncyclic(self): + prefix = '' + self.history.cyclic = False + test = self.fetch_test + test(False, prefix, None, None, bell=True) + test(True, line2, prefix, 1) + test(False, prefix, None, None, bell=True) + test(False, prefix, None, None, bell=True) + + def test_fetch_cursor_move(self): + # Move cursor after fetch + self.history.fetch(reverse=True) # initialization + self.text.mark_set('insert', 'iomark') + self.fetch_test(True, line2, None, None, bell=True) + + def test_fetch_edit(self): + # Edit after fetch + self.history.fetch(reverse=True) # initialization + self.text.delete('iomark', 'insert', ) + self.text.insert('iomark', 'a =') + self.fetch_test(True, line1, 'a =', 0) # prefix is reset + + def test_history_prev_next(self): + # Minimally test functions bound to events + self.history.history_prev('dummy event') + self.assertEqual(self.history.pointer, 1) + self.history.history_next('dummy event') + self.assertEqual(self.history.pointer, None) + + +if __name__ == '__main__': + unittest.main(verbosity=2, exit=2) diff --git a/micromamba_root/envs/pytorch_env/Lib/idlelib/idle_test/test_hyperparser.py b/micromamba_root/envs/pytorch_env/Lib/idlelib/idle_test/test_hyperparser.py new file mode 100644 index 0000000000000000000000000000000000000000..343843c4166e97dcab123c4b9835341e15f65739 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/idlelib/idle_test/test_hyperparser.py @@ -0,0 +1,276 @@ +"Test hyperparser, coverage 98%." + +from idlelib.hyperparser import HyperParser +import unittest +from test.support import requires +from tkinter import Tk, Text +from idlelib.editor import EditorWindow + +class DummyEditwin: + def __init__(self, text): + self.text = text + self.indentwidth = 8 + self.tabwidth = 8 + self.prompt_last_line = '>>>' + self.num_context_lines = 50, 500, 1000 + + _build_char_in_string_func = EditorWindow._build_char_in_string_func + is_char_in_string = EditorWindow.is_char_in_string + + +class HyperParserTest(unittest.TestCase): + code = ( + '"""This is a module docstring"""\n' + '# this line is a comment\n' + 'x = "this is a string"\n' + "y = 'this is also a string'\n" + 'l = [i for i in range(10)]\n' + 'm = [py*py for # comment\n' + ' py in l]\n' + 'x.__len__\n' + "z = ((r'asdf')+('a')))\n" + '[x for x in\n' + 'for = False\n' + 'cliché = "this is a string with unicode, what a cliché"' + ) + + @classmethod + def setUpClass(cls): + requires('gui') + cls.root = Tk() + cls.root.withdraw() + cls.text = Text(cls.root) + cls.editwin = DummyEditwin(cls.text) + + @classmethod + def tearDownClass(cls): + del cls.text, cls.editwin + cls.root.destroy() + del cls.root + + def setUp(self): + self.text.insert('insert', self.code) + + def tearDown(self): + self.text.delete('1.0', 'end') + self.editwin.prompt_last_line = '>>>' + + def get_parser(self, index): + """ + Return a parser object with index at 'index' + """ + return HyperParser(self.editwin, index) + + def test_init(self): + """ + test corner cases in the init method + """ + with self.assertRaises(ValueError) as ve: + self.text.tag_add('console', '1.0', '1.end') + p = self.get_parser('1.5') + self.assertIn('precedes', str(ve.exception)) + + # test without ps1 + self.editwin.prompt_last_line = '' + + # number of lines lesser than 50 + p = self.get_parser('end') + self.assertEqual(p.rawtext, self.text.get('1.0', 'end')) + + # number of lines greater than 50 + self.text.insert('end', self.text.get('1.0', 'end')*4) + p = self.get_parser('54.5') + + def test_is_in_string(self): + get = self.get_parser + + p = get('1.0') + self.assertFalse(p.is_in_string()) + p = get('1.4') + self.assertTrue(p.is_in_string()) + p = get('2.3') + self.assertFalse(p.is_in_string()) + p = get('3.3') + self.assertFalse(p.is_in_string()) + p = get('3.7') + self.assertTrue(p.is_in_string()) + p = get('4.6') + self.assertTrue(p.is_in_string()) + p = get('12.54') + self.assertTrue(p.is_in_string()) + + def test_is_in_code(self): + get = self.get_parser + + p = get('1.0') + self.assertTrue(p.is_in_code()) + p = get('1.1') + self.assertFalse(p.is_in_code()) + p = get('2.5') + self.assertFalse(p.is_in_code()) + p = get('3.4') + self.assertTrue(p.is_in_code()) + p = get('3.6') + self.assertFalse(p.is_in_code()) + p = get('4.14') + self.assertFalse(p.is_in_code()) + + def test_get_surrounding_bracket(self): + get = self.get_parser + + def without_mustclose(parser): + # a utility function to get surrounding bracket + # with mustclose=False + return parser.get_surrounding_brackets(mustclose=False) + + def with_mustclose(parser): + # a utility function to get surrounding bracket + # with mustclose=True + return parser.get_surrounding_brackets(mustclose=True) + + p = get('3.2') + self.assertIsNone(with_mustclose(p)) + self.assertIsNone(without_mustclose(p)) + + p = get('5.6') + self.assertTupleEqual(without_mustclose(p), ('5.4', '5.25')) + self.assertTupleEqual(without_mustclose(p), with_mustclose(p)) + + p = get('5.23') + self.assertTupleEqual(without_mustclose(p), ('5.21', '5.24')) + self.assertTupleEqual(without_mustclose(p), with_mustclose(p)) + + p = get('6.15') + self.assertTupleEqual(without_mustclose(p), ('6.4', '6.end')) + self.assertIsNone(with_mustclose(p)) + + p = get('9.end') + self.assertIsNone(with_mustclose(p)) + self.assertIsNone(without_mustclose(p)) + + def test_get_expression(self): + get = self.get_parser + + p = get('4.2') + self.assertEqual(p.get_expression(), 'y ') + + p = get('4.7') + with self.assertRaises(ValueError) as ve: + p.get_expression() + self.assertIn('is inside a code', str(ve.exception)) + + p = get('5.25') + self.assertEqual(p.get_expression(), 'range(10)') + + p = get('6.7') + self.assertEqual(p.get_expression(), 'py') + + p = get('6.8') + self.assertEqual(p.get_expression(), '') + + p = get('7.9') + self.assertEqual(p.get_expression(), 'py') + + p = get('8.end') + self.assertEqual(p.get_expression(), 'x.__len__') + + p = get('9.13') + self.assertEqual(p.get_expression(), "r'asdf'") + + p = get('9.17') + with self.assertRaises(ValueError) as ve: + p.get_expression() + self.assertIn('is inside a code', str(ve.exception)) + + p = get('10.0') + self.assertEqual(p.get_expression(), '') + + p = get('10.6') + self.assertEqual(p.get_expression(), '') + + p = get('10.11') + self.assertEqual(p.get_expression(), '') + + p = get('11.3') + self.assertEqual(p.get_expression(), '') + + p = get('11.11') + self.assertEqual(p.get_expression(), 'False') + + p = get('12.6') + self.assertEqual(p.get_expression(), 'cliché') + + def test_eat_identifier(self): + def is_valid_id(candidate): + result = HyperParser._eat_identifier(candidate, 0, len(candidate)) + if result == len(candidate): + return True + elif result == 0: + return False + else: + err_msg = "Unexpected result: {} (expected 0 or {}".format( + result, len(candidate) + ) + raise Exception(err_msg) + + # invalid first character which is valid elsewhere in an identifier + self.assertFalse(is_valid_id('2notid')) + + # ASCII-only valid identifiers + self.assertTrue(is_valid_id('valid_id')) + self.assertTrue(is_valid_id('_valid_id')) + self.assertTrue(is_valid_id('valid_id_')) + self.assertTrue(is_valid_id('_2valid_id')) + + # keywords which should be "eaten" + self.assertTrue(is_valid_id('True')) + self.assertTrue(is_valid_id('False')) + self.assertTrue(is_valid_id('None')) + + # keywords which should not be "eaten" + self.assertFalse(is_valid_id('for')) + self.assertFalse(is_valid_id('import')) + self.assertFalse(is_valid_id('return')) + + # valid unicode identifiers + self.assertTrue(is_valid_id('cliche')) + self.assertTrue(is_valid_id('cliché')) + self.assertTrue(is_valid_id('a٢')) + + # invalid unicode identifiers + self.assertFalse(is_valid_id('2a')) + self.assertFalse(is_valid_id('٢a')) + self.assertFalse(is_valid_id('a²')) + + # valid identifier after "punctuation" + self.assertEqual(HyperParser._eat_identifier('+ var', 0, 5), len('var')) + self.assertEqual(HyperParser._eat_identifier('+var', 0, 4), len('var')) + self.assertEqual(HyperParser._eat_identifier('.var', 0, 4), len('var')) + + # invalid identifiers + self.assertFalse(is_valid_id('+')) + self.assertFalse(is_valid_id(' ')) + self.assertFalse(is_valid_id(':')) + self.assertFalse(is_valid_id('?')) + self.assertFalse(is_valid_id('^')) + self.assertFalse(is_valid_id('\\')) + self.assertFalse(is_valid_id('"')) + self.assertFalse(is_valid_id('"a string"')) + + def test_eat_identifier_various_lengths(self): + eat_id = HyperParser._eat_identifier + + for length in range(1, 21): + self.assertEqual(eat_id('a' * length, 0, length), length) + self.assertEqual(eat_id('é' * length, 0, length), length) + self.assertEqual(eat_id('a' + '2' * (length - 1), 0, length), length) + self.assertEqual(eat_id('é' + '2' * (length - 1), 0, length), length) + self.assertEqual(eat_id('é' + 'a' * (length - 1), 0, length), length) + self.assertEqual(eat_id('é' * (length - 1) + 'a', 0, length), length) + self.assertEqual(eat_id('+' * length, 0, length), 0) + self.assertEqual(eat_id('2' + 'a' * (length - 1), 0, length), 0) + self.assertEqual(eat_id('2' + 'é' * (length - 1), 0, length), 0) + + +if __name__ == '__main__': + unittest.main(verbosity=2) diff --git a/micromamba_root/envs/pytorch_env/Lib/idlelib/idle_test/test_iomenu.py b/micromamba_root/envs/pytorch_env/Lib/idlelib/idle_test/test_iomenu.py new file mode 100644 index 0000000000000000000000000000000000000000..e0642cf0cabef0470424d9e04cfc4aa68c4adb26 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/idlelib/idle_test/test_iomenu.py @@ -0,0 +1,84 @@ +"Test , coverage 17%." + +from idlelib import iomenu +import unittest +from test.support import requires +from tkinter import Tk +from idlelib.editor import EditorWindow +from idlelib import util +from idlelib.idle_test.mock_idle import Func + +# Fail if either tokenize.open and t.detect_encoding does not exist. +# These are used in loadfile and encode. +# Also used in pyshell.MI.execfile and runscript.tabnanny. +from tokenize import open, detect_encoding +# Remove when we have proper tests that use both. + + +class IOBindingTest(unittest.TestCase): + + @classmethod + def setUpClass(cls): + requires('gui') + cls.root = Tk() + cls.root.withdraw() + cls.editwin = EditorWindow(root=cls.root) + cls.io = iomenu.IOBinding(cls.editwin) + + @classmethod + def tearDownClass(cls): + cls.io.close() + cls.editwin._close() + del cls.editwin + cls.root.update_idletasks() + for id in cls.root.tk.call('after', 'info'): + cls.root.after_cancel(id) # Need for EditorWindow. + cls.root.destroy() + del cls.root + + def test_init(self): + self.assertIs(self.io.editwin, self.editwin) + + def test_fixnewlines_end(self): + eq = self.assertEqual + io = self.io + fix = io.fixnewlines + text = io.editwin.text + + # Make the editor temporarily look like Shell. + self.editwin.interp = None + shelltext = '>>> if 1' + self.editwin.get_prompt_text = Func(result=shelltext) + eq(fix(), shelltext) # Get... call and '\n' not added. + del self.editwin.interp, self.editwin.get_prompt_text + + text.insert(1.0, 'a') + eq(fix(), 'a'+io.eol_convention) + eq(text.get('1.0', 'end-1c'), 'a\n') + eq(fix(), 'a'+io.eol_convention) + + +def _extension_in_filetypes(extension): + return any( + f'*{extension}' in filetype_tuple[1] + for filetype_tuple in iomenu.IOBinding.filetypes + ) + + +class FiletypesTest(unittest.TestCase): + def test_python_source_files(self): + for extension in util.py_extensions: + with self.subTest(extension=extension): + self.assertTrue( + _extension_in_filetypes(extension) + ) + + def test_text_files(self): + self.assertTrue(_extension_in_filetypes('.txt')) + + def test_all_files(self): + self.assertTrue(_extension_in_filetypes('')) + + +if __name__ == '__main__': + unittest.main(verbosity=2) diff --git a/micromamba_root/envs/pytorch_env/Lib/idlelib/idle_test/test_macosx.py b/micromamba_root/envs/pytorch_env/Lib/idlelib/idle_test/test_macosx.py new file mode 100644 index 0000000000000000000000000000000000000000..86da8849e5ca00f55affd806b4b89e74f55fdcb5 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/idlelib/idle_test/test_macosx.py @@ -0,0 +1,113 @@ +"Test macosx, coverage 45% on Windows." + +from idlelib import macosx +import unittest +from test.support import requires +import tkinter as tk +import unittest.mock as mock +from idlelib.filelist import FileList + +mactypes = {'carbon', 'cocoa', 'xquartz'} +nontypes = {'other'} +alltypes = mactypes | nontypes + + +def setUpModule(): + global orig_tktype + orig_tktype = macosx._tk_type + + +def tearDownModule(): + macosx._tk_type = orig_tktype + + +class InitTktypeTest(unittest.TestCase): + "Test _init_tk_type." + + @classmethod + def setUpClass(cls): + requires('gui') + cls.root = tk.Tk() + cls.root.withdraw() + cls.orig_platform = macosx.platform + + @classmethod + def tearDownClass(cls): + cls.root.update_idletasks() + cls.root.destroy() + del cls.root + macosx.platform = cls.orig_platform + + def test_init_sets_tktype(self): + "Test that _init_tk_type sets _tk_type according to platform." + for platform, types in ('darwin', alltypes), ('other', nontypes): + with self.subTest(platform=platform): + macosx.platform = platform + macosx._tk_type = None + macosx._init_tk_type() + self.assertIn(macosx._tk_type, types) + + +class IsTypeTkTest(unittest.TestCase): + "Test each of the four isTypeTk predecates." + isfuncs = ((macosx.isAquaTk, ('carbon', 'cocoa')), + (macosx.isCarbonTk, ('carbon')), + (macosx.isCocoaTk, ('cocoa')), + (macosx.isXQuartz, ('xquartz')), + ) + + @mock.patch('idlelib.macosx._init_tk_type') + def test_is_calls_init(self, mockinit): + "Test that each isTypeTk calls _init_tk_type when _tk_type is None." + macosx._tk_type = None + for func, whentrue in self.isfuncs: + with self.subTest(func=func): + func() + self.assertTrue(mockinit.called) + mockinit.reset_mock() + + def test_isfuncs(self): + "Test that each isTypeTk return correct bool." + for func, whentrue in self.isfuncs: + for tktype in alltypes: + with self.subTest(func=func, whentrue=whentrue, tktype=tktype): + macosx._tk_type = tktype + (self.assertTrue if tktype in whentrue else self.assertFalse)\ + (func()) + + +class SetupTest(unittest.TestCase): + "Test setupApp." + + @classmethod + def setUpClass(cls): + requires('gui') + cls.root = tk.Tk() + cls.root.withdraw() + def cmd(tkpath, func): + assert isinstance(tkpath, str) + assert isinstance(func, type(cmd)) + cls.root.createcommand = cmd + + @classmethod + def tearDownClass(cls): + cls.root.update_idletasks() + cls.root.destroy() + del cls.root + + @mock.patch('idlelib.macosx.overrideRootMenu') #27312 + def test_setupapp(self, overrideRootMenu): + "Call setupApp with each possible graphics type." + root = self.root + flist = FileList(root) + for tktype in alltypes: + with self.subTest(tktype=tktype): + macosx._tk_type = tktype + macosx.setupApp(root, flist) + if tktype in ('carbon', 'cocoa'): + self.assertTrue(overrideRootMenu.called) + overrideRootMenu.reset_mock() + + +if __name__ == '__main__': + unittest.main(verbosity=2) diff --git a/micromamba_root/envs/pytorch_env/Lib/idlelib/idle_test/test_mainmenu.py b/micromamba_root/envs/pytorch_env/Lib/idlelib/idle_test/test_mainmenu.py new file mode 100644 index 0000000000000000000000000000000000000000..51d2accfe48a1c738b73509563d21bc59e5d3a12 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/idlelib/idle_test/test_mainmenu.py @@ -0,0 +1,42 @@ +"Test mainmenu, coverage 100%." +# Reported as 88%; mocking turtledemo absence would have no point. + +from idlelib import mainmenu +import re +import unittest + + +class MainMenuTest(unittest.TestCase): + + def test_menudefs(self): + actual = [item[0] for item in mainmenu.menudefs] + expect = ['file', 'edit', 'format', 'run', 'shell', + 'debug', 'options', 'window', 'help'] + self.assertEqual(actual, expect) + + def test_default_keydefs(self): + self.assertGreaterEqual(len(mainmenu.default_keydefs), 50) + + def test_tcl_indexes(self): + # Test tcl patterns used to find menuitem to alter. + # On failure, change pattern here and in function(s). + # Patterns here have '.*' for re instead of '*' for tcl. + for menu, pattern in ( + ('debug', '.*tack.*iewer'), # PyShell.debug_menu_postcommand + ('options', '.*ode.*ontext'), # EW.__init__, CodeContext.toggle... + ('options', '.*ine.*umbers'), # EW.__init__, EW.toggle...event. + ): + with self.subTest(menu=menu, pattern=pattern): + for menutup in mainmenu.menudefs: + if menutup[0] == menu: + break + else: + self.assertTrue(0, f"{menu} not in menudefs") + self.assertTrue(any(re.search(pattern, menuitem[0]) + for menuitem in menutup[1] + if menuitem is not None), # Separator. + f"{pattern} not in {menu}") + + +if __name__ == '__main__': + unittest.main(verbosity=2) diff --git a/micromamba_root/envs/pytorch_env/Lib/idlelib/idle_test/test_multicall.py b/micromamba_root/envs/pytorch_env/Lib/idlelib/idle_test/test_multicall.py new file mode 100644 index 0000000000000000000000000000000000000000..b3a3bfb88f9c31fa025d112803991212261e2508 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/idlelib/idle_test/test_multicall.py @@ -0,0 +1,48 @@ +"Test multicall, coverage 33%." + +from idlelib import multicall +import unittest +from test.support import requires +from tkinter import Tk, Text + + +class MultiCallTest(unittest.TestCase): + + @classmethod + def setUpClass(cls): + requires('gui') + cls.root = Tk() + cls.root.withdraw() + cls.mc = multicall.MultiCallCreator(Text) + + @classmethod + def tearDownClass(cls): + del cls.mc + cls.root.update_idletasks() +## for id in cls.root.tk.call('after', 'info'): +## cls.root.after_cancel(id) # Need for EditorWindow. + cls.root.destroy() + del cls.root + + def test_creator(self): + mc = self.mc + self.assertIs(multicall._multicall_dict[Text], mc) + self.assertTrue(issubclass(mc, Text)) + mc2 = multicall.MultiCallCreator(Text) + self.assertIs(mc, mc2) + + def test_init(self): + mctext = self.mc(self.root) + self.assertIsInstance(mctext._MultiCall__binders, list) + + def test_yview(self): + # Added for tree.wheel_event + # (it depends on yview to not be overridden) + mc = self.mc + self.assertIs(mc.yview, Text.yview) + mctext = self.mc(self.root) + self.assertIs(mctext.yview.__func__, Text.yview) + + +if __name__ == '__main__': + unittest.main(verbosity=2) diff --git a/micromamba_root/envs/pytorch_env/Lib/idlelib/idle_test/test_outwin.py b/micromamba_root/envs/pytorch_env/Lib/idlelib/idle_test/test_outwin.py new file mode 100644 index 0000000000000000000000000000000000000000..d6e85ad674417c13bed1e95adf32ac83521382ee --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/idlelib/idle_test/test_outwin.py @@ -0,0 +1,166 @@ +"Test outwin, coverage 76%." + +from idlelib import outwin +import unittest +from test.support import requires +from tkinter import Tk, Text +from idlelib.idle_test.mock_tk import Mbox_func +from idlelib.idle_test.mock_idle import Func +from unittest import mock + + +class OutputWindowTest(unittest.TestCase): + + @classmethod + def setUpClass(cls): + requires('gui') + root = cls.root = Tk() + root.withdraw() + w = cls.window = outwin.OutputWindow(None, None, None, root) + cls.text = w.text = Text(root) + + @classmethod + def tearDownClass(cls): + cls.window.close() + del cls.text, cls.window + cls.root.destroy() + del cls.root + + def setUp(self): + self.text.delete('1.0', 'end') + + def test_ispythonsource(self): + # OutputWindow overrides ispythonsource to always return False. + w = self.window + self.assertFalse(w.ispythonsource('test.txt')) + self.assertFalse(w.ispythonsource(__file__)) + + def test_window_title(self): + self.assertEqual(self.window.top.title(), 'Output') + + def test_maybesave(self): + w = self.window + eq = self.assertEqual + w.get_saved = Func() + + w.get_saved.result = False + eq(w.maybesave(), 'no') + eq(w.get_saved.called, 1) + + w.get_saved.result = True + eq(w.maybesave(), 'yes') + eq(w.get_saved.called, 2) + del w.get_saved + + def test_write(self): + eq = self.assertEqual + delete = self.text.delete + get = self.text.get + write = self.window.write + + # No new line - insert stays on same line. + delete('1.0', 'end') + test_text = 'test text' + eq(write(test_text), len(test_text)) + eq(get('1.0', '1.end'), 'test text') + eq(get('insert linestart', 'insert lineend'), 'test text') + + # New line - insert moves to next line. + delete('1.0', 'end') + test_text = 'test text\n' + eq(write(test_text), len(test_text)) + eq(get('1.0', '1.end'), 'test text') + eq(get('insert linestart', 'insert lineend'), '') + + # Text after new line is tagged for second line of Text widget. + delete('1.0', 'end') + test_text = 'test text\nLine 2' + eq(write(test_text), len(test_text)) + eq(get('1.0', '1.end'), 'test text') + eq(get('2.0', '2.end'), 'Line 2') + eq(get('insert linestart', 'insert lineend'), 'Line 2') + + # Test tags. + delete('1.0', 'end') + test_text = 'test text\n' + test_text2 = 'Line 2\n' + eq(write(test_text, tags='mytag'), len(test_text)) + eq(write(test_text2, tags='secondtag'), len(test_text2)) + eq(get('mytag.first', 'mytag.last'), test_text) + eq(get('secondtag.first', 'secondtag.last'), test_text2) + eq(get('1.0', '1.end'), test_text.rstrip('\n')) + eq(get('2.0', '2.end'), test_text2.rstrip('\n')) + + def test_writelines(self): + eq = self.assertEqual + get = self.text.get + writelines = self.window.writelines + + writelines(('Line 1\n', 'Line 2\n', 'Line 3\n')) + eq(get('1.0', '1.end'), 'Line 1') + eq(get('2.0', '2.end'), 'Line 2') + eq(get('3.0', '3.end'), 'Line 3') + eq(get('insert linestart', 'insert lineend'), '') + + def test_goto_file_line(self): + eq = self.assertEqual + w = self.window + text = self.text + + w.flist = mock.Mock() + gfl = w.flist.gotofileline = Func() + showerror = w.showerror = Mbox_func() + + # No file/line number. + w.write('Not a file line') + self.assertIsNone(w.goto_file_line()) + eq(gfl.called, 0) + eq(showerror.title, 'No special line') + + # Current file/line number. + w.write(f'{str(__file__)}: 42: spam\n') + w.write(f'{str(__file__)}: 21: spam') + self.assertIsNone(w.goto_file_line()) + eq(gfl.args, (str(__file__), 21)) + + # Previous line has file/line number. + text.delete('1.0', 'end') + w.write(f'{str(__file__)}: 42: spam\n') + w.write('Not a file line') + self.assertIsNone(w.goto_file_line()) + eq(gfl.args, (str(__file__), 42)) + + del w.flist.gotofileline, w.showerror + + +class ModuleFunctionTest(unittest.TestCase): + + @classmethod + def setUp(cls): + outwin.file_line_progs = None + + def test_compile_progs(self): + outwin.compile_progs() + for pat, regex in zip(outwin.file_line_pats, outwin.file_line_progs): + self.assertEqual(regex.pattern, pat) + + @mock.patch('builtins.open') + def test_file_line_helper(self, mock_open): + flh = outwin.file_line_helper + test_lines = ( + (r'foo file "testfile1", line 42, bar', ('testfile1', 42)), + (r'foo testfile2(21) bar', ('testfile2', 21)), + (r' testfile3 : 42: foo bar\n', (' testfile3 ', 42)), + (r'foo testfile4.py :1: ', ('foo testfile4.py ', 1)), + ('testfile5: \u19D4\u19D2: ', ('testfile5', 42)), + (r'testfile6: 42', None), # only one `:` + (r'testfile7 42 text', None) # no separators + ) + for line, expected_output in test_lines: + self.assertEqual(flh(line), expected_output) + if expected_output: + mock_open.assert_called_with(expected_output[0]) + + +if __name__ == '__main__': + unittest.main(verbosity=2) diff --git a/micromamba_root/envs/pytorch_env/Lib/idlelib/idle_test/test_parenmatch.py b/micromamba_root/envs/pytorch_env/Lib/idlelib/idle_test/test_parenmatch.py new file mode 100644 index 0000000000000000000000000000000000000000..2e10d7cd36760ff66f33c4b22ab62e5ac3f7d46c --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/idlelib/idle_test/test_parenmatch.py @@ -0,0 +1,112 @@ +"""Test parenmatch, coverage 91%. + +This must currently be a gui test because ParenMatch methods use +several text methods not defined on idlelib.idle_test.mock_tk.Text. +""" +from idlelib.parenmatch import ParenMatch +from test.support import requires +requires('gui') + +import unittest +from unittest.mock import Mock +from tkinter import Tk, Text + + +class DummyEditwin: + def __init__(self, text): + self.text = text + self.indentwidth = 8 + self.tabwidth = 8 + self.prompt_last_line = '>>>' # Currently not used by parenmatch. + + +class ParenMatchTest(unittest.TestCase): + + @classmethod + def setUpClass(cls): + cls.root = Tk() + cls.root.withdraw() + cls.text = Text(cls.root) + cls.editwin = DummyEditwin(cls.text) + cls.editwin.text_frame = Mock() + + @classmethod + def tearDownClass(cls): + del cls.text, cls.editwin + cls.root.update_idletasks() + cls.root.destroy() + del cls.root + + def tearDown(self): + self.text.delete('1.0', 'end') + + def get_parenmatch(self): + pm = ParenMatch(self.editwin) + pm.bell = lambda: None + return pm + + def test_paren_styles(self): + """ + Test ParenMatch with each style. + """ + text = self.text + pm = self.get_parenmatch() + for style, range1, range2 in ( + ('opener', ('1.10', '1.11'), ('1.10', '1.11')), + ('default',('1.10', '1.11'),('1.10', '1.11')), + ('parens', ('1.14', '1.15'), ('1.15', '1.16')), + ('expression', ('1.10', '1.15'), ('1.10', '1.16'))): + with self.subTest(style=style): + text.delete('1.0', 'end') + pm.STYLE = style + text.insert('insert', 'def foobar(a, b') + + pm.flash_paren_event('event') + self.assertIn('<>', text.event_info()) + if style == 'parens': + self.assertTupleEqual(text.tag_nextrange('paren', '1.0'), + ('1.10', '1.11')) + self.assertTupleEqual( + text.tag_prevrange('paren', 'end'), range1) + + text.insert('insert', ')') + pm.restore_event() + self.assertNotIn('<>', + text.event_info()) + self.assertEqual(text.tag_prevrange('paren', 'end'), ()) + + pm.paren_closed_event('event') + self.assertTupleEqual( + text.tag_prevrange('paren', 'end'), range2) + + def test_paren_corner(self): + """ + Test corner cases in flash_paren_event and paren_closed_event. + + Force execution of conditional expressions and alternate paths. + """ + text = self.text + pm = self.get_parenmatch() + + text.insert('insert', '# Comment.)') + pm.paren_closed_event('event') + + text.insert('insert', '\ndef') + pm.flash_paren_event('event') + pm.paren_closed_event('event') + + text.insert('insert', ' a, *arg)') + pm.paren_closed_event('event') + + def test_handle_restore_timer(self): + pm = self.get_parenmatch() + pm.restore_event = Mock() + pm.handle_restore_timer(0) + self.assertTrue(pm.restore_event.called) + pm.restore_event.reset_mock() + pm.handle_restore_timer(1) + self.assertFalse(pm.restore_event.called) + + +if __name__ == '__main__': + unittest.main(verbosity=2) diff --git a/micromamba_root/envs/pytorch_env/Lib/idlelib/idle_test/test_pathbrowser.py b/micromamba_root/envs/pytorch_env/Lib/idlelib/idle_test/test_pathbrowser.py new file mode 100644 index 0000000000000000000000000000000000000000..13d8b9e1ba9572afeefc20b2bf0f6b7bf3a50716 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/idlelib/idle_test/test_pathbrowser.py @@ -0,0 +1,86 @@ +"Test pathbrowser, coverage 95%." + +from idlelib import pathbrowser +import unittest +from test.support import requires +from tkinter import Tk + +import os.path +import pyclbr # for _modules +import sys # for sys.path + +from idlelib.idle_test.mock_idle import Func +import idlelib # for __file__ +from idlelib import browser +from idlelib.tree import TreeNode + + +class PathBrowserTest(unittest.TestCase): + + @classmethod + def setUpClass(cls): + requires('gui') + cls.root = Tk() + cls.root.withdraw() + cls.pb = pathbrowser.PathBrowser(cls.root, _utest=True) + + @classmethod + def tearDownClass(cls): + cls.pb.close() + cls.root.update_idletasks() + cls.root.destroy() + del cls.root, cls.pb + + def test_init(self): + pb = self.pb + eq = self.assertEqual + eq(pb.master, self.root) + eq(pyclbr._modules, {}) + self.assertIsInstance(pb.node, TreeNode) + self.assertIsNotNone(browser.file_open) + + def test_settitle(self): + pb = self.pb + self.assertEqual(pb.top.title(), 'Path Browser') + self.assertEqual(pb.top.iconname(), 'Path Browser') + + def test_rootnode(self): + pb = self.pb + rn = pb.rootnode() + self.assertIsInstance(rn, pathbrowser.PathBrowserTreeItem) + + def test_close(self): + pb = self.pb + pb.top.destroy = Func() + pb.node.destroy = Func() + pb.close() + self.assertTrue(pb.top.destroy.called) + self.assertTrue(pb.node.destroy.called) + del pb.top.destroy, pb.node.destroy + + +class DirBrowserTreeItemTest(unittest.TestCase): + + def test_DirBrowserTreeItem(self): + # Issue16226 - make sure that getting a sublist works + d = pathbrowser.DirBrowserTreeItem('') + d.GetSubList() + self.assertEqual('', d.GetText()) + + dir = os.path.split(os.path.abspath(idlelib.__file__))[0] + self.assertEqual(d.ispackagedir(dir), True) + self.assertEqual(d.ispackagedir(dir + '/Icons'), False) + + +class PathBrowserTreeItemTest(unittest.TestCase): + + def test_PathBrowserTreeItem(self): + p = pathbrowser.PathBrowserTreeItem() + self.assertEqual(p.GetText(), 'sys.path') + sub = p.GetSubList() + self.assertEqual(len(sub), len(sys.path)) + self.assertEqual(type(sub[0]), pathbrowser.DirBrowserTreeItem) + + +if __name__ == '__main__': + unittest.main(verbosity=2, exit=False) diff --git a/micromamba_root/envs/pytorch_env/Lib/idlelib/idle_test/test_percolator.py b/micromamba_root/envs/pytorch_env/Lib/idlelib/idle_test/test_percolator.py new file mode 100644 index 0000000000000000000000000000000000000000..17668ccd1227b7834cdf374287c812f23f048337 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/idlelib/idle_test/test_percolator.py @@ -0,0 +1,118 @@ +"Test percolator, coverage 100%." + +from idlelib.percolator import Percolator, Delegator +import unittest +from test.support import requires +requires('gui') +from tkinter import Text, Tk, END + + +class MyFilter(Delegator): + def __init__(self): + Delegator.__init__(self, None) + + def insert(self, *args): + self.insert_called_with = args + self.delegate.insert(*args) + + def delete(self, *args): + self.delete_called_with = args + self.delegate.delete(*args) + + def uppercase_insert(self, index, chars, tags=None): + chars = chars.upper() + self.delegate.insert(index, chars) + + def lowercase_insert(self, index, chars, tags=None): + chars = chars.lower() + self.delegate.insert(index, chars) + + def dont_insert(self, index, chars, tags=None): + pass + + +class PercolatorTest(unittest.TestCase): + + @classmethod + def setUpClass(cls): + cls.root = Tk() + cls.text = Text(cls.root) + + @classmethod + def tearDownClass(cls): + del cls.text + cls.root.destroy() + del cls.root + + def setUp(self): + self.percolator = Percolator(self.text) + self.filter_one = MyFilter() + self.filter_two = MyFilter() + self.percolator.insertfilter(self.filter_one) + self.percolator.insertfilter(self.filter_two) + + def tearDown(self): + self.percolator.close() + self.text.delete('1.0', END) + + def test_insertfilter(self): + self.assertIsNotNone(self.filter_one.delegate) + self.assertEqual(self.percolator.top, self.filter_two) + self.assertEqual(self.filter_two.delegate, self.filter_one) + self.assertEqual(self.filter_one.delegate, self.percolator.bottom) + + def test_removefilter(self): + filter_three = MyFilter() + self.percolator.removefilter(self.filter_two) + self.assertEqual(self.percolator.top, self.filter_one) + self.assertIsNone(self.filter_two.delegate) + + filter_three = MyFilter() + self.percolator.insertfilter(self.filter_two) + self.percolator.insertfilter(filter_three) + self.percolator.removefilter(self.filter_one) + self.assertEqual(self.percolator.top, filter_three) + self.assertEqual(filter_three.delegate, self.filter_two) + self.assertEqual(self.filter_two.delegate, self.percolator.bottom) + self.assertIsNone(self.filter_one.delegate) + + def test_insert(self): + self.text.insert('insert', 'foo') + self.assertEqual(self.text.get('1.0', END), 'foo\n') + self.assertTupleEqual(self.filter_one.insert_called_with, + ('insert', 'foo', None)) + + def test_modify_insert(self): + self.filter_one.insert = self.filter_one.uppercase_insert + self.text.insert('insert', 'bAr') + self.assertEqual(self.text.get('1.0', END), 'BAR\n') + + def test_modify_chain_insert(self): + filter_three = MyFilter() + self.percolator.insertfilter(filter_three) + self.filter_two.insert = self.filter_two.uppercase_insert + self.filter_one.insert = self.filter_one.lowercase_insert + self.text.insert('insert', 'BaR') + self.assertEqual(self.text.get('1.0', END), 'bar\n') + + def test_dont_insert(self): + self.filter_one.insert = self.filter_one.dont_insert + self.text.insert('insert', 'foo bar') + self.assertEqual(self.text.get('1.0', END), '\n') + self.filter_one.insert = self.filter_one.dont_insert + self.text.insert('insert', 'foo bar') + self.assertEqual(self.text.get('1.0', END), '\n') + + def test_without_filter(self): + self.text.insert('insert', 'hello') + self.assertEqual(self.text.get('1.0', 'end'), 'hello\n') + + def test_delete(self): + self.text.insert('insert', 'foo') + self.text.delete('1.0', '1.2') + self.assertEqual(self.text.get('1.0', END), 'o\n') + self.assertTupleEqual(self.filter_one.delete_called_with, + ('1.0', '1.2')) + +if __name__ == '__main__': + unittest.main(verbosity=2) diff --git a/micromamba_root/envs/pytorch_env/Lib/idlelib/idle_test/test_pyparse.py b/micromamba_root/envs/pytorch_env/Lib/idlelib/idle_test/test_pyparse.py new file mode 100644 index 0000000000000000000000000000000000000000..384db566ac76cdb44fb3c2998a989e848d56cd6c --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/idlelib/idle_test/test_pyparse.py @@ -0,0 +1,483 @@ +"Test pyparse, coverage 96%." + +from idlelib import pyparse +import unittest +from collections import namedtuple + + +class ParseMapTest(unittest.TestCase): + + def test_parsemap(self): + keepwhite = {ord(c): ord(c) for c in ' \t\n\r'} + mapping = pyparse.ParseMap(keepwhite) + self.assertEqual(mapping[ord('\t')], ord('\t')) + self.assertEqual(mapping[ord('a')], ord('x')) + self.assertEqual(mapping[1000], ord('x')) + + def test_trans(self): + # trans is the production instance of ParseMap, used in _study1 + parser = pyparse.Parser(4, 4) + self.assertEqual('\t a([{b}])b"c\'d\n'.translate(pyparse.trans), + 'xxx(((x)))x"x\'x\n') + + +class PyParseTest(unittest.TestCase): + + @classmethod + def setUpClass(cls): + cls.parser = pyparse.Parser(indentwidth=4, tabwidth=4) + + @classmethod + def tearDownClass(cls): + del cls.parser + + def test_init(self): + self.assertEqual(self.parser.indentwidth, 4) + self.assertEqual(self.parser.tabwidth, 4) + + def test_set_code(self): + eq = self.assertEqual + p = self.parser + setcode = p.set_code + + # Not empty and doesn't end with newline. + with self.assertRaises(AssertionError): + setcode('a') + + tests = ('', + 'a\n') + + for string in tests: + with self.subTest(string=string): + setcode(string) + eq(p.code, string) + eq(p.study_level, 0) + + def test_find_good_parse_start(self): + eq = self.assertEqual + p = self.parser + setcode = p.set_code + start = p.find_good_parse_start + def char_in_string_false(index): return False + + # First line starts with 'def' and ends with ':', then 0 is the pos. + setcode('def spam():\n') + eq(start(char_in_string_false), 0) + + # First line begins with a keyword in the list and ends + # with an open brace, then 0 is the pos. This is how + # hyperparser calls this function as the newline is not added + # in the editor, but rather on the call to setcode. + setcode('class spam( ' + ' \n') + eq(start(char_in_string_false), 0) + + # Split def across lines. + setcode('"""This is a module docstring"""\n' + 'class C:\n' + ' def __init__(self, a,\n' + ' b=True):\n' + ' pass\n' + ) + pos0, pos = 33, 42 # Start of 'class...', ' def' lines. + + # Passing no value or non-callable should fail (issue 32989). + with self.assertRaises(TypeError): + start() + with self.assertRaises(TypeError): + start(False) + + # Make text look like a string. This returns pos as the start + # position, but it's set to None. + self.assertIsNone(start(is_char_in_string=lambda index: True)) + + # Make all text look like it's not in a string. This means that it + # found a good start position. + eq(start(char_in_string_false), pos) + + # If the beginning of the def line is not in a string, then it + # returns that as the index. + eq(start(is_char_in_string=lambda index: index > pos), pos) + # If the beginning of the def line is in a string, then it + # looks for a previous index. + eq(start(is_char_in_string=lambda index: index >= pos), pos0) + # If everything before the 'def' is in a string, then returns None. + # The non-continuation def line returns 44 (see below). + eq(start(is_char_in_string=lambda index: index < pos), None) + + # Code without extra line break in def line - mostly returns the same + # values. + setcode('"""This is a module docstring"""\n' + 'class C:\n' + ' def __init__(self, a, b=True):\n' + ' pass\n' + ) # Does not affect class, def positions. + eq(start(char_in_string_false), pos) + eq(start(is_char_in_string=lambda index: index > pos), pos) + eq(start(is_char_in_string=lambda index: index >= pos), pos0) + # When the def line isn't split, this returns which doesn't match the + # split line test. + eq(start(is_char_in_string=lambda index: index < pos), pos) + + def test_set_lo(self): + code = ( + '"""This is a module docstring"""\n' + 'class C:\n' + ' def __init__(self, a,\n' + ' b=True):\n' + ' pass\n' + ) + pos = 42 + p = self.parser + p.set_code(code) + + # Previous character is not a newline. + with self.assertRaises(AssertionError): + p.set_lo(5) + + # A value of 0 doesn't change self.code. + p.set_lo(0) + self.assertEqual(p.code, code) + + # An index that is preceded by a newline. + p.set_lo(pos) + self.assertEqual(p.code, code[pos:]) + + def test_study1(self): + eq = self.assertEqual + p = self.parser + setcode = p.set_code + study = p._study1 + + (NONE, BACKSLASH, FIRST, NEXT, BRACKET) = range(5) + TestInfo = namedtuple('TestInfo', ['string', 'goodlines', + 'continuation']) + tests = ( + TestInfo('', [0], NONE), + # Docstrings. + TestInfo('"""This is a complete docstring."""\n', [0, 1], NONE), + TestInfo("'''This is a complete docstring.'''\n", [0, 1], NONE), + TestInfo('"""This is a continued docstring.\n', [0, 1], FIRST), + TestInfo("'''This is a continued docstring.\n", [0, 1], FIRST), + TestInfo('"""Closing quote does not match."\n', [0, 1], FIRST), + TestInfo('"""Bracket in docstring [\n', [0, 1], FIRST), + TestInfo("'''Incomplete two line docstring.\n\n", [0, 2], NEXT), + # Single-quoted strings. + TestInfo('"This is a complete string."\n', [0, 1], NONE), + TestInfo('"This is an incomplete string.\n', [0, 1], NONE), + TestInfo("'This is more incomplete.\n\n", [0, 1, 2], NONE), + # Comment (backslash does not continue comments). + TestInfo('# Comment\\\n', [0, 1], NONE), + # Brackets. + TestInfo('("""Complete string in bracket"""\n', [0, 1], BRACKET), + TestInfo('("""Open string in bracket\n', [0, 1], FIRST), + TestInfo('a = (1 + 2) - 5 *\\\n', [0, 1], BACKSLASH), # No bracket. + TestInfo('\n def function1(self, a,\n b):\n', + [0, 1, 3], NONE), + TestInfo('\n def function1(self, a,\\\n', [0, 1, 2], BRACKET), + TestInfo('\n def function1(self, a,\n', [0, 1, 2], BRACKET), + TestInfo('())\n', [0, 1], NONE), # Extra closer. + TestInfo(')(\n', [0, 1], BRACKET), # Extra closer. + # For the mismatched example, it doesn't look like continuation. + TestInfo('{)(]\n', [0, 1], NONE), # Mismatched. + ) + + for test in tests: + with self.subTest(string=test.string): + setcode(test.string) # resets study_level + study() + eq(p.study_level, 1) + eq(p.goodlines, test.goodlines) + eq(p.continuation, test.continuation) + + # Called again, just returns without reprocessing. + self.assertIsNone(study()) + + def test_get_continuation_type(self): + eq = self.assertEqual + p = self.parser + setcode = p.set_code + gettype = p.get_continuation_type + + (NONE, BACKSLASH, FIRST, NEXT, BRACKET) = range(5) + TestInfo = namedtuple('TestInfo', ['string', 'continuation']) + tests = ( + TestInfo('', NONE), + TestInfo('"""This is a continuation docstring.\n', FIRST), + TestInfo("'''This is a multiline-continued docstring.\n\n", NEXT), + TestInfo('a = (1 + 2) - 5 *\\\n', BACKSLASH), + TestInfo('\n def function1(self, a,\\\n', BRACKET) + ) + + for test in tests: + with self.subTest(string=test.string): + setcode(test.string) + eq(gettype(), test.continuation) + + def test_study2(self): + eq = self.assertEqual + p = self.parser + setcode = p.set_code + study = p._study2 + + TestInfo = namedtuple('TestInfo', ['string', 'start', 'end', 'lastch', + 'openbracket', 'bracketing']) + tests = ( + TestInfo('', 0, 0, '', None, ((0, 0),)), + TestInfo("'''This is a multiline continuation docstring.\n\n", + 0, 48, "'", None, ((0, 0), (0, 1), (48, 0))), + TestInfo(' # Comment\\\n', + 0, 12, '', None, ((0, 0), (1, 1), (12, 0))), + # A comment without a space is a special case + TestInfo(' #Comment\\\n', + 0, 0, '', None, ((0, 0),)), + # Backslash continuation. + TestInfo('a = (1 + 2) - 5 *\\\n', + 0, 19, '*', None, ((0, 0), (4, 1), (11, 0))), + # Bracket continuation with close. + TestInfo('\n def function1(self, a,\n b):\n', + 1, 48, ':', None, ((1, 0), (17, 1), (46, 0))), + # Bracket continuation with unneeded backslash. + TestInfo('\n def function1(self, a,\\\n', + 1, 28, ',', 17, ((1, 0), (17, 1))), + # Bracket continuation. + TestInfo('\n def function1(self, a,\n', + 1, 27, ',', 17, ((1, 0), (17, 1))), + # Bracket continuation with comment at end of line with text. + TestInfo('\n def function1(self, a, # End of line comment.\n', + 1, 51, ',', 17, ((1, 0), (17, 1), (28, 2), (51, 1))), + # Multi-line statement with comment line in between code lines. + TestInfo(' a = ["first item",\n # Comment line\n "next item",\n', + 0, 55, ',', 6, ((0, 0), (6, 1), (7, 2), (19, 1), + (23, 2), (38, 1), (42, 2), (53, 1))), + TestInfo('())\n', + 0, 4, ')', None, ((0, 0), (0, 1), (2, 0), (3, 0))), + TestInfo(')(\n', 0, 3, '(', 1, ((0, 0), (1, 0), (1, 1))), + # Wrong closers still decrement stack level. + TestInfo('{)(]\n', + 0, 5, ']', None, ((0, 0), (0, 1), (2, 0), (2, 1), (4, 0))), + # Character after backslash. + TestInfo(':\\a\n', 0, 4, '\\a', None, ((0, 0),)), + TestInfo('\n', 0, 0, '', None, ((0, 0),)), + ) + + for test in tests: + with self.subTest(string=test.string): + setcode(test.string) + study() + eq(p.study_level, 2) + eq(p.stmt_start, test.start) + eq(p.stmt_end, test.end) + eq(p.lastch, test.lastch) + eq(p.lastopenbracketpos, test.openbracket) + eq(p.stmt_bracketing, test.bracketing) + + # Called again, just returns without reprocessing. + self.assertIsNone(study()) + + def test_get_num_lines_in_stmt(self): + eq = self.assertEqual + p = self.parser + setcode = p.set_code + getlines = p.get_num_lines_in_stmt + + TestInfo = namedtuple('TestInfo', ['string', 'lines']) + tests = ( + TestInfo('[x for x in a]\n', 1), # Closed on one line. + TestInfo('[x\nfor x in a\n', 2), # Not closed. + TestInfo('[x\\\nfor x in a\\\n', 2), # "", unneeded backslashes. + TestInfo('[x\nfor x in a\n]\n', 3), # Closed on multi-line. + TestInfo('\n"""Docstring comment L1"""\nL2\nL3\nL4\n', 1), + TestInfo('\n"""Docstring comment L1\nL2"""\nL3\nL4\n', 1), + TestInfo('\n"""Docstring comment L1\\\nL2\\\nL3\\\nL4\\\n', 4), + TestInfo('\n\n"""Docstring comment L1\\\nL2\\\nL3\\\nL4\\\n"""\n', 5) + ) + + # Blank string doesn't have enough elements in goodlines. + setcode('') + with self.assertRaises(IndexError): + getlines() + + for test in tests: + with self.subTest(string=test.string): + setcode(test.string) + eq(getlines(), test.lines) + + def test_compute_bracket_indent(self): + eq = self.assertEqual + p = self.parser + setcode = p.set_code + indent = p.compute_bracket_indent + + TestInfo = namedtuple('TestInfo', ['string', 'spaces']) + tests = ( + TestInfo('def function1(self, a,\n', 14), + # Characters after bracket. + TestInfo('\n def function1(self, a,\n', 18), + TestInfo('\n\tdef function1(self, a,\n', 18), + # No characters after bracket. + TestInfo('\n def function1(\n', 8), + TestInfo('\n\tdef function1(\n', 8), + TestInfo('\n def function1( \n', 8), # Ignore extra spaces. + TestInfo('[\n"first item",\n # Comment line\n "next item",\n', 0), + TestInfo('[\n "first item",\n # Comment line\n "next item",\n', 2), + TestInfo('["first item",\n # Comment line\n "next item",\n', 1), + TestInfo('(\n', 4), + TestInfo('(a\n', 1), + ) + + # Must be C_BRACKET continuation type. + setcode('def function1(self, a, b):\n') + with self.assertRaises(AssertionError): + indent() + + for test in tests: + setcode(test.string) + eq(indent(), test.spaces) + + def test_compute_backslash_indent(self): + eq = self.assertEqual + p = self.parser + setcode = p.set_code + indent = p.compute_backslash_indent + + # Must be C_BACKSLASH continuation type. + errors = (('def function1(self, a, b\\\n'), # Bracket. + (' """ (\\\n'), # Docstring. + ('a = #\\\n'), # Inline comment. + ) + for string in errors: + with self.subTest(string=string): + setcode(string) + with self.assertRaises(AssertionError): + indent() + + TestInfo = namedtuple('TestInfo', ('string', 'spaces')) + tests = (TestInfo('a = (1 + 2) - 5 *\\\n', 4), + TestInfo('a = 1 + 2 - 5 *\\\n', 4), + TestInfo(' a = 1 + 2 - 5 *\\\n', 8), + TestInfo(' a = "spam"\\\n', 6), + TestInfo(' a = \\\n"a"\\\n', 4), + TestInfo(' a = #\\\n"a"\\\n', 5), + TestInfo('a == \\\n', 2), + TestInfo('a != \\\n', 2), + # Difference between containing = and those not. + TestInfo('\\\n', 2), + TestInfo(' \\\n', 6), + TestInfo('\t\\\n', 6), + TestInfo('a\\\n', 3), + TestInfo('{}\\\n', 4), + TestInfo('(1 + 2) - 5 *\\\n', 3), + ) + for test in tests: + with self.subTest(string=test.string): + setcode(test.string) + eq(indent(), test.spaces) + + def test_get_base_indent_string(self): + eq = self.assertEqual + p = self.parser + setcode = p.set_code + baseindent = p.get_base_indent_string + + TestInfo = namedtuple('TestInfo', ['string', 'indent']) + tests = (TestInfo('', ''), + TestInfo('def a():\n', ''), + TestInfo('\tdef a():\n', '\t'), + TestInfo(' def a():\n', ' '), + TestInfo(' def a(\n', ' '), + TestInfo('\t\n def a(\n', ' '), + TestInfo('\t\n # Comment.\n', ' '), + ) + + for test in tests: + with self.subTest(string=test.string): + setcode(test.string) + eq(baseindent(), test.indent) + + def test_is_block_opener(self): + yes = self.assertTrue + no = self.assertFalse + p = self.parser + setcode = p.set_code + opener = p.is_block_opener + + TestInfo = namedtuple('TestInfo', ['string', 'assert_']) + tests = ( + TestInfo('def a():\n', yes), + TestInfo('\n def function1(self, a,\n b):\n', yes), + TestInfo(':\n', yes), + TestInfo('a:\n', yes), + TestInfo('):\n', yes), + TestInfo('(:\n', yes), + TestInfo('":\n', no), + TestInfo('\n def function1(self, a,\n', no), + TestInfo('def function1(self, a):\n pass\n', no), + TestInfo('# A comment:\n', no), + TestInfo('"""A docstring:\n', no), + TestInfo('"""A docstring:\n', no), + ) + + for test in tests: + with self.subTest(string=test.string): + setcode(test.string) + test.assert_(opener()) + + def test_is_block_closer(self): + yes = self.assertTrue + no = self.assertFalse + p = self.parser + setcode = p.set_code + closer = p.is_block_closer + + TestInfo = namedtuple('TestInfo', ['string', 'assert_']) + tests = ( + TestInfo('return\n', yes), + TestInfo('\tbreak\n', yes), + TestInfo(' continue\n', yes), + TestInfo(' raise\n', yes), + TestInfo('pass \n', yes), + TestInfo('pass\t\n', yes), + TestInfo('return #\n', yes), + TestInfo('raised\n', no), + TestInfo('returning\n', no), + TestInfo('# return\n', no), + TestInfo('"""break\n', no), + TestInfo('"continue\n', no), + TestInfo('def function1(self, a):\n pass\n', yes), + ) + + for test in tests: + with self.subTest(string=test.string): + setcode(test.string) + test.assert_(closer()) + + def test_get_last_stmt_bracketing(self): + eq = self.assertEqual + p = self.parser + setcode = p.set_code + bracketing = p.get_last_stmt_bracketing + + TestInfo = namedtuple('TestInfo', ['string', 'bracket']) + tests = ( + TestInfo('', ((0, 0),)), + TestInfo('a\n', ((0, 0),)), + TestInfo('()()\n', ((0, 0), (0, 1), (2, 0), (2, 1), (4, 0))), + TestInfo('(\n)()\n', ((0, 0), (0, 1), (3, 0), (3, 1), (5, 0))), + TestInfo('()\n()\n', ((3, 0), (3, 1), (5, 0))), + TestInfo('()(\n)\n', ((0, 0), (0, 1), (2, 0), (2, 1), (5, 0))), + TestInfo('(())\n', ((0, 0), (0, 1), (1, 2), (3, 1), (4, 0))), + TestInfo('(\n())\n', ((0, 0), (0, 1), (2, 2), (4, 1), (5, 0))), + # Same as matched test. + TestInfo('{)(]\n', ((0, 0), (0, 1), (2, 0), (2, 1), (4, 0))), + TestInfo('(((())\n', + ((0, 0), (0, 1), (1, 2), (2, 3), (3, 4), (5, 3), (6, 2))), + ) + + for test in tests: + with self.subTest(string=test.string): + setcode(test.string) + eq(bracketing(), test.bracket) + + +if __name__ == '__main__': + unittest.main(verbosity=2) diff --git a/micromamba_root/envs/pytorch_env/Lib/idlelib/idle_test/test_pyshell.py b/micromamba_root/envs/pytorch_env/Lib/idlelib/idle_test/test_pyshell.py new file mode 100644 index 0000000000000000000000000000000000000000..706703965bffd6f74d3b5916b4c21be8c897426b --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/idlelib/idle_test/test_pyshell.py @@ -0,0 +1,148 @@ +"Test pyshell, coverage 12%." +# Plus coverage of test_warning. Was 20% with test_openshell. + +from idlelib import pyshell +import unittest +from test.support import requires +from tkinter import Tk + + +class FunctionTest(unittest.TestCase): + # Test stand-alone module level non-gui functions. + + def test_restart_line_wide(self): + eq = self.assertEqual + for file, mul, extra in (('', 22, ''), ('finame', 21, '=')): + width = 60 + bar = mul * '=' + with self.subTest(file=file, bar=bar): + file = file or 'Shell' + line = pyshell.restart_line(width, file) + eq(len(line), width) + eq(line, f"{bar+extra} RESTART: {file} {bar}") + + def test_restart_line_narrow(self): + expect, taglen = "= RESTART: Shell", 16 + for width in (taglen-1, taglen, taglen+1): + with self.subTest(width=width): + self.assertEqual(pyshell.restart_line(width, ''), expect) + self.assertEqual(pyshell.restart_line(taglen+2, ''), expect+' =') + + +class PyShellFileListTest(unittest.TestCase): + + @classmethod + def setUpClass(cls): + requires('gui') + cls.root = Tk() + cls.root.withdraw() + + @classmethod + def tearDownClass(cls): + #cls.root.update_idletasks() +## for id in cls.root.tk.call('after', 'info'): +## cls.root.after_cancel(id) # Need for EditorWindow. + cls.root.destroy() + del cls.root + + def test_init(self): + psfl = pyshell.PyShellFileList(self.root) + self.assertEqual(psfl.EditorWindow, pyshell.PyShellEditorWindow) + self.assertIsNone(psfl.pyshell) + +# The following sometimes causes 'invalid command name "109734456recolorize"'. +# Uncommenting after_cancel above prevents this, but results in +# TclError: bad window path name ".!listedtoplevel.!frame.text" +# which is normally prevented by after_cancel. +## def test_openshell(self): +## pyshell.use_subprocess = False +## ps = pyshell.PyShellFileList(self.root).open_shell() +## self.assertIsInstance(ps, pyshell.PyShell) + + +class PyShellRemoveLastNewlineAndSurroundingWhitespaceTest(unittest.TestCase): + regexp = pyshell.PyShell._last_newline_re + + def all_removed(self, text): + self.assertEqual('', self.regexp.sub('', text)) + + def none_removed(self, text): + self.assertEqual(text, self.regexp.sub('', text)) + + def check_result(self, text, expected): + self.assertEqual(expected, self.regexp.sub('', text)) + + def test_empty(self): + self.all_removed('') + + def test_newline(self): + self.all_removed('\n') + + def test_whitespace_no_newline(self): + self.all_removed(' ') + self.all_removed(' ') + self.all_removed(' ') + self.all_removed(' ' * 20) + self.all_removed('\t') + self.all_removed('\t\t') + self.all_removed('\t\t\t') + self.all_removed('\t' * 20) + self.all_removed('\t ') + self.all_removed(' \t') + self.all_removed(' \t \t ') + self.all_removed('\t \t \t') + + def test_newline_with_whitespace(self): + self.all_removed(' \n') + self.all_removed('\t\n') + self.all_removed(' \t\n') + self.all_removed('\t \n') + self.all_removed('\n ') + self.all_removed('\n\t') + self.all_removed('\n \t') + self.all_removed('\n\t ') + self.all_removed(' \n ') + self.all_removed('\t\n ') + self.all_removed(' \n\t') + self.all_removed('\t\n\t') + self.all_removed('\t \t \t\n') + self.all_removed(' \t \t \n') + self.all_removed('\n\t \t \t') + self.all_removed('\n \t \t ') + + def test_multiple_newlines(self): + self.check_result('\n\n', '\n') + self.check_result('\n' * 5, '\n' * 4) + self.check_result('\n' * 5 + '\t', '\n' * 4) + self.check_result('\n' * 20, '\n' * 19) + self.check_result('\n' * 20 + ' ', '\n' * 19) + self.check_result(' \n \n ', ' \n') + self.check_result(' \n\n ', ' \n') + self.check_result(' \n\n', ' \n') + self.check_result('\t\n\n', '\t\n') + self.check_result('\n\n ', '\n') + self.check_result('\n\n\t', '\n') + self.check_result(' \n \n ', ' \n') + self.check_result('\t\n\t\n\t', '\t\n') + + def test_non_whitespace(self): + self.none_removed('a') + self.check_result('a\n', 'a') + self.check_result('a\n ', 'a') + self.check_result('a \n ', 'a') + self.check_result('a \n\t', 'a') + self.none_removed('-') + self.check_result('-\n', '-') + self.none_removed('.') + self.check_result('.\n', '.') + + def test_unsupported_whitespace(self): + self.none_removed('\v') + self.none_removed('\n\v') + self.check_result('\v\n', '\v') + self.none_removed(' \n\v') + self.check_result('\v\n ', '\v') + + +if __name__ == '__main__': + unittest.main(verbosity=2) diff --git a/micromamba_root/envs/pytorch_env/Lib/idlelib/idle_test/test_query.py b/micromamba_root/envs/pytorch_env/Lib/idlelib/idle_test/test_query.py new file mode 100644 index 0000000000000000000000000000000000000000..bb12b2b08652d54717f314849d28a8bfc8f5c3bb --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/idlelib/idle_test/test_query.py @@ -0,0 +1,451 @@ +"""Test query, coverage 93%. + +Non-gui tests for Query, SectionName, ModuleName, and HelpSource use +dummy versions that extract the non-gui methods and add other needed +attributes. GUI tests create an instance of each class and simulate +entries and button clicks. Subclass tests only target the new code in +the subclass definition. + +The appearance of the widgets is checked by the Query and +HelpSource htests. These are run by running query.py. +""" +from idlelib import query +import unittest +from test.support import requires +from tkinter import Tk, END + +import sys +from unittest import mock +from idlelib.idle_test.mock_tk import Var + + +# NON-GUI TESTS + +class QueryTest(unittest.TestCase): + "Test Query base class." + + class Dummy_Query: + # Test the following Query methods. + entry_ok = query.Query.entry_ok + ok = query.Query.ok + cancel = query.Query.cancel + # Add attributes and initialization needed for tests. + def __init__(self, dummy_entry): + self.entry = Var(value=dummy_entry) + self.entry_error = {'text': ''} + self.result = None + self.destroyed = False + def showerror(self, message): + self.entry_error['text'] = message + def destroy(self): + self.destroyed = True + + def test_entry_ok_blank(self): + dialog = self.Dummy_Query(' ') + self.assertEqual(dialog.entry_ok(), None) + self.assertEqual((dialog.result, dialog.destroyed), (None, False)) + self.assertIn('blank line', dialog.entry_error['text']) + + def test_entry_ok_good(self): + dialog = self.Dummy_Query(' good ') + Equal = self.assertEqual + Equal(dialog.entry_ok(), 'good') + Equal((dialog.result, dialog.destroyed), (None, False)) + Equal(dialog.entry_error['text'], '') + + def test_ok_blank(self): + dialog = self.Dummy_Query('') + dialog.entry.focus_set = mock.Mock() + self.assertEqual(dialog.ok(), None) + self.assertTrue(dialog.entry.focus_set.called) + del dialog.entry.focus_set + self.assertEqual((dialog.result, dialog.destroyed), (None, False)) + + def test_ok_good(self): + dialog = self.Dummy_Query('good') + self.assertEqual(dialog.ok(), None) + self.assertEqual((dialog.result, dialog.destroyed), ('good', True)) + + def test_cancel(self): + dialog = self.Dummy_Query('does not matter') + self.assertEqual(dialog.cancel(), None) + self.assertEqual((dialog.result, dialog.destroyed), (None, True)) + + +class SectionNameTest(unittest.TestCase): + "Test SectionName subclass of Query." + + class Dummy_SectionName: + entry_ok = query.SectionName.entry_ok # Function being tested. + used_names = ['used'] + def __init__(self, dummy_entry): + self.entry = Var(value=dummy_entry) + self.entry_error = {'text': ''} + def showerror(self, message): + self.entry_error['text'] = message + + def test_blank_section_name(self): + dialog = self.Dummy_SectionName(' ') + self.assertEqual(dialog.entry_ok(), None) + self.assertIn('no name', dialog.entry_error['text']) + + def test_used_section_name(self): + dialog = self.Dummy_SectionName('used') + self.assertEqual(dialog.entry_ok(), None) + self.assertIn('use', dialog.entry_error['text']) + + def test_long_section_name(self): + dialog = self.Dummy_SectionName('good'*8) + self.assertEqual(dialog.entry_ok(), None) + self.assertIn('longer than 30', dialog.entry_error['text']) + + def test_good_section_name(self): + dialog = self.Dummy_SectionName(' good ') + self.assertEqual(dialog.entry_ok(), 'good') + self.assertEqual(dialog.entry_error['text'], '') + + +class ModuleNameTest(unittest.TestCase): + "Test ModuleName subclass of Query." + + class Dummy_ModuleName: + entry_ok = query.ModuleName.entry_ok # Function being tested. + text0 = '' + def __init__(self, dummy_entry): + self.entry = Var(value=dummy_entry) + self.entry_error = {'text': ''} + def showerror(self, message): + self.entry_error['text'] = message + + def test_blank_module_name(self): + dialog = self.Dummy_ModuleName(' ') + self.assertEqual(dialog.entry_ok(), None) + self.assertIn('no name', dialog.entry_error['text']) + + def test_bogus_module_name(self): + dialog = self.Dummy_ModuleName('__name_xyz123_should_not_exist__') + self.assertEqual(dialog.entry_ok(), None) + self.assertIn('not found', dialog.entry_error['text']) + + def test_c_source_name(self): + dialog = self.Dummy_ModuleName('itertools') + self.assertEqual(dialog.entry_ok(), None) + self.assertIn('source-based', dialog.entry_error['text']) + + def test_good_module_name(self): + dialog = self.Dummy_ModuleName('idlelib') + self.assertTrue(dialog.entry_ok().endswith('__init__.py')) + self.assertEqual(dialog.entry_error['text'], '') + dialog = self.Dummy_ModuleName('idlelib.idle') + self.assertTrue(dialog.entry_ok().endswith('idle.py')) + self.assertEqual(dialog.entry_error['text'], '') + + +class GotoTest(unittest.TestCase): + "Test Goto subclass of Query." + + class Dummy_ModuleName: + entry_ok = query.Goto.entry_ok # Function being tested. + def __init__(self, dummy_entry): + self.entry = Var(value=dummy_entry) + self.entry_error = {'text': ''} + def showerror(self, message): + self.entry_error['text'] = message + + def test_bogus_goto(self): + dialog = self.Dummy_ModuleName('a') + self.assertEqual(dialog.entry_ok(), None) + self.assertIn('not a base 10 integer', dialog.entry_error['text']) + + def test_bad_goto(self): + dialog = self.Dummy_ModuleName('0') + self.assertEqual(dialog.entry_ok(), None) + self.assertIn('not a positive integer', dialog.entry_error['text']) + + def test_good_goto(self): + dialog = self.Dummy_ModuleName('1') + self.assertEqual(dialog.entry_ok(), 1) + self.assertEqual(dialog.entry_error['text'], '') + + +# 3 HelpSource test classes each test one method. + +class HelpsourceBrowsefileTest(unittest.TestCase): + "Test browse_file method of ModuleName subclass of Query." + + class Dummy_HelpSource: + browse_file = query.HelpSource.browse_file + pathvar = Var() + + def test_file_replaces_path(self): + dialog = self.Dummy_HelpSource() + # Path is widget entry, either '' or something. + # Func return is file dialog return, either '' or something. + # Func return should override widget entry. + # We need all 4 combinations to test all (most) code paths. + for path, func, result in ( + ('', lambda a,b,c:'', ''), + ('', lambda a,b,c: __file__, __file__), + ('htest', lambda a,b,c:'', 'htest'), + ('htest', lambda a,b,c: __file__, __file__)): + with self.subTest(): + dialog.pathvar.set(path) + dialog.askfilename = func + dialog.browse_file() + self.assertEqual(dialog.pathvar.get(), result) + + +class HelpsourcePathokTest(unittest.TestCase): + "Test path_ok method of HelpSource subclass of Query." + + class Dummy_HelpSource: + path_ok = query.HelpSource.path_ok + def __init__(self, dummy_path): + self.path = Var(value=dummy_path) + self.path_error = {'text': ''} + def showerror(self, message, widget=None): + self.path_error['text'] = message + + orig_platform = query.platform # Set in test_path_ok_file. + @classmethod + def tearDownClass(cls): + query.platform = cls.orig_platform + + def test_path_ok_blank(self): + dialog = self.Dummy_HelpSource(' ') + self.assertEqual(dialog.path_ok(), None) + self.assertIn('no help file', dialog.path_error['text']) + + def test_path_ok_bad(self): + dialog = self.Dummy_HelpSource(__file__ + 'bad-bad-bad') + self.assertEqual(dialog.path_ok(), None) + self.assertIn('not exist', dialog.path_error['text']) + + def test_path_ok_web(self): + dialog = self.Dummy_HelpSource('') + Equal = self.assertEqual + for url in 'www.py.org', 'http://py.org': + with self.subTest(): + dialog.path.set(url) + self.assertEqual(dialog.path_ok(), url) + self.assertEqual(dialog.path_error['text'], '') + + def test_path_ok_file(self): + dialog = self.Dummy_HelpSource('') + for platform, prefix in ('darwin', 'file://'), ('other', ''): + with self.subTest(): + query.platform = platform + dialog.path.set(__file__) + self.assertEqual(dialog.path_ok(), prefix + __file__) + self.assertEqual(dialog.path_error['text'], '') + + +class HelpsourceEntryokTest(unittest.TestCase): + "Test entry_ok method of HelpSource subclass of Query." + + class Dummy_HelpSource: + entry_ok = query.HelpSource.entry_ok + entry_error = {} + path_error = {} + def item_ok(self): + return self.name + def path_ok(self): + return self.path + + def test_entry_ok_helpsource(self): + dialog = self.Dummy_HelpSource() + for name, path, result in ((None, None, None), + (None, 'doc.txt', None), + ('doc', None, None), + ('doc', 'doc.txt', ('doc', 'doc.txt'))): + with self.subTest(): + dialog.name, dialog.path = name, path + self.assertEqual(dialog.entry_ok(), result) + + +# 2 CustomRun test classes each test one method. + +class CustomRunCLIargsokTest(unittest.TestCase): + "Test cli_ok method of the CustomRun subclass of Query." + + class Dummy_CustomRun: + cli_args_ok = query.CustomRun.cli_args_ok + def __init__(self, dummy_entry): + self.entry = Var(value=dummy_entry) + self.entry_error = {'text': ''} + def showerror(self, message): + self.entry_error['text'] = message + + def test_blank_args(self): + dialog = self.Dummy_CustomRun(' ') + self.assertEqual(dialog.cli_args_ok(), []) + + def test_invalid_args(self): + dialog = self.Dummy_CustomRun("'no-closing-quote") + self.assertEqual(dialog.cli_args_ok(), None) + self.assertIn('No closing', dialog.entry_error['text']) + + def test_good_args(self): + args = ['-n', '10', '--verbose', '-p', '/path', '--name'] + dialog = self.Dummy_CustomRun(' '.join(args) + ' "my name"') + self.assertEqual(dialog.cli_args_ok(), args + ["my name"]) + self.assertEqual(dialog.entry_error['text'], '') + + +class CustomRunEntryokTest(unittest.TestCase): + "Test entry_ok method of the CustomRun subclass of Query." + + class Dummy_CustomRun: + entry_ok = query.CustomRun.entry_ok + entry_error = {} + restartvar = Var() + def cli_args_ok(self): + return self.cli_args + + def test_entry_ok_customrun(self): + dialog = self.Dummy_CustomRun() + for restart in {True, False}: + dialog.restartvar.set(restart) + for cli_args, result in ((None, None), + (['my arg'], (['my arg'], restart))): + with self.subTest(restart=restart, cli_args=cli_args): + dialog.cli_args = cli_args + self.assertEqual(dialog.entry_ok(), result) + + +# GUI TESTS + +class QueryGuiTest(unittest.TestCase): + + @classmethod + def setUpClass(cls): + requires('gui') + cls.root = root = Tk() + cls.root.withdraw() + cls.dialog = query.Query(root, 'TEST', 'test', _utest=True) + cls.dialog.destroy = mock.Mock() + + @classmethod + def tearDownClass(cls): + del cls.dialog.destroy + del cls.dialog + cls.root.destroy() + del cls.root + + def setUp(self): + self.dialog.entry.delete(0, 'end') + self.dialog.result = None + self.dialog.destroy.reset_mock() + + def test_click_ok(self): + dialog = self.dialog + dialog.entry.insert(0, 'abc') + dialog.button_ok.invoke() + self.assertEqual(dialog.result, 'abc') + self.assertTrue(dialog.destroy.called) + + def test_click_blank(self): + dialog = self.dialog + dialog.button_ok.invoke() + self.assertEqual(dialog.result, None) + self.assertFalse(dialog.destroy.called) + + def test_click_cancel(self): + dialog = self.dialog + dialog.entry.insert(0, 'abc') + dialog.button_cancel.invoke() + self.assertEqual(dialog.result, None) + self.assertTrue(dialog.destroy.called) + + +class SectionnameGuiTest(unittest.TestCase): + + @classmethod + def setUpClass(cls): + requires('gui') + + def test_click_section_name(self): + root = Tk() + root.withdraw() + dialog = query.SectionName(root, 'T', 't', {'abc'}, _utest=True) + Equal = self.assertEqual + self.assertEqual(dialog.used_names, {'abc'}) + dialog.entry.insert(0, 'okay') + dialog.button_ok.invoke() + self.assertEqual(dialog.result, 'okay') + root.destroy() + + +class ModulenameGuiTest(unittest.TestCase): + + @classmethod + def setUpClass(cls): + requires('gui') + + def test_click_module_name(self): + root = Tk() + root.withdraw() + dialog = query.ModuleName(root, 'T', 't', 'idlelib', _utest=True) + self.assertEqual(dialog.text0, 'idlelib') + self.assertEqual(dialog.entry.get(), 'idlelib') + dialog.button_ok.invoke() + self.assertTrue(dialog.result.endswith('__init__.py')) + root.destroy() + + +class GotoGuiTest(unittest.TestCase): + + @classmethod + def setUpClass(cls): + requires('gui') + + def test_click_module_name(self): + root = Tk() + root.withdraw() + dialog = query.Goto(root, 'T', 't', _utest=True) + dialog.entry.insert(0, '22') + dialog.button_ok.invoke() + self.assertEqual(dialog.result, 22) + root.destroy() + + +class HelpsourceGuiTest(unittest.TestCase): + + @classmethod + def setUpClass(cls): + requires('gui') + + def test_click_help_source(self): + root = Tk() + root.withdraw() + dialog = query.HelpSource(root, 'T', menuitem='__test__', + filepath=__file__, _utest=True) + Equal = self.assertEqual + Equal(dialog.entry.get(), '__test__') + Equal(dialog.path.get(), __file__) + dialog.button_ok.invoke() + prefix = "file://" if sys.platform == 'darwin' else '' + Equal(dialog.result, ('__test__', prefix + __file__)) + root.destroy() + + +class CustomRunGuiTest(unittest.TestCase): + + @classmethod + def setUpClass(cls): + requires('gui') + + def test_click_args(self): + root = Tk() + root.withdraw() + dialog = query.CustomRun(root, 'Title', + cli_args=['a', 'b=1'], _utest=True) + self.assertEqual(dialog.entry.get(), 'a b=1') + dialog.entry.insert(END, ' c') + dialog.button_ok.invoke() + self.assertEqual(dialog.result, (['a', 'b=1', 'c'], True)) + root.destroy() + + +if __name__ == '__main__': + unittest.main(verbosity=2, exit=False) diff --git a/micromamba_root/envs/pytorch_env/Lib/idlelib/idle_test/test_redirector.py b/micromamba_root/envs/pytorch_env/Lib/idlelib/idle_test/test_redirector.py new file mode 100644 index 0000000000000000000000000000000000000000..a97b3002afcf12cec74c77a036978e2a22b45598 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/idlelib/idle_test/test_redirector.py @@ -0,0 +1,122 @@ +"Test redirector, coverage 100%." + +from idlelib.redirector import WidgetRedirector +import unittest +from test.support import requires +from tkinter import Tk, Text, TclError +from idlelib.idle_test.mock_idle import Func + + +class InitCloseTest(unittest.TestCase): + + @classmethod + def setUpClass(cls): + requires('gui') + cls.root = Tk() + cls.root.withdraw() + cls.text = Text(cls.root) + + @classmethod + def tearDownClass(cls): + del cls.text + cls.root.destroy() + del cls.root + + def test_init(self): + redir = WidgetRedirector(self.text) + self.assertEqual(redir.widget, self.text) + self.assertEqual(redir.tk, self.text.tk) + self.assertRaises(TclError, WidgetRedirector, self.text) + redir.close() # restore self.tk, self.text + + def test_close(self): + redir = WidgetRedirector(self.text) + redir.register('insert', Func) + redir.close() + self.assertEqual(redir._operations, {}) + self.assertFalse(hasattr(self.text, 'widget')) + + +class WidgetRedirectorTest(unittest.TestCase): + + @classmethod + def setUpClass(cls): + requires('gui') + cls.root = Tk() + cls.root.withdraw() + cls.text = Text(cls.root) + + @classmethod + def tearDownClass(cls): + del cls.text + cls.root.update_idletasks() + cls.root.destroy() + del cls.root + + def setUp(self): + self.redir = WidgetRedirector(self.text) + self.func = Func() + self.orig_insert = self.redir.register('insert', self.func) + self.text.insert('insert', 'asdf') # leaves self.text empty + + def tearDown(self): + self.text.delete('1.0', 'end') + self.redir.close() + + def test_repr(self): # partly for 100% coverage + self.assertIn('Redirector', repr(self.redir)) + self.assertIn('Original', repr(self.orig_insert)) + + def test_register(self): + self.assertEqual(self.text.get('1.0', 'end'), '\n') + self.assertEqual(self.func.args, ('insert', 'asdf')) + self.assertIn('insert', self.redir._operations) + self.assertIn('insert', self.text.__dict__) + self.assertEqual(self.text.insert, self.func) + + def test_original_command(self): + self.assertEqual(self.orig_insert.operation, 'insert') + self.assertEqual(self.orig_insert.tk_call, self.text.tk.call) + self.orig_insert('insert', 'asdf') + self.assertEqual(self.text.get('1.0', 'end'), 'asdf\n') + + def test_unregister(self): + self.assertIsNone(self.redir.unregister('invalid operation name')) + self.assertEqual(self.redir.unregister('insert'), self.func) + self.assertNotIn('insert', self.redir._operations) + self.assertNotIn('insert', self.text.__dict__) + + def test_unregister_no_attribute(self): + del self.text.insert + self.assertEqual(self.redir.unregister('insert'), self.func) + + def test_dispatch_intercept(self): + self.func.__init__(True) + self.assertTrue(self.redir.dispatch('insert', False)) + self.assertFalse(self.func.args[0]) + + def test_dispatch_bypass(self): + self.orig_insert('insert', 'asdf') + # tk.call returns '' where Python would return None + self.assertEqual(self.redir.dispatch('delete', '1.0', 'end'), '') + self.assertEqual(self.text.get('1.0', 'end'), '\n') + + def test_dispatch_error(self): + self.func.__init__(TclError()) + self.assertEqual(self.redir.dispatch('insert', False), '') + self.assertEqual(self.redir.dispatch('invalid'), '') + + def test_command_dispatch(self): + # Test that .__init__ causes redirection of tk calls + # through redir.dispatch + self.root.call(self.text._w, 'insert', 'hello') + self.assertEqual(self.func.args, ('hello',)) + self.assertEqual(self.text.get('1.0', 'end'), '\n') + # Ensure that called through redir .dispatch and not through + # self.text.insert by having mock raise TclError. + self.func.__init__(TclError()) + self.assertEqual(self.root.call(self.text._w, 'insert', 'boo'), '') + + +if __name__ == '__main__': + unittest.main(verbosity=2) diff --git a/micromamba_root/envs/pytorch_env/Lib/idlelib/idle_test/test_replace.py b/micromamba_root/envs/pytorch_env/Lib/idlelib/idle_test/test_replace.py new file mode 100644 index 0000000000000000000000000000000000000000..6c07389b29ad4558077353dd65eccb32c722dcba --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/idlelib/idle_test/test_replace.py @@ -0,0 +1,294 @@ +"Test replace, coverage 78%." + +from idlelib.replace import ReplaceDialog +import unittest +from test.support import requires +requires('gui') +from tkinter import Tk, Text + +from unittest.mock import Mock +from idlelib.idle_test.mock_tk import Mbox +import idlelib.searchengine as se + +orig_mbox = se.messagebox +showerror = Mbox.showerror + + +class ReplaceDialogTest(unittest.TestCase): + + @classmethod + def setUpClass(cls): + cls.root = Tk() + cls.root.withdraw() + se.messagebox = Mbox + cls.engine = se.SearchEngine(cls.root) + cls.dialog = ReplaceDialog(cls.root, cls.engine) + cls.dialog.bell = lambda: None + cls.dialog.ok = Mock() + cls.text = Text(cls.root) + cls.text.undo_block_start = Mock() + cls.text.undo_block_stop = Mock() + cls.dialog.text = cls.text + + @classmethod + def tearDownClass(cls): + se.messagebox = orig_mbox + del cls.text, cls.dialog, cls.engine + cls.root.destroy() + del cls.root + + def setUp(self): + self.text.insert('insert', 'This is a sample sTring') + + def tearDown(self): + self.engine.patvar.set('') + self.dialog.replvar.set('') + self.engine.wordvar.set(False) + self.engine.casevar.set(False) + self.engine.revar.set(False) + self.engine.wrapvar.set(True) + self.engine.backvar.set(False) + showerror.title = '' + showerror.message = '' + self.text.delete('1.0', 'end') + + def test_replace_simple(self): + # Test replace function with all options at default setting. + # Wrap around - True + # Regular Expression - False + # Match case - False + # Match word - False + # Direction - Forwards + text = self.text + equal = self.assertEqual + pv = self.engine.patvar + rv = self.dialog.replvar + replace = self.dialog.replace_it + + # test accessor method + self.engine.setpat('asdf') + equal(self.engine.getpat(), pv.get()) + + # text found and replaced + pv.set('a') + rv.set('asdf') + replace() + equal(text.get('1.8', '1.12'), 'asdf') + + # don't "match word" case + text.mark_set('insert', '1.0') + pv.set('is') + rv.set('hello') + replace() + equal(text.get('1.2', '1.7'), 'hello') + + # don't "match case" case + pv.set('string') + rv.set('world') + replace() + equal(text.get('1.23', '1.28'), 'world') + + # without "regular expression" case + text.mark_set('insert', 'end') + text.insert('insert', '\nline42:') + before_text = text.get('1.0', 'end') + pv.set(r'[a-z][\d]+') + replace() + after_text = text.get('1.0', 'end') + equal(before_text, after_text) + + # test with wrap around selected and complete a cycle + text.mark_set('insert', '1.9') + pv.set('i') + rv.set('j') + replace() + equal(text.get('1.8'), 'i') + equal(text.get('2.1'), 'j') + replace() + equal(text.get('2.1'), 'j') + equal(text.get('1.8'), 'j') + before_text = text.get('1.0', 'end') + replace() + after_text = text.get('1.0', 'end') + equal(before_text, after_text) + + # text not found + before_text = text.get('1.0', 'end') + pv.set('foobar') + replace() + after_text = text.get('1.0', 'end') + equal(before_text, after_text) + + # test access method + self.dialog.find_it(0) + + def test_replace_wrap_around(self): + text = self.text + equal = self.assertEqual + pv = self.engine.patvar + rv = self.dialog.replvar + replace = self.dialog.replace_it + self.engine.wrapvar.set(False) + + # replace candidate found both after and before 'insert' + text.mark_set('insert', '1.4') + pv.set('i') + rv.set('j') + replace() + equal(text.get('1.2'), 'i') + equal(text.get('1.5'), 'j') + replace() + equal(text.get('1.2'), 'i') + equal(text.get('1.20'), 'j') + replace() + equal(text.get('1.2'), 'i') + + # replace candidate found only before 'insert' + text.mark_set('insert', '1.8') + pv.set('is') + before_text = text.get('1.0', 'end') + replace() + after_text = text.get('1.0', 'end') + equal(before_text, after_text) + + def test_replace_whole_word(self): + text = self.text + equal = self.assertEqual + pv = self.engine.patvar + rv = self.dialog.replvar + replace = self.dialog.replace_it + self.engine.wordvar.set(True) + + pv.set('is') + rv.set('hello') + replace() + equal(text.get('1.0', '1.4'), 'This') + equal(text.get('1.5', '1.10'), 'hello') + + def test_replace_match_case(self): + equal = self.assertEqual + text = self.text + pv = self.engine.patvar + rv = self.dialog.replvar + replace = self.dialog.replace_it + self.engine.casevar.set(True) + + before_text = self.text.get('1.0', 'end') + pv.set('this') + rv.set('that') + replace() + after_text = self.text.get('1.0', 'end') + equal(before_text, after_text) + + pv.set('This') + replace() + equal(text.get('1.0', '1.4'), 'that') + + def test_replace_regex(self): + equal = self.assertEqual + text = self.text + pv = self.engine.patvar + rv = self.dialog.replvar + replace = self.dialog.replace_it + self.engine.revar.set(True) + + before_text = text.get('1.0', 'end') + pv.set(r'[a-z][\d]+') + rv.set('hello') + replace() + after_text = text.get('1.0', 'end') + equal(before_text, after_text) + + text.insert('insert', '\nline42') + replace() + equal(text.get('2.0', '2.8'), 'linhello') + + pv.set('') + replace() + self.assertIn('error', showerror.title) + self.assertIn('Empty', showerror.message) + + pv.set(r'[\d') + replace() + self.assertIn('error', showerror.title) + self.assertIn('Pattern', showerror.message) + + showerror.title = '' + showerror.message = '' + pv.set('[a]') + rv.set('test\\') + replace() + self.assertIn('error', showerror.title) + self.assertIn('Invalid Replace Expression', showerror.message) + + # test access method + self.engine.setcookedpat("?") + equal(pv.get(), "\\?") + + def test_replace_backwards(self): + equal = self.assertEqual + text = self.text + pv = self.engine.patvar + rv = self.dialog.replvar + replace = self.dialog.replace_it + self.engine.backvar.set(True) + + text.insert('insert', '\nis as ') + + pv.set('is') + rv.set('was') + replace() + equal(text.get('1.2', '1.4'), 'is') + equal(text.get('2.0', '2.3'), 'was') + replace() + equal(text.get('1.5', '1.8'), 'was') + replace() + equal(text.get('1.2', '1.5'), 'was') + + def test_replace_all(self): + text = self.text + pv = self.engine.patvar + rv = self.dialog.replvar + replace_all = self.dialog.replace_all + + text.insert('insert', '\n') + text.insert('insert', text.get('1.0', 'end')*100) + pv.set('is') + rv.set('was') + replace_all() + self.assertNotIn('is', text.get('1.0', 'end')) + + self.engine.revar.set(True) + pv.set('') + replace_all() + self.assertIn('error', showerror.title) + self.assertIn('Empty', showerror.message) + + pv.set('[s][T]') + rv.set('\\') + replace_all() + + self.engine.revar.set(False) + pv.set('text which is not present') + rv.set('foobar') + replace_all() + + def test_default_command(self): + text = self.text + pv = self.engine.patvar + rv = self.dialog.replvar + replace_find = self.dialog.default_command + equal = self.assertEqual + + pv.set('This') + rv.set('was') + replace_find() + equal(text.get('sel.first', 'sel.last'), 'was') + + self.engine.revar.set(True) + pv.set('') + replace_find() + + +if __name__ == '__main__': + unittest.main(verbosity=2) diff --git a/micromamba_root/envs/pytorch_env/Lib/idlelib/idle_test/test_rpc.py b/micromamba_root/envs/pytorch_env/Lib/idlelib/idle_test/test_rpc.py new file mode 100644 index 0000000000000000000000000000000000000000..81eff398c72f45b9cc25546513be2cb861e490b8 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/idlelib/idle_test/test_rpc.py @@ -0,0 +1,29 @@ +"Test rpc, coverage 20%." + +from idlelib import rpc +import unittest + + + +class CodePicklerTest(unittest.TestCase): + + def test_pickle_unpickle(self): + def f(): return a + b + c + func, (cbytes,) = rpc.pickle_code(f.__code__) + self.assertIs(func, rpc.unpickle_code) + self.assertIn(b'test_rpc.py', cbytes) + code = rpc.unpickle_code(cbytes) + self.assertEqual(code.co_names, ('a', 'b', 'c')) + + def test_code_pickler(self): + self.assertIn(type((lambda:None).__code__), + rpc.CodePickler.dispatch_table) + + def test_dumps(self): + def f(): pass + # The main test here is that pickling code does not raise. + self.assertIn(b'test_rpc.py', rpc.dumps(f.__code__)) + + +if __name__ == '__main__': + unittest.main(verbosity=2) diff --git a/micromamba_root/envs/pytorch_env/Lib/idlelib/idle_test/test_run.py b/micromamba_root/envs/pytorch_env/Lib/idlelib/idle_test/test_run.py new file mode 100644 index 0000000000000000000000000000000000000000..ec4637c5ca617a9eb380d46825ee32c429520edc --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/idlelib/idle_test/test_run.py @@ -0,0 +1,429 @@ +"Test run, coverage 54%." + +from idlelib import run +import io +import sys +from test.support import captured_output, captured_stderr +import unittest +from unittest import mock +import idlelib +from idlelib.idle_test.mock_idle import Func + +idlelib.testing = True # Use {} for executing test user code. + + +class ExceptionTest(unittest.TestCase): + + def test_print_exception_unhashable(self): + class UnhashableException(Exception): + def __eq__(self, other): + return True + + ex1 = UnhashableException('ex1') + ex2 = UnhashableException('ex2') + try: + raise ex2 from ex1 + except UnhashableException: + try: + raise ex1 + except UnhashableException: + with captured_stderr() as output: + with mock.patch.object(run, 'cleanup_traceback') as ct: + ct.side_effect = lambda t, e: t + run.print_exception() + + tb = output.getvalue().strip().splitlines() + self.assertEqual(11, len(tb)) + self.assertIn('UnhashableException: ex2', tb[3]) + self.assertIn('UnhashableException: ex1', tb[10]) + + data = (('1/0', ZeroDivisionError, "division by zero\n"), + ('abc', NameError, "name 'abc' is not defined. " + "Did you mean: 'abs'?\n"), + ('int.reel', AttributeError, + "type object 'int' has no attribute 'reel'. " + "Did you mean: 'real'?\n"), + ) + + def test_get_message(self): + for code, exc, msg in self.data: + with self.subTest(code=code): + try: + eval(compile(code, '', 'eval')) + except exc: + typ, val, tb = sys.exc_info() + actual = run.get_message_lines(typ, val, tb)[0] + expect = f'{exc.__name__}: {msg}' + self.assertEqual(actual, expect) + + @mock.patch.object(run, 'cleanup_traceback', + new_callable=lambda: (lambda t, e: None)) + def test_get_multiple_message(self, mock): + d = self.data + data2 = ((d[0], d[1]), (d[1], d[2]), (d[2], d[0])) + subtests = 0 + for (code1, exc1, msg1), (code2, exc2, msg2) in data2: + with self.subTest(codes=(code1,code2)): + try: + eval(compile(code1, '', 'eval')) + except exc1: + try: + eval(compile(code2, '', 'eval')) + except exc2: + with captured_stderr() as output: + run.print_exception() + actual = output.getvalue() + self.assertIn(msg1, actual) + self.assertIn(msg2, actual) + subtests += 1 + self.assertEqual(subtests, len(data2)) # All subtests ran? + +# StdioFile tests. + +class S(str): + def __str__(self): + return '%s:str' % type(self).__name__ + def __unicode__(self): + return '%s:unicode' % type(self).__name__ + def __len__(self): + return 3 + def __iter__(self): + return iter('abc') + def __getitem__(self, *args): + return '%s:item' % type(self).__name__ + def __getslice__(self, *args): + return '%s:slice' % type(self).__name__ + + +class MockShell: + def __init__(self): + self.reset() + def write(self, *args): + self.written.append(args) + def readline(self): + return self.lines.pop() + def close(self): + pass + def reset(self): + self.written = [] + def push(self, lines): + self.lines = list(lines)[::-1] + + +class StdInputFilesTest(unittest.TestCase): + + def test_misc(self): + shell = MockShell() + f = run.StdInputFile(shell, 'stdin') + self.assertIsInstance(f, io.TextIOBase) + self.assertEqual(f.encoding, 'utf-8') + self.assertEqual(f.errors, 'strict') + self.assertIsNone(f.newlines) + self.assertEqual(f.name, '') + self.assertFalse(f.closed) + self.assertTrue(f.isatty()) + self.assertTrue(f.readable()) + self.assertFalse(f.writable()) + self.assertFalse(f.seekable()) + + def test_unsupported(self): + shell = MockShell() + f = run.StdInputFile(shell, 'stdin') + self.assertRaises(OSError, f.fileno) + self.assertRaises(OSError, f.tell) + self.assertRaises(OSError, f.seek, 0) + self.assertRaises(OSError, f.write, 'x') + self.assertRaises(OSError, f.writelines, ['x']) + + def test_read(self): + shell = MockShell() + f = run.StdInputFile(shell, 'stdin') + shell.push(['one\n', 'two\n', '']) + self.assertEqual(f.read(), 'one\ntwo\n') + shell.push(['one\n', 'two\n', '']) + self.assertEqual(f.read(-1), 'one\ntwo\n') + shell.push(['one\n', 'two\n', '']) + self.assertEqual(f.read(None), 'one\ntwo\n') + shell.push(['one\n', 'two\n', 'three\n', '']) + self.assertEqual(f.read(2), 'on') + self.assertEqual(f.read(3), 'e\nt') + self.assertEqual(f.read(10), 'wo\nthree\n') + + shell.push(['one\n', 'two\n']) + self.assertEqual(f.read(0), '') + self.assertRaises(TypeError, f.read, 1.5) + self.assertRaises(TypeError, f.read, '1') + self.assertRaises(TypeError, f.read, 1, 1) + + def test_readline(self): + shell = MockShell() + f = run.StdInputFile(shell, 'stdin') + shell.push(['one\n', 'two\n', 'three\n', 'four\n']) + self.assertEqual(f.readline(), 'one\n') + self.assertEqual(f.readline(-1), 'two\n') + self.assertEqual(f.readline(None), 'three\n') + shell.push(['one\ntwo\n']) + self.assertEqual(f.readline(), 'one\n') + self.assertEqual(f.readline(), 'two\n') + shell.push(['one', 'two', 'three']) + self.assertEqual(f.readline(), 'one') + self.assertEqual(f.readline(), 'two') + shell.push(['one\n', 'two\n', 'three\n']) + self.assertEqual(f.readline(2), 'on') + self.assertEqual(f.readline(1), 'e') + self.assertEqual(f.readline(1), '\n') + self.assertEqual(f.readline(10), 'two\n') + + shell.push(['one\n', 'two\n']) + self.assertEqual(f.readline(0), '') + self.assertRaises(TypeError, f.readlines, 1.5) + self.assertRaises(TypeError, f.readlines, '1') + self.assertRaises(TypeError, f.readlines, 1, 1) + + def test_readlines(self): + shell = MockShell() + f = run.StdInputFile(shell, 'stdin') + shell.push(['one\n', 'two\n', '']) + self.assertEqual(f.readlines(), ['one\n', 'two\n']) + shell.push(['one\n', 'two\n', '']) + self.assertEqual(f.readlines(-1), ['one\n', 'two\n']) + shell.push(['one\n', 'two\n', '']) + self.assertEqual(f.readlines(None), ['one\n', 'two\n']) + shell.push(['one\n', 'two\n', '']) + self.assertEqual(f.readlines(0), ['one\n', 'two\n']) + shell.push(['one\n', 'two\n', '']) + self.assertEqual(f.readlines(3), ['one\n']) + shell.push(['one\n', 'two\n', '']) + self.assertEqual(f.readlines(4), ['one\n', 'two\n']) + + shell.push(['one\n', 'two\n', '']) + self.assertRaises(TypeError, f.readlines, 1.5) + self.assertRaises(TypeError, f.readlines, '1') + self.assertRaises(TypeError, f.readlines, 1, 1) + + def test_close(self): + shell = MockShell() + f = run.StdInputFile(shell, 'stdin') + shell.push(['one\n', 'two\n', '']) + self.assertFalse(f.closed) + self.assertEqual(f.readline(), 'one\n') + f.close() + self.assertFalse(f.closed) + self.assertEqual(f.readline(), 'two\n') + self.assertRaises(TypeError, f.close, 1) + + +class StdOutputFilesTest(unittest.TestCase): + + def test_misc(self): + shell = MockShell() + f = run.StdOutputFile(shell, 'stdout') + self.assertIsInstance(f, io.TextIOBase) + self.assertEqual(f.encoding, 'utf-8') + self.assertEqual(f.errors, 'strict') + self.assertIsNone(f.newlines) + self.assertEqual(f.name, '') + self.assertFalse(f.closed) + self.assertTrue(f.isatty()) + self.assertFalse(f.readable()) + self.assertTrue(f.writable()) + self.assertFalse(f.seekable()) + + def test_unsupported(self): + shell = MockShell() + f = run.StdOutputFile(shell, 'stdout') + self.assertRaises(OSError, f.fileno) + self.assertRaises(OSError, f.tell) + self.assertRaises(OSError, f.seek, 0) + self.assertRaises(OSError, f.read, 0) + self.assertRaises(OSError, f.readline, 0) + + def test_write(self): + shell = MockShell() + f = run.StdOutputFile(shell, 'stdout') + f.write('test') + self.assertEqual(shell.written, [('test', 'stdout')]) + shell.reset() + f.write('t\xe8\u015b\U0001d599') + self.assertEqual(shell.written, [('t\xe8\u015b\U0001d599', 'stdout')]) + shell.reset() + + f.write(S('t\xe8\u015b\U0001d599')) + self.assertEqual(shell.written, [('t\xe8\u015b\U0001d599', 'stdout')]) + self.assertEqual(type(shell.written[0][0]), str) + shell.reset() + + self.assertRaises(TypeError, f.write) + self.assertEqual(shell.written, []) + self.assertRaises(TypeError, f.write, b'test') + self.assertRaises(TypeError, f.write, 123) + self.assertEqual(shell.written, []) + self.assertRaises(TypeError, f.write, 'test', 'spam') + self.assertEqual(shell.written, []) + + def test_write_stderr_nonencodable(self): + shell = MockShell() + f = run.StdOutputFile(shell, 'stderr', 'iso-8859-15', 'backslashreplace') + f.write('t\xe8\u015b\U0001d599\xa4') + self.assertEqual(shell.written, [('t\xe8\\u015b\\U0001d599\\xa4', 'stderr')]) + shell.reset() + + f.write(S('t\xe8\u015b\U0001d599\xa4')) + self.assertEqual(shell.written, [('t\xe8\\u015b\\U0001d599\\xa4', 'stderr')]) + self.assertEqual(type(shell.written[0][0]), str) + shell.reset() + + self.assertRaises(TypeError, f.write) + self.assertEqual(shell.written, []) + self.assertRaises(TypeError, f.write, b'test') + self.assertRaises(TypeError, f.write, 123) + self.assertEqual(shell.written, []) + self.assertRaises(TypeError, f.write, 'test', 'spam') + self.assertEqual(shell.written, []) + + def test_writelines(self): + shell = MockShell() + f = run.StdOutputFile(shell, 'stdout') + f.writelines([]) + self.assertEqual(shell.written, []) + shell.reset() + f.writelines(['one\n', 'two']) + self.assertEqual(shell.written, + [('one\n', 'stdout'), ('two', 'stdout')]) + shell.reset() + f.writelines(['on\xe8\n', 'tw\xf2']) + self.assertEqual(shell.written, + [('on\xe8\n', 'stdout'), ('tw\xf2', 'stdout')]) + shell.reset() + + f.writelines([S('t\xe8st')]) + self.assertEqual(shell.written, [('t\xe8st', 'stdout')]) + self.assertEqual(type(shell.written[0][0]), str) + shell.reset() + + self.assertRaises(TypeError, f.writelines) + self.assertEqual(shell.written, []) + self.assertRaises(TypeError, f.writelines, 123) + self.assertEqual(shell.written, []) + self.assertRaises(TypeError, f.writelines, [b'test']) + self.assertRaises(TypeError, f.writelines, [123]) + self.assertEqual(shell.written, []) + self.assertRaises(TypeError, f.writelines, [], []) + self.assertEqual(shell.written, []) + + def test_close(self): + shell = MockShell() + f = run.StdOutputFile(shell, 'stdout') + self.assertFalse(f.closed) + f.write('test') + f.close() + self.assertTrue(f.closed) + self.assertRaises(ValueError, f.write, 'x') + self.assertEqual(shell.written, [('test', 'stdout')]) + f.close() + self.assertRaises(TypeError, f.close, 1) + + +class RecursionLimitTest(unittest.TestCase): + # Test (un)install_recursionlimit_wrappers and fixdoc. + + def test_bad_setrecursionlimit_calls(self): + run.install_recursionlimit_wrappers() + self.addCleanup(run.uninstall_recursionlimit_wrappers) + f = sys.setrecursionlimit + self.assertRaises(TypeError, f, limit=100) + self.assertRaises(TypeError, f, 100, 1000) + self.assertRaises(ValueError, f, 0) + + def test_roundtrip(self): + run.install_recursionlimit_wrappers() + self.addCleanup(run.uninstall_recursionlimit_wrappers) + + # Check that setting the recursion limit works. + orig_reclimit = sys.getrecursionlimit() + self.addCleanup(sys.setrecursionlimit, orig_reclimit) + sys.setrecursionlimit(orig_reclimit + 3) + + # Check that the new limit is returned by sys.getrecursionlimit(). + new_reclimit = sys.getrecursionlimit() + self.assertEqual(new_reclimit, orig_reclimit + 3) + + def test_default_recursion_limit_preserved(self): + orig_reclimit = sys.getrecursionlimit() + run.install_recursionlimit_wrappers() + self.addCleanup(run.uninstall_recursionlimit_wrappers) + new_reclimit = sys.getrecursionlimit() + self.assertEqual(new_reclimit, orig_reclimit) + + def test_fixdoc(self): + # Put here until better place for miscellaneous test. + def func(): "docstring" + run.fixdoc(func, "more") + self.assertEqual(func.__doc__, "docstring\n\nmore") + func.__doc__ = None + run.fixdoc(func, "more") + self.assertEqual(func.__doc__, "more") + + +class HandleErrorTest(unittest.TestCase): + # Method of MyRPCServer + def test_fatal_error(self): + eq = self.assertEqual + with captured_output('__stderr__') as err,\ + mock.patch('idlelib.run.thread.interrupt_main', + new_callable=Func) as func: + try: + raise EOFError + except EOFError: + run.MyRPCServer.handle_error(None, 'abc', '123') + eq(run.exit_now, True) + run.exit_now = False + eq(err.getvalue(), '') + + try: + raise IndexError + except IndexError: + run.MyRPCServer.handle_error(None, 'abc', '123') + eq(run.quitting, True) + run.quitting = False + msg = err.getvalue() + self.assertIn('abc', msg) + self.assertIn('123', msg) + self.assertIn('IndexError', msg) + eq(func.called, 2) + + +class ExecRuncodeTest(unittest.TestCase): + + @classmethod + def setUpClass(cls): + cls.addClassCleanup(setattr,run,'print_exception',run.print_exception) + cls.prt = Func() # Need reference. + run.print_exception = cls.prt + mockrpc = mock.Mock() + mockrpc.console.getvar = Func(result=False) + cls.ex = run.Executive(mockrpc) + + @classmethod + def tearDownClass(cls): + assert sys.excepthook == sys.__excepthook__ + + def test_exceptions(self): + ex = self.ex + ex.runcode('1/0') + self.assertIs(ex.user_exc_info[0], ZeroDivisionError) + + self.addCleanup(setattr, sys, 'excepthook', sys.__excepthook__) + sys.excepthook = lambda t, e, tb: run.print_exception(t) + ex.runcode('1/0') + self.assertIs(self.prt.args[0], ZeroDivisionError) + + sys.excepthook = lambda: None + ex.runcode('1/0') + t, e, tb = ex.user_exc_info + self.assertIs(t, TypeError) + self.assertTrue(isinstance(e.__context__, ZeroDivisionError)) + + +if __name__ == '__main__': + unittest.main(verbosity=2) diff --git a/micromamba_root/envs/pytorch_env/Lib/idlelib/idle_test/test_runscript.py b/micromamba_root/envs/pytorch_env/Lib/idlelib/idle_test/test_runscript.py new file mode 100644 index 0000000000000000000000000000000000000000..5fc60185a663e8f33d5fd10591df989190e038f8 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/idlelib/idle_test/test_runscript.py @@ -0,0 +1,33 @@ +"Test runscript, coverage 16%." + +from idlelib import runscript +import unittest +from test.support import requires +from tkinter import Tk +from idlelib.editor import EditorWindow + + +class ScriptBindingTest(unittest.TestCase): + + @classmethod + def setUpClass(cls): + requires('gui') + cls.root = Tk() + cls.root.withdraw() + + @classmethod + def tearDownClass(cls): + cls.root.update_idletasks() + for id in cls.root.tk.call('after', 'info'): + cls.root.after_cancel(id) # Need for EditorWindow. + cls.root.destroy() + del cls.root + + def test_init(self): + ew = EditorWindow(root=self.root) + sb = runscript.ScriptBinding(ew) + ew._close() + + +if __name__ == '__main__': + unittest.main(verbosity=2) diff --git a/micromamba_root/envs/pytorch_env/Lib/idlelib/idle_test/test_scrolledlist.py b/micromamba_root/envs/pytorch_env/Lib/idlelib/idle_test/test_scrolledlist.py new file mode 100644 index 0000000000000000000000000000000000000000..2f819fda025ba3d453e081327a05ffc2fd7cf972 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/idlelib/idle_test/test_scrolledlist.py @@ -0,0 +1,27 @@ +"Test scrolledlist, coverage 38%." + +from idlelib.scrolledlist import ScrolledList +import unittest +from test.support import requires +requires('gui') +from tkinter import Tk + + +class ScrolledListTest(unittest.TestCase): + + @classmethod + def setUpClass(cls): + cls.root = Tk() + + @classmethod + def tearDownClass(cls): + cls.root.destroy() + del cls.root + + + def test_init(self): + ScrolledList(self.root) + + +if __name__ == '__main__': + unittest.main(verbosity=2) diff --git a/micromamba_root/envs/pytorch_env/Lib/idlelib/idle_test/test_search.py b/micromamba_root/envs/pytorch_env/Lib/idlelib/idle_test/test_search.py new file mode 100644 index 0000000000000000000000000000000000000000..de703c195cd22900b92f3b239018f805bbf373da --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/idlelib/idle_test/test_search.py @@ -0,0 +1,80 @@ +"Test search, coverage 69%." + +from idlelib import search +import unittest +from test.support import requires +requires('gui') +from tkinter import Tk, Text, BooleanVar +from idlelib import searchengine + +# Does not currently test the event handler wrappers. +# A usage test should simulate clicks and check highlighting. +# Tests need to be coordinated with SearchDialogBase tests +# to avoid duplication. + + +class SearchDialogTest(unittest.TestCase): + + @classmethod + def setUpClass(cls): + cls.root = Tk() + + @classmethod + def tearDownClass(cls): + cls.root.destroy() + del cls.root + + def setUp(self): + self.engine = searchengine.SearchEngine(self.root) + self.dialog = search.SearchDialog(self.root, self.engine) + self.dialog.bell = lambda: None + self.text = Text(self.root) + self.text.insert('1.0', 'Hello World!') + + def test_find_again(self): + # Search for various expressions + text = self.text + + self.engine.setpat('') + self.assertFalse(self.dialog.find_again(text)) + self.dialog.bell = lambda: None + + self.engine.setpat('Hello') + self.assertTrue(self.dialog.find_again(text)) + + self.engine.setpat('Goodbye') + self.assertFalse(self.dialog.find_again(text)) + + self.engine.setpat('World!') + self.assertTrue(self.dialog.find_again(text)) + + self.engine.setpat('Hello World!') + self.assertTrue(self.dialog.find_again(text)) + + # Regular expression + self.engine.revar = BooleanVar(self.root, True) + self.engine.setpat('W[aeiouy]r') + self.assertTrue(self.dialog.find_again(text)) + + def test_find_selection(self): + # Select some text and make sure it's found + text = self.text + # Add additional line to find + self.text.insert('2.0', 'Hello World!') + + text.tag_add('sel', '1.0', '1.4') # Select 'Hello' + self.assertTrue(self.dialog.find_selection(text)) + + text.tag_remove('sel', '1.0', 'end') + text.tag_add('sel', '1.6', '1.11') # Select 'World!' + self.assertTrue(self.dialog.find_selection(text)) + + text.tag_remove('sel', '1.0', 'end') + text.tag_add('sel', '1.0', '1.11') # Select 'Hello World!' + self.assertTrue(self.dialog.find_selection(text)) + + # Remove additional line + text.delete('2.0', 'end') + +if __name__ == '__main__': + unittest.main(verbosity=2, exit=2) diff --git a/micromamba_root/envs/pytorch_env/Lib/idlelib/idle_test/test_searchbase.py b/micromamba_root/envs/pytorch_env/Lib/idlelib/idle_test/test_searchbase.py new file mode 100644 index 0000000000000000000000000000000000000000..8c9c410ebaf47c0626655cffe0fda4db83960819 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/idlelib/idle_test/test_searchbase.py @@ -0,0 +1,160 @@ +"Test searchbase, coverage 98%." +# The only thing not covered is inconsequential -- +# testing skipping of suite when self.needwrapbutton is false. + +import unittest +from test.support import requires +from tkinter import Text, Tk, Toplevel +from tkinter.ttk import Frame +from idlelib import searchengine as se +from idlelib import searchbase as sdb +from idlelib.idle_test.mock_idle import Func +## from idlelib.idle_test.mock_tk import Var + +# The ## imports above & following could help make some tests gui-free. +# However, they currently make radiobutton tests fail. +##def setUpModule(): +## # Replace tk objects used to initialize se.SearchEngine. +## se.BooleanVar = Var +## se.StringVar = Var +## +##def tearDownModule(): +## se.BooleanVar = BooleanVar +## se.StringVar = StringVar + + +class SearchDialogBaseTest(unittest.TestCase): + + @classmethod + def setUpClass(cls): + requires('gui') + cls.root = Tk() + + @classmethod + def tearDownClass(cls): + cls.root.update_idletasks() + cls.root.destroy() + del cls.root + + def setUp(self): + self.engine = se.SearchEngine(self.root) # None also seems to work + self.dialog = sdb.SearchDialogBase(root=self.root, engine=self.engine) + + def tearDown(self): + self.dialog.close() + + def test_open_and_close(self): + # open calls create_widgets, which needs default_command + self.dialog.default_command = None + + toplevel = Toplevel(self.root) + text = Text(toplevel) + self.dialog.open(text) + self.assertEqual(self.dialog.top.state(), 'normal') + self.dialog.close() + self.assertEqual(self.dialog.top.state(), 'withdrawn') + + self.dialog.open(text, searchphrase="hello") + self.assertEqual(self.dialog.ent.get(), 'hello') + toplevel.update_idletasks() + toplevel.destroy() + + def test_create_widgets(self): + self.dialog.create_entries = Func() + self.dialog.create_option_buttons = Func() + self.dialog.create_other_buttons = Func() + self.dialog.create_command_buttons = Func() + + self.dialog.default_command = None + self.dialog.create_widgets() + + self.assertTrue(self.dialog.create_entries.called) + self.assertTrue(self.dialog.create_option_buttons.called) + self.assertTrue(self.dialog.create_other_buttons.called) + self.assertTrue(self.dialog.create_command_buttons.called) + + def test_make_entry(self): + equal = self.assertEqual + self.dialog.row = 0 + self.dialog.frame = Frame(self.root) + entry, label = self.dialog.make_entry("Test:", 'hello') + equal(label['text'], 'Test:') + + self.assertIn(entry.get(), 'hello') + egi = entry.grid_info() + equal(int(egi['row']), 0) + equal(int(egi['column']), 1) + equal(int(egi['rowspan']), 1) + equal(int(egi['columnspan']), 1) + equal(self.dialog.row, 1) + + def test_create_entries(self): + self.dialog.frame = Frame(self.root) + self.dialog.row = 0 + self.engine.setpat('hello') + self.dialog.create_entries() + self.assertIn(self.dialog.ent.get(), 'hello') + + def test_make_frame(self): + self.dialog.row = 0 + self.dialog.frame = Frame(self.root) + frame, label = self.dialog.make_frame() + self.assertEqual(label, '') + self.assertEqual(str(type(frame)), "") + # self.assertIsInstance(frame, Frame) fails when test is run by + # test_idle not run from IDLE editor. See issue 33987 PR. + + frame, label = self.dialog.make_frame('testlabel') + self.assertEqual(label['text'], 'testlabel') + + def btn_test_setup(self, meth): + self.dialog.frame = Frame(self.root) + self.dialog.row = 0 + return meth() + + def test_create_option_buttons(self): + e = self.engine + for state in (0, 1): + for var in (e.revar, e.casevar, e.wordvar, e.wrapvar): + var.set(state) + frame, options = self.btn_test_setup( + self.dialog.create_option_buttons) + for spec, button in zip (options, frame.pack_slaves()): + var, label = spec + self.assertEqual(button['text'], label) + self.assertEqual(var.get(), state) + + def test_create_other_buttons(self): + for state in (False, True): + var = self.engine.backvar + var.set(state) + frame, others = self.btn_test_setup( + self.dialog.create_other_buttons) + buttons = frame.pack_slaves() + for spec, button in zip(others, buttons): + val, label = spec + self.assertEqual(button['text'], label) + if val == state: + # hit other button, then this one + # indexes depend on button order + self.assertEqual(var.get(), state) + + def test_make_button(self): + self.dialog.frame = Frame(self.root) + self.dialog.buttonframe = Frame(self.dialog.frame) + btn = self.dialog.make_button('Test', self.dialog.close) + self.assertEqual(btn['text'], 'Test') + + def test_create_command_buttons(self): + self.dialog.frame = Frame(self.root) + self.dialog.create_command_buttons() + # Look for close button command in buttonframe + closebuttoncommand = '' + for child in self.dialog.buttonframe.winfo_children(): + if child['text'] == 'Close': + closebuttoncommand = child['command'] + self.assertIn('close', closebuttoncommand) + + +if __name__ == '__main__': + unittest.main(verbosity=2, exit=2) diff --git a/micromamba_root/envs/pytorch_env/Lib/idlelib/idle_test/test_searchengine.py b/micromamba_root/envs/pytorch_env/Lib/idlelib/idle_test/test_searchengine.py new file mode 100644 index 0000000000000000000000000000000000000000..9d97983941958606af154d8a4f8bb70bf9695d00 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/idlelib/idle_test/test_searchengine.py @@ -0,0 +1,332 @@ +"Test searchengine, coverage 99%." + +from idlelib import searchengine as se +import unittest +# from test.support import requires +from tkinter import BooleanVar, StringVar, TclError # ,Tk, Text +from tkinter import messagebox +from idlelib.idle_test.mock_tk import Var, Mbox +from idlelib.idle_test.mock_tk import Text as mockText +import re + +# With mock replacements, the module does not use any gui widgets. +# The use of tk.Text is avoided (for now, until mock Text is improved) +# by patching instances with an index function returning what is needed. +# This works because mock Text.get does not use .index. +# The tkinter imports are used to restore searchengine. + +def setUpModule(): + # Replace s-e module tkinter imports other than non-gui TclError. + se.BooleanVar = Var + se.StringVar = Var + se.messagebox = Mbox + +def tearDownModule(): + # Restore 'just in case', though other tests should also replace. + se.BooleanVar = BooleanVar + se.StringVar = StringVar + se.messagebox = messagebox + + +class Mock: + def __init__(self, *args, **kwargs): pass + +class GetTest(unittest.TestCase): + # SearchEngine.get returns singleton created & saved on first call. + def test_get(self): + saved_Engine = se.SearchEngine + se.SearchEngine = Mock # monkey-patch class + try: + root = Mock() + engine = se.get(root) + self.assertIsInstance(engine, se.SearchEngine) + self.assertIs(root._searchengine, engine) + self.assertIs(se.get(root), engine) + finally: + se.SearchEngine = saved_Engine # restore class to module + +class GetLineColTest(unittest.TestCase): + # Test simple text-independent helper function + def test_get_line_col(self): + self.assertEqual(se.get_line_col('1.0'), (1, 0)) + self.assertEqual(se.get_line_col('1.11'), (1, 11)) + + self.assertRaises(ValueError, se.get_line_col, ('1.0 lineend')) + self.assertRaises(ValueError, se.get_line_col, ('end')) + +class GetSelectionTest(unittest.TestCase): + # Test text-dependent helper function. +## # Need gui for text.index('sel.first/sel.last/insert'). +## @classmethod +## def setUpClass(cls): +## requires('gui') +## cls.root = Tk() +## +## @classmethod +## def tearDownClass(cls): +## cls.root.destroy() +## del cls.root + + def test_get_selection(self): + # text = Text(master=self.root) + text = mockText() + text.insert('1.0', 'Hello World!') + + # fix text.index result when called in get_selection + def sel(s): + # select entire text, cursor irrelevant + if s == 'sel.first': return '1.0' + if s == 'sel.last': return '1.12' + raise TclError + text.index = sel # replaces .tag_add('sel', '1.0, '1.12') + self.assertEqual(se.get_selection(text), ('1.0', '1.12')) + + def mark(s): + # no selection, cursor after 'Hello' + if s == 'insert': return '1.5' + raise TclError + text.index = mark # replaces .mark_set('insert', '1.5') + self.assertEqual(se.get_selection(text), ('1.5', '1.5')) + + +class ReverseSearchTest(unittest.TestCase): + # Test helper function that searches backwards within a line. + def test_search_reverse(self): + Equal = self.assertEqual + line = "Here is an 'is' test text." + prog = re.compile('is') + Equal(se.search_reverse(prog, line, len(line)).span(), (12, 14)) + Equal(se.search_reverse(prog, line, 14).span(), (12, 14)) + Equal(se.search_reverse(prog, line, 13).span(), (5, 7)) + Equal(se.search_reverse(prog, line, 7).span(), (5, 7)) + Equal(se.search_reverse(prog, line, 6), None) + + +class SearchEngineTest(unittest.TestCase): + # Test class methods that do not use Text widget. + + def setUp(self): + self.engine = se.SearchEngine(root=None) + # Engine.root is only used to create error message boxes. + # The mock replacement ignores the root argument. + + def test_is_get(self): + engine = self.engine + Equal = self.assertEqual + + Equal(engine.getpat(), '') + engine.setpat('hello') + Equal(engine.getpat(), 'hello') + + Equal(engine.isre(), False) + engine.revar.set(1) + Equal(engine.isre(), True) + + Equal(engine.iscase(), False) + engine.casevar.set(1) + Equal(engine.iscase(), True) + + Equal(engine.isword(), False) + engine.wordvar.set(1) + Equal(engine.isword(), True) + + Equal(engine.iswrap(), True) + engine.wrapvar.set(0) + Equal(engine.iswrap(), False) + + Equal(engine.isback(), False) + engine.backvar.set(1) + Equal(engine.isback(), True) + + def test_setcookedpat(self): + engine = self.engine + engine.setcookedpat(r'\s') + self.assertEqual(engine.getpat(), r'\s') + engine.revar.set(1) + engine.setcookedpat(r'\s') + self.assertEqual(engine.getpat(), r'\\s') + + def test_getcookedpat(self): + engine = self.engine + Equal = self.assertEqual + + Equal(engine.getcookedpat(), '') + engine.setpat('hello') + Equal(engine.getcookedpat(), 'hello') + engine.wordvar.set(True) + Equal(engine.getcookedpat(), r'\bhello\b') + engine.wordvar.set(False) + + engine.setpat(r'\s') + Equal(engine.getcookedpat(), r'\\s') + engine.revar.set(True) + Equal(engine.getcookedpat(), r'\s') + + def test_getprog(self): + engine = self.engine + Equal = self.assertEqual + + engine.setpat('Hello') + temppat = engine.getprog() + Equal(temppat.pattern, re.compile('Hello', re.IGNORECASE).pattern) + engine.casevar.set(1) + temppat = engine.getprog() + Equal(temppat.pattern, re.compile('Hello').pattern, 0) + + engine.setpat('') + Equal(engine.getprog(), None) + Equal(Mbox.showerror.message, + 'Error: Empty regular expression') + engine.setpat('+') + engine.revar.set(1) + Equal(engine.getprog(), None) + Equal(Mbox.showerror.message, + 'Error: nothing to repeat\nPattern: +\nOffset: 0') + + def test_report_error(self): + showerror = Mbox.showerror + Equal = self.assertEqual + pat = '[a-z' + msg = 'unexpected end of regular expression' + + Equal(self.engine.report_error(pat, msg), None) + Equal(showerror.title, 'Regular expression error') + expected_message = ("Error: " + msg + "\nPattern: [a-z") + Equal(showerror.message, expected_message) + + Equal(self.engine.report_error(pat, msg, 5), None) + Equal(showerror.title, 'Regular expression error') + expected_message += "\nOffset: 5" + Equal(showerror.message, expected_message) + + +class SearchTest(unittest.TestCase): + # Test that search_text makes right call to right method. + + @classmethod + def setUpClass(cls): +## requires('gui') +## cls.root = Tk() +## cls.text = Text(master=cls.root) + cls.text = mockText() + test_text = ( + 'First line\n' + 'Line with target\n' + 'Last line\n') + cls.text.insert('1.0', test_text) + cls.pat = re.compile('target') + + cls.engine = se.SearchEngine(None) + cls.engine.search_forward = lambda *args: ('f', args) + cls.engine.search_backward = lambda *args: ('b', args) + +## @classmethod +## def tearDownClass(cls): +## cls.root.destroy() +## del cls.root + + def test_search(self): + Equal = self.assertEqual + engine = self.engine + search = engine.search_text + text = self.text + pat = self.pat + + engine.patvar.set(None) + #engine.revar.set(pat) + Equal(search(text), None) + + def mark(s): + # no selection, cursor after 'Hello' + if s == 'insert': return '1.5' + raise TclError + text.index = mark + Equal(search(text, pat), ('f', (text, pat, 1, 5, True, False))) + engine.wrapvar.set(False) + Equal(search(text, pat), ('f', (text, pat, 1, 5, False, False))) + engine.wrapvar.set(True) + engine.backvar.set(True) + Equal(search(text, pat), ('b', (text, pat, 1, 5, True, False))) + engine.backvar.set(False) + + def sel(s): + if s == 'sel.first': return '2.10' + if s == 'sel.last': return '2.16' + raise TclError + text.index = sel + Equal(search(text, pat), ('f', (text, pat, 2, 16, True, False))) + Equal(search(text, pat, True), ('f', (text, pat, 2, 10, True, True))) + engine.backvar.set(True) + Equal(search(text, pat), ('b', (text, pat, 2, 10, True, False))) + Equal(search(text, pat, True), ('b', (text, pat, 2, 16, True, True))) + + +class ForwardBackwardTest(unittest.TestCase): + # Test that search_forward method finds the target. +## @classmethod +## def tearDownClass(cls): +## cls.root.destroy() +## del cls.root + + @classmethod + def setUpClass(cls): + cls.engine = se.SearchEngine(None) +## requires('gui') +## cls.root = Tk() +## cls.text = Text(master=cls.root) + cls.text = mockText() + # search_backward calls index('end-1c') + cls.text.index = lambda index: '4.0' + test_text = ( + 'First line\n' + 'Line with target\n' + 'Last line\n') + cls.text.insert('1.0', test_text) + cls.pat = re.compile('target') + cls.res = (2, (10, 16)) # line, slice indexes of 'target' + cls.failpat = re.compile('xyz') # not in text + cls.emptypat = re.compile(r'\w*') # empty match possible + + def make_search(self, func): + def search(pat, line, col, wrap, ok=0): + res = func(self.text, pat, line, col, wrap, ok) + # res is (line, matchobject) or None + return (res[0], res[1].span()) if res else res + return search + + def test_search_forward(self): + # search for non-empty match + Equal = self.assertEqual + forward = self.make_search(self.engine.search_forward) + pat = self.pat + Equal(forward(pat, 1, 0, True), self.res) + Equal(forward(pat, 3, 0, True), self.res) # wrap + Equal(forward(pat, 3, 0, False), None) # no wrap + Equal(forward(pat, 2, 10, False), self.res) + + Equal(forward(self.failpat, 1, 0, True), None) + Equal(forward(self.emptypat, 2, 9, True, ok=True), (2, (9, 9))) + #Equal(forward(self.emptypat, 2, 9, True), self.res) + # While the initial empty match is correctly ignored, skipping + # the rest of the line and returning (3, (0,4)) seems buggy - tjr. + Equal(forward(self.emptypat, 2, 10, True), self.res) + + def test_search_backward(self): + # search for non-empty match + Equal = self.assertEqual + backward = self.make_search(self.engine.search_backward) + pat = self.pat + Equal(backward(pat, 3, 5, True), self.res) + Equal(backward(pat, 2, 0, True), self.res) # wrap + Equal(backward(pat, 2, 0, False), None) # no wrap + Equal(backward(pat, 2, 16, False), self.res) + + Equal(backward(self.failpat, 3, 9, True), None) + Equal(backward(self.emptypat, 2, 10, True, ok=True), (2, (9,9))) + # Accepted because 9 < 10, not because ok=True. + # It is not clear that ok=True is useful going back - tjr + Equal(backward(self.emptypat, 2, 9, True), (2, (5, 9))) + + +if __name__ == '__main__': + unittest.main(verbosity=2) diff --git a/micromamba_root/envs/pytorch_env/Lib/idlelib/idle_test/test_sidebar.py b/micromamba_root/envs/pytorch_env/Lib/idlelib/idle_test/test_sidebar.py new file mode 100644 index 0000000000000000000000000000000000000000..605e7a892570d7d7003095551ce1a27c3a8e9e0f --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/idlelib/idle_test/test_sidebar.py @@ -0,0 +1,775 @@ +"""Test sidebar, coverage 85%""" +from textwrap import dedent +import sys + +from itertools import chain +import unittest +import unittest.mock +from test.support import requires, swap_attr +from test import support +import tkinter as tk +from idlelib.idle_test.tkinter_testing_utils import run_in_tk_mainloop + +from idlelib.delegator import Delegator +from idlelib.editor import fixwordbreaks +from idlelib.percolator import Percolator +import idlelib.pyshell +from idlelib.pyshell import fix_x11_paste, PyShell, PyShellFileList +from idlelib.run import fix_scaling +import idlelib.sidebar +from idlelib.sidebar import get_end_linenumber, get_lineno + + +class Dummy_editwin: + def __init__(self, text): + self.text = text + self.text_frame = self.text.master + self.per = Percolator(text) + self.undo = Delegator() + self.per.insertfilter(self.undo) + + def setvar(self, name, value): + pass + + def getlineno(self, index): + return int(float(self.text.index(index))) + + +class LineNumbersTest(unittest.TestCase): + + @classmethod + def setUpClass(cls): + requires('gui') + cls.root = tk.Tk() + cls.root.withdraw() + + cls.text_frame = tk.Frame(cls.root) + cls.text_frame.pack(side=tk.LEFT, fill=tk.BOTH, expand=True) + cls.text_frame.rowconfigure(1, weight=1) + cls.text_frame.columnconfigure(1, weight=1) + + cls.text = tk.Text(cls.text_frame, width=80, height=24, wrap=tk.NONE) + cls.text.grid(row=1, column=1, sticky=tk.NSEW) + + cls.editwin = Dummy_editwin(cls.text) + cls.editwin.vbar = tk.Scrollbar(cls.text_frame) + + @classmethod + def tearDownClass(cls): + cls.editwin.per.close() + cls.root.update_idletasks() + cls.root.destroy() + del cls.text, cls.text_frame, cls.editwin, cls.root + + def setUp(self): + self.linenumber = idlelib.sidebar.LineNumbers(self.editwin) + + self.highlight_cfg = {"background": '#abcdef', + "foreground": '#123456'} + orig_idleConf_GetHighlight = idlelib.sidebar.idleConf.GetHighlight + def mock_idleconf_GetHighlight(theme, element): + if element == 'linenumber': + return self.highlight_cfg + return orig_idleConf_GetHighlight(theme, element) + GetHighlight_patcher = unittest.mock.patch.object( + idlelib.sidebar.idleConf, 'GetHighlight', mock_idleconf_GetHighlight) + GetHighlight_patcher.start() + self.addCleanup(GetHighlight_patcher.stop) + + self.font_override = 'TkFixedFont' + def mock_idleconf_GetFont(root, configType, section): + return self.font_override + GetFont_patcher = unittest.mock.patch.object( + idlelib.sidebar.idleConf, 'GetFont', mock_idleconf_GetFont) + GetFont_patcher.start() + self.addCleanup(GetFont_patcher.stop) + + def tearDown(self): + self.text.delete('1.0', 'end') + + def get_selection(self): + return tuple(map(str, self.text.tag_ranges('sel'))) + + def get_line_screen_position(self, line): + bbox = self.linenumber.sidebar_text.bbox(f'{line}.end -1c') + x = bbox[0] + 2 + y = bbox[1] + 2 + return x, y + + def assert_state_disabled(self): + state = self.linenumber.sidebar_text.config()['state'] + self.assertEqual(state[-1], tk.DISABLED) + + def get_sidebar_text_contents(self): + return self.linenumber.sidebar_text.get('1.0', tk.END) + + def assert_sidebar_n_lines(self, n_lines): + expected = '\n'.join(chain(map(str, range(1, n_lines + 1)), [''])) + self.assertEqual(self.get_sidebar_text_contents(), expected) + + def assert_text_equals(self, expected): + return self.assertEqual(self.text.get('1.0', 'end'), expected) + + def test_init_empty(self): + self.assert_sidebar_n_lines(1) + + def test_init_not_empty(self): + self.text.insert('insert', 'foo bar\n'*3) + self.assert_text_equals('foo bar\n'*3 + '\n') + self.assert_sidebar_n_lines(4) + + def test_toggle_linenumbering(self): + self.assertEqual(self.linenumber.is_shown, False) + self.linenumber.show_sidebar() + self.assertEqual(self.linenumber.is_shown, True) + self.linenumber.hide_sidebar() + self.assertEqual(self.linenumber.is_shown, False) + self.linenumber.hide_sidebar() + self.assertEqual(self.linenumber.is_shown, False) + self.linenumber.show_sidebar() + self.assertEqual(self.linenumber.is_shown, True) + self.linenumber.show_sidebar() + self.assertEqual(self.linenumber.is_shown, True) + + def test_insert(self): + self.text.insert('insert', 'foobar') + self.assert_text_equals('foobar\n') + self.assert_sidebar_n_lines(1) + self.assert_state_disabled() + + self.text.insert('insert', '\nfoo') + self.assert_text_equals('foobar\nfoo\n') + self.assert_sidebar_n_lines(2) + self.assert_state_disabled() + + self.text.insert('insert', 'hello\n'*2) + self.assert_text_equals('foobar\nfoohello\nhello\n\n') + self.assert_sidebar_n_lines(4) + self.assert_state_disabled() + + self.text.insert('insert', '\nworld') + self.assert_text_equals('foobar\nfoohello\nhello\n\nworld\n') + self.assert_sidebar_n_lines(5) + self.assert_state_disabled() + + def test_delete(self): + self.text.insert('insert', 'foobar') + self.assert_text_equals('foobar\n') + self.text.delete('1.1', '1.3') + self.assert_text_equals('fbar\n') + self.assert_sidebar_n_lines(1) + self.assert_state_disabled() + + self.text.insert('insert', 'foo\n'*2) + self.assert_text_equals('fbarfoo\nfoo\n\n') + self.assert_sidebar_n_lines(3) + self.assert_state_disabled() + + # Deleting up to "2.end" doesn't delete the final newline. + self.text.delete('2.0', '2.end') + self.assert_text_equals('fbarfoo\n\n\n') + self.assert_sidebar_n_lines(3) + self.assert_state_disabled() + + self.text.delete('1.3', 'end') + self.assert_text_equals('fba\n') + self.assert_sidebar_n_lines(1) + self.assert_state_disabled() + + # Text widgets always keep a single '\n' character at the end. + self.text.delete('1.0', 'end') + self.assert_text_equals('\n') + self.assert_sidebar_n_lines(1) + self.assert_state_disabled() + + def test_sidebar_text_width(self): + """ + Test that linenumber text widget is always at the minimum + width + """ + def get_width(): + return self.linenumber.sidebar_text.config()['width'][-1] + + self.assert_sidebar_n_lines(1) + self.assertEqual(get_width(), 1) + + self.text.insert('insert', 'foo') + self.assert_sidebar_n_lines(1) + self.assertEqual(get_width(), 1) + + self.text.insert('insert', 'foo\n'*8) + self.assert_sidebar_n_lines(9) + self.assertEqual(get_width(), 1) + + self.text.insert('insert', 'foo\n') + self.assert_sidebar_n_lines(10) + self.assertEqual(get_width(), 2) + + self.text.insert('insert', 'foo\n') + self.assert_sidebar_n_lines(11) + self.assertEqual(get_width(), 2) + + self.text.delete('insert -1l linestart', 'insert linestart') + self.assert_sidebar_n_lines(10) + self.assertEqual(get_width(), 2) + + self.text.delete('insert -1l linestart', 'insert linestart') + self.assert_sidebar_n_lines(9) + self.assertEqual(get_width(), 1) + + self.text.insert('insert', 'foo\n'*90) + self.assert_sidebar_n_lines(99) + self.assertEqual(get_width(), 2) + + self.text.insert('insert', 'foo\n') + self.assert_sidebar_n_lines(100) + self.assertEqual(get_width(), 3) + + self.text.insert('insert', 'foo\n') + self.assert_sidebar_n_lines(101) + self.assertEqual(get_width(), 3) + + self.text.delete('insert -1l linestart', 'insert linestart') + self.assert_sidebar_n_lines(100) + self.assertEqual(get_width(), 3) + + self.text.delete('insert -1l linestart', 'insert linestart') + self.assert_sidebar_n_lines(99) + self.assertEqual(get_width(), 2) + + self.text.delete('50.0 -1c', 'end -1c') + self.assert_sidebar_n_lines(49) + self.assertEqual(get_width(), 2) + + self.text.delete('5.0 -1c', 'end -1c') + self.assert_sidebar_n_lines(4) + self.assertEqual(get_width(), 1) + + # Text widgets always keep a single '\n' character at the end. + self.text.delete('1.0', 'end -1c') + self.assert_sidebar_n_lines(1) + self.assertEqual(get_width(), 1) + + # The following tests are temporarily disabled due to relying on + # simulated user input and inspecting which text is selected, which + # are fragile and can fail when several GUI tests are run in parallel + # or when the windows created by the test lose focus. + # + # TODO: Re-work these tests or remove them from the test suite. + + @unittest.skip('test disabled') + def test_click_selection(self): + self.linenumber.show_sidebar() + self.text.insert('1.0', 'one\ntwo\nthree\nfour\n') + self.root.update() + + # Click on the second line. + x, y = self.get_line_screen_position(2) + self.linenumber.sidebar_text.event_generate('', x=x, y=y) + self.linenumber.sidebar_text.update() + self.root.update() + + self.assertEqual(self.get_selection(), ('2.0', '3.0')) + + def simulate_drag(self, start_line, end_line): + start_x, start_y = self.get_line_screen_position(start_line) + end_x, end_y = self.get_line_screen_position(end_line) + + self.linenumber.sidebar_text.event_generate('', + x=start_x, y=start_y) + self.root.update() + + def lerp(a, b, steps): + """linearly interpolate from a to b (inclusive) in equal steps""" + last_step = steps - 1 + for i in range(steps): + yield ((last_step - i) / last_step) * a + (i / last_step) * b + + for x, y in zip( + map(int, lerp(start_x, end_x, steps=11)), + map(int, lerp(start_y, end_y, steps=11)), + ): + self.linenumber.sidebar_text.event_generate('', x=x, y=y) + self.root.update() + + self.linenumber.sidebar_text.event_generate('', + x=end_x, y=end_y) + self.root.update() + + @unittest.skip('test disabled') + def test_drag_selection_down(self): + self.linenumber.show_sidebar() + self.text.insert('1.0', 'one\ntwo\nthree\nfour\nfive\n') + self.root.update() + + # Drag from the second line to the fourth line. + self.simulate_drag(2, 4) + self.assertEqual(self.get_selection(), ('2.0', '5.0')) + + @unittest.skip('test disabled') + def test_drag_selection_up(self): + self.linenumber.show_sidebar() + self.text.insert('1.0', 'one\ntwo\nthree\nfour\nfive\n') + self.root.update() + + # Drag from the fourth line to the second line. + self.simulate_drag(4, 2) + self.assertEqual(self.get_selection(), ('2.0', '5.0')) + + def test_scroll(self): + self.linenumber.show_sidebar() + self.text.insert('1.0', 'line\n' * 100) + self.root.update() + + # Scroll down 10 lines. + self.text.yview_scroll(10, 'unit') + self.root.update() + self.assertEqual(self.text.index('@0,0'), '11.0') + self.assertEqual(self.linenumber.sidebar_text.index('@0,0'), '11.0') + + # Generate a mouse-wheel event and make sure it scrolled up or down. + # The meaning of the "delta" is OS-dependent, so this just checks for + # any change. + self.linenumber.sidebar_text.event_generate('', + x=0, y=0, + delta=10) + self.root.update() + self.assertNotEqual(self.text.index('@0,0'), '11.0') + self.assertNotEqual(self.linenumber.sidebar_text.index('@0,0'), '11.0') + + def test_font(self): + ln = self.linenumber + + orig_font = ln.sidebar_text['font'] + test_font = 'TkTextFont' + self.assertNotEqual(orig_font, test_font) + + # Ensure line numbers aren't shown. + ln.hide_sidebar() + + self.font_override = test_font + # Nothing breaks when line numbers aren't shown. + ln.update_font() + + # Activate line numbers, previous font change is immediately effective. + ln.show_sidebar() + self.assertEqual(ln.sidebar_text['font'], test_font) + + # Call the font update with line numbers shown, change is picked up. + self.font_override = orig_font + ln.update_font() + self.assertEqual(ln.sidebar_text['font'], orig_font) + + def test_highlight_colors(self): + ln = self.linenumber + + orig_colors = dict(self.highlight_cfg) + test_colors = {'background': '#222222', 'foreground': '#ffff00'} + + def assert_colors_are_equal(colors): + self.assertEqual(ln.sidebar_text['background'], colors['background']) + self.assertEqual(ln.sidebar_text['foreground'], colors['foreground']) + + # Ensure line numbers aren't shown. + ln.hide_sidebar() + + self.highlight_cfg = test_colors + # Nothing breaks with inactive line numbers. + ln.update_colors() + + # Show line numbers, previous colors change is immediately effective. + ln.show_sidebar() + assert_colors_are_equal(test_colors) + + # Call colors update with no change to the configured colors. + ln.update_colors() + assert_colors_are_equal(test_colors) + + # Call the colors update with line numbers shown, change is picked up. + self.highlight_cfg = orig_colors + ln.update_colors() + assert_colors_are_equal(orig_colors) + + +class ShellSidebarTest(unittest.TestCase): + root: tk.Tk = None + shell: PyShell = None + + @classmethod + def setUpClass(cls): + requires('gui') + + cls.root = root = tk.Tk() + root.withdraw() + + fix_scaling(root) + fixwordbreaks(root) + fix_x11_paste(root) + + cls.flist = flist = PyShellFileList(root) + # See #43981 about macosx.setupApp(root, flist) causing failure. + root.update_idletasks() + + cls.init_shell() + + @classmethod + def tearDownClass(cls): + if cls.shell is not None: + cls.shell.executing = False + cls.shell.close() + cls.shell = None + cls.flist = None + cls.root.update_idletasks() + cls.root.destroy() + cls.root = None + + @classmethod + def init_shell(cls): + cls.shell = cls.flist.open_shell() + cls.shell.pollinterval = 10 + cls.root.update() + cls.n_preface_lines = get_lineno(cls.shell.text, 'end-1c') - 1 + + @classmethod + def reset_shell(cls): + cls.shell.per.bottom.delete(f'{cls.n_preface_lines+1}.0', 'end-1c') + cls.shell.shell_sidebar.update_sidebar() + cls.root.update() + + def setUp(self): + # In some test environments, e.g. Azure Pipelines (as of + # Apr. 2021), sys.stdout is changed between tests. However, + # PyShell relies on overriding sys.stdout when run without a + # sub-process (as done here; see setUpClass). + self._saved_stdout = None + if sys.stdout != self.shell.stdout: + self._saved_stdout = sys.stdout + sys.stdout = self.shell.stdout + + self.reset_shell() + + def tearDown(self): + if self._saved_stdout is not None: + sys.stdout = self._saved_stdout + + def get_sidebar_lines(self): + canvas = self.shell.shell_sidebar.canvas + texts = list(canvas.find(tk.ALL)) + texts_by_y_coords = { + canvas.bbox(text)[1]: canvas.itemcget(text, 'text') + for text in texts + } + line_y_coords = self.get_shell_line_y_coords() + return [texts_by_y_coords.get(y, None) for y in line_y_coords] + + def assert_sidebar_lines_end_with(self, expected_lines): + self.shell.shell_sidebar.update_sidebar() + self.assertEqual( + self.get_sidebar_lines()[-len(expected_lines):], + expected_lines, + ) + + def get_shell_line_y_coords(self): + text = self.shell.text + y_coords = [] + index = text.index("@0,0") + if index.split('.', 1)[1] != '0': + index = text.index(f"{index} +1line linestart") + while (lineinfo := text.dlineinfo(index)) is not None: + y_coords.append(lineinfo[1]) + index = text.index(f"{index} +1line") + return y_coords + + def get_sidebar_line_y_coords(self): + canvas = self.shell.shell_sidebar.canvas + texts = list(canvas.find(tk.ALL)) + texts.sort(key=lambda text: canvas.bbox(text)[1]) + return [canvas.bbox(text)[1] for text in texts] + + def assert_sidebar_lines_synced(self): + self.assertLessEqual( + set(self.get_sidebar_line_y_coords()), + set(self.get_shell_line_y_coords()), + ) + + def do_input(self, input): + shell = self.shell + text = shell.text + for line_index, line in enumerate(input.split('\n')): + if line_index > 0: + text.event_generate('<>') + text.insert('insert', line, 'stdin') + + def test_initial_state(self): + sidebar_lines = self.get_sidebar_lines() + self.assertEqual( + sidebar_lines, + [None] * (len(sidebar_lines) - 1) + ['>>>'], + ) + self.assert_sidebar_lines_synced() + + @run_in_tk_mainloop() + def test_single_empty_input(self): + self.do_input('\n') + yield + self.assert_sidebar_lines_end_with(['>>>', '>>>']) + + @run_in_tk_mainloop() + def test_single_line_statement(self): + self.do_input('1\n') + yield + self.assert_sidebar_lines_end_with(['>>>', None, '>>>']) + + @run_in_tk_mainloop() + def test_multi_line_statement(self): + # Block statements are not indented because IDLE auto-indents. + self.do_input(dedent('''\ + if True: + print(1) + + ''')) + yield + self.assert_sidebar_lines_end_with([ + '>>>', + '...', + '...', + '...', + None, + '>>>', + ]) + + @run_in_tk_mainloop() + def test_single_long_line_wraps(self): + self.do_input('1' * 200 + '\n') + yield + self.assert_sidebar_lines_end_with(['>>>', None, '>>>']) + self.assert_sidebar_lines_synced() + + @run_in_tk_mainloop() + def test_squeeze_multi_line_output(self): + shell = self.shell + text = shell.text + + self.do_input('print("a\\nb\\nc")\n') + yield + self.assert_sidebar_lines_end_with(['>>>', None, None, None, '>>>']) + + text.mark_set('insert', f'insert -1line linestart') + text.event_generate('<>') + yield + self.assert_sidebar_lines_end_with(['>>>', None, '>>>']) + self.assert_sidebar_lines_synced() + + shell.squeezer.expandingbuttons[0].expand() + yield + self.assert_sidebar_lines_end_with(['>>>', None, None, None, '>>>']) + self.assert_sidebar_lines_synced() + + @run_in_tk_mainloop() + def test_interrupt_recall_undo_redo(self): + text = self.shell.text + # Block statements are not indented because IDLE auto-indents. + initial_sidebar_lines = self.get_sidebar_lines() + + self.do_input(dedent('''\ + if True: + print(1) + ''')) + yield + self.assert_sidebar_lines_end_with(['>>>', '...', '...']) + with_block_sidebar_lines = self.get_sidebar_lines() + self.assertNotEqual(with_block_sidebar_lines, initial_sidebar_lines) + + # Control-C + text.event_generate('<>') + yield + self.assert_sidebar_lines_end_with(['>>>', '...', '...', None, '>>>']) + + # Recall previous via history + text.event_generate('<>') + text.event_generate('<>') + yield + self.assert_sidebar_lines_end_with(['>>>', '...', None, '>>>']) + + # Recall previous via recall + text.mark_set('insert', text.index('insert -2l')) + text.event_generate('<>') + yield + + text.event_generate('<>') + yield + self.assert_sidebar_lines_end_with(['>>>']) + + text.event_generate('<>') + yield + self.assert_sidebar_lines_end_with(['>>>', '...']) + + text.event_generate('<>') + text.event_generate('<>') + yield + self.assert_sidebar_lines_end_with( + ['>>>', '...', '...', '...', None, '>>>'] + ) + + @run_in_tk_mainloop() + def test_very_long_wrapped_line(self): + with support.adjust_int_max_str_digits(11_111), \ + swap_attr(self.shell, 'squeezer', None): + self.do_input('x = ' + '1'*10_000 + '\n') + yield + self.assertEqual(self.get_sidebar_lines(), ['>>>']) + + def test_font(self): + sidebar = self.shell.shell_sidebar + + test_font = 'TkTextFont' + + def mock_idleconf_GetFont(root, configType, section): + return test_font + GetFont_patcher = unittest.mock.patch.object( + idlelib.sidebar.idleConf, 'GetFont', mock_idleconf_GetFont) + GetFont_patcher.start() + def cleanup(): + GetFont_patcher.stop() + sidebar.update_font() + self.addCleanup(cleanup) + + def get_sidebar_font(): + canvas = sidebar.canvas + texts = list(canvas.find(tk.ALL)) + fonts = {canvas.itemcget(text, 'font') for text in texts} + self.assertEqual(len(fonts), 1) + return next(iter(fonts)) + + self.assertNotEqual(get_sidebar_font(), test_font) + sidebar.update_font() + self.assertEqual(get_sidebar_font(), test_font) + + def test_highlight_colors(self): + sidebar = self.shell.shell_sidebar + + test_colors = {"background": '#abcdef', "foreground": '#123456'} + + orig_idleConf_GetHighlight = idlelib.sidebar.idleConf.GetHighlight + def mock_idleconf_GetHighlight(theme, element): + if element in ['linenumber', 'console']: + return test_colors + return orig_idleConf_GetHighlight(theme, element) + GetHighlight_patcher = unittest.mock.patch.object( + idlelib.sidebar.idleConf, 'GetHighlight', + mock_idleconf_GetHighlight) + GetHighlight_patcher.start() + def cleanup(): + GetHighlight_patcher.stop() + sidebar.update_colors() + self.addCleanup(cleanup) + + def get_sidebar_colors(): + canvas = sidebar.canvas + texts = list(canvas.find(tk.ALL)) + fgs = {canvas.itemcget(text, 'fill') for text in texts} + self.assertEqual(len(fgs), 1) + fg = next(iter(fgs)) + bg = canvas.cget('background') + return {"background": bg, "foreground": fg} + + self.assertNotEqual(get_sidebar_colors(), test_colors) + sidebar.update_colors() + self.assertEqual(get_sidebar_colors(), test_colors) + + @run_in_tk_mainloop() + def test_mousewheel(self): + sidebar = self.shell.shell_sidebar + text = self.shell.text + + # Enter a 100-line string to scroll the shell screen down. + self.do_input('x = """' + '\n'*100 + '"""\n') + yield + self.assertGreater(get_lineno(text, '@0,0'), 1) + + last_lineno = get_end_linenumber(text) + self.assertIsNotNone(text.dlineinfo(text.index(f'{last_lineno}.0'))) + + # Delta for , whose meaning is platform-dependent. + delta = 1 if sidebar.canvas._windowingsystem == 'aqua' else 120 + + # Scroll up. + if sidebar.canvas._windowingsystem == 'x11': + sidebar.canvas.event_generate('', x=0, y=0) + else: + sidebar.canvas.event_generate('', x=0, y=0, delta=delta) + yield + self.assertIsNone(text.dlineinfo(text.index(f'{last_lineno}.0'))) + + # Scroll back down. + if sidebar.canvas._windowingsystem == 'x11': + sidebar.canvas.event_generate('', x=0, y=0) + else: + sidebar.canvas.event_generate('', x=0, y=0, delta=-delta) + yield + self.assertIsNotNone(text.dlineinfo(text.index(f'{last_lineno}.0'))) + + @run_in_tk_mainloop() + def test_copy(self): + sidebar = self.shell.shell_sidebar + text = self.shell.text + + first_line = get_end_linenumber(text) + + self.do_input(dedent('''\ + if True: + print(1) + + ''')) + yield + + text.tag_add('sel', f'{first_line}.0', 'end-1c') + selected_text = text.get('sel.first', 'sel.last') + self.assertTrue(selected_text.startswith('if True:\n')) + self.assertIn('\n1\n', selected_text) + + text.event_generate('<>') + self.addCleanup(text.clipboard_clear) + + copied_text = text.clipboard_get() + self.assertEqual(copied_text, selected_text) + + @run_in_tk_mainloop() + def test_copy_with_prompts(self): + sidebar = self.shell.shell_sidebar + text = self.shell.text + + first_line = get_end_linenumber(text) + self.do_input(dedent('''\ + if True: + print(1) + + ''')) + yield + + text.tag_add('sel', f'{first_line}.3', 'end-1c') + selected_text = text.get('sel.first', 'sel.last') + self.assertTrue(selected_text.startswith('True:\n')) + + selected_lines_text = text.get('sel.first linestart', 'sel.last') + selected_lines = selected_lines_text.split('\n') + selected_lines.pop() # Final '' is a split artifact, not a line. + # Expect a block of input and a single output line. + expected_prompts = \ + ['>>>'] + ['...'] * (len(selected_lines) - 2) + [None] + selected_text_with_prompts = '\n'.join( + line if prompt is None else prompt + ' ' + line + for prompt, line in zip(expected_prompts, + selected_lines, + strict=True) + ) + '\n' + + text.event_generate('<>') + self.addCleanup(text.clipboard_clear) + + copied_text = text.clipboard_get() + self.assertEqual(copied_text, selected_text_with_prompts) + + +if __name__ == '__main__': + unittest.main(verbosity=2) diff --git a/micromamba_root/envs/pytorch_env/Lib/importlib/__pycache__/__init__.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/importlib/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..544ad39a74882e21a1afa4816e148d88fd50dc1a Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/importlib/__pycache__/__init__.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/importlib/__pycache__/_abc.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/importlib/__pycache__/_abc.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4188fcde4ad252ad7ae270494e65e7cb3c4871b6 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/importlib/__pycache__/_abc.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/importlib/__pycache__/_bootstrap.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/importlib/__pycache__/_bootstrap.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..81aa974b95d726d512354b20ed6ff5444d43dd6d Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/importlib/__pycache__/_bootstrap.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/importlib/__pycache__/_bootstrap_external.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/importlib/__pycache__/_bootstrap_external.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..98d2caf68f4d185e7a5eac925b8a78ea2b35e817 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/importlib/__pycache__/_bootstrap_external.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/importlib/__pycache__/abc.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/importlib/__pycache__/abc.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1ff1b145f57fba22e87c5954557dc32479195ffb Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/importlib/__pycache__/abc.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/importlib/__pycache__/machinery.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/importlib/__pycache__/machinery.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..bc4ffa83149e1a786230df8a696cea27db9c0ef5 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/importlib/__pycache__/machinery.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/importlib/__pycache__/readers.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/importlib/__pycache__/readers.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..32bc9f3b1283b9d9e9a0068a15c37acb1751ada0 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/importlib/__pycache__/readers.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/importlib/__pycache__/simple.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/importlib/__pycache__/simple.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..57ef62f3f0e7172e16efe3cdc09c889ce753c52a Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/importlib/__pycache__/simple.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/importlib/__pycache__/util.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/importlib/__pycache__/util.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..631152a9531611d3151b611ce56ab50a2d2172f9 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/importlib/__pycache__/util.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/importlib/metadata/__init__.py b/micromamba_root/envs/pytorch_env/Lib/importlib/metadata/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..7b2858f8621d006b2a773251914189f76b0e41c8 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/importlib/metadata/__init__.py @@ -0,0 +1,1089 @@ +import os +import re +import abc +import csv +import sys +import email +import pathlib +import zipfile +import operator +import textwrap +import warnings +import functools +import itertools +import posixpath +import collections + +from . import _adapters, _meta +from ._collections import FreezableDefaultDict, Pair +from ._functools import method_cache, pass_none +from ._itertools import always_iterable, unique_everseen +from ._meta import PackageMetadata, SimplePath + +from contextlib import suppress +from importlib import import_module +from importlib.abc import MetaPathFinder +from itertools import starmap +from typing import List, Mapping, Optional, Union + + +__all__ = [ + 'Distribution', + 'DistributionFinder', + 'PackageMetadata', + 'PackageNotFoundError', + 'distribution', + 'distributions', + 'entry_points', + 'files', + 'metadata', + 'packages_distributions', + 'requires', + 'version', +] + + +class PackageNotFoundError(ModuleNotFoundError): + """The package was not found.""" + + def __str__(self): + return f"No package metadata was found for {self.name}" + + @property + def name(self): + (name,) = self.args + return name + + +class Sectioned: + """ + A simple entry point config parser for performance + + >>> for item in Sectioned.read(Sectioned._sample): + ... print(item) + Pair(name='sec1', value='# comments ignored') + Pair(name='sec1', value='a = 1') + Pair(name='sec1', value='b = 2') + Pair(name='sec2', value='a = 2') + + >>> res = Sectioned.section_pairs(Sectioned._sample) + >>> item = next(res) + >>> item.name + 'sec1' + >>> item.value + Pair(name='a', value='1') + >>> item = next(res) + >>> item.value + Pair(name='b', value='2') + >>> item = next(res) + >>> item.name + 'sec2' + >>> item.value + Pair(name='a', value='2') + >>> list(res) + [] + """ + + _sample = textwrap.dedent( + """ + [sec1] + # comments ignored + a = 1 + b = 2 + + [sec2] + a = 2 + """ + ).lstrip() + + @classmethod + def section_pairs(cls, text): + return ( + section._replace(value=Pair.parse(section.value)) + for section in cls.read(text, filter_=cls.valid) + if section.name is not None + ) + + @staticmethod + def read(text, filter_=None): + lines = filter(filter_, map(str.strip, text.splitlines())) + name = None + for value in lines: + section_match = value.startswith('[') and value.endswith(']') + if section_match: + name = value.strip('[]') + continue + yield Pair(name, value) + + @staticmethod + def valid(line): + return line and not line.startswith('#') + + +class DeprecatedTuple: + """ + Provide subscript item access for backward compatibility. + + >>> recwarn = getfixture('recwarn') + >>> ep = EntryPoint(name='name', value='value', group='group') + >>> ep[:] + ('name', 'value', 'group') + >>> ep[0] + 'name' + >>> len(recwarn) + 1 + """ + + _warn = functools.partial( + warnings.warn, + "EntryPoint tuple interface is deprecated. Access members by name.", + DeprecationWarning, + stacklevel=2, + ) + + def __getitem__(self, item): + self._warn() + return self._key()[item] + + +class EntryPoint(DeprecatedTuple): + """An entry point as defined by Python packaging conventions. + + See `the packaging docs on entry points + `_ + for more information. + + >>> ep = EntryPoint( + ... name=None, group=None, value='package.module:attr [extra1, extra2]') + >>> ep.module + 'package.module' + >>> ep.attr + 'attr' + >>> ep.extras + ['extra1', 'extra2'] + """ + + pattern = re.compile( + r'(?P[\w.]+)\s*' + r'(:\s*(?P[\w.]+)\s*)?' + r'((?P\[.*\])\s*)?$' + ) + """ + A regular expression describing the syntax for an entry point, + which might look like: + + - module + - package.module + - package.module:attribute + - package.module:object.attribute + - package.module:attr [extra1, extra2] + + Other combinations are possible as well. + + The expression is lenient about whitespace around the ':', + following the attr, and following any extras. + """ + + name: str + value: str + group: str + + dist: Optional['Distribution'] = None + + def __init__(self, name, value, group): + vars(self).update(name=name, value=value, group=group) + + def load(self): + """Load the entry point from its definition. If only a module + is indicated by the value, return that module. Otherwise, + return the named object. + """ + match = self.pattern.match(self.value) + module = import_module(match.group('module')) + attrs = filter(None, (match.group('attr') or '').split('.')) + return functools.reduce(getattr, attrs, module) + + @property + def module(self): + match = self.pattern.match(self.value) + return match.group('module') + + @property + def attr(self): + match = self.pattern.match(self.value) + return match.group('attr') + + @property + def extras(self): + match = self.pattern.match(self.value) + return re.findall(r'\w+', match.group('extras') or '') + + def _for(self, dist): + vars(self).update(dist=dist) + return self + + def __iter__(self): + """ + Supply iter so one may construct dicts of EntryPoints by name. + """ + msg = ( + "Construction of dict of EntryPoints is deprecated in " + "favor of EntryPoints." + ) + warnings.warn(msg, DeprecationWarning) + return iter((self.name, self)) + + def matches(self, **params): + """ + EntryPoint matches the given parameters. + + >>> ep = EntryPoint(group='foo', name='bar', value='bing:bong [extra1, extra2]') + >>> ep.matches(group='foo') + True + >>> ep.matches(name='bar', value='bing:bong [extra1, extra2]') + True + >>> ep.matches(group='foo', name='other') + False + >>> ep.matches() + True + >>> ep.matches(extras=['extra1', 'extra2']) + True + >>> ep.matches(module='bing') + True + >>> ep.matches(attr='bong') + True + """ + attrs = (getattr(self, param) for param in params) + return all(map(operator.eq, params.values(), attrs)) + + def _key(self): + return self.name, self.value, self.group + + def __lt__(self, other): + return self._key() < other._key() + + def __eq__(self, other): + return self._key() == other._key() + + def __setattr__(self, name, value): + raise AttributeError("EntryPoint objects are immutable.") + + def __repr__(self): + return ( + f'EntryPoint(name={self.name!r}, value={self.value!r}, ' + f'group={self.group!r})' + ) + + def __hash__(self): + return hash(self._key()) + + +class DeprecatedList(list): + """ + Allow an otherwise immutable object to implement mutability + for compatibility. + + >>> recwarn = getfixture('recwarn') + >>> dl = DeprecatedList(range(3)) + >>> dl[0] = 1 + >>> dl.append(3) + >>> del dl[3] + >>> dl.reverse() + >>> dl.sort() + >>> dl.extend([4]) + >>> dl.pop(-1) + 4 + >>> dl.remove(1) + >>> dl += [5] + >>> dl + [6] + [1, 2, 5, 6] + >>> dl + (6,) + [1, 2, 5, 6] + >>> dl.insert(0, 0) + >>> dl + [0, 1, 2, 5] + >>> dl == [0, 1, 2, 5] + True + >>> dl == (0, 1, 2, 5) + True + >>> len(recwarn) + 1 + """ + + __slots__ = () + + _warn = functools.partial( + warnings.warn, + "EntryPoints list interface is deprecated. Cast to list if needed.", + DeprecationWarning, + stacklevel=2, + ) + + def _wrap_deprecated_method(method_name: str): # type: ignore + def wrapped(self, *args, **kwargs): + self._warn() + return getattr(super(), method_name)(*args, **kwargs) + + return method_name, wrapped + + locals().update( + map( + _wrap_deprecated_method, + '__setitem__ __delitem__ append reverse extend pop remove ' + '__iadd__ insert sort'.split(), + ) + ) + + def __add__(self, other): + if not isinstance(other, tuple): + self._warn() + other = tuple(other) + return self.__class__(tuple(self) + other) + + def __eq__(self, other): + if not isinstance(other, tuple): + self._warn() + other = tuple(other) + + return tuple(self).__eq__(other) + + +class EntryPoints(DeprecatedList): + """ + An immutable collection of selectable EntryPoint objects. + """ + + __slots__ = () + + def __getitem__(self, name): # -> EntryPoint: + """ + Get the EntryPoint in self matching name. + """ + if isinstance(name, int): + warnings.warn( + "Accessing entry points by index is deprecated. " + "Cast to tuple if needed.", + DeprecationWarning, + stacklevel=2, + ) + return super().__getitem__(name) + try: + return next(iter(self.select(name=name))) + except StopIteration: + raise KeyError(name) + + def select(self, **params): + """ + Select entry points from self that match the + given parameters (typically group and/or name). + """ + return EntryPoints(ep for ep in self if ep.matches(**params)) + + @property + def names(self): + """ + Return the set of all names of all entry points. + """ + return {ep.name for ep in self} + + @property + def groups(self): + """ + Return the set of all groups of all entry points. + + For coverage while SelectableGroups is present. + >>> EntryPoints().groups + set() + """ + return {ep.group for ep in self} + + @classmethod + def _from_text_for(cls, text, dist): + return cls(ep._for(dist) for ep in cls._from_text(text)) + + @staticmethod + def _from_text(text): + return ( + EntryPoint(name=item.value.name, value=item.value.value, group=item.name) + for item in Sectioned.section_pairs(text or '') + ) + + +class Deprecated: + """ + Compatibility add-in for mapping to indicate that + mapping behavior is deprecated. + + >>> recwarn = getfixture('recwarn') + >>> class DeprecatedDict(Deprecated, dict): pass + >>> dd = DeprecatedDict(foo='bar') + >>> dd.get('baz', None) + >>> dd['foo'] + 'bar' + >>> list(dd) + ['foo'] + >>> list(dd.keys()) + ['foo'] + >>> 'foo' in dd + True + >>> list(dd.values()) + ['bar'] + >>> len(recwarn) + 1 + """ + + _warn = functools.partial( + warnings.warn, + "SelectableGroups dict interface is deprecated. Use select.", + DeprecationWarning, + stacklevel=2, + ) + + def __getitem__(self, name): + self._warn() + return super().__getitem__(name) + + def get(self, name, default=None): + self._warn() + return super().get(name, default) + + def __iter__(self): + self._warn() + return super().__iter__() + + def __contains__(self, *args): + self._warn() + return super().__contains__(*args) + + def keys(self): + self._warn() + return super().keys() + + def values(self): + self._warn() + return super().values() + + +class SelectableGroups(Deprecated, dict): + """ + A backward- and forward-compatible result from + entry_points that fully implements the dict interface. + """ + + @classmethod + def load(cls, eps): + by_group = operator.attrgetter('group') + ordered = sorted(eps, key=by_group) + grouped = itertools.groupby(ordered, by_group) + return cls((group, EntryPoints(eps)) for group, eps in grouped) + + @property + def _all(self): + """ + Reconstruct a list of all entrypoints from the groups. + """ + groups = super(Deprecated, self).values() + return EntryPoints(itertools.chain.from_iterable(groups)) + + @property + def groups(self): + return self._all.groups + + @property + def names(self): + """ + for coverage: + >>> SelectableGroups().names + set() + """ + return self._all.names + + def select(self, **params): + if not params: + return self + return self._all.select(**params) + + +class PackagePath(pathlib.PurePosixPath): + """A reference to a path in a package""" + + def read_text(self, encoding='utf-8'): + with self.locate().open(encoding=encoding) as stream: + return stream.read() + + def read_binary(self): + with self.locate().open('rb') as stream: + return stream.read() + + def locate(self): + """Return a path-like object for this path""" + return self.dist.locate_file(self) + + +class FileHash: + def __init__(self, spec): + self.mode, _, self.value = spec.partition('=') + + def __repr__(self): + return f'' + + +class Distribution: + """A Python distribution package.""" + + @abc.abstractmethod + def read_text(self, filename): + """Attempt to load metadata file given by the name. + + :param filename: The name of the file in the distribution info. + :return: The text if found, otherwise None. + """ + + @abc.abstractmethod + def locate_file(self, path): + """ + Given a path to a file in this distribution, return a path + to it. + """ + + @classmethod + def from_name(cls, name: str): + """Return the Distribution for the given package name. + + :param name: The name of the distribution package to search for. + :return: The Distribution instance (or subclass thereof) for the named + package, if found. + :raises PackageNotFoundError: When the named package's distribution + metadata cannot be found. + :raises ValueError: When an invalid value is supplied for name. + """ + if not name: + raise ValueError("A distribution name is required.") + try: + return next(cls.discover(name=name)) + except StopIteration: + raise PackageNotFoundError(name) + + @classmethod + def discover(cls, **kwargs): + """Return an iterable of Distribution objects for all packages. + + Pass a ``context`` or pass keyword arguments for constructing + a context. + + :context: A ``DistributionFinder.Context`` object. + :return: Iterable of Distribution objects for all packages. + """ + context = kwargs.pop('context', None) + if context and kwargs: + raise ValueError("cannot accept context and kwargs") + context = context or DistributionFinder.Context(**kwargs) + return itertools.chain.from_iterable( + resolver(context) for resolver in cls._discover_resolvers() + ) + + @staticmethod + def at(path): + """Return a Distribution for the indicated metadata path + + :param path: a string or path-like object + :return: a concrete Distribution instance for the path + """ + return PathDistribution(pathlib.Path(path)) + + @staticmethod + def _discover_resolvers(): + """Search the meta_path for resolvers.""" + declared = ( + getattr(finder, 'find_distributions', None) for finder in sys.meta_path + ) + return filter(None, declared) + + @property + def metadata(self) -> _meta.PackageMetadata: + """Return the parsed metadata for this Distribution. + + The returned object will have keys that name the various bits of + metadata. See PEP 566 for details. + """ + text = ( + self.read_text('METADATA') + or self.read_text('PKG-INFO') + # This last clause is here to support old egg-info files. Its + # effect is to just end up using the PathDistribution's self._path + # (which points to the egg-info file) attribute unchanged. + or self.read_text('') + ) + return _adapters.Message(email.message_from_string(text)) + + @property + def name(self): + """Return the 'Name' metadata for the distribution package.""" + return self.metadata['Name'] + + @property + def _normalized_name(self): + """Return a normalized version of the name.""" + return Prepared.normalize(self.name) + + @property + def version(self): + """Return the 'Version' metadata for the distribution package.""" + return self.metadata['Version'] + + @property + def entry_points(self): + return EntryPoints._from_text_for(self.read_text('entry_points.txt'), self) + + @property + def files(self): + """Files in this distribution. + + :return: List of PackagePath for this distribution or None + + Result is `None` if the metadata file that enumerates files + (i.e. RECORD for dist-info or SOURCES.txt for egg-info) is + missing. + Result may be empty if the metadata exists but is empty. + """ + + def make_file(name, hash=None, size_str=None): + result = PackagePath(name) + result.hash = FileHash(hash) if hash else None + result.size = int(size_str) if size_str else None + result.dist = self + return result + + @pass_none + def make_files(lines): + return list(starmap(make_file, csv.reader(lines))) + + return make_files(self._read_files_distinfo() or self._read_files_egginfo()) + + def _read_files_distinfo(self): + """ + Read the lines of RECORD + """ + text = self.read_text('RECORD') + return text and text.splitlines() + + def _read_files_egginfo(self): + """ + SOURCES.txt might contain literal commas, so wrap each line + in quotes. + """ + text = self.read_text('SOURCES.txt') + return text and map('"{}"'.format, text.splitlines()) + + @property + def requires(self): + """Generated requirements specified for this Distribution""" + reqs = self._read_dist_info_reqs() or self._read_egg_info_reqs() + return reqs and list(reqs) + + def _read_dist_info_reqs(self): + return self.metadata.get_all('Requires-Dist') + + def _read_egg_info_reqs(self): + source = self.read_text('requires.txt') + return pass_none(self._deps_from_requires_text)(source) + + @classmethod + def _deps_from_requires_text(cls, source): + return cls._convert_egg_info_reqs_to_simple_reqs(Sectioned.read(source)) + + @staticmethod + def _convert_egg_info_reqs_to_simple_reqs(sections): + """ + Historically, setuptools would solicit and store 'extra' + requirements, including those with environment markers, + in separate sections. More modern tools expect each + dependency to be defined separately, with any relevant + extras and environment markers attached directly to that + requirement. This method converts the former to the + latter. See _test_deps_from_requires_text for an example. + """ + + def make_condition(name): + return name and f'extra == "{name}"' + + def quoted_marker(section): + section = section or '' + extra, sep, markers = section.partition(':') + if extra and markers: + markers = f'({markers})' + conditions = list(filter(None, [markers, make_condition(extra)])) + return '; ' + ' and '.join(conditions) if conditions else '' + + def url_req_space(req): + """ + PEP 508 requires a space between the url_spec and the quoted_marker. + Ref python/importlib_metadata#357. + """ + # '@' is uniquely indicative of a url_req. + return ' ' * ('@' in req) + + for section in sections: + space = url_req_space(section.value) + yield section.value + space + quoted_marker(section.name) + + +class DistributionFinder(MetaPathFinder): + """ + A MetaPathFinder capable of discovering installed distributions. + """ + + class Context: + """ + Keyword arguments presented by the caller to + ``distributions()`` or ``Distribution.discover()`` + to narrow the scope of a search for distributions + in all DistributionFinders. + + Each DistributionFinder may expect any parameters + and should attempt to honor the canonical + parameters defined below when appropriate. + """ + + name = None + """ + Specific name for which a distribution finder should match. + A name of ``None`` matches all distributions. + """ + + def __init__(self, **kwargs): + vars(self).update(kwargs) + + @property + def path(self): + """ + The sequence of directory path that a distribution finder + should search. + + Typically refers to Python installed package paths such as + "site-packages" directories and defaults to ``sys.path``. + """ + return vars(self).get('path', sys.path) + + @abc.abstractmethod + def find_distributions(self, context=Context()): + """ + Find distributions. + + Return an iterable of all Distribution instances capable of + loading the metadata for packages matching the ``context``, + a DistributionFinder.Context instance. + """ + + +class FastPath: + """ + Micro-optimized class for searching a path for + children. + + >>> FastPath('').children() + ['...'] + """ + + @functools.lru_cache() # type: ignore + def __new__(cls, root): + return super().__new__(cls) + + def __init__(self, root): + self.root = root + + def joinpath(self, child): + return pathlib.Path(self.root, child) + + def children(self): + with suppress(Exception): + return os.listdir(self.root or '.') + with suppress(Exception): + return self.zip_children() + return [] + + def zip_children(self): + zip_path = zipfile.Path(self.root) + names = zip_path.root.namelist() + self.joinpath = zip_path.joinpath + + return dict.fromkeys(child.split(posixpath.sep, 1)[0] for child in names) + + def search(self, name): + return self.lookup(self.mtime).search(name) + + @property + def mtime(self): + with suppress(OSError): + return os.stat(self.root).st_mtime + self.lookup.cache_clear() + + @method_cache + def lookup(self, mtime): + return Lookup(self) + + +class Lookup: + def __init__(self, path: FastPath): + base = os.path.basename(path.root).lower() + base_is_egg = base.endswith(".egg") + self.infos = FreezableDefaultDict(list) + self.eggs = FreezableDefaultDict(list) + + for child in path.children(): + low = child.lower() + if low.endswith((".dist-info", ".egg-info")): + # rpartition is faster than splitext and suitable for this purpose. + name = low.rpartition(".")[0].partition("-")[0] + normalized = Prepared.normalize(name) + self.infos[normalized].append(path.joinpath(child)) + elif base_is_egg and low == "egg-info": + name = base.rpartition(".")[0].partition("-")[0] + legacy_normalized = Prepared.legacy_normalize(name) + self.eggs[legacy_normalized].append(path.joinpath(child)) + + self.infos.freeze() + self.eggs.freeze() + + def search(self, prepared): + infos = ( + self.infos[prepared.normalized] + if prepared + else itertools.chain.from_iterable(self.infos.values()) + ) + eggs = ( + self.eggs[prepared.legacy_normalized] + if prepared + else itertools.chain.from_iterable(self.eggs.values()) + ) + return itertools.chain(infos, eggs) + + +class Prepared: + """ + A prepared search for metadata on a possibly-named package. + """ + + normalized = None + legacy_normalized = None + + def __init__(self, name): + self.name = name + if name is None: + return + self.normalized = self.normalize(name) + self.legacy_normalized = self.legacy_normalize(name) + + @staticmethod + def normalize(name): + """ + PEP 503 normalization plus dashes as underscores. + """ + return re.sub(r"[-_.]+", "-", name).lower().replace('-', '_') + + @staticmethod + def legacy_normalize(name): + """ + Normalize the package name as found in the convention in + older packaging tools versions and specs. + """ + return name.lower().replace('-', '_') + + def __bool__(self): + return bool(self.name) + + +class MetadataPathFinder(DistributionFinder): + @classmethod + def find_distributions(cls, context=DistributionFinder.Context()): + """ + Find distributions. + + Return an iterable of all Distribution instances capable of + loading the metadata for packages matching ``context.name`` + (or all names if ``None`` indicated) along the paths in the list + of directories ``context.path``. + """ + found = cls._search_paths(context.name, context.path) + return map(PathDistribution, found) + + @classmethod + def _search_paths(cls, name, paths): + """Find metadata directories in paths heuristically.""" + prepared = Prepared(name) + return itertools.chain.from_iterable( + path.search(prepared) for path in map(FastPath, paths) + ) + + @classmethod + def invalidate_caches(cls): + FastPath.__new__.cache_clear() + + +class PathDistribution(Distribution): + def __init__(self, path: SimplePath): + """Construct a distribution. + + :param path: SimplePath indicating the metadata directory. + """ + self._path = path + + def read_text(self, filename): + with suppress( + FileNotFoundError, + IsADirectoryError, + KeyError, + NotADirectoryError, + PermissionError, + ): + return self._path.joinpath(filename).read_text(encoding='utf-8') + + read_text.__doc__ = Distribution.read_text.__doc__ + + def locate_file(self, path): + return self._path.parent / path + + @property + def _normalized_name(self): + """ + Performance optimization: where possible, resolve the + normalized name from the file system path. + """ + stem = os.path.basename(str(self._path)) + return ( + pass_none(Prepared.normalize)(self._name_from_stem(stem)) + or super()._normalized_name + ) + + @staticmethod + def _name_from_stem(stem): + """ + >>> PathDistribution._name_from_stem('foo-3.0.egg-info') + 'foo' + >>> PathDistribution._name_from_stem('CherryPy-3.0.dist-info') + 'CherryPy' + >>> PathDistribution._name_from_stem('face.egg-info') + 'face' + >>> PathDistribution._name_from_stem('foo.bar') + """ + filename, ext = os.path.splitext(stem) + if ext not in ('.dist-info', '.egg-info'): + return + name, sep, rest = filename.partition('-') + return name + + +def distribution(distribution_name): + """Get the ``Distribution`` instance for the named package. + + :param distribution_name: The name of the distribution package as a string. + :return: A ``Distribution`` instance (or subclass thereof). + """ + return Distribution.from_name(distribution_name) + + +def distributions(**kwargs): + """Get all ``Distribution`` instances in the current environment. + + :return: An iterable of ``Distribution`` instances. + """ + return Distribution.discover(**kwargs) + + +def metadata(distribution_name) -> _meta.PackageMetadata: + """Get the metadata for the named package. + + :param distribution_name: The name of the distribution package to query. + :return: A PackageMetadata containing the parsed metadata. + """ + return Distribution.from_name(distribution_name).metadata + + +def version(distribution_name): + """Get the version string for the named package. + + :param distribution_name: The name of the distribution package to query. + :return: The version string for the package as defined in the package's + "Version" metadata key. + """ + return distribution(distribution_name).version + + +_unique = functools.partial( + unique_everseen, + key=operator.attrgetter('_normalized_name'), +) +""" +Wrapper for ``distributions`` to return unique distributions by name. +""" + + +def entry_points(**params) -> Union[EntryPoints, SelectableGroups]: + """Return EntryPoint objects for all installed packages. + + Pass selection parameters (group or name) to filter the + result to entry points matching those properties (see + EntryPoints.select()). + + For compatibility, returns ``SelectableGroups`` object unless + selection parameters are supplied. In the future, this function + will return ``EntryPoints`` instead of ``SelectableGroups`` + even when no selection parameters are supplied. + + For maximum future compatibility, pass selection parameters + or invoke ``.select`` with parameters on the result. + + :return: EntryPoints or SelectableGroups for all installed packages. + """ + eps = itertools.chain.from_iterable( + dist.entry_points for dist in _unique(distributions()) + ) + return SelectableGroups.load(eps).select(**params) + + +def files(distribution_name): + """Return a list of files for the named package. + + :param distribution_name: The name of the distribution package to query. + :return: List of files composing the distribution. + """ + return distribution(distribution_name).files + + +def requires(distribution_name): + """ + Return a list of requirements for the named package. + + :return: An iterator of requirements, suitable for + packaging.requirement.Requirement. + """ + return distribution(distribution_name).requires + + +def packages_distributions() -> Mapping[str, List[str]]: + """ + Return a mapping of top-level packages to their + distributions. + + >>> import collections.abc + >>> pkgs = packages_distributions() + >>> all(isinstance(dist, collections.abc.Sequence) for dist in pkgs.values()) + True + """ + pkg_to_dist = collections.defaultdict(list) + for dist in distributions(): + for pkg in _top_level_declared(dist) or _top_level_inferred(dist): + pkg_to_dist[pkg].append(dist.metadata['Name']) + return dict(pkg_to_dist) + + +def _top_level_declared(dist): + return (dist.read_text('top_level.txt') or '').split() + + +def _top_level_inferred(dist): + return { + f.parts[0] if len(f.parts) > 1 else f.with_suffix('').name + for f in always_iterable(dist.files) + if f.suffix == ".py" + } diff --git a/micromamba_root/envs/pytorch_env/Lib/importlib/metadata/__pycache__/__init__.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/importlib/metadata/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..246fbbcd938087840edb7010845ca8482d523167 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/importlib/metadata/__pycache__/__init__.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/importlib/metadata/__pycache__/_adapters.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/importlib/metadata/__pycache__/_adapters.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..20cecf42a279121deddf75454cd6d1e55faafdc0 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/importlib/metadata/__pycache__/_adapters.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/importlib/metadata/__pycache__/_collections.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/importlib/metadata/__pycache__/_collections.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..57a40320dbe3d2f99887e1ab73228f2193eee5fd Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/importlib/metadata/__pycache__/_collections.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/importlib/metadata/__pycache__/_functools.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/importlib/metadata/__pycache__/_functools.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f51d4651985963eb5695d5db0b17f5d530dc9133 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/importlib/metadata/__pycache__/_functools.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/importlib/metadata/__pycache__/_itertools.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/importlib/metadata/__pycache__/_itertools.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9dba0b71712d0cfd65a8a54f6df49a87d34c1d22 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/importlib/metadata/__pycache__/_itertools.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/importlib/metadata/__pycache__/_meta.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/importlib/metadata/__pycache__/_meta.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..159275ed068e713fa1b5f20f34a3f2587bb327ee Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/importlib/metadata/__pycache__/_meta.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/importlib/metadata/__pycache__/_text.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/importlib/metadata/__pycache__/_text.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0de33515233bfe3f591397e47f1780b219c84229 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/importlib/metadata/__pycache__/_text.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/importlib/metadata/_adapters.py b/micromamba_root/envs/pytorch_env/Lib/importlib/metadata/_adapters.py new file mode 100644 index 0000000000000000000000000000000000000000..aa460d3eda50fbb174623a1b5bbca54645fd588a --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/importlib/metadata/_adapters.py @@ -0,0 +1,68 @@ +import re +import textwrap +import email.message + +from ._text import FoldedCase + + +class Message(email.message.Message): + multiple_use_keys = set( + map( + FoldedCase, + [ + 'Classifier', + 'Obsoletes-Dist', + 'Platform', + 'Project-URL', + 'Provides-Dist', + 'Provides-Extra', + 'Requires-Dist', + 'Requires-External', + 'Supported-Platform', + 'Dynamic', + ], + ) + ) + """ + Keys that may be indicated multiple times per PEP 566. + """ + + def __new__(cls, orig: email.message.Message): + res = super().__new__(cls) + vars(res).update(vars(orig)) + return res + + def __init__(self, *args, **kwargs): + self._headers = self._repair_headers() + + # suppress spurious error from mypy + def __iter__(self): + return super().__iter__() + + def _repair_headers(self): + def redent(value): + "Correct for RFC822 indentation" + if not value or '\n' not in value: + return value + return textwrap.dedent(' ' * 8 + value) + + headers = [(key, redent(value)) for key, value in vars(self)['_headers']] + if self._payload: + headers.append(('Description', self.get_payload())) + return headers + + @property + def json(self): + """ + Convert PackageMetadata to a JSON-compatible format + per PEP 0566. + """ + + def transform(key): + value = self.get_all(key) if key in self.multiple_use_keys else self[key] + if key == 'Keywords': + value = re.split(r'\s+', value) + tk = key.lower().replace('-', '_') + return tk, value + + return dict(map(transform, map(FoldedCase, self))) diff --git a/micromamba_root/envs/pytorch_env/Lib/importlib/metadata/_collections.py b/micromamba_root/envs/pytorch_env/Lib/importlib/metadata/_collections.py new file mode 100644 index 0000000000000000000000000000000000000000..cf0954e1a30546d781bf25781ec716ef92a77e32 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/importlib/metadata/_collections.py @@ -0,0 +1,30 @@ +import collections + + +# from jaraco.collections 3.3 +class FreezableDefaultDict(collections.defaultdict): + """ + Often it is desirable to prevent the mutation of + a default dict after its initial construction, such + as to prevent mutation during iteration. + + >>> dd = FreezableDefaultDict(list) + >>> dd[0].append('1') + >>> dd.freeze() + >>> dd[1] + [] + >>> len(dd) + 1 + """ + + def __missing__(self, key): + return getattr(self, '_frozen', super().__missing__)(key) + + def freeze(self): + self._frozen = lambda key: self.default_factory() + + +class Pair(collections.namedtuple('Pair', 'name value')): + @classmethod + def parse(cls, text): + return cls(*map(str.strip, text.split("=", 1))) diff --git a/micromamba_root/envs/pytorch_env/Lib/importlib/metadata/_functools.py b/micromamba_root/envs/pytorch_env/Lib/importlib/metadata/_functools.py new file mode 100644 index 0000000000000000000000000000000000000000..71f66bd03cb713a2190853bdf7170c4ea80d2425 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/importlib/metadata/_functools.py @@ -0,0 +1,104 @@ +import types +import functools + + +# from jaraco.functools 3.3 +def method_cache(method, cache_wrapper=None): + """ + Wrap lru_cache to support storing the cache data in the object instances. + + Abstracts the common paradigm where the method explicitly saves an + underscore-prefixed protected property on first call and returns that + subsequently. + + >>> class MyClass: + ... calls = 0 + ... + ... @method_cache + ... def method(self, value): + ... self.calls += 1 + ... return value + + >>> a = MyClass() + >>> a.method(3) + 3 + >>> for x in range(75): + ... res = a.method(x) + >>> a.calls + 75 + + Note that the apparent behavior will be exactly like that of lru_cache + except that the cache is stored on each instance, so values in one + instance will not flush values from another, and when an instance is + deleted, so are the cached values for that instance. + + >>> b = MyClass() + >>> for x in range(35): + ... res = b.method(x) + >>> b.calls + 35 + >>> a.method(0) + 0 + >>> a.calls + 75 + + Note that if method had been decorated with ``functools.lru_cache()``, + a.calls would have been 76 (due to the cached value of 0 having been + flushed by the 'b' instance). + + Clear the cache with ``.cache_clear()`` + + >>> a.method.cache_clear() + + Same for a method that hasn't yet been called. + + >>> c = MyClass() + >>> c.method.cache_clear() + + Another cache wrapper may be supplied: + + >>> cache = functools.lru_cache(maxsize=2) + >>> MyClass.method2 = method_cache(lambda self: 3, cache_wrapper=cache) + >>> a = MyClass() + >>> a.method2() + 3 + + Caution - do not subsequently wrap the method with another decorator, such + as ``@property``, which changes the semantics of the function. + + See also + http://code.activestate.com/recipes/577452-a-memoize-decorator-for-instance-methods/ + for another implementation and additional justification. + """ + cache_wrapper = cache_wrapper or functools.lru_cache() + + def wrapper(self, *args, **kwargs): + # it's the first call, replace the method with a cached, bound method + bound_method = types.MethodType(method, self) + cached_method = cache_wrapper(bound_method) + setattr(self, method.__name__, cached_method) + return cached_method(*args, **kwargs) + + # Support cache clear even before cache has been created. + wrapper.cache_clear = lambda: None + + return wrapper + + +# From jaraco.functools 3.3 +def pass_none(func): + """ + Wrap func so it's not called if its first param is None + + >>> print_text = pass_none(print) + >>> print_text('text') + text + >>> print_text(None) + """ + + @functools.wraps(func) + def wrapper(param, *args, **kwargs): + if param is not None: + return func(param, *args, **kwargs) + + return wrapper diff --git a/micromamba_root/envs/pytorch_env/Lib/importlib/metadata/_itertools.py b/micromamba_root/envs/pytorch_env/Lib/importlib/metadata/_itertools.py new file mode 100644 index 0000000000000000000000000000000000000000..d4ca9b9140e3f085b36609bb8dfdaea79c78e144 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/importlib/metadata/_itertools.py @@ -0,0 +1,73 @@ +from itertools import filterfalse + + +def unique_everseen(iterable, key=None): + "List unique elements, preserving order. Remember all elements ever seen." + # unique_everseen('AAAABBBCCDAABBB') --> A B C D + # unique_everseen('ABBCcAD', str.lower) --> A B C D + seen = set() + seen_add = seen.add + if key is None: + for element in filterfalse(seen.__contains__, iterable): + seen_add(element) + yield element + else: + for element in iterable: + k = key(element) + if k not in seen: + seen_add(k) + yield element + + +# copied from more_itertools 8.8 +def always_iterable(obj, base_type=(str, bytes)): + """If *obj* is iterable, return an iterator over its items:: + + >>> obj = (1, 2, 3) + >>> list(always_iterable(obj)) + [1, 2, 3] + + If *obj* is not iterable, return a one-item iterable containing *obj*:: + + >>> obj = 1 + >>> list(always_iterable(obj)) + [1] + + If *obj* is ``None``, return an empty iterable: + + >>> obj = None + >>> list(always_iterable(None)) + [] + + By default, binary and text strings are not considered iterable:: + + >>> obj = 'foo' + >>> list(always_iterable(obj)) + ['foo'] + + If *base_type* is set, objects for which ``isinstance(obj, base_type)`` + returns ``True`` won't be considered iterable. + + >>> obj = {'a': 1} + >>> list(always_iterable(obj)) # Iterate over the dict's keys + ['a'] + >>> list(always_iterable(obj, base_type=dict)) # Treat dicts as a unit + [{'a': 1}] + + Set *base_type* to ``None`` to avoid any special handling and treat objects + Python considers iterable as iterable: + + >>> obj = 'foo' + >>> list(always_iterable(obj, base_type=None)) + ['f', 'o', 'o'] + """ + if obj is None: + return iter(()) + + if (base_type is not None) and isinstance(obj, base_type): + return iter((obj,)) + + try: + return iter(obj) + except TypeError: + return iter((obj,)) diff --git a/micromamba_root/envs/pytorch_env/Lib/importlib/metadata/_meta.py b/micromamba_root/envs/pytorch_env/Lib/importlib/metadata/_meta.py new file mode 100644 index 0000000000000000000000000000000000000000..d5c0576194ece238b6062b97dcdea443c5630bc8 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/importlib/metadata/_meta.py @@ -0,0 +1,47 @@ +from typing import Any, Dict, Iterator, List, Protocol, TypeVar, Union + + +_T = TypeVar("_T") + + +class PackageMetadata(Protocol): + def __len__(self) -> int: + ... # pragma: no cover + + def __contains__(self, item: str) -> bool: + ... # pragma: no cover + + def __getitem__(self, key: str) -> str: + ... # pragma: no cover + + def __iter__(self) -> Iterator[str]: + ... # pragma: no cover + + def get_all(self, name: str, failobj: _T = ...) -> Union[List[Any], _T]: + """ + Return all values associated with a possibly multi-valued key. + """ + + @property + def json(self) -> Dict[str, Union[str, List[str]]]: + """ + A JSON-compatible form of the metadata. + """ + + +class SimplePath(Protocol): + """ + A minimal subset of pathlib.Path required by PathDistribution. + """ + + def joinpath(self) -> 'SimplePath': + ... # pragma: no cover + + def __truediv__(self) -> 'SimplePath': + ... # pragma: no cover + + def parent(self) -> 'SimplePath': + ... # pragma: no cover + + def read_text(self) -> str: + ... # pragma: no cover diff --git a/micromamba_root/envs/pytorch_env/Lib/importlib/metadata/_text.py b/micromamba_root/envs/pytorch_env/Lib/importlib/metadata/_text.py new file mode 100644 index 0000000000000000000000000000000000000000..c88cfbb2349c6401336bc5ba6623f51afd1eb59d --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/importlib/metadata/_text.py @@ -0,0 +1,99 @@ +import re + +from ._functools import method_cache + + +# from jaraco.text 3.5 +class FoldedCase(str): + """ + A case insensitive string class; behaves just like str + except compares equal when the only variation is case. + + >>> s = FoldedCase('hello world') + + >>> s == 'Hello World' + True + + >>> 'Hello World' == s + True + + >>> s != 'Hello World' + False + + >>> s.index('O') + 4 + + >>> s.split('O') + ['hell', ' w', 'rld'] + + >>> sorted(map(FoldedCase, ['GAMMA', 'alpha', 'Beta'])) + ['alpha', 'Beta', 'GAMMA'] + + Sequence membership is straightforward. + + >>> "Hello World" in [s] + True + >>> s in ["Hello World"] + True + + You may test for set inclusion, but candidate and elements + must both be folded. + + >>> FoldedCase("Hello World") in {s} + True + >>> s in {FoldedCase("Hello World")} + True + + String inclusion works as long as the FoldedCase object + is on the right. + + >>> "hello" in FoldedCase("Hello World") + True + + But not if the FoldedCase object is on the left: + + >>> FoldedCase('hello') in 'Hello World' + False + + In that case, use in_: + + >>> FoldedCase('hello').in_('Hello World') + True + + >>> FoldedCase('hello') > FoldedCase('Hello') + False + """ + + def __lt__(self, other): + return self.lower() < other.lower() + + def __gt__(self, other): + return self.lower() > other.lower() + + def __eq__(self, other): + return self.lower() == other.lower() + + def __ne__(self, other): + return self.lower() != other.lower() + + def __hash__(self): + return hash(self.lower()) + + def __contains__(self, other): + return super().lower().__contains__(other.lower()) + + def in_(self, other): + "Does self appear in other?" + return self in FoldedCase(other) + + # cache lower since it's likely to be called frequently. + @method_cache + def lower(self): + return super().lower() + + def index(self, sub): + return self.lower().index(sub.lower()) + + def split(self, splitter=' ', maxsplit=0): + pattern = re.compile(re.escape(splitter), re.I) + return pattern.split(self, maxsplit) diff --git a/micromamba_root/envs/pytorch_env/Lib/importlib/resources/__init__.py b/micromamba_root/envs/pytorch_env/Lib/importlib/resources/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..34e3a9950cc557879af8d797f9382b18a870fb56 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/importlib/resources/__init__.py @@ -0,0 +1,36 @@ +"""Read resources contained within a package.""" + +from ._common import ( + as_file, + files, + Package, +) + +from ._legacy import ( + contents, + open_binary, + read_binary, + open_text, + read_text, + is_resource, + path, + Resource, +) + +from .abc import ResourceReader + + +__all__ = [ + 'Package', + 'Resource', + 'ResourceReader', + 'as_file', + 'contents', + 'files', + 'is_resource', + 'open_binary', + 'open_text', + 'path', + 'read_binary', + 'read_text', +] diff --git a/micromamba_root/envs/pytorch_env/Lib/importlib/resources/__pycache__/__init__.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/importlib/resources/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7aa06d8e77690bd623125da466b8a0336d8991a2 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/importlib/resources/__pycache__/__init__.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/importlib/resources/__pycache__/_adapters.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/importlib/resources/__pycache__/_adapters.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4f1fb9b97c3072a238ca421f5c2a6939d9e71e44 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/importlib/resources/__pycache__/_adapters.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/importlib/resources/__pycache__/_common.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/importlib/resources/__pycache__/_common.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0b64c18e2fec6919005a620cf39fce9de8e9618f Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/importlib/resources/__pycache__/_common.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/importlib/resources/__pycache__/_itertools.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/importlib/resources/__pycache__/_itertools.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..994bb6ca91022a5cae358ed5f58d22698901051c Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/importlib/resources/__pycache__/_itertools.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/importlib/resources/__pycache__/_legacy.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/importlib/resources/__pycache__/_legacy.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8d21f7c58835a41ef5083a8432a407d688ef30e2 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/importlib/resources/__pycache__/_legacy.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/importlib/resources/__pycache__/abc.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/importlib/resources/__pycache__/abc.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..698ec1284b47b92e9c34fad655fadce2274a8259 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/importlib/resources/__pycache__/abc.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/importlib/resources/__pycache__/readers.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/importlib/resources/__pycache__/readers.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0295097b35f7a71ac421611662529a3f931d71b8 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/importlib/resources/__pycache__/readers.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/importlib/resources/__pycache__/simple.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/importlib/resources/__pycache__/simple.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2452478ac8cc1d2838e5cdcf0696cea5e79406cb Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/importlib/resources/__pycache__/simple.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/importlib/resources/_adapters.py b/micromamba_root/envs/pytorch_env/Lib/importlib/resources/_adapters.py new file mode 100644 index 0000000000000000000000000000000000000000..ea363d86a564b5450666aa00aecd46353326a75a --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/importlib/resources/_adapters.py @@ -0,0 +1,170 @@ +from contextlib import suppress +from io import TextIOWrapper + +from . import abc + + +class SpecLoaderAdapter: + """ + Adapt a package spec to adapt the underlying loader. + """ + + def __init__(self, spec, adapter=lambda spec: spec.loader): + self.spec = spec + self.loader = adapter(spec) + + def __getattr__(self, name): + return getattr(self.spec, name) + + +class TraversableResourcesLoader: + """ + Adapt a loader to provide TraversableResources. + """ + + def __init__(self, spec): + self.spec = spec + + def get_resource_reader(self, name): + return CompatibilityFiles(self.spec)._native() + + +def _io_wrapper(file, mode='r', *args, **kwargs): + if mode == 'r': + return TextIOWrapper(file, *args, **kwargs) + elif mode == 'rb': + return file + raise ValueError( + "Invalid mode value '{}', only 'r' and 'rb' are supported".format(mode) + ) + + +class CompatibilityFiles: + """ + Adapter for an existing or non-existent resource reader + to provide a compatibility .files(). + """ + + class SpecPath(abc.Traversable): + """ + Path tied to a module spec. + Can be read and exposes the resource reader children. + """ + + def __init__(self, spec, reader): + self._spec = spec + self._reader = reader + + def iterdir(self): + if not self._reader: + return iter(()) + return iter( + CompatibilityFiles.ChildPath(self._reader, path) + for path in self._reader.contents() + ) + + def is_file(self): + return False + + is_dir = is_file + + def joinpath(self, other): + if not self._reader: + return CompatibilityFiles.OrphanPath(other) + return CompatibilityFiles.ChildPath(self._reader, other) + + @property + def name(self): + return self._spec.name + + def open(self, mode='r', *args, **kwargs): + return _io_wrapper(self._reader.open_resource(None), mode, *args, **kwargs) + + class ChildPath(abc.Traversable): + """ + Path tied to a resource reader child. + Can be read but doesn't expose any meaningful children. + """ + + def __init__(self, reader, name): + self._reader = reader + self._name = name + + def iterdir(self): + return iter(()) + + def is_file(self): + return self._reader.is_resource(self.name) + + def is_dir(self): + return not self.is_file() + + def joinpath(self, other): + return CompatibilityFiles.OrphanPath(self.name, other) + + @property + def name(self): + return self._name + + def open(self, mode='r', *args, **kwargs): + return _io_wrapper( + self._reader.open_resource(self.name), mode, *args, **kwargs + ) + + class OrphanPath(abc.Traversable): + """ + Orphan path, not tied to a module spec or resource reader. + Can't be read and doesn't expose any meaningful children. + """ + + def __init__(self, *path_parts): + if len(path_parts) < 1: + raise ValueError('Need at least one path part to construct a path') + self._path = path_parts + + def iterdir(self): + return iter(()) + + def is_file(self): + return False + + is_dir = is_file + + def joinpath(self, other): + return CompatibilityFiles.OrphanPath(*self._path, other) + + @property + def name(self): + return self._path[-1] + + def open(self, mode='r', *args, **kwargs): + raise FileNotFoundError("Can't open orphan path") + + def __init__(self, spec): + self.spec = spec + + @property + def _reader(self): + with suppress(AttributeError): + return self.spec.loader.get_resource_reader(self.spec.name) + + def _native(self): + """ + Return the native reader if it supports files(). + """ + reader = self._reader + return reader if hasattr(reader, 'files') else self + + def __getattr__(self, attr): + return getattr(self._reader, attr) + + def files(self): + return CompatibilityFiles.SpecPath(self.spec, self._reader) + + +def wrap_spec(package): + """ + Construct a package spec with traversable compatibility + on the spec/loader/reader. + """ + return SpecLoaderAdapter(package.__spec__, TraversableResourcesLoader) diff --git a/micromamba_root/envs/pytorch_env/Lib/importlib/resources/_common.py b/micromamba_root/envs/pytorch_env/Lib/importlib/resources/_common.py new file mode 100644 index 0000000000000000000000000000000000000000..ca1fa8ab2fe6ff28313134ef37d7c71676280b35 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/importlib/resources/_common.py @@ -0,0 +1,107 @@ +import os +import pathlib +import tempfile +import functools +import contextlib +import types +import importlib + +from typing import Union, Optional +from .abc import ResourceReader, Traversable + +from ._adapters import wrap_spec + +Package = Union[types.ModuleType, str] + + +def files(package): + # type: (Package) -> Traversable + """ + Get a Traversable resource from a package + """ + return from_package(get_package(package)) + + +def get_resource_reader(package): + # type: (types.ModuleType) -> Optional[ResourceReader] + """ + Return the package's loader if it's a ResourceReader. + """ + # We can't use + # a issubclass() check here because apparently abc.'s __subclasscheck__() + # hook wants to create a weak reference to the object, but + # zipimport.zipimporter does not support weak references, resulting in a + # TypeError. That seems terrible. + spec = package.__spec__ + reader = getattr(spec.loader, 'get_resource_reader', None) # type: ignore + if reader is None: + return None + return reader(spec.name) # type: ignore + + +def resolve(cand): + # type: (Package) -> types.ModuleType + return cand if isinstance(cand, types.ModuleType) else importlib.import_module(cand) + + +def get_package(package): + # type: (Package) -> types.ModuleType + """Take a package name or module object and return the module. + + Raise an exception if the resolved module is not a package. + """ + resolved = resolve(package) + if wrap_spec(resolved).submodule_search_locations is None: + raise TypeError(f'{package!r} is not a package') + return resolved + + +def from_package(package): + """ + Return a Traversable object for the given package. + + """ + spec = wrap_spec(package) + reader = spec.loader.get_resource_reader(spec.name) + return reader.files() + + +@contextlib.contextmanager +def _tempfile(reader, suffix='', + # gh-93353: Keep a reference to call os.remove() in late Python + # finalization. + *, _os_remove=os.remove): + # Not using tempfile.NamedTemporaryFile as it leads to deeper 'try' + # blocks due to the need to close the temporary file to work on Windows + # properly. + fd, raw_path = tempfile.mkstemp(suffix=suffix) + try: + try: + os.write(fd, reader()) + finally: + os.close(fd) + del reader + yield pathlib.Path(raw_path) + finally: + try: + _os_remove(raw_path) + except FileNotFoundError: + pass + + +@functools.singledispatch +def as_file(path): + """ + Given a Traversable object, return that object as a + path on the local file system in a context manager. + """ + return _tempfile(path.read_bytes, suffix=path.name) + + +@as_file.register(pathlib.Path) +@contextlib.contextmanager +def _(path): + """ + Degenerate behavior for pathlib.Path objects. + """ + yield path diff --git a/micromamba_root/envs/pytorch_env/Lib/importlib/resources/_itertools.py b/micromamba_root/envs/pytorch_env/Lib/importlib/resources/_itertools.py new file mode 100644 index 0000000000000000000000000000000000000000..cce05582ffc6fe6d72027194f4ccc44ee42f1fcd --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/importlib/resources/_itertools.py @@ -0,0 +1,35 @@ +from itertools import filterfalse + +from typing import ( + Callable, + Iterable, + Iterator, + Optional, + Set, + TypeVar, + Union, +) + +# Type and type variable definitions +_T = TypeVar('_T') +_U = TypeVar('_U') + + +def unique_everseen( + iterable: Iterable[_T], key: Optional[Callable[[_T], _U]] = None +) -> Iterator[_T]: + "List unique elements, preserving order. Remember all elements ever seen." + # unique_everseen('AAAABBBCCDAABBB') --> A B C D + # unique_everseen('ABBCcAD', str.lower) --> A B C D + seen: Set[Union[_T, _U]] = set() + seen_add = seen.add + if key is None: + for element in filterfalse(seen.__contains__, iterable): + seen_add(element) + yield element + else: + for element in iterable: + k = key(element) + if k not in seen: + seen_add(k) + yield element diff --git a/micromamba_root/envs/pytorch_env/Lib/importlib/resources/_legacy.py b/micromamba_root/envs/pytorch_env/Lib/importlib/resources/_legacy.py new file mode 100644 index 0000000000000000000000000000000000000000..1d5d3f1fbb1f6c69d0da2a50e1d4492ad3378f17 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/importlib/resources/_legacy.py @@ -0,0 +1,121 @@ +import functools +import os +import pathlib +import types +import warnings + +from typing import Union, Iterable, ContextManager, BinaryIO, TextIO, Any + +from . import _common + +Package = Union[types.ModuleType, str] +Resource = str + + +def deprecated(func): + @functools.wraps(func) + def wrapper(*args, **kwargs): + warnings.warn( + f"{func.__name__} is deprecated. Use files() instead. " + "Refer to https://importlib-resources.readthedocs.io" + "/en/latest/using.html#migrating-from-legacy for migration advice.", + DeprecationWarning, + stacklevel=2, + ) + return func(*args, **kwargs) + + return wrapper + + +def normalize_path(path): + # type: (Any) -> str + """Normalize a path by ensuring it is a string. + + If the resulting string contains path separators, an exception is raised. + """ + str_path = str(path) + parent, file_name = os.path.split(str_path) + if parent: + raise ValueError(f'{path!r} must be only a file name') + return file_name + + +@deprecated +def open_binary(package: Package, resource: Resource) -> BinaryIO: + """Return a file-like object opened for binary reading of the resource.""" + return (_common.files(package) / normalize_path(resource)).open('rb') + + +@deprecated +def read_binary(package: Package, resource: Resource) -> bytes: + """Return the binary contents of the resource.""" + return (_common.files(package) / normalize_path(resource)).read_bytes() + + +@deprecated +def open_text( + package: Package, + resource: Resource, + encoding: str = 'utf-8', + errors: str = 'strict', +) -> TextIO: + """Return a file-like object opened for text reading of the resource.""" + return (_common.files(package) / normalize_path(resource)).open( + 'r', encoding=encoding, errors=errors + ) + + +@deprecated +def read_text( + package: Package, + resource: Resource, + encoding: str = 'utf-8', + errors: str = 'strict', +) -> str: + """Return the decoded string of the resource. + + The decoding-related arguments have the same semantics as those of + bytes.decode(). + """ + with open_text(package, resource, encoding, errors) as fp: + return fp.read() + + +@deprecated +def contents(package: Package) -> Iterable[str]: + """Return an iterable of entries in `package`. + + Note that not all entries are resources. Specifically, directories are + not considered resources. Use `is_resource()` on each entry returned here + to check if it is a resource or not. + """ + return [path.name for path in _common.files(package).iterdir()] + + +@deprecated +def is_resource(package: Package, name: str) -> bool: + """True if `name` is a resource inside `package`. + + Directories are *not* resources. + """ + resource = normalize_path(name) + return any( + traversable.name == resource and traversable.is_file() + for traversable in _common.files(package).iterdir() + ) + + +@deprecated +def path( + package: Package, + resource: Resource, +) -> ContextManager[pathlib.Path]: + """A context manager providing a file path object to the resource. + + If the resource does not already exist on its own on the file system, + a temporary file will be created. If the file was created, the file + will be deleted upon exiting the context manager (no exception is + raised if the file was deleted prior to the context manager + exiting). + """ + return _common.as_file(_common.files(package) / normalize_path(resource)) diff --git a/micromamba_root/envs/pytorch_env/Lib/importlib/resources/abc.py b/micromamba_root/envs/pytorch_env/Lib/importlib/resources/abc.py new file mode 100644 index 0000000000000000000000000000000000000000..0b7bfdc415829e15a77ac94420a0e5258e359d79 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/importlib/resources/abc.py @@ -0,0 +1,151 @@ +import abc +import io +import os +from typing import Any, BinaryIO, Iterable, Iterator, NoReturn, Text, Optional +from typing import runtime_checkable, Protocol +from typing import Union + + +StrPath = Union[str, os.PathLike[str]] + +__all__ = ["ResourceReader", "Traversable", "TraversableResources"] + + +class ResourceReader(metaclass=abc.ABCMeta): + """Abstract base class for loaders to provide resource reading support.""" + + @abc.abstractmethod + def open_resource(self, resource: Text) -> BinaryIO: + """Return an opened, file-like object for binary reading. + + The 'resource' argument is expected to represent only a file name. + If the resource cannot be found, FileNotFoundError is raised. + """ + # This deliberately raises FileNotFoundError instead of + # NotImplementedError so that if this method is accidentally called, + # it'll still do the right thing. + raise FileNotFoundError + + @abc.abstractmethod + def resource_path(self, resource: Text) -> Text: + """Return the file system path to the specified resource. + + The 'resource' argument is expected to represent only a file name. + If the resource does not exist on the file system, raise + FileNotFoundError. + """ + # This deliberately raises FileNotFoundError instead of + # NotImplementedError so that if this method is accidentally called, + # it'll still do the right thing. + raise FileNotFoundError + + @abc.abstractmethod + def is_resource(self, path: Text) -> bool: + """Return True if the named 'path' is a resource. + + Files are resources, directories are not. + """ + raise FileNotFoundError + + @abc.abstractmethod + def contents(self) -> Iterable[str]: + """Return an iterable of entries in `package`.""" + raise FileNotFoundError + + +@runtime_checkable +class Traversable(Protocol): + """ + An object with a subset of pathlib.Path methods suitable for + traversing directories and opening files. + + Any exceptions that occur when accessing the backing resource + may propagate unaltered. + """ + + @abc.abstractmethod + def iterdir(self) -> Iterator["Traversable"]: + """ + Yield Traversable objects in self + """ + + def read_bytes(self) -> bytes: + """ + Read contents of self as bytes + """ + with self.open('rb') as strm: + return strm.read() + + def read_text(self, encoding: Optional[str] = None) -> str: + """ + Read contents of self as text + """ + with self.open(encoding=encoding) as strm: + return strm.read() + + @abc.abstractmethod + def is_dir(self) -> bool: + """ + Return True if self is a directory + """ + + @abc.abstractmethod + def is_file(self) -> bool: + """ + Return True if self is a file + """ + + @abc.abstractmethod + def joinpath(self, *descendants: StrPath) -> "Traversable": + """ + Return Traversable resolved with any descendants applied. + + Each descendant should be a path segment relative to self + and each may contain multiple levels separated by + ``posixpath.sep`` (``/``). + """ + + def __truediv__(self, child: StrPath) -> "Traversable": + """ + Return Traversable child in self + """ + return self.joinpath(child) + + @abc.abstractmethod + def open(self, mode='r', *args, **kwargs): + """ + mode may be 'r' or 'rb' to open as text or binary. Return a handle + suitable for reading (same as pathlib.Path.open). + + When opening as text, accepts encoding parameters such as those + accepted by io.TextIOWrapper. + """ + + @abc.abstractproperty + def name(self) -> str: + """ + The base name of this object without any parent references. + """ + + +class TraversableResources(ResourceReader): + """ + The required interface for providing traversable + resources. + """ + + @abc.abstractmethod + def files(self) -> "Traversable": + """Return a Traversable object for the loaded package.""" + + def open_resource(self, resource: StrPath) -> io.BufferedReader: + return self.files().joinpath(resource).open('rb') + + def resource_path(self, resource: Any) -> NoReturn: + raise FileNotFoundError(resource) + + def is_resource(self, path: StrPath) -> bool: + return self.files().joinpath(path).is_file() + + def contents(self) -> Iterator[str]: + return (item.name for item in self.files().iterdir()) diff --git a/micromamba_root/envs/pytorch_env/Lib/importlib/resources/readers.py b/micromamba_root/envs/pytorch_env/Lib/importlib/resources/readers.py new file mode 100644 index 0000000000000000000000000000000000000000..b470a2062b2b3acad0a29528a78ba898b296abd9 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/importlib/resources/readers.py @@ -0,0 +1,122 @@ +import collections +import operator +import pathlib +import zipfile + +from . import abc + +from ._itertools import unique_everseen + + +def remove_duplicates(items): + return iter(collections.OrderedDict.fromkeys(items)) + + +class FileReader(abc.TraversableResources): + def __init__(self, loader): + self.path = pathlib.Path(loader.path).parent + + def resource_path(self, resource): + """ + Return the file system path to prevent + `resources.path()` from creating a temporary + copy. + """ + return str(self.path.joinpath(resource)) + + def files(self): + return self.path + + +class ZipReader(abc.TraversableResources): + def __init__(self, loader, module): + _, _, name = module.rpartition('.') + self.prefix = loader.prefix.replace('\\', '/') + name + '/' + self.archive = loader.archive + + def open_resource(self, resource): + try: + return super().open_resource(resource) + except KeyError as exc: + raise FileNotFoundError(exc.args[0]) + + def is_resource(self, path): + # workaround for `zipfile.Path.is_file` returning true + # for non-existent paths. + target = self.files().joinpath(path) + return target.is_file() and target.exists() + + def files(self): + return zipfile.Path(self.archive, self.prefix) + + +class MultiplexedPath(abc.Traversable): + """ + Given a series of Traversable objects, implement a merged + version of the interface across all objects. Useful for + namespace packages which may be multihomed at a single + name. + """ + + def __init__(self, *paths): + self._paths = list(map(pathlib.Path, remove_duplicates(paths))) + if not self._paths: + message = 'MultiplexedPath must contain at least one path' + raise FileNotFoundError(message) + if not all(path.is_dir() for path in self._paths): + raise NotADirectoryError('MultiplexedPath only supports directories') + + def iterdir(self): + files = (file for path in self._paths for file in path.iterdir()) + return unique_everseen(files, key=operator.attrgetter('name')) + + def read_bytes(self): + raise FileNotFoundError(f'{self} is not a file') + + def read_text(self, *args, **kwargs): + raise FileNotFoundError(f'{self} is not a file') + + def is_dir(self): + return True + + def is_file(self): + return False + + def joinpath(self, child): + # first try to find child in current paths + for file in self.iterdir(): + if file.name == child: + return file + # if it does not exist, construct it with the first path + return self._paths[0] / child + + __truediv__ = joinpath + + def open(self, *args, **kwargs): + raise FileNotFoundError(f'{self} is not a file') + + @property + def name(self): + return self._paths[0].name + + def __repr__(self): + paths = ', '.join(f"'{path}'" for path in self._paths) + return f'MultiplexedPath({paths})' + + +class NamespaceReader(abc.TraversableResources): + def __init__(self, namespace_path): + if 'NamespacePath' not in str(namespace_path): + raise ValueError('Invalid path') + self.path = MultiplexedPath(*list(namespace_path)) + + def resource_path(self, resource): + """ + Return the file system path to prevent + `resources.path()` from creating a temporary + copy. + """ + return str(self.path.joinpath(resource)) + + def files(self): + return self.path diff --git a/micromamba_root/envs/pytorch_env/Lib/importlib/resources/simple.py b/micromamba_root/envs/pytorch_env/Lib/importlib/resources/simple.py new file mode 100644 index 0000000000000000000000000000000000000000..3d1b0a1acd1ec1248550d7b94d19f434f6859ba2 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/importlib/resources/simple.py @@ -0,0 +1,125 @@ +""" +Interface adapters for low-level readers. +""" + +import abc +import io +import itertools +from typing import BinaryIO, List + +from .abc import Traversable, TraversableResources + + +class SimpleReader(abc.ABC): + """ + The minimum, low-level interface required from a resource + provider. + """ + + @abc.abstractproperty + def package(self): + # type: () -> str + """ + The name of the package for which this reader loads resources. + """ + + @abc.abstractmethod + def children(self): + # type: () -> List['SimpleReader'] + """ + Obtain an iterable of SimpleReader for available + child containers (e.g. directories). + """ + + @abc.abstractmethod + def resources(self): + # type: () -> List[str] + """ + Obtain available named resources for this virtual package. + """ + + @abc.abstractmethod + def open_binary(self, resource): + # type: (str) -> BinaryIO + """ + Obtain a File-like for a named resource. + """ + + @property + def name(self): + return self.package.split('.')[-1] + + +class ResourceHandle(Traversable): + """ + Handle to a named resource in a ResourceReader. + """ + + def __init__(self, parent, name): + # type: (ResourceContainer, str) -> None + self.parent = parent + self.name = name # type: ignore + + def is_file(self): + return True + + def is_dir(self): + return False + + def open(self, mode='r', *args, **kwargs): + stream = self.parent.reader.open_binary(self.name) + if 'b' not in mode: + stream = io.TextIOWrapper(stream, *args, **kwargs) + return stream + + def joinpath(self, name): + raise RuntimeError("Cannot traverse into a resource") + + +class ResourceContainer(Traversable): + """ + Traversable container for a package's resources via its reader. + """ + + def __init__(self, reader): + # type: (SimpleReader) -> None + self.reader = reader + + def is_dir(self): + return True + + def is_file(self): + return False + + def iterdir(self): + files = (ResourceHandle(self, name) for name in self.reader.resources) + dirs = map(ResourceContainer, self.reader.children()) + return itertools.chain(files, dirs) + + def open(self, *args, **kwargs): + raise IsADirectoryError() + + @staticmethod + def _flatten(compound_names): + for name in compound_names: + yield from name.split('/') + + def joinpath(self, *descendants): + if not descendants: + return self + names = self._flatten(descendants) + target = next(names) + return next( + traversable for traversable in self.iterdir() if traversable.name == target + ).joinpath(*names) + + +class TraversableReader(TraversableResources, SimpleReader): + """ + A TraversableResources based on SimpleReader. Resource providers + may derive from this class to provide the TraversableResources + interface by supplying the SimpleReader interface. + """ + + def files(self): + return ResourceContainer(self) diff --git a/micromamba_root/envs/pytorch_env/Lib/json/__pycache__/__init__.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/json/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d30505e512e0cf12acdd693f14f74bc62519663a Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/json/__pycache__/__init__.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/json/__pycache__/decoder.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/json/__pycache__/decoder.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3ef3226c7935c78729ebd44480971be1145dc70c Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/json/__pycache__/decoder.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/json/__pycache__/encoder.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/json/__pycache__/encoder.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d93e7bac09c7eea816ec8d5e5677428804f08612 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/json/__pycache__/encoder.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/json/__pycache__/scanner.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/json/__pycache__/scanner.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..30e422040d540f5062f6aac7c281947c5e9cc620 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/json/__pycache__/scanner.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/json/__pycache__/tool.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/json/__pycache__/tool.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a4073ea4698fb6742de16d4d10d838c0b74d232c Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/json/__pycache__/tool.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/lib2to3/__pycache__/__init__.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/lib2to3/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0c6d8339501a94afab97fb01ca17a025415b2464 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/lib2to3/__pycache__/__init__.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/lib2to3/__pycache__/__main__.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/lib2to3/__pycache__/__main__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..fcfa78b0066a36f350b486ac36fe284d59010d1e Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/lib2to3/__pycache__/__main__.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/lib2to3/__pycache__/btm_matcher.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/lib2to3/__pycache__/btm_matcher.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..10eaecc0abdbf8b8165a2d83f85d9e6d83776f76 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/lib2to3/__pycache__/btm_matcher.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/lib2to3/__pycache__/btm_utils.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/lib2to3/__pycache__/btm_utils.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5be48d9e5a2f04ac15a1419d543d71947470c702 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/lib2to3/__pycache__/btm_utils.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/lib2to3/__pycache__/fixer_base.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/lib2to3/__pycache__/fixer_base.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4eada53dc8c73515fad3eae3feae259235452e9d Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/lib2to3/__pycache__/fixer_base.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/lib2to3/__pycache__/fixer_util.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/lib2to3/__pycache__/fixer_util.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..99ddd6b583c6dd4f6a7d54009997d1909d3aaa64 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/lib2to3/__pycache__/fixer_util.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/lib2to3/__pycache__/main.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/lib2to3/__pycache__/main.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2ad1f104180403296eaee5fc938492f2a0e3ff2f Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/lib2to3/__pycache__/main.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/lib2to3/__pycache__/patcomp.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/lib2to3/__pycache__/patcomp.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6fc1c9b52da37ac55e64a058ca0273080a70cb15 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/lib2to3/__pycache__/patcomp.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/lib2to3/__pycache__/pygram.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/lib2to3/__pycache__/pygram.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1420746043b868bf35db57a147f74fe8c2f322c8 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/lib2to3/__pycache__/pygram.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/lib2to3/__pycache__/pytree.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/lib2to3/__pycache__/pytree.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..71b3d0890de2d7c78272dae9cbf461fa40999f65 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/lib2to3/__pycache__/pytree.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/lib2to3/__pycache__/refactor.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/lib2to3/__pycache__/refactor.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..656ef1de5d405157dc4d00071bbd91004f8c963d Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/lib2to3/__pycache__/refactor.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/lib2to3/fixes/__init__.py b/micromamba_root/envs/pytorch_env/Lib/lib2to3/fixes/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..b93054b3ecf3a5af96f4772e7208e7a18b5dd4a4 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/lib2to3/fixes/__init__.py @@ -0,0 +1 @@ +# Dummy file to make this directory a package. diff --git a/micromamba_root/envs/pytorch_env/Lib/lib2to3/fixes/__pycache__/__init__.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/lib2to3/fixes/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..be05ad4cd6c7a1e34ed85110025ce02163464b08 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/lib2to3/fixes/__pycache__/__init__.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/lib2to3/fixes/__pycache__/fix_apply.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/lib2to3/fixes/__pycache__/fix_apply.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ce5d1deb536b1302c1c5198456fc7e7612d33808 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/lib2to3/fixes/__pycache__/fix_apply.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/lib2to3/fixes/__pycache__/fix_asserts.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/lib2to3/fixes/__pycache__/fix_asserts.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b9955030db0900d499946c91a8f0813930e31253 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/lib2to3/fixes/__pycache__/fix_asserts.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/lib2to3/fixes/__pycache__/fix_basestring.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/lib2to3/fixes/__pycache__/fix_basestring.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2658299a344ac306f3097988821622d9261cb700 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/lib2to3/fixes/__pycache__/fix_basestring.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/lib2to3/fixes/__pycache__/fix_buffer.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/lib2to3/fixes/__pycache__/fix_buffer.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d5f912652d3c41544b2b3b837782a4419bc14525 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/lib2to3/fixes/__pycache__/fix_buffer.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/lib2to3/fixes/__pycache__/fix_dict.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/lib2to3/fixes/__pycache__/fix_dict.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f1ccd2c644f4c305823dad64cfa196fbc92cba43 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/lib2to3/fixes/__pycache__/fix_dict.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/lib2to3/fixes/__pycache__/fix_except.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/lib2to3/fixes/__pycache__/fix_except.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..50ef05bf0ba1dc6c702f20c41cd67e3a4342e53e Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/lib2to3/fixes/__pycache__/fix_except.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/lib2to3/fixes/__pycache__/fix_exec.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/lib2to3/fixes/__pycache__/fix_exec.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..689841b43ced3e61ca572acbf7a7e91da25a69f0 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/lib2to3/fixes/__pycache__/fix_exec.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/lib2to3/fixes/__pycache__/fix_execfile.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/lib2to3/fixes/__pycache__/fix_execfile.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..85d0a0249ee8d278504e21014d148cf15d3a37a3 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/lib2to3/fixes/__pycache__/fix_execfile.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/lib2to3/fixes/__pycache__/fix_exitfunc.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/lib2to3/fixes/__pycache__/fix_exitfunc.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..55587911c2a0bb10ec62ce7cf7b818ef3fc7465e Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/lib2to3/fixes/__pycache__/fix_exitfunc.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/lib2to3/fixes/__pycache__/fix_filter.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/lib2to3/fixes/__pycache__/fix_filter.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6af0b07704039d44725207d1ebe89255af9018dc Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/lib2to3/fixes/__pycache__/fix_filter.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/lib2to3/fixes/__pycache__/fix_funcattrs.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/lib2to3/fixes/__pycache__/fix_funcattrs.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ee3a79b9a047cd2759a12352376c96d14287b4fd Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/lib2to3/fixes/__pycache__/fix_funcattrs.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/lib2to3/fixes/__pycache__/fix_future.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/lib2to3/fixes/__pycache__/fix_future.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1e54ca2bc2f791f0b6f8d196b4332bbee4aed816 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/lib2to3/fixes/__pycache__/fix_future.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/lib2to3/fixes/__pycache__/fix_getcwdu.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/lib2to3/fixes/__pycache__/fix_getcwdu.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..18ac300772d564da5c8d93dd9d30ba059e90c93b Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/lib2to3/fixes/__pycache__/fix_getcwdu.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/lib2to3/fixes/__pycache__/fix_has_key.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/lib2to3/fixes/__pycache__/fix_has_key.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7845d5bf349f7d340950eceec02aace3bb26bfcf Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/lib2to3/fixes/__pycache__/fix_has_key.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/lib2to3/fixes/__pycache__/fix_idioms.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/lib2to3/fixes/__pycache__/fix_idioms.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f7afa9a669b65577d7eeed39510bab85f535f4a2 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/lib2to3/fixes/__pycache__/fix_idioms.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/lib2to3/fixes/__pycache__/fix_import.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/lib2to3/fixes/__pycache__/fix_import.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8421fec0f04c02ccf7e973ddf194a8473e3851d2 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/lib2to3/fixes/__pycache__/fix_import.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/lib2to3/fixes/__pycache__/fix_imports.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/lib2to3/fixes/__pycache__/fix_imports.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4e1b431627714607b12ab6d58f2c9e2e342bce01 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/lib2to3/fixes/__pycache__/fix_imports.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/lib2to3/fixes/__pycache__/fix_imports2.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/lib2to3/fixes/__pycache__/fix_imports2.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c4bfde631ef5e43ebcd2c9d7aa5043b8135a62d5 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/lib2to3/fixes/__pycache__/fix_imports2.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/lib2to3/fixes/__pycache__/fix_input.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/lib2to3/fixes/__pycache__/fix_input.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..496ee432fe2588fb12c2227d26ac4f9b70a9d4e4 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/lib2to3/fixes/__pycache__/fix_input.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/lib2to3/fixes/__pycache__/fix_intern.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/lib2to3/fixes/__pycache__/fix_intern.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0805adfabc5686422323a508f6e0113a63282d3d Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/lib2to3/fixes/__pycache__/fix_intern.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/lib2to3/fixes/__pycache__/fix_isinstance.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/lib2to3/fixes/__pycache__/fix_isinstance.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7ce143f9e3b3bbdfb1967dfe20d59288efa7b4ac Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/lib2to3/fixes/__pycache__/fix_isinstance.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/lib2to3/fixes/__pycache__/fix_itertools.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/lib2to3/fixes/__pycache__/fix_itertools.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..acee6d9cd9debdadca7989b78c46eeced06c6a94 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/lib2to3/fixes/__pycache__/fix_itertools.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/lib2to3/fixes/__pycache__/fix_itertools_imports.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/lib2to3/fixes/__pycache__/fix_itertools_imports.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..97bd2fd5eea29b76070b69d5e121d6922b615d18 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/lib2to3/fixes/__pycache__/fix_itertools_imports.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/lib2to3/fixes/__pycache__/fix_long.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/lib2to3/fixes/__pycache__/fix_long.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..61d1e617000d9e69954a689bb2e4250f81d7ef9b Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/lib2to3/fixes/__pycache__/fix_long.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/lib2to3/fixes/__pycache__/fix_map.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/lib2to3/fixes/__pycache__/fix_map.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2c084ec2995e92c4e341bfff1d79d4a55869efb0 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/lib2to3/fixes/__pycache__/fix_map.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/lib2to3/fixes/__pycache__/fix_metaclass.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/lib2to3/fixes/__pycache__/fix_metaclass.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1a143869e26b4637162ed743cf8ff02b0399c17e Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/lib2to3/fixes/__pycache__/fix_metaclass.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/lib2to3/fixes/__pycache__/fix_methodattrs.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/lib2to3/fixes/__pycache__/fix_methodattrs.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1a2a3dd587a19bd94a64351cbf3249fb2dafdb3a Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/lib2to3/fixes/__pycache__/fix_methodattrs.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/lib2to3/fixes/__pycache__/fix_ne.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/lib2to3/fixes/__pycache__/fix_ne.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a58e82cf3962374244bfd651bfa01472fb93860f Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/lib2to3/fixes/__pycache__/fix_ne.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/lib2to3/fixes/__pycache__/fix_next.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/lib2to3/fixes/__pycache__/fix_next.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1a86931da12f95e8672536a6db2c90374e1df810 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/lib2to3/fixes/__pycache__/fix_next.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/lib2to3/fixes/__pycache__/fix_nonzero.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/lib2to3/fixes/__pycache__/fix_nonzero.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1b88261bc86b8340d1961b138f7870c093c49611 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/lib2to3/fixes/__pycache__/fix_nonzero.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/lib2to3/fixes/__pycache__/fix_numliterals.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/lib2to3/fixes/__pycache__/fix_numliterals.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f0d533f9ea979c2bf7f1676c7c04fc505d7c9f95 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/lib2to3/fixes/__pycache__/fix_numliterals.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/lib2to3/fixes/__pycache__/fix_operator.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/lib2to3/fixes/__pycache__/fix_operator.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8ea71b57f1959bf370145ce23c7c17510734c71e Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/lib2to3/fixes/__pycache__/fix_operator.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/lib2to3/fixes/__pycache__/fix_paren.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/lib2to3/fixes/__pycache__/fix_paren.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9e6c6e87580238f5e68abd240526f390eefc2f4b Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/lib2to3/fixes/__pycache__/fix_paren.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/lib2to3/fixes/__pycache__/fix_print.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/lib2to3/fixes/__pycache__/fix_print.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5352dd3aa8f13a1160bb6726f7b0af6886c5ec67 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/lib2to3/fixes/__pycache__/fix_print.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/lib2to3/fixes/__pycache__/fix_raise.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/lib2to3/fixes/__pycache__/fix_raise.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e18665ba24e8b7551b017e2bf1d5431fd8154c7c Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/lib2to3/fixes/__pycache__/fix_raise.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/lib2to3/fixes/__pycache__/fix_raw_input.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/lib2to3/fixes/__pycache__/fix_raw_input.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f39cb3e1eecebc96ad6d34874264437c4d69992c Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/lib2to3/fixes/__pycache__/fix_raw_input.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/lib2to3/fixes/__pycache__/fix_reduce.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/lib2to3/fixes/__pycache__/fix_reduce.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0ea6b5a02c8fa29f067252506da46dfded3c7a4f Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/lib2to3/fixes/__pycache__/fix_reduce.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/lib2to3/fixes/__pycache__/fix_reload.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/lib2to3/fixes/__pycache__/fix_reload.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..94c96a2a4d3e5f4d3710c92a94518b4be9720964 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/lib2to3/fixes/__pycache__/fix_reload.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/lib2to3/fixes/__pycache__/fix_renames.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/lib2to3/fixes/__pycache__/fix_renames.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..189790e98aa70d0eb73a4bac63504541ee8289c8 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/lib2to3/fixes/__pycache__/fix_renames.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/lib2to3/fixes/__pycache__/fix_repr.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/lib2to3/fixes/__pycache__/fix_repr.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..25fa64e6064e93fc82f11c78796c9b776d30b316 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/lib2to3/fixes/__pycache__/fix_repr.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/lib2to3/fixes/__pycache__/fix_set_literal.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/lib2to3/fixes/__pycache__/fix_set_literal.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..27863ffe00f1b4563d1ad04db9d372106c1351f2 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/lib2to3/fixes/__pycache__/fix_set_literal.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/lib2to3/fixes/__pycache__/fix_standarderror.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/lib2to3/fixes/__pycache__/fix_standarderror.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8d1ba7ff8f3c8e2ed2db6f135f863c786bea6b45 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/lib2to3/fixes/__pycache__/fix_standarderror.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/lib2to3/fixes/__pycache__/fix_sys_exc.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/lib2to3/fixes/__pycache__/fix_sys_exc.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..fbcd081b4f5d94b7ed6719a86e8803ca6d3a3f19 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/lib2to3/fixes/__pycache__/fix_sys_exc.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/lib2to3/fixes/__pycache__/fix_throw.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/lib2to3/fixes/__pycache__/fix_throw.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..282753a6c37205f661c94447ceee4d05d0ad27ca Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/lib2to3/fixes/__pycache__/fix_throw.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/lib2to3/fixes/__pycache__/fix_tuple_params.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/lib2to3/fixes/__pycache__/fix_tuple_params.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..31ad7f4c8f49b8070bd72fb15ab61adf7547ede6 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/lib2to3/fixes/__pycache__/fix_tuple_params.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/lib2to3/fixes/__pycache__/fix_types.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/lib2to3/fixes/__pycache__/fix_types.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c4d78c3f7a3fa196f2d5609c37222339b622f3db Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/lib2to3/fixes/__pycache__/fix_types.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/lib2to3/fixes/__pycache__/fix_unicode.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/lib2to3/fixes/__pycache__/fix_unicode.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9561c5af5e25ad8738625aff6ade154a8994ae24 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/lib2to3/fixes/__pycache__/fix_unicode.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/lib2to3/fixes/__pycache__/fix_urllib.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/lib2to3/fixes/__pycache__/fix_urllib.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..32d13ff8fad764bdfaa9c22b2097d0f5857ff249 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/lib2to3/fixes/__pycache__/fix_urllib.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/lib2to3/fixes/__pycache__/fix_ws_comma.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/lib2to3/fixes/__pycache__/fix_ws_comma.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..59d4072ae8bab3a6b15b2eb0f2102e817989d240 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/lib2to3/fixes/__pycache__/fix_ws_comma.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/lib2to3/fixes/__pycache__/fix_xrange.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/lib2to3/fixes/__pycache__/fix_xrange.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3d3152ff033849fe80244bd567bb5a3691acb74a Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/lib2to3/fixes/__pycache__/fix_xrange.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/lib2to3/fixes/__pycache__/fix_xreadlines.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/lib2to3/fixes/__pycache__/fix_xreadlines.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0be3e7878277044616dbd301b03b1e42a0d46c42 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/lib2to3/fixes/__pycache__/fix_xreadlines.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/lib2to3/fixes/__pycache__/fix_zip.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/lib2to3/fixes/__pycache__/fix_zip.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..462435f53f2176ea3429ba6f7f55007cb6ab9b0a Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/lib2to3/fixes/__pycache__/fix_zip.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/lib2to3/fixes/fix_apply.py b/micromamba_root/envs/pytorch_env/Lib/lib2to3/fixes/fix_apply.py new file mode 100644 index 0000000000000000000000000000000000000000..6408582c42647741416968f92c351a5581bc5e3e --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/lib2to3/fixes/fix_apply.py @@ -0,0 +1,68 @@ +# Copyright 2006 Google, Inc. All Rights Reserved. +# Licensed to PSF under a Contributor Agreement. + +"""Fixer for apply(). + +This converts apply(func, v, k) into (func)(*v, **k).""" + +# Local imports +from .. import pytree +from ..pgen2 import token +from .. import fixer_base +from ..fixer_util import Call, Comma, parenthesize + +class FixApply(fixer_base.BaseFix): + BM_compatible = True + + PATTERN = """ + power< 'apply' + trailer< + '(' + arglist< + (not argument + ')' + > + > + """ + + def transform(self, node, results): + syms = self.syms + assert results + func = results["func"] + args = results["args"] + kwds = results.get("kwds") + # I feel like we should be able to express this logic in the + # PATTERN above but I don't know how to do it so... + if args: + if (args.type == self.syms.argument and + args.children[0].value in {'**', '*'}): + return # Make no change. + if kwds and (kwds.type == self.syms.argument and + kwds.children[0].value == '**'): + return # Make no change. + prefix = node.prefix + func = func.clone() + if (func.type not in (token.NAME, syms.atom) and + (func.type != syms.power or + func.children[-2].type == token.DOUBLESTAR)): + # Need to parenthesize + func = parenthesize(func) + func.prefix = "" + args = args.clone() + args.prefix = "" + if kwds is not None: + kwds = kwds.clone() + kwds.prefix = "" + l_newargs = [pytree.Leaf(token.STAR, "*"), args] + if kwds is not None: + l_newargs.extend([Comma(), + pytree.Leaf(token.DOUBLESTAR, "**"), + kwds]) + l_newargs[-2].prefix = " " # that's the ** token + # XXX Sometimes we could be cleverer, e.g. apply(f, (x, y) + t) + # can be translated into f(x, y, *t) instead of f(*(x, y) + t) + #new = pytree.Node(syms.power, (func, ArgList(l_newargs))) + return Call(func, l_newargs, prefix=prefix) diff --git a/micromamba_root/envs/pytorch_env/Lib/lib2to3/fixes/fix_asserts.py b/micromamba_root/envs/pytorch_env/Lib/lib2to3/fixes/fix_asserts.py new file mode 100644 index 0000000000000000000000000000000000000000..5bcec885f52cbf3a8a4a7bcf3331402a54f76967 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/lib2to3/fixes/fix_asserts.py @@ -0,0 +1,34 @@ +"""Fixer that replaces deprecated unittest method names.""" + +# Author: Ezio Melotti + +from ..fixer_base import BaseFix +from ..fixer_util import Name + +NAMES = dict( + assert_="assertTrue", + assertEquals="assertEqual", + assertNotEquals="assertNotEqual", + assertAlmostEquals="assertAlmostEqual", + assertNotAlmostEquals="assertNotAlmostEqual", + assertRegexpMatches="assertRegex", + assertRaisesRegexp="assertRaisesRegex", + failUnlessEqual="assertEqual", + failIfEqual="assertNotEqual", + failUnlessAlmostEqual="assertAlmostEqual", + failIfAlmostEqual="assertNotAlmostEqual", + failUnless="assertTrue", + failUnlessRaises="assertRaises", + failIf="assertFalse", +) + + +class FixAsserts(BaseFix): + + PATTERN = """ + power< any+ trailer< '.' meth=(%s)> any* > + """ % '|'.join(map(repr, NAMES)) + + def transform(self, node, results): + name = results["meth"][0] + name.replace(Name(NAMES[str(name)], prefix=name.prefix)) diff --git a/micromamba_root/envs/pytorch_env/Lib/lib2to3/fixes/fix_basestring.py b/micromamba_root/envs/pytorch_env/Lib/lib2to3/fixes/fix_basestring.py new file mode 100644 index 0000000000000000000000000000000000000000..5fe69a0f03b1b885e28e508a8670406c67a4896a --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/lib2to3/fixes/fix_basestring.py @@ -0,0 +1,14 @@ +"""Fixer for basestring -> str.""" +# Author: Christian Heimes + +# Local imports +from .. import fixer_base +from ..fixer_util import Name + +class FixBasestring(fixer_base.BaseFix): + BM_compatible = True + + PATTERN = "'basestring'" + + def transform(self, node, results): + return Name("str", prefix=node.prefix) diff --git a/micromamba_root/envs/pytorch_env/Lib/lib2to3/fixes/fix_buffer.py b/micromamba_root/envs/pytorch_env/Lib/lib2to3/fixes/fix_buffer.py new file mode 100644 index 0000000000000000000000000000000000000000..f9a1958ad3b93e502126396e02caca773f1f01fa --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/lib2to3/fixes/fix_buffer.py @@ -0,0 +1,22 @@ +# Copyright 2007 Google, Inc. All Rights Reserved. +# Licensed to PSF under a Contributor Agreement. + +"""Fixer that changes buffer(...) into memoryview(...).""" + +# Local imports +from .. import fixer_base +from ..fixer_util import Name + + +class FixBuffer(fixer_base.BaseFix): + BM_compatible = True + + explicit = True # The user must ask for this fixer + + PATTERN = """ + power< name='buffer' trailer< '(' [any] ')' > any* > + """ + + def transform(self, node, results): + name = results["name"] + name.replace(Name("memoryview", prefix=name.prefix)) diff --git a/micromamba_root/envs/pytorch_env/Lib/lib2to3/fixes/fix_dict.py b/micromamba_root/envs/pytorch_env/Lib/lib2to3/fixes/fix_dict.py new file mode 100644 index 0000000000000000000000000000000000000000..d3655c9f1b2d9bf82d8ce3a2140cfeff9ba97323 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/lib2to3/fixes/fix_dict.py @@ -0,0 +1,106 @@ +# Copyright 2007 Google, Inc. All Rights Reserved. +# Licensed to PSF under a Contributor Agreement. + +"""Fixer for dict methods. + +d.keys() -> list(d.keys()) +d.items() -> list(d.items()) +d.values() -> list(d.values()) + +d.iterkeys() -> iter(d.keys()) +d.iteritems() -> iter(d.items()) +d.itervalues() -> iter(d.values()) + +d.viewkeys() -> d.keys() +d.viewitems() -> d.items() +d.viewvalues() -> d.values() + +Except in certain very specific contexts: the iter() can be dropped +when the context is list(), sorted(), iter() or for...in; the list() +can be dropped when the context is list() or sorted() (but not iter() +or for...in!). Special contexts that apply to both: list(), sorted(), tuple() +set(), any(), all(), sum(). + +Note: iter(d.keys()) could be written as iter(d) but since the +original d.iterkeys() was also redundant we don't fix this. And there +are (rare) contexts where it makes a difference (e.g. when passing it +as an argument to a function that introspects the argument). +""" + +# Local imports +from .. import pytree +from .. import patcomp +from .. import fixer_base +from ..fixer_util import Name, Call, Dot +from .. import fixer_util + + +iter_exempt = fixer_util.consuming_calls | {"iter"} + + +class FixDict(fixer_base.BaseFix): + BM_compatible = True + + PATTERN = """ + power< head=any+ + trailer< '.' method=('keys'|'items'|'values'| + 'iterkeys'|'iteritems'|'itervalues'| + 'viewkeys'|'viewitems'|'viewvalues') > + parens=trailer< '(' ')' > + tail=any* + > + """ + + def transform(self, node, results): + head = results["head"] + method = results["method"][0] # Extract node for method name + tail = results["tail"] + syms = self.syms + method_name = method.value + isiter = method_name.startswith("iter") + isview = method_name.startswith("view") + if isiter or isview: + method_name = method_name[4:] + assert method_name in ("keys", "items", "values"), repr(method) + head = [n.clone() for n in head] + tail = [n.clone() for n in tail] + special = not tail and self.in_special_context(node, isiter) + args = head + [pytree.Node(syms.trailer, + [Dot(), + Name(method_name, + prefix=method.prefix)]), + results["parens"].clone()] + new = pytree.Node(syms.power, args) + if not (special or isview): + new.prefix = "" + new = Call(Name("iter" if isiter else "list"), [new]) + if tail: + new = pytree.Node(syms.power, [new] + tail) + new.prefix = node.prefix + return new + + P1 = "power< func=NAME trailer< '(' node=any ')' > any* >" + p1 = patcomp.compile_pattern(P1) + + P2 = """for_stmt< 'for' any 'in' node=any ':' any* > + | comp_for< 'for' any 'in' node=any any* > + """ + p2 = patcomp.compile_pattern(P2) + + def in_special_context(self, node, isiter): + if node.parent is None: + return False + results = {} + if (node.parent.parent is not None and + self.p1.match(node.parent.parent, results) and + results["node"] is node): + if isiter: + # iter(d.iterkeys()) -> iter(d.keys()), etc. + return results["func"].value in iter_exempt + else: + # list(d.keys()) -> list(d.keys()), etc. + return results["func"].value in fixer_util.consuming_calls + if not isiter: + return False + # for ... in d.iterkeys() -> for ... in d.keys(), etc. + return self.p2.match(node.parent, results) and results["node"] is node diff --git a/micromamba_root/envs/pytorch_env/Lib/lib2to3/fixes/fix_except.py b/micromamba_root/envs/pytorch_env/Lib/lib2to3/fixes/fix_except.py new file mode 100644 index 0000000000000000000000000000000000000000..49bd3d5ab7d6ccd8a98016a12b4ed54ff0c800de --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/lib2to3/fixes/fix_except.py @@ -0,0 +1,93 @@ +"""Fixer for except statements with named exceptions. + +The following cases will be converted: + +- "except E, T:" where T is a name: + + except E as T: + +- "except E, T:" where T is not a name, tuple or list: + + except E as t: + T = t + + This is done because the target of an "except" clause must be a + name. + +- "except E, T:" where T is a tuple or list literal: + + except E as t: + T = t.args +""" +# Author: Collin Winter + +# Local imports +from .. import pytree +from ..pgen2 import token +from .. import fixer_base +from ..fixer_util import Assign, Attr, Name, is_tuple, is_list, syms + +def find_excepts(nodes): + for i, n in enumerate(nodes): + if n.type == syms.except_clause: + if n.children[0].value == 'except': + yield (n, nodes[i+2]) + +class FixExcept(fixer_base.BaseFix): + BM_compatible = True + + PATTERN = """ + try_stmt< 'try' ':' (simple_stmt | suite) + cleanup=(except_clause ':' (simple_stmt | suite))+ + tail=(['except' ':' (simple_stmt | suite)] + ['else' ':' (simple_stmt | suite)] + ['finally' ':' (simple_stmt | suite)]) > + """ + + def transform(self, node, results): + syms = self.syms + + tail = [n.clone() for n in results["tail"]] + + try_cleanup = [ch.clone() for ch in results["cleanup"]] + for except_clause, e_suite in find_excepts(try_cleanup): + if len(except_clause.children) == 4: + (E, comma, N) = except_clause.children[1:4] + comma.replace(Name("as", prefix=" ")) + + if N.type != token.NAME: + # Generate a new N for the except clause + new_N = Name(self.new_name(), prefix=" ") + target = N.clone() + target.prefix = "" + N.replace(new_N) + new_N = new_N.clone() + + # Insert "old_N = new_N" as the first statement in + # the except body. This loop skips leading whitespace + # and indents + #TODO(cwinter) suite-cleanup + suite_stmts = e_suite.children + for i, stmt in enumerate(suite_stmts): + if isinstance(stmt, pytree.Node): + break + + # The assignment is different if old_N is a tuple or list + # In that case, the assignment is old_N = new_N.args + if is_tuple(N) or is_list(N): + assign = Assign(target, Attr(new_N, Name('args'))) + else: + assign = Assign(target, new_N) + + #TODO(cwinter) stopgap until children becomes a smart list + for child in reversed(suite_stmts[:i]): + e_suite.insert_child(0, child) + e_suite.insert_child(i, assign) + elif N.prefix == "": + # No space after a comma is legal; no space after "as", + # not so much. + N.prefix = " " + + #TODO(cwinter) fix this when children becomes a smart list + children = [c.clone() for c in node.children[:3]] + try_cleanup + tail + return pytree.Node(node.type, children) diff --git a/micromamba_root/envs/pytorch_env/Lib/lib2to3/fixes/fix_exec.py b/micromamba_root/envs/pytorch_env/Lib/lib2to3/fixes/fix_exec.py new file mode 100644 index 0000000000000000000000000000000000000000..ab921ee80cdf366532f027b2549e5bcba55a4fd5 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/lib2to3/fixes/fix_exec.py @@ -0,0 +1,39 @@ +# Copyright 2006 Google, Inc. All Rights Reserved. +# Licensed to PSF under a Contributor Agreement. + +"""Fixer for exec. + +This converts usages of the exec statement into calls to a built-in +exec() function. + +exec code in ns1, ns2 -> exec(code, ns1, ns2) +""" + +# Local imports +from .. import fixer_base +from ..fixer_util import Comma, Name, Call + + +class FixExec(fixer_base.BaseFix): + BM_compatible = True + + PATTERN = """ + exec_stmt< 'exec' a=any 'in' b=any [',' c=any] > + | + exec_stmt< 'exec' (not atom<'(' [any] ')'>) a=any > + """ + + def transform(self, node, results): + assert results + syms = self.syms + a = results["a"] + b = results.get("b") + c = results.get("c") + args = [a.clone()] + args[0].prefix = "" + if b is not None: + args.extend([Comma(), b.clone()]) + if c is not None: + args.extend([Comma(), c.clone()]) + + return Call(Name("exec"), args, prefix=node.prefix) diff --git a/micromamba_root/envs/pytorch_env/Lib/lib2to3/fixes/fix_execfile.py b/micromamba_root/envs/pytorch_env/Lib/lib2to3/fixes/fix_execfile.py new file mode 100644 index 0000000000000000000000000000000000000000..b6c786fd4e8b6a141ab3619ba2b2576db158fcd4 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/lib2to3/fixes/fix_execfile.py @@ -0,0 +1,53 @@ +# Copyright 2006 Google, Inc. All Rights Reserved. +# Licensed to PSF under a Contributor Agreement. + +"""Fixer for execfile. + +This converts usages of the execfile function into calls to the built-in +exec() function. +""" + +from .. import fixer_base +from ..fixer_util import (Comma, Name, Call, LParen, RParen, Dot, Node, + ArgList, String, syms) + + +class FixExecfile(fixer_base.BaseFix): + BM_compatible = True + + PATTERN = """ + power< 'execfile' trailer< '(' arglist< filename=any [',' globals=any [',' locals=any ] ] > ')' > > + | + power< 'execfile' trailer< '(' filename=any ')' > > + """ + + def transform(self, node, results): + assert results + filename = results["filename"] + globals = results.get("globals") + locals = results.get("locals") + + # Copy over the prefix from the right parentheses end of the execfile + # call. + execfile_paren = node.children[-1].children[-1].clone() + # Construct open().read(). + open_args = ArgList([filename.clone(), Comma(), String('"rb"', ' ')], + rparen=execfile_paren) + open_call = Node(syms.power, [Name("open"), open_args]) + read = [Node(syms.trailer, [Dot(), Name('read')]), + Node(syms.trailer, [LParen(), RParen()])] + open_expr = [open_call] + read + # Wrap the open call in a compile call. This is so the filename will be + # preserved in the execed code. + filename_arg = filename.clone() + filename_arg.prefix = " " + exec_str = String("'exec'", " ") + compile_args = open_expr + [Comma(), filename_arg, Comma(), exec_str] + compile_call = Call(Name("compile"), compile_args, "") + # Finally, replace the execfile call with an exec call. + args = [compile_call] + if globals is not None: + args.extend([Comma(), globals.clone()]) + if locals is not None: + args.extend([Comma(), locals.clone()]) + return Call(Name("exec"), args, prefix=node.prefix) diff --git a/micromamba_root/envs/pytorch_env/Lib/lib2to3/fixes/fix_exitfunc.py b/micromamba_root/envs/pytorch_env/Lib/lib2to3/fixes/fix_exitfunc.py new file mode 100644 index 0000000000000000000000000000000000000000..2e47887afead368518e7930397410335887d60f9 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/lib2to3/fixes/fix_exitfunc.py @@ -0,0 +1,72 @@ +""" +Convert use of sys.exitfunc to use the atexit module. +""" + +# Author: Benjamin Peterson + +from lib2to3 import pytree, fixer_base +from lib2to3.fixer_util import Name, Attr, Call, Comma, Newline, syms + + +class FixExitfunc(fixer_base.BaseFix): + keep_line_order = True + BM_compatible = True + + PATTERN = """ + ( + sys_import=import_name<'import' + ('sys' + | + dotted_as_names< (any ',')* 'sys' (',' any)* > + ) + > + | + expr_stmt< + power< 'sys' trailer< '.' 'exitfunc' > > + '=' func=any > + ) + """ + + def __init__(self, *args): + super(FixExitfunc, self).__init__(*args) + + def start_tree(self, tree, filename): + super(FixExitfunc, self).start_tree(tree, filename) + self.sys_import = None + + def transform(self, node, results): + # First, find the sys import. We'll just hope it's global scope. + if "sys_import" in results: + if self.sys_import is None: + self.sys_import = results["sys_import"] + return + + func = results["func"].clone() + func.prefix = "" + register = pytree.Node(syms.power, + Attr(Name("atexit"), Name("register")) + ) + call = Call(register, [func], node.prefix) + node.replace(call) + + if self.sys_import is None: + # That's interesting. + self.warning(node, "Can't find sys import; Please add an atexit " + "import at the top of your file.") + return + + # Now add an atexit import after the sys import. + names = self.sys_import.children[1] + if names.type == syms.dotted_as_names: + names.append_child(Comma()) + names.append_child(Name("atexit", " ")) + else: + containing_stmt = self.sys_import.parent + position = containing_stmt.children.index(self.sys_import) + stmt_container = containing_stmt.parent + new_import = pytree.Node(syms.import_name, + [Name("import"), Name("atexit", " ")] + ) + new = pytree.Node(syms.simple_stmt, [new_import]) + containing_stmt.insert_child(position + 1, Newline()) + containing_stmt.insert_child(position + 2, new) diff --git a/micromamba_root/envs/pytorch_env/Lib/lib2to3/fixes/fix_filter.py b/micromamba_root/envs/pytorch_env/Lib/lib2to3/fixes/fix_filter.py new file mode 100644 index 0000000000000000000000000000000000000000..38e9078f11ac88f346b7ba2468c69dc5a4f74dd5 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/lib2to3/fixes/fix_filter.py @@ -0,0 +1,94 @@ +# Copyright 2007 Google, Inc. All Rights Reserved. +# Licensed to PSF under a Contributor Agreement. + +"""Fixer that changes filter(F, X) into list(filter(F, X)). + +We avoid the transformation if the filter() call is directly contained +in iter(<>), list(<>), tuple(<>), sorted(<>), ...join(<>), or +for V in <>:. + +NOTE: This is still not correct if the original code was depending on +filter(F, X) to return a string if X is a string and a tuple if X is a +tuple. That would require type inference, which we don't do. Let +Python 2.6 figure it out. +""" + +# Local imports +from .. import fixer_base +from ..pytree import Node +from ..pygram import python_symbols as syms +from ..fixer_util import Name, ArgList, ListComp, in_special_context, parenthesize + + +class FixFilter(fixer_base.ConditionalFix): + BM_compatible = True + + PATTERN = """ + filter_lambda=power< + 'filter' + trailer< + '(' + arglist< + lambdef< 'lambda' + (fp=NAME | vfpdef< '(' fp=NAME ')'> ) ':' xp=any + > + ',' + it=any + > + ')' + > + [extra_trailers=trailer*] + > + | + power< + 'filter' + trailer< '(' arglist< none='None' ',' seq=any > ')' > + [extra_trailers=trailer*] + > + | + power< + 'filter' + args=trailer< '(' [any] ')' > + [extra_trailers=trailer*] + > + """ + + skip_on = "future_builtins.filter" + + def transform(self, node, results): + if self.should_skip(node): + return + + trailers = [] + if 'extra_trailers' in results: + for t in results['extra_trailers']: + trailers.append(t.clone()) + + if "filter_lambda" in results: + xp = results.get("xp").clone() + if xp.type == syms.test: + xp.prefix = "" + xp = parenthesize(xp) + + new = ListComp(results.get("fp").clone(), + results.get("fp").clone(), + results.get("it").clone(), xp) + new = Node(syms.power, [new] + trailers, prefix="") + + elif "none" in results: + new = ListComp(Name("_f"), + Name("_f"), + results["seq"].clone(), + Name("_f")) + new = Node(syms.power, [new] + trailers, prefix="") + + else: + if in_special_context(node): + return None + + args = results['args'].clone() + new = Node(syms.power, [Name("filter"), args], prefix="") + new = Node(syms.power, [Name("list"), ArgList([new])] + trailers) + new.prefix = "" + new.prefix = node.prefix + return new diff --git a/micromamba_root/envs/pytorch_env/Lib/lib2to3/fixes/fix_funcattrs.py b/micromamba_root/envs/pytorch_env/Lib/lib2to3/fixes/fix_funcattrs.py new file mode 100644 index 0000000000000000000000000000000000000000..67f3e18e061bdb10395bf73e82f440ad6842e2bd --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/lib2to3/fixes/fix_funcattrs.py @@ -0,0 +1,21 @@ +"""Fix function attribute names (f.func_x -> f.__x__).""" +# Author: Collin Winter + +# Local imports +from .. import fixer_base +from ..fixer_util import Name + + +class FixFuncattrs(fixer_base.BaseFix): + BM_compatible = True + + PATTERN = """ + power< any+ trailer< '.' attr=('func_closure' | 'func_doc' | 'func_globals' + | 'func_name' | 'func_defaults' | 'func_code' + | 'func_dict') > any* > + """ + + def transform(self, node, results): + attr = results["attr"][0] + attr.replace(Name(("__%s__" % attr.value[5:]), + prefix=attr.prefix)) diff --git a/micromamba_root/envs/pytorch_env/Lib/lib2to3/fixes/fix_future.py b/micromamba_root/envs/pytorch_env/Lib/lib2to3/fixes/fix_future.py new file mode 100644 index 0000000000000000000000000000000000000000..fbcb86af0791338e4edebd2f68bd49cd7a9160c2 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/lib2to3/fixes/fix_future.py @@ -0,0 +1,22 @@ +"""Remove __future__ imports + +from __future__ import foo is replaced with an empty line. +""" +# Author: Christian Heimes + +# Local imports +from .. import fixer_base +from ..fixer_util import BlankLine + +class FixFuture(fixer_base.BaseFix): + BM_compatible = True + + PATTERN = """import_from< 'from' module_name="__future__" 'import' any >""" + + # This should be run last -- some things check for the import + run_order = 10 + + def transform(self, node, results): + new = BlankLine() + new.prefix = node.prefix + return new diff --git a/micromamba_root/envs/pytorch_env/Lib/lib2to3/fixes/fix_getcwdu.py b/micromamba_root/envs/pytorch_env/Lib/lib2to3/fixes/fix_getcwdu.py new file mode 100644 index 0000000000000000000000000000000000000000..087eaedcb26f9cfa139f524a67464154a23d79ac --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/lib2to3/fixes/fix_getcwdu.py @@ -0,0 +1,19 @@ +""" +Fixer that changes os.getcwdu() to os.getcwd(). +""" +# Author: Victor Stinner + +# Local imports +from .. import fixer_base +from ..fixer_util import Name + +class FixGetcwdu(fixer_base.BaseFix): + BM_compatible = True + + PATTERN = """ + power< 'os' trailer< dot='.' name='getcwdu' > any* > + """ + + def transform(self, node, results): + name = results["name"] + name.replace(Name("getcwd", prefix=name.prefix)) diff --git a/micromamba_root/envs/pytorch_env/Lib/lib2to3/fixes/fix_has_key.py b/micromamba_root/envs/pytorch_env/Lib/lib2to3/fixes/fix_has_key.py new file mode 100644 index 0000000000000000000000000000000000000000..439708c9923404312dfabb964615062ea32c0aea --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/lib2to3/fixes/fix_has_key.py @@ -0,0 +1,109 @@ +# Copyright 2006 Google, Inc. All Rights Reserved. +# Licensed to PSF under a Contributor Agreement. + +"""Fixer for has_key(). + +Calls to .has_key() methods are expressed in terms of the 'in' +operator: + + d.has_key(k) -> k in d + +CAVEATS: +1) While the primary target of this fixer is dict.has_key(), the + fixer will change any has_key() method call, regardless of its + class. + +2) Cases like this will not be converted: + + m = d.has_key + if m(k): + ... + + Only *calls* to has_key() are converted. While it is possible to + convert the above to something like + + m = d.__contains__ + if m(k): + ... + + this is currently not done. +""" + +# Local imports +from .. import pytree +from .. import fixer_base +from ..fixer_util import Name, parenthesize + + +class FixHasKey(fixer_base.BaseFix): + BM_compatible = True + + PATTERN = """ + anchor=power< + before=any+ + trailer< '.' 'has_key' > + trailer< + '(' + ( not(arglist | argument) arg=any ','> + ) + ')' + > + after=any* + > + | + negation=not_test< + 'not' + anchor=power< + before=any+ + trailer< '.' 'has_key' > + trailer< + '(' + ( not(arglist | argument) arg=any ','> + ) + ')' + > + > + > + """ + + def transform(self, node, results): + assert results + syms = self.syms + if (node.parent.type == syms.not_test and + self.pattern.match(node.parent)): + # Don't transform a node matching the first alternative of the + # pattern when its parent matches the second alternative + return None + negation = results.get("negation") + anchor = results["anchor"] + prefix = node.prefix + before = [n.clone() for n in results["before"]] + arg = results["arg"].clone() + after = results.get("after") + if after: + after = [n.clone() for n in after] + if arg.type in (syms.comparison, syms.not_test, syms.and_test, + syms.or_test, syms.test, syms.lambdef, syms.argument): + arg = parenthesize(arg) + if len(before) == 1: + before = before[0] + else: + before = pytree.Node(syms.power, before) + before.prefix = " " + n_op = Name("in", prefix=" ") + if negation: + n_not = Name("not", prefix=" ") + n_op = pytree.Node(syms.comp_op, (n_not, n_op)) + new = pytree.Node(syms.comparison, (arg, n_op, before)) + if after: + new = parenthesize(new) + new = pytree.Node(syms.power, (new,) + tuple(after)) + if node.parent.type in (syms.comparison, syms.expr, syms.xor_expr, + syms.and_expr, syms.shift_expr, + syms.arith_expr, syms.term, + syms.factor, syms.power): + new = parenthesize(new) + new.prefix = prefix + return new diff --git a/micromamba_root/envs/pytorch_env/Lib/lib2to3/fixes/fix_idioms.py b/micromamba_root/envs/pytorch_env/Lib/lib2to3/fixes/fix_idioms.py new file mode 100644 index 0000000000000000000000000000000000000000..6905913d7cb79d2ead79ca7c0c88ea6c9b98d79d --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/lib2to3/fixes/fix_idioms.py @@ -0,0 +1,152 @@ +"""Adjust some old Python 2 idioms to their modern counterparts. + +* Change some type comparisons to isinstance() calls: + type(x) == T -> isinstance(x, T) + type(x) is T -> isinstance(x, T) + type(x) != T -> not isinstance(x, T) + type(x) is not T -> not isinstance(x, T) + +* Change "while 1:" into "while True:". + +* Change both + + v = list(EXPR) + v.sort() + foo(v) + +and the more general + + v = EXPR + v.sort() + foo(v) + +into + + v = sorted(EXPR) + foo(v) +""" +# Author: Jacques Frechet, Collin Winter + +# Local imports +from .. import fixer_base +from ..fixer_util import Call, Comma, Name, Node, BlankLine, syms + +CMP = "(n='!=' | '==' | 'is' | n=comp_op< 'is' 'not' >)" +TYPE = "power< 'type' trailer< '(' x=any ')' > >" + +class FixIdioms(fixer_base.BaseFix): + explicit = True # The user must ask for this fixer + + PATTERN = r""" + isinstance=comparison< %s %s T=any > + | + isinstance=comparison< T=any %s %s > + | + while_stmt< 'while' while='1' ':' any+ > + | + sorted=any< + any* + simple_stmt< + expr_stmt< id1=any '=' + power< list='list' trailer< '(' (not arglist) any ')' > > + > + '\n' + > + sort= + simple_stmt< + power< id2=any + trailer< '.' 'sort' > trailer< '(' ')' > + > + '\n' + > + next=any* + > + | + sorted=any< + any* + simple_stmt< expr_stmt< id1=any '=' expr=any > '\n' > + sort= + simple_stmt< + power< id2=any + trailer< '.' 'sort' > trailer< '(' ')' > + > + '\n' + > + next=any* + > + """ % (TYPE, CMP, CMP, TYPE) + + def match(self, node): + r = super(FixIdioms, self).match(node) + # If we've matched one of the sort/sorted subpatterns above, we + # want to reject matches where the initial assignment and the + # subsequent .sort() call involve different identifiers. + if r and "sorted" in r: + if r["id1"] == r["id2"]: + return r + return None + return r + + def transform(self, node, results): + if "isinstance" in results: + return self.transform_isinstance(node, results) + elif "while" in results: + return self.transform_while(node, results) + elif "sorted" in results: + return self.transform_sort(node, results) + else: + raise RuntimeError("Invalid match") + + def transform_isinstance(self, node, results): + x = results["x"].clone() # The thing inside of type() + T = results["T"].clone() # The type being compared against + x.prefix = "" + T.prefix = " " + test = Call(Name("isinstance"), [x, Comma(), T]) + if "n" in results: + test.prefix = " " + test = Node(syms.not_test, [Name("not"), test]) + test.prefix = node.prefix + return test + + def transform_while(self, node, results): + one = results["while"] + one.replace(Name("True", prefix=one.prefix)) + + def transform_sort(self, node, results): + sort_stmt = results["sort"] + next_stmt = results["next"] + list_call = results.get("list") + simple_expr = results.get("expr") + + if list_call: + list_call.replace(Name("sorted", prefix=list_call.prefix)) + elif simple_expr: + new = simple_expr.clone() + new.prefix = "" + simple_expr.replace(Call(Name("sorted"), [new], + prefix=simple_expr.prefix)) + else: + raise RuntimeError("should not have reached here") + sort_stmt.remove() + + btwn = sort_stmt.prefix + # Keep any prefix lines between the sort_stmt and the list_call and + # shove them right after the sorted() call. + if "\n" in btwn: + if next_stmt: + # The new prefix should be everything from the sort_stmt's + # prefix up to the last newline, then the old prefix after a new + # line. + prefix_lines = (btwn.rpartition("\n")[0], next_stmt[0].prefix) + next_stmt[0].prefix = "\n".join(prefix_lines) + else: + assert list_call.parent + assert list_call.next_sibling is None + # Put a blank line after list_call and set its prefix. + end_line = BlankLine() + list_call.parent.append_child(end_line) + assert list_call.next_sibling is end_line + # The new prefix should be everything up to the first new line + # of sort_stmt's prefix. + end_line.prefix = btwn.rpartition("\n")[0] diff --git a/micromamba_root/envs/pytorch_env/Lib/lib2to3/fixes/fix_import.py b/micromamba_root/envs/pytorch_env/Lib/lib2to3/fixes/fix_import.py new file mode 100644 index 0000000000000000000000000000000000000000..734ca294699c36400b2c1d59c1badfb9c296ec14 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/lib2to3/fixes/fix_import.py @@ -0,0 +1,99 @@ +"""Fixer for import statements. +If spam is being imported from the local directory, this import: + from spam import eggs +Becomes: + from .spam import eggs + +And this import: + import spam +Becomes: + from . import spam +""" + +# Local imports +from .. import fixer_base +from os.path import dirname, join, exists, sep +from ..fixer_util import FromImport, syms, token + + +def traverse_imports(names): + """ + Walks over all the names imported in a dotted_as_names node. + """ + pending = [names] + while pending: + node = pending.pop() + if node.type == token.NAME: + yield node.value + elif node.type == syms.dotted_name: + yield "".join([ch.value for ch in node.children]) + elif node.type == syms.dotted_as_name: + pending.append(node.children[0]) + elif node.type == syms.dotted_as_names: + pending.extend(node.children[::-2]) + else: + raise AssertionError("unknown node type") + + +class FixImport(fixer_base.BaseFix): + BM_compatible = True + + PATTERN = """ + import_from< 'from' imp=any 'import' ['('] any [')'] > + | + import_name< 'import' imp=any > + """ + + def start_tree(self, tree, name): + super(FixImport, self).start_tree(tree, name) + self.skip = "absolute_import" in tree.future_features + + def transform(self, node, results): + if self.skip: + return + imp = results['imp'] + + if node.type == syms.import_from: + # Some imps are top-level (eg: 'import ham') + # some are first level (eg: 'import ham.eggs') + # some are third level (eg: 'import ham.eggs as spam') + # Hence, the loop + while not hasattr(imp, 'value'): + imp = imp.children[0] + if self.probably_a_local_import(imp.value): + imp.value = "." + imp.value + imp.changed() + else: + have_local = False + have_absolute = False + for mod_name in traverse_imports(imp): + if self.probably_a_local_import(mod_name): + have_local = True + else: + have_absolute = True + if have_absolute: + if have_local: + # We won't handle both sibling and absolute imports in the + # same statement at the moment. + self.warning(node, "absolute and local imports together") + return + + new = FromImport(".", [imp]) + new.prefix = node.prefix + return new + + def probably_a_local_import(self, imp_name): + if imp_name.startswith("."): + # Relative imports are certainly not local imports. + return False + imp_name = imp_name.split(".", 1)[0] + base_path = dirname(self.filename) + base_path = join(base_path, imp_name) + # If there is no __init__.py next to the file its not in a package + # so can't be a relative import. + if not exists(join(dirname(base_path), "__init__.py")): + return False + for ext in [".py", sep, ".pyc", ".so", ".sl", ".pyd"]: + if exists(base_path + ext): + return True + return False diff --git a/micromamba_root/envs/pytorch_env/Lib/lib2to3/fixes/fix_imports.py b/micromamba_root/envs/pytorch_env/Lib/lib2to3/fixes/fix_imports.py new file mode 100644 index 0000000000000000000000000000000000000000..aaf4f2f642efb52d50eabdca67527a3cbf60014e --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/lib2to3/fixes/fix_imports.py @@ -0,0 +1,145 @@ +"""Fix incompatible imports and module references.""" +# Authors: Collin Winter, Nick Edds + +# Local imports +from .. import fixer_base +from ..fixer_util import Name, attr_chain + +MAPPING = {'StringIO': 'io', + 'cStringIO': 'io', + 'cPickle': 'pickle', + '__builtin__' : 'builtins', + 'copy_reg': 'copyreg', + 'Queue': 'queue', + 'SocketServer': 'socketserver', + 'ConfigParser': 'configparser', + 'repr': 'reprlib', + 'FileDialog': 'tkinter.filedialog', + 'tkFileDialog': 'tkinter.filedialog', + 'SimpleDialog': 'tkinter.simpledialog', + 'tkSimpleDialog': 'tkinter.simpledialog', + 'tkColorChooser': 'tkinter.colorchooser', + 'tkCommonDialog': 'tkinter.commondialog', + 'Dialog': 'tkinter.dialog', + 'Tkdnd': 'tkinter.dnd', + 'tkFont': 'tkinter.font', + 'tkMessageBox': 'tkinter.messagebox', + 'ScrolledText': 'tkinter.scrolledtext', + 'Tkconstants': 'tkinter.constants', + 'Tix': 'tkinter.tix', + 'ttk': 'tkinter.ttk', + 'Tkinter': 'tkinter', + 'markupbase': '_markupbase', + '_winreg': 'winreg', + 'thread': '_thread', + 'dummy_thread': '_dummy_thread', + # anydbm and whichdb are handled by fix_imports2 + 'dbhash': 'dbm.bsd', + 'dumbdbm': 'dbm.dumb', + 'dbm': 'dbm.ndbm', + 'gdbm': 'dbm.gnu', + 'xmlrpclib': 'xmlrpc.client', + 'DocXMLRPCServer': 'xmlrpc.server', + 'SimpleXMLRPCServer': 'xmlrpc.server', + 'httplib': 'http.client', + 'htmlentitydefs' : 'html.entities', + 'HTMLParser' : 'html.parser', + 'Cookie': 'http.cookies', + 'cookielib': 'http.cookiejar', + 'BaseHTTPServer': 'http.server', + 'SimpleHTTPServer': 'http.server', + 'CGIHTTPServer': 'http.server', + #'test.test_support': 'test.support', + 'commands': 'subprocess', + 'UserString' : 'collections', + 'UserList' : 'collections', + 'urlparse' : 'urllib.parse', + 'robotparser' : 'urllib.robotparser', +} + + +def alternates(members): + return "(" + "|".join(map(repr, members)) + ")" + + +def build_pattern(mapping=MAPPING): + mod_list = ' | '.join(["module_name='%s'" % key for key in mapping]) + bare_names = alternates(mapping.keys()) + + yield """name_import=import_name< 'import' ((%s) | + multiple_imports=dotted_as_names< any* (%s) any* >) > + """ % (mod_list, mod_list) + yield """import_from< 'from' (%s) 'import' ['('] + ( any | import_as_name< any 'as' any > | + import_as_names< any* >) [')'] > + """ % mod_list + yield """import_name< 'import' (dotted_as_name< (%s) 'as' any > | + multiple_imports=dotted_as_names< + any* dotted_as_name< (%s) 'as' any > any* >) > + """ % (mod_list, mod_list) + + # Find usages of module members in code e.g. thread.foo(bar) + yield "power< bare_with_attr=(%s) trailer<'.' any > any* >" % bare_names + + +class FixImports(fixer_base.BaseFix): + + BM_compatible = True + keep_line_order = True + # This is overridden in fix_imports2. + mapping = MAPPING + + # We want to run this fixer late, so fix_import doesn't try to make stdlib + # renames into relative imports. + run_order = 6 + + def build_pattern(self): + return "|".join(build_pattern(self.mapping)) + + def compile_pattern(self): + # We override this, so MAPPING can be pragmatically altered and the + # changes will be reflected in PATTERN. + self.PATTERN = self.build_pattern() + super(FixImports, self).compile_pattern() + + # Don't match the node if it's within another match. + def match(self, node): + match = super(FixImports, self).match + results = match(node) + if results: + # Module usage could be in the trailer of an attribute lookup, so we + # might have nested matches when "bare_with_attr" is present. + if "bare_with_attr" not in results and \ + any(match(obj) for obj in attr_chain(node, "parent")): + return False + return results + return False + + def start_tree(self, tree, filename): + super(FixImports, self).start_tree(tree, filename) + self.replace = {} + + def transform(self, node, results): + import_mod = results.get("module_name") + if import_mod: + mod_name = import_mod.value + new_name = self.mapping[mod_name] + import_mod.replace(Name(new_name, prefix=import_mod.prefix)) + if "name_import" in results: + # If it's not a "from x import x, y" or "import x as y" import, + # marked its usage to be replaced. + self.replace[mod_name] = new_name + if "multiple_imports" in results: + # This is a nasty hack to fix multiple imports on a line (e.g., + # "import StringIO, urlparse"). The problem is that I can't + # figure out an easy way to make a pattern recognize the keys of + # MAPPING randomly sprinkled in an import statement. + results = self.match(node) + if results: + self.transform(node, results) + else: + # Replace usage of the module. + bare_name = results["bare_with_attr"][0] + new_name = self.replace.get(bare_name.value) + if new_name: + bare_name.replace(Name(new_name, prefix=bare_name.prefix)) diff --git a/micromamba_root/envs/pytorch_env/Lib/lib2to3/fixes/fix_imports2.py b/micromamba_root/envs/pytorch_env/Lib/lib2to3/fixes/fix_imports2.py new file mode 100644 index 0000000000000000000000000000000000000000..9a33c67b1dc1940b2e271fad30b73f8e06b24e33 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/lib2to3/fixes/fix_imports2.py @@ -0,0 +1,16 @@ +"""Fix incompatible imports and module references that must be fixed after +fix_imports.""" +from . import fix_imports + + +MAPPING = { + 'whichdb': 'dbm', + 'anydbm': 'dbm', + } + + +class FixImports2(fix_imports.FixImports): + + run_order = 7 + + mapping = MAPPING diff --git a/micromamba_root/envs/pytorch_env/Lib/lib2to3/fixes/fix_input.py b/micromamba_root/envs/pytorch_env/Lib/lib2to3/fixes/fix_input.py new file mode 100644 index 0000000000000000000000000000000000000000..9cf9a48c471f35e39fa0e99a40a1cc75fae6fe6d --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/lib2to3/fixes/fix_input.py @@ -0,0 +1,26 @@ +"""Fixer that changes input(...) into eval(input(...)).""" +# Author: Andre Roberge + +# Local imports +from .. import fixer_base +from ..fixer_util import Call, Name +from .. import patcomp + + +context = patcomp.compile_pattern("power< 'eval' trailer< '(' any ')' > >") + + +class FixInput(fixer_base.BaseFix): + BM_compatible = True + PATTERN = """ + power< 'input' args=trailer< '(' [any] ')' > > + """ + + def transform(self, node, results): + # If we're already wrapped in an eval() call, we're done. + if context.match(node.parent.parent): + return + + new = node.clone() + new.prefix = "" + return Call(Name("eval"), [new], prefix=node.prefix) diff --git a/micromamba_root/envs/pytorch_env/Lib/lib2to3/fixes/fix_intern.py b/micromamba_root/envs/pytorch_env/Lib/lib2to3/fixes/fix_intern.py new file mode 100644 index 0000000000000000000000000000000000000000..d752843092aacd8bc6e84c80f5bc6116563b9d25 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/lib2to3/fixes/fix_intern.py @@ -0,0 +1,39 @@ +# Copyright 2006 Georg Brandl. +# Licensed to PSF under a Contributor Agreement. + +"""Fixer for intern(). + +intern(s) -> sys.intern(s)""" + +# Local imports +from .. import fixer_base +from ..fixer_util import ImportAndCall, touch_import + + +class FixIntern(fixer_base.BaseFix): + BM_compatible = True + order = "pre" + + PATTERN = """ + power< 'intern' + trailer< lpar='(' + ( not(arglist | argument) any ','> ) + rpar=')' > + after=any* + > + """ + + def transform(self, node, results): + if results: + # I feel like we should be able to express this logic in the + # PATTERN above but I don't know how to do it so... + obj = results['obj'] + if obj: + if (obj.type == self.syms.argument and + obj.children[0].value in {'**', '*'}): + return # Make no change. + names = ('sys', 'intern') + new = ImportAndCall(node, results, names) + touch_import(None, 'sys', node) + return new diff --git a/micromamba_root/envs/pytorch_env/Lib/lib2to3/fixes/fix_isinstance.py b/micromamba_root/envs/pytorch_env/Lib/lib2to3/fixes/fix_isinstance.py new file mode 100644 index 0000000000000000000000000000000000000000..bebb1de120424b6b568ae3243eab55ad12305194 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/lib2to3/fixes/fix_isinstance.py @@ -0,0 +1,52 @@ +# Copyright 2008 Armin Ronacher. +# Licensed to PSF under a Contributor Agreement. + +"""Fixer that cleans up a tuple argument to isinstance after the tokens +in it were fixed. This is mainly used to remove double occurrences of +tokens as a leftover of the long -> int / unicode -> str conversion. + +eg. isinstance(x, (int, long)) -> isinstance(x, (int, int)) + -> isinstance(x, int) +""" + +from .. import fixer_base +from ..fixer_util import token + + +class FixIsinstance(fixer_base.BaseFix): + BM_compatible = True + PATTERN = """ + power< + 'isinstance' + trailer< '(' arglist< any ',' atom< '(' + args=testlist_gexp< any+ > + ')' > > ')' > + > + """ + + run_order = 6 + + def transform(self, node, results): + names_inserted = set() + testlist = results["args"] + args = testlist.children + new_args = [] + iterator = enumerate(args) + for idx, arg in iterator: + if arg.type == token.NAME and arg.value in names_inserted: + if idx < len(args) - 1 and args[idx + 1].type == token.COMMA: + next(iterator) + continue + else: + new_args.append(arg) + if arg.type == token.NAME: + names_inserted.add(arg.value) + if new_args and new_args[-1].type == token.COMMA: + del new_args[-1] + if len(new_args) == 1: + atom = testlist.parent + new_args[0].prefix = atom.prefix + atom.replace(new_args[0]) + else: + args[:] = new_args + node.changed() diff --git a/micromamba_root/envs/pytorch_env/Lib/lib2to3/fixes/fix_itertools.py b/micromamba_root/envs/pytorch_env/Lib/lib2to3/fixes/fix_itertools.py new file mode 100644 index 0000000000000000000000000000000000000000..8e78d6c689f4396421414248f15b39e01a844833 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/lib2to3/fixes/fix_itertools.py @@ -0,0 +1,43 @@ +""" Fixer for itertools.(imap|ifilter|izip) --> (map|filter|zip) and + itertools.ifilterfalse --> itertools.filterfalse (bugs 2360-2363) + + imports from itertools are fixed in fix_itertools_import.py + + If itertools is imported as something else (ie: import itertools as it; + it.izip(spam, eggs)) method calls will not get fixed. + """ + +# Local imports +from .. import fixer_base +from ..fixer_util import Name + +class FixItertools(fixer_base.BaseFix): + BM_compatible = True + it_funcs = "('imap'|'ifilter'|'izip'|'izip_longest'|'ifilterfalse')" + PATTERN = """ + power< it='itertools' + trailer< + dot='.' func=%(it_funcs)s > trailer< '(' [any] ')' > > + | + power< func=%(it_funcs)s trailer< '(' [any] ')' > > + """ %(locals()) + + # Needs to be run after fix_(map|zip|filter) + run_order = 6 + + def transform(self, node, results): + prefix = None + func = results['func'][0] + if ('it' in results and + func.value not in ('ifilterfalse', 'izip_longest')): + dot, it = (results['dot'], results['it']) + # Remove the 'itertools' + prefix = it.prefix + it.remove() + # Replace the node which contains ('.', 'function') with the + # function (to be consistent with the second part of the pattern) + dot.remove() + func.parent.replace(func) + + prefix = prefix or func.prefix + func.replace(Name(func.value[1:], prefix=prefix)) diff --git a/micromamba_root/envs/pytorch_env/Lib/lib2to3/fixes/fix_itertools_imports.py b/micromamba_root/envs/pytorch_env/Lib/lib2to3/fixes/fix_itertools_imports.py new file mode 100644 index 0000000000000000000000000000000000000000..0ddbc7b8422991bacc398d8641091a478ee84f55 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/lib2to3/fixes/fix_itertools_imports.py @@ -0,0 +1,57 @@ +""" Fixer for imports of itertools.(imap|ifilter|izip|ifilterfalse) """ + +# Local imports +from lib2to3 import fixer_base +from lib2to3.fixer_util import BlankLine, syms, token + + +class FixItertoolsImports(fixer_base.BaseFix): + BM_compatible = True + PATTERN = """ + import_from< 'from' 'itertools' 'import' imports=any > + """ %(locals()) + + def transform(self, node, results): + imports = results['imports'] + if imports.type == syms.import_as_name or not imports.children: + children = [imports] + else: + children = imports.children + for child in children[::2]: + if child.type == token.NAME: + member = child.value + name_node = child + elif child.type == token.STAR: + # Just leave the import as is. + return + else: + assert child.type == syms.import_as_name + name_node = child.children[0] + member_name = name_node.value + if member_name in ('imap', 'izip', 'ifilter'): + child.value = None + child.remove() + elif member_name in ('ifilterfalse', 'izip_longest'): + node.changed() + name_node.value = ('filterfalse' if member_name[1] == 'f' + else 'zip_longest') + + # Make sure the import statement is still sane + children = imports.children[:] or [imports] + remove_comma = True + for child in children: + if remove_comma and child.type == token.COMMA: + child.remove() + else: + remove_comma ^= True + + while children and children[-1].type == token.COMMA: + children.pop().remove() + + # If there are no imports left, just get rid of the entire statement + if (not (imports.children or getattr(imports, 'value', None)) or + imports.parent is None): + p = node.prefix + node = BlankLine() + node.prefix = p + return node diff --git a/micromamba_root/envs/pytorch_env/Lib/lib2to3/fixes/fix_long.py b/micromamba_root/envs/pytorch_env/Lib/lib2to3/fixes/fix_long.py new file mode 100644 index 0000000000000000000000000000000000000000..f227c9f49815388ed58a79e773c8114bced1e58f --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/lib2to3/fixes/fix_long.py @@ -0,0 +1,19 @@ +# Copyright 2006 Google, Inc. All Rights Reserved. +# Licensed to PSF under a Contributor Agreement. + +"""Fixer that turns 'long' into 'int' everywhere. +""" + +# Local imports +from lib2to3 import fixer_base +from lib2to3.fixer_util import is_probably_builtin + + +class FixLong(fixer_base.BaseFix): + BM_compatible = True + PATTERN = "'long'" + + def transform(self, node, results): + if is_probably_builtin(node): + node.value = "int" + node.changed() diff --git a/micromamba_root/envs/pytorch_env/Lib/lib2to3/fixes/fix_map.py b/micromamba_root/envs/pytorch_env/Lib/lib2to3/fixes/fix_map.py new file mode 100644 index 0000000000000000000000000000000000000000..78cf81c6f94098aad11edf351ff0f31da9cdbccd --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/lib2to3/fixes/fix_map.py @@ -0,0 +1,110 @@ +# Copyright 2007 Google, Inc. All Rights Reserved. +# Licensed to PSF under a Contributor Agreement. + +"""Fixer that changes map(F, ...) into list(map(F, ...)) unless there +exists a 'from future_builtins import map' statement in the top-level +namespace. + +As a special case, map(None, X) is changed into list(X). (This is +necessary because the semantics are changed in this case -- the new +map(None, X) is equivalent to [(x,) for x in X].) + +We avoid the transformation (except for the special case mentioned +above) if the map() call is directly contained in iter(<>), list(<>), +tuple(<>), sorted(<>), ...join(<>), or for V in <>:. + +NOTE: This is still not correct if the original code was depending on +map(F, X, Y, ...) to go on until the longest argument is exhausted, +substituting None for missing values -- like zip(), it now stops as +soon as the shortest argument is exhausted. +""" + +# Local imports +from ..pgen2 import token +from .. import fixer_base +from ..fixer_util import Name, ArgList, Call, ListComp, in_special_context +from ..pygram import python_symbols as syms +from ..pytree import Node + + +class FixMap(fixer_base.ConditionalFix): + BM_compatible = True + + PATTERN = """ + map_none=power< + 'map' + trailer< '(' arglist< 'None' ',' arg=any [','] > ')' > + [extra_trailers=trailer*] + > + | + map_lambda=power< + 'map' + trailer< + '(' + arglist< + lambdef< 'lambda' + (fp=NAME | vfpdef< '(' fp=NAME ')'> ) ':' xp=any + > + ',' + it=any + > + ')' + > + [extra_trailers=trailer*] + > + | + power< + 'map' args=trailer< '(' [any] ')' > + [extra_trailers=trailer*] + > + """ + + skip_on = 'future_builtins.map' + + def transform(self, node, results): + if self.should_skip(node): + return + + trailers = [] + if 'extra_trailers' in results: + for t in results['extra_trailers']: + trailers.append(t.clone()) + + if node.parent.type == syms.simple_stmt: + self.warning(node, "You should use a for loop here") + new = node.clone() + new.prefix = "" + new = Call(Name("list"), [new]) + elif "map_lambda" in results: + new = ListComp(results["xp"].clone(), + results["fp"].clone(), + results["it"].clone()) + new = Node(syms.power, [new] + trailers, prefix="") + + else: + if "map_none" in results: + new = results["arg"].clone() + new.prefix = "" + else: + if "args" in results: + args = results["args"] + if args.type == syms.trailer and \ + args.children[1].type == syms.arglist and \ + args.children[1].children[0].type == token.NAME and \ + args.children[1].children[0].value == "None": + self.warning(node, "cannot convert map(None, ...) " + "with multiple arguments because map() " + "now truncates to the shortest sequence") + return + + new = Node(syms.power, [Name("map"), args.clone()]) + new.prefix = "" + + if in_special_context(node): + return None + + new = Node(syms.power, [Name("list"), ArgList([new])] + trailers) + new.prefix = "" + + new.prefix = node.prefix + return new diff --git a/micromamba_root/envs/pytorch_env/Lib/lib2to3/fixes/fix_metaclass.py b/micromamba_root/envs/pytorch_env/Lib/lib2to3/fixes/fix_metaclass.py new file mode 100644 index 0000000000000000000000000000000000000000..fe547b2228072a3cf436733f40154004e98c215c --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/lib2to3/fixes/fix_metaclass.py @@ -0,0 +1,228 @@ +"""Fixer for __metaclass__ = X -> (metaclass=X) methods. + + The various forms of classef (inherits nothing, inherits once, inherits + many) don't parse the same in the CST so we look at ALL classes for + a __metaclass__ and if we find one normalize the inherits to all be + an arglist. + + For one-liner classes ('class X: pass') there is no indent/dedent so + we normalize those into having a suite. + + Moving the __metaclass__ into the classdef can also cause the class + body to be empty so there is some special casing for that as well. + + This fixer also tries very hard to keep original indenting and spacing + in all those corner cases. + +""" +# Author: Jack Diederich + +# Local imports +from .. import fixer_base +from ..pygram import token +from ..fixer_util import syms, Node, Leaf + + +def has_metaclass(parent): + """ we have to check the cls_node without changing it. + There are two possibilities: + 1) clsdef => suite => simple_stmt => expr_stmt => Leaf('__meta') + 2) clsdef => simple_stmt => expr_stmt => Leaf('__meta') + """ + for node in parent.children: + if node.type == syms.suite: + return has_metaclass(node) + elif node.type == syms.simple_stmt and node.children: + expr_node = node.children[0] + if expr_node.type == syms.expr_stmt and expr_node.children: + left_side = expr_node.children[0] + if isinstance(left_side, Leaf) and \ + left_side.value == '__metaclass__': + return True + return False + + +def fixup_parse_tree(cls_node): + """ one-line classes don't get a suite in the parse tree so we add + one to normalize the tree + """ + for node in cls_node.children: + if node.type == syms.suite: + # already in the preferred format, do nothing + return + + # !%@#! one-liners have no suite node, we have to fake one up + for i, node in enumerate(cls_node.children): + if node.type == token.COLON: + break + else: + raise ValueError("No class suite and no ':'!") + + # move everything into a suite node + suite = Node(syms.suite, []) + while cls_node.children[i+1:]: + move_node = cls_node.children[i+1] + suite.append_child(move_node.clone()) + move_node.remove() + cls_node.append_child(suite) + node = suite + + +def fixup_simple_stmt(parent, i, stmt_node): + """ if there is a semi-colon all the parts count as part of the same + simple_stmt. We just want the __metaclass__ part so we move + everything after the semi-colon into its own simple_stmt node + """ + for semi_ind, node in enumerate(stmt_node.children): + if node.type == token.SEMI: # *sigh* + break + else: + return + + node.remove() # kill the semicolon + new_expr = Node(syms.expr_stmt, []) + new_stmt = Node(syms.simple_stmt, [new_expr]) + while stmt_node.children[semi_ind:]: + move_node = stmt_node.children[semi_ind] + new_expr.append_child(move_node.clone()) + move_node.remove() + parent.insert_child(i, new_stmt) + new_leaf1 = new_stmt.children[0].children[0] + old_leaf1 = stmt_node.children[0].children[0] + new_leaf1.prefix = old_leaf1.prefix + + +def remove_trailing_newline(node): + if node.children and node.children[-1].type == token.NEWLINE: + node.children[-1].remove() + + +def find_metas(cls_node): + # find the suite node (Mmm, sweet nodes) + for node in cls_node.children: + if node.type == syms.suite: + break + else: + raise ValueError("No class suite!") + + # look for simple_stmt[ expr_stmt[ Leaf('__metaclass__') ] ] + for i, simple_node in list(enumerate(node.children)): + if simple_node.type == syms.simple_stmt and simple_node.children: + expr_node = simple_node.children[0] + if expr_node.type == syms.expr_stmt and expr_node.children: + # Check if the expr_node is a simple assignment. + left_node = expr_node.children[0] + if isinstance(left_node, Leaf) and \ + left_node.value == '__metaclass__': + # We found an assignment to __metaclass__. + fixup_simple_stmt(node, i, simple_node) + remove_trailing_newline(simple_node) + yield (node, i, simple_node) + + +def fixup_indent(suite): + """ If an INDENT is followed by a thing with a prefix then nuke the prefix + Otherwise we get in trouble when removing __metaclass__ at suite start + """ + kids = suite.children[::-1] + # find the first indent + while kids: + node = kids.pop() + if node.type == token.INDENT: + break + + # find the first Leaf + while kids: + node = kids.pop() + if isinstance(node, Leaf) and node.type != token.DEDENT: + if node.prefix: + node.prefix = '' + return + else: + kids.extend(node.children[::-1]) + + +class FixMetaclass(fixer_base.BaseFix): + BM_compatible = True + + PATTERN = """ + classdef + """ + + def transform(self, node, results): + if not has_metaclass(node): + return + + fixup_parse_tree(node) + + # find metaclasses, keep the last one + last_metaclass = None + for suite, i, stmt in find_metas(node): + last_metaclass = stmt + stmt.remove() + + text_type = node.children[0].type # always Leaf(nnn, 'class') + + # figure out what kind of classdef we have + if len(node.children) == 7: + # Node(classdef, ['class', 'name', '(', arglist, ')', ':', suite]) + # 0 1 2 3 4 5 6 + if node.children[3].type == syms.arglist: + arglist = node.children[3] + # Node(classdef, ['class', 'name', '(', 'Parent', ')', ':', suite]) + else: + parent = node.children[3].clone() + arglist = Node(syms.arglist, [parent]) + node.set_child(3, arglist) + elif len(node.children) == 6: + # Node(classdef, ['class', 'name', '(', ')', ':', suite]) + # 0 1 2 3 4 5 + arglist = Node(syms.arglist, []) + node.insert_child(3, arglist) + elif len(node.children) == 4: + # Node(classdef, ['class', 'name', ':', suite]) + # 0 1 2 3 + arglist = Node(syms.arglist, []) + node.insert_child(2, Leaf(token.RPAR, ')')) + node.insert_child(2, arglist) + node.insert_child(2, Leaf(token.LPAR, '(')) + else: + raise ValueError("Unexpected class definition") + + # now stick the metaclass in the arglist + meta_txt = last_metaclass.children[0].children[0] + meta_txt.value = 'metaclass' + orig_meta_prefix = meta_txt.prefix + + if arglist.children: + arglist.append_child(Leaf(token.COMMA, ',')) + meta_txt.prefix = ' ' + else: + meta_txt.prefix = '' + + # compact the expression "metaclass = Meta" -> "metaclass=Meta" + expr_stmt = last_metaclass.children[0] + assert expr_stmt.type == syms.expr_stmt + expr_stmt.children[1].prefix = '' + expr_stmt.children[2].prefix = '' + + arglist.append_child(last_metaclass) + + fixup_indent(suite) + + # check for empty suite + if not suite.children: + # one-liner that was just __metaclass_ + suite.remove() + pass_leaf = Leaf(text_type, 'pass') + pass_leaf.prefix = orig_meta_prefix + node.append_child(pass_leaf) + node.append_child(Leaf(token.NEWLINE, '\n')) + + elif len(suite.children) > 1 and \ + (suite.children[-2].type == token.INDENT and + suite.children[-1].type == token.DEDENT): + # there was only one line in the class body and it was __metaclass__ + pass_leaf = Leaf(text_type, 'pass') + suite.insert_child(-1, pass_leaf) + suite.insert_child(-1, Leaf(token.NEWLINE, '\n')) diff --git a/micromamba_root/envs/pytorch_env/Lib/lib2to3/fixes/fix_methodattrs.py b/micromamba_root/envs/pytorch_env/Lib/lib2to3/fixes/fix_methodattrs.py new file mode 100644 index 0000000000000000000000000000000000000000..7f9004f00e6e8f2a7d4f72d90b6af3a2674d0fa0 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/lib2to3/fixes/fix_methodattrs.py @@ -0,0 +1,24 @@ +"""Fix bound method attributes (method.im_? -> method.__?__). +""" +# Author: Christian Heimes + +# Local imports +from .. import fixer_base +from ..fixer_util import Name + +MAP = { + "im_func" : "__func__", + "im_self" : "__self__", + "im_class" : "__self__.__class__" + } + +class FixMethodattrs(fixer_base.BaseFix): + BM_compatible = True + PATTERN = """ + power< any+ trailer< '.' attr=('im_func' | 'im_self' | 'im_class') > any* > + """ + + def transform(self, node, results): + attr = results["attr"][0] + new = MAP[attr.value] + attr.replace(Name(new, prefix=attr.prefix)) diff --git a/micromamba_root/envs/pytorch_env/Lib/lib2to3/fixes/fix_ne.py b/micromamba_root/envs/pytorch_env/Lib/lib2to3/fixes/fix_ne.py new file mode 100644 index 0000000000000000000000000000000000000000..e3ee10f4a63e0c211d2fb430095dfd784d68518e --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/lib2to3/fixes/fix_ne.py @@ -0,0 +1,23 @@ +# Copyright 2006 Google, Inc. All Rights Reserved. +# Licensed to PSF under a Contributor Agreement. + +"""Fixer that turns <> into !=.""" + +# Local imports +from .. import pytree +from ..pgen2 import token +from .. import fixer_base + + +class FixNe(fixer_base.BaseFix): + # This is so simple that we don't need the pattern compiler. + + _accept_type = token.NOTEQUAL + + def match(self, node): + # Override + return node.value == "<>" + + def transform(self, node, results): + new = pytree.Leaf(token.NOTEQUAL, "!=", prefix=node.prefix) + return new diff --git a/micromamba_root/envs/pytorch_env/Lib/lib2to3/fixes/fix_next.py b/micromamba_root/envs/pytorch_env/Lib/lib2to3/fixes/fix_next.py new file mode 100644 index 0000000000000000000000000000000000000000..9f6305e1d49dc5327338912f2e6ed0b5794c5062 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/lib2to3/fixes/fix_next.py @@ -0,0 +1,103 @@ +"""Fixer for it.next() -> next(it), per PEP 3114.""" +# Author: Collin Winter + +# Things that currently aren't covered: +# - listcomp "next" names aren't warned +# - "with" statement targets aren't checked + +# Local imports +from ..pgen2 import token +from ..pygram import python_symbols as syms +from .. import fixer_base +from ..fixer_util import Name, Call, find_binding + +bind_warning = "Calls to builtin next() possibly shadowed by global binding" + + +class FixNext(fixer_base.BaseFix): + BM_compatible = True + PATTERN = """ + power< base=any+ trailer< '.' attr='next' > trailer< '(' ')' > > + | + power< head=any+ trailer< '.' attr='next' > not trailer< '(' ')' > > + | + classdef< 'class' any+ ':' + suite< any* + funcdef< 'def' + name='next' + parameters< '(' NAME ')' > any+ > + any* > > + | + global=global_stmt< 'global' any* 'next' any* > + """ + + order = "pre" # Pre-order tree traversal + + def start_tree(self, tree, filename): + super(FixNext, self).start_tree(tree, filename) + + n = find_binding('next', tree) + if n: + self.warning(n, bind_warning) + self.shadowed_next = True + else: + self.shadowed_next = False + + def transform(self, node, results): + assert results + + base = results.get("base") + attr = results.get("attr") + name = results.get("name") + + if base: + if self.shadowed_next: + attr.replace(Name("__next__", prefix=attr.prefix)) + else: + base = [n.clone() for n in base] + base[0].prefix = "" + node.replace(Call(Name("next", prefix=node.prefix), base)) + elif name: + n = Name("__next__", prefix=name.prefix) + name.replace(n) + elif attr: + # We don't do this transformation if we're assigning to "x.next". + # Unfortunately, it doesn't seem possible to do this in PATTERN, + # so it's being done here. + if is_assign_target(node): + head = results["head"] + if "".join([str(n) for n in head]).strip() == '__builtin__': + self.warning(node, bind_warning) + return + attr.replace(Name("__next__")) + elif "global" in results: + self.warning(node, bind_warning) + self.shadowed_next = True + + +### The following functions help test if node is part of an assignment +### target. + +def is_assign_target(node): + assign = find_assign(node) + if assign is None: + return False + + for child in assign.children: + if child.type == token.EQUAL: + return False + elif is_subtree(child, node): + return True + return False + +def find_assign(node): + if node.type == syms.expr_stmt: + return node + if node.type == syms.simple_stmt or node.parent is None: + return None + return find_assign(node.parent) + +def is_subtree(root, node): + if root == node: + return True + return any(is_subtree(c, node) for c in root.children) diff --git a/micromamba_root/envs/pytorch_env/Lib/lib2to3/fixes/fix_nonzero.py b/micromamba_root/envs/pytorch_env/Lib/lib2to3/fixes/fix_nonzero.py new file mode 100644 index 0000000000000000000000000000000000000000..c2295969a7728f78617677b01aac8122fa15539c --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/lib2to3/fixes/fix_nonzero.py @@ -0,0 +1,21 @@ +"""Fixer for __nonzero__ -> __bool__ methods.""" +# Author: Collin Winter + +# Local imports +from .. import fixer_base +from ..fixer_util import Name + +class FixNonzero(fixer_base.BaseFix): + BM_compatible = True + PATTERN = """ + classdef< 'class' any+ ':' + suite< any* + funcdef< 'def' name='__nonzero__' + parameters< '(' NAME ')' > any+ > + any* > > + """ + + def transform(self, node, results): + name = results["name"] + new = Name("__bool__", prefix=name.prefix) + name.replace(new) diff --git a/micromamba_root/envs/pytorch_env/Lib/lib2to3/fixes/fix_numliterals.py b/micromamba_root/envs/pytorch_env/Lib/lib2to3/fixes/fix_numliterals.py new file mode 100644 index 0000000000000000000000000000000000000000..79207d4aa368aee20a2ac9ae1e44072aabb2afd2 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/lib2to3/fixes/fix_numliterals.py @@ -0,0 +1,28 @@ +"""Fixer that turns 1L into 1, 0755 into 0o755. +""" +# Copyright 2007 Georg Brandl. +# Licensed to PSF under a Contributor Agreement. + +# Local imports +from ..pgen2 import token +from .. import fixer_base +from ..fixer_util import Number + + +class FixNumliterals(fixer_base.BaseFix): + # This is so simple that we don't need the pattern compiler. + + _accept_type = token.NUMBER + + def match(self, node): + # Override + return (node.value.startswith("0") or node.value[-1] in "Ll") + + def transform(self, node, results): + val = node.value + if val[-1] in 'Ll': + val = val[:-1] + elif val.startswith('0') and val.isdigit() and len(set(val)) > 1: + val = "0o" + val[1:] + + return Number(val, prefix=node.prefix) diff --git a/micromamba_root/envs/pytorch_env/Lib/lib2to3/fixes/fix_operator.py b/micromamba_root/envs/pytorch_env/Lib/lib2to3/fixes/fix_operator.py new file mode 100644 index 0000000000000000000000000000000000000000..d303cd2018befb0745f2868068becf9f350b9b3d --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/lib2to3/fixes/fix_operator.py @@ -0,0 +1,97 @@ +"""Fixer for operator functions. + +operator.isCallable(obj) -> callable(obj) +operator.sequenceIncludes(obj) -> operator.contains(obj) +operator.isSequenceType(obj) -> isinstance(obj, collections.abc.Sequence) +operator.isMappingType(obj) -> isinstance(obj, collections.abc.Mapping) +operator.isNumberType(obj) -> isinstance(obj, numbers.Number) +operator.repeat(obj, n) -> operator.mul(obj, n) +operator.irepeat(obj, n) -> operator.imul(obj, n) +""" + +import collections.abc + +# Local imports +from lib2to3 import fixer_base +from lib2to3.fixer_util import Call, Name, String, touch_import + + +def invocation(s): + def dec(f): + f.invocation = s + return f + return dec + + +class FixOperator(fixer_base.BaseFix): + BM_compatible = True + order = "pre" + + methods = """ + method=('isCallable'|'sequenceIncludes' + |'isSequenceType'|'isMappingType'|'isNumberType' + |'repeat'|'irepeat') + """ + obj = "'(' obj=any ')'" + PATTERN = """ + power< module='operator' + trailer< '.' %(methods)s > trailer< %(obj)s > > + | + power< %(methods)s trailer< %(obj)s > > + """ % dict(methods=methods, obj=obj) + + def transform(self, node, results): + method = self._check_method(node, results) + if method is not None: + return method(node, results) + + @invocation("operator.contains(%s)") + def _sequenceIncludes(self, node, results): + return self._handle_rename(node, results, "contains") + + @invocation("callable(%s)") + def _isCallable(self, node, results): + obj = results["obj"] + return Call(Name("callable"), [obj.clone()], prefix=node.prefix) + + @invocation("operator.mul(%s)") + def _repeat(self, node, results): + return self._handle_rename(node, results, "mul") + + @invocation("operator.imul(%s)") + def _irepeat(self, node, results): + return self._handle_rename(node, results, "imul") + + @invocation("isinstance(%s, collections.abc.Sequence)") + def _isSequenceType(self, node, results): + return self._handle_type2abc(node, results, "collections.abc", "Sequence") + + @invocation("isinstance(%s, collections.abc.Mapping)") + def _isMappingType(self, node, results): + return self._handle_type2abc(node, results, "collections.abc", "Mapping") + + @invocation("isinstance(%s, numbers.Number)") + def _isNumberType(self, node, results): + return self._handle_type2abc(node, results, "numbers", "Number") + + def _handle_rename(self, node, results, name): + method = results["method"][0] + method.value = name + method.changed() + + def _handle_type2abc(self, node, results, module, abc): + touch_import(None, module, node) + obj = results["obj"] + args = [obj.clone(), String(", " + ".".join([module, abc]))] + return Call(Name("isinstance"), args, prefix=node.prefix) + + def _check_method(self, node, results): + method = getattr(self, "_" + results["method"][0].value) + if isinstance(method, collections.abc.Callable): + if "module" in results: + return method + else: + sub = (str(results["obj"]),) + invocation_str = method.invocation % sub + self.warning(node, "You should use '%s' here." % invocation_str) + return None diff --git a/micromamba_root/envs/pytorch_env/Lib/lib2to3/fixes/fix_paren.py b/micromamba_root/envs/pytorch_env/Lib/lib2to3/fixes/fix_paren.py new file mode 100644 index 0000000000000000000000000000000000000000..df3da5f5232c9c42fc53c904f8c0b886b4dd4a51 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/lib2to3/fixes/fix_paren.py @@ -0,0 +1,44 @@ +"""Fixer that adds parentheses where they are required + +This converts ``[x for x in 1, 2]`` to ``[x for x in (1, 2)]``.""" + +# By Taek Joo Kim and Benjamin Peterson + +# Local imports +from .. import fixer_base +from ..fixer_util import LParen, RParen + +# XXX This doesn't support nested for loops like [x for x in 1, 2 for x in 1, 2] +class FixParen(fixer_base.BaseFix): + BM_compatible = True + + PATTERN = """ + atom< ('[' | '(') + (listmaker< any + comp_for< + 'for' NAME 'in' + target=testlist_safe< any (',' any)+ [','] + > + [any] + > + > + | + testlist_gexp< any + comp_for< + 'for' NAME 'in' + target=testlist_safe< any (',' any)+ [','] + > + [any] + > + >) + (']' | ')') > + """ + + def transform(self, node, results): + target = results["target"] + + lparen = LParen() + lparen.prefix = target.prefix + target.prefix = "" # Make it hug the parentheses + target.insert_child(0, lparen) + target.append_child(RParen()) diff --git a/micromamba_root/envs/pytorch_env/Lib/lib2to3/fixes/fix_print.py b/micromamba_root/envs/pytorch_env/Lib/lib2to3/fixes/fix_print.py new file mode 100644 index 0000000000000000000000000000000000000000..8780322265f6fe526cb35e7961f3cfb5aaa8e052 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/lib2to3/fixes/fix_print.py @@ -0,0 +1,87 @@ +# Copyright 2006 Google, Inc. All Rights Reserved. +# Licensed to PSF under a Contributor Agreement. + +"""Fixer for print. + +Change: + 'print' into 'print()' + 'print ...' into 'print(...)' + 'print ... ,' into 'print(..., end=" ")' + 'print >>x, ...' into 'print(..., file=x)' + +No changes are applied if print_function is imported from __future__ + +""" + +# Local imports +from .. import patcomp +from .. import pytree +from ..pgen2 import token +from .. import fixer_base +from ..fixer_util import Name, Call, Comma, String + + +parend_expr = patcomp.compile_pattern( + """atom< '(' [atom|STRING|NAME] ')' >""" + ) + + +class FixPrint(fixer_base.BaseFix): + + BM_compatible = True + + PATTERN = """ + simple_stmt< any* bare='print' any* > | print_stmt + """ + + def transform(self, node, results): + assert results + + bare_print = results.get("bare") + + if bare_print: + # Special-case print all by itself + bare_print.replace(Call(Name("print"), [], + prefix=bare_print.prefix)) + return + assert node.children[0] == Name("print") + args = node.children[1:] + if len(args) == 1 and parend_expr.match(args[0]): + # We don't want to keep sticking parens around an + # already-parenthesised expression. + return + + sep = end = file = None + if args and args[-1] == Comma(): + args = args[:-1] + end = " " + if args and args[0] == pytree.Leaf(token.RIGHTSHIFT, ">>"): + assert len(args) >= 2 + file = args[1].clone() + args = args[3:] # Strip a possible comma after the file expression + # Now synthesize a print(args, sep=..., end=..., file=...) node. + l_args = [arg.clone() for arg in args] + if l_args: + l_args[0].prefix = "" + if sep is not None or end is not None or file is not None: + if sep is not None: + self.add_kwarg(l_args, "sep", String(repr(sep))) + if end is not None: + self.add_kwarg(l_args, "end", String(repr(end))) + if file is not None: + self.add_kwarg(l_args, "file", file) + n_stmt = Call(Name("print"), l_args) + n_stmt.prefix = node.prefix + return n_stmt + + def add_kwarg(self, l_nodes, s_kwd, n_expr): + # XXX All this prefix-setting may lose comments (though rarely) + n_expr.prefix = "" + n_argument = pytree.Node(self.syms.argument, + (Name(s_kwd), + pytree.Leaf(token.EQUAL, "="), + n_expr)) + if l_nodes: + l_nodes.append(Comma()) + n_argument.prefix = " " + l_nodes.append(n_argument) diff --git a/micromamba_root/envs/pytorch_env/Lib/lib2to3/fixes/fix_raise.py b/micromamba_root/envs/pytorch_env/Lib/lib2to3/fixes/fix_raise.py new file mode 100644 index 0000000000000000000000000000000000000000..05aa21e74a30ff101c593dc03514efc26f10cecf --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/lib2to3/fixes/fix_raise.py @@ -0,0 +1,90 @@ +"""Fixer for 'raise E, V, T' + +raise -> raise +raise E -> raise E +raise E, V -> raise E(V) +raise E, V, T -> raise E(V).with_traceback(T) +raise E, None, T -> raise E.with_traceback(T) + +raise (((E, E'), E''), E'''), V -> raise E(V) +raise "foo", V, T -> warns about string exceptions + + +CAVEATS: +1) "raise E, V" will be incorrectly translated if V is an exception + instance. The correct Python 3 idiom is + + raise E from V + + but since we can't detect instance-hood by syntax alone and since + any client code would have to be changed as well, we don't automate + this. +""" +# Author: Collin Winter + +# Local imports +from .. import pytree +from ..pgen2 import token +from .. import fixer_base +from ..fixer_util import Name, Call, Attr, ArgList, is_tuple + +class FixRaise(fixer_base.BaseFix): + + BM_compatible = True + PATTERN = """ + raise_stmt< 'raise' exc=any [',' val=any [',' tb=any]] > + """ + + def transform(self, node, results): + syms = self.syms + + exc = results["exc"].clone() + if exc.type == token.STRING: + msg = "Python 3 does not support string exceptions" + self.cannot_convert(node, msg) + return + + # Python 2 supports + # raise ((((E1, E2), E3), E4), E5), V + # as a synonym for + # raise E1, V + # Since Python 3 will not support this, we recurse down any tuple + # literals, always taking the first element. + if is_tuple(exc): + while is_tuple(exc): + # exc.children[1:-1] is the unparenthesized tuple + # exc.children[1].children[0] is the first element of the tuple + exc = exc.children[1].children[0].clone() + exc.prefix = " " + + if "val" not in results: + # One-argument raise + new = pytree.Node(syms.raise_stmt, [Name("raise"), exc]) + new.prefix = node.prefix + return new + + val = results["val"].clone() + if is_tuple(val): + args = [c.clone() for c in val.children[1:-1]] + else: + val.prefix = "" + args = [val] + + if "tb" in results: + tb = results["tb"].clone() + tb.prefix = "" + + e = exc + # If there's a traceback and None is passed as the value, then don't + # add a call, since the user probably just wants to add a + # traceback. See issue #9661. + if val.type != token.NAME or val.value != "None": + e = Call(exc, args) + with_tb = Attr(e, Name('with_traceback')) + [ArgList([tb])] + new = pytree.Node(syms.simple_stmt, [Name("raise")] + with_tb) + new.prefix = node.prefix + return new + else: + return pytree.Node(syms.raise_stmt, + [Name("raise"), Call(exc, args)], + prefix=node.prefix) diff --git a/micromamba_root/envs/pytorch_env/Lib/lib2to3/fixes/fix_raw_input.py b/micromamba_root/envs/pytorch_env/Lib/lib2to3/fixes/fix_raw_input.py new file mode 100644 index 0000000000000000000000000000000000000000..a51bb694b9e01e8d6f382f359118df1d74135924 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/lib2to3/fixes/fix_raw_input.py @@ -0,0 +1,17 @@ +"""Fixer that changes raw_input(...) into input(...).""" +# Author: Andre Roberge + +# Local imports +from .. import fixer_base +from ..fixer_util import Name + +class FixRawInput(fixer_base.BaseFix): + + BM_compatible = True + PATTERN = """ + power< name='raw_input' trailer< '(' [any] ')' > any* > + """ + + def transform(self, node, results): + name = results["name"] + name.replace(Name("input", prefix=name.prefix)) diff --git a/micromamba_root/envs/pytorch_env/Lib/lib2to3/fixes/fix_reduce.py b/micromamba_root/envs/pytorch_env/Lib/lib2to3/fixes/fix_reduce.py new file mode 100644 index 0000000000000000000000000000000000000000..00e5aa1c33d4826e976cccee05b8f7398954459f --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/lib2to3/fixes/fix_reduce.py @@ -0,0 +1,35 @@ +# Copyright 2008 Armin Ronacher. +# Licensed to PSF under a Contributor Agreement. + +"""Fixer for reduce(). + +Makes sure reduce() is imported from the functools module if reduce is +used in that module. +""" + +from lib2to3 import fixer_base +from lib2to3.fixer_util import touch_import + + + +class FixReduce(fixer_base.BaseFix): + + BM_compatible = True + order = "pre" + + PATTERN = """ + power< 'reduce' + trailer< '(' + arglist< ( + (not(argument) any ',' + not(argument + > + """ + + def transform(self, node, results): + touch_import('functools', 'reduce', node) diff --git a/micromamba_root/envs/pytorch_env/Lib/lib2to3/fixes/fix_reload.py b/micromamba_root/envs/pytorch_env/Lib/lib2to3/fixes/fix_reload.py new file mode 100644 index 0000000000000000000000000000000000000000..b30841131c51f9b6311d1e10629dd9e5049fd6ab --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/lib2to3/fixes/fix_reload.py @@ -0,0 +1,36 @@ +"""Fixer for reload(). + +reload(s) -> importlib.reload(s)""" + +# Local imports +from .. import fixer_base +from ..fixer_util import ImportAndCall, touch_import + + +class FixReload(fixer_base.BaseFix): + BM_compatible = True + order = "pre" + + PATTERN = """ + power< 'reload' + trailer< lpar='(' + ( not(arglist | argument) any ','> ) + rpar=')' > + after=any* + > + """ + + def transform(self, node, results): + if results: + # I feel like we should be able to express this logic in the + # PATTERN above but I don't know how to do it so... + obj = results['obj'] + if obj: + if (obj.type == self.syms.argument and + obj.children[0].value in {'**', '*'}): + return # Make no change. + names = ('importlib', 'reload') + new = ImportAndCall(node, results, names) + touch_import(None, 'importlib', node) + return new diff --git a/micromamba_root/envs/pytorch_env/Lib/lib2to3/fixes/fix_renames.py b/micromamba_root/envs/pytorch_env/Lib/lib2to3/fixes/fix_renames.py new file mode 100644 index 0000000000000000000000000000000000000000..c0e3705ab7be19c037b833bc43e76eafc21067d8 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/lib2to3/fixes/fix_renames.py @@ -0,0 +1,70 @@ +"""Fix incompatible renames + +Fixes: + * sys.maxint -> sys.maxsize +""" +# Author: Christian Heimes +# based on Collin Winter's fix_import + +# Local imports +from .. import fixer_base +from ..fixer_util import Name, attr_chain + +MAPPING = {"sys": {"maxint" : "maxsize"}, + } +LOOKUP = {} + +def alternates(members): + return "(" + "|".join(map(repr, members)) + ")" + + +def build_pattern(): + #bare = set() + for module, replace in list(MAPPING.items()): + for old_attr, new_attr in list(replace.items()): + LOOKUP[(module, old_attr)] = new_attr + #bare.add(module) + #bare.add(old_attr) + #yield """ + # import_name< 'import' (module=%r + # | dotted_as_names< any* module=%r any* >) > + # """ % (module, module) + yield """ + import_from< 'from' module_name=%r 'import' + ( attr_name=%r | import_as_name< attr_name=%r 'as' any >) > + """ % (module, old_attr, old_attr) + yield """ + power< module_name=%r trailer< '.' attr_name=%r > any* > + """ % (module, old_attr) + #yield """bare_name=%s""" % alternates(bare) + + +class FixRenames(fixer_base.BaseFix): + BM_compatible = True + PATTERN = "|".join(build_pattern()) + + order = "pre" # Pre-order tree traversal + + # Don't match the node if it's within another match + def match(self, node): + match = super(FixRenames, self).match + results = match(node) + if results: + if any(match(obj) for obj in attr_chain(node, "parent")): + return False + return results + return False + + #def start_tree(self, tree, filename): + # super(FixRenames, self).start_tree(tree, filename) + # self.replace = {} + + def transform(self, node, results): + mod_name = results.get("module_name") + attr_name = results.get("attr_name") + #bare_name = results.get("bare_name") + #import_mod = results.get("module") + + if mod_name and attr_name: + new_attr = LOOKUP[(mod_name.value, attr_name.value)] + attr_name.replace(Name(new_attr, prefix=attr_name.prefix)) diff --git a/micromamba_root/envs/pytorch_env/Lib/lib2to3/fixes/fix_repr.py b/micromamba_root/envs/pytorch_env/Lib/lib2to3/fixes/fix_repr.py new file mode 100644 index 0000000000000000000000000000000000000000..1150bb8b9db2afba11a18f2661fdfd4d9bd4b633 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/lib2to3/fixes/fix_repr.py @@ -0,0 +1,23 @@ +# Copyright 2006 Google, Inc. All Rights Reserved. +# Licensed to PSF under a Contributor Agreement. + +"""Fixer that transforms `xyzzy` into repr(xyzzy).""" + +# Local imports +from .. import fixer_base +from ..fixer_util import Call, Name, parenthesize + + +class FixRepr(fixer_base.BaseFix): + + BM_compatible = True + PATTERN = """ + atom < '`' expr=any '`' > + """ + + def transform(self, node, results): + expr = results["expr"].clone() + + if expr.type == self.syms.testlist1: + expr = parenthesize(expr) + return Call(Name("repr"), [expr], prefix=node.prefix) diff --git a/micromamba_root/envs/pytorch_env/Lib/lib2to3/fixes/fix_set_literal.py b/micromamba_root/envs/pytorch_env/Lib/lib2to3/fixes/fix_set_literal.py new file mode 100644 index 0000000000000000000000000000000000000000..762550cf73dc0b627612465e63f0368d06847ae1 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/lib2to3/fixes/fix_set_literal.py @@ -0,0 +1,53 @@ +""" +Optional fixer to transform set() calls to set literals. +""" + +# Author: Benjamin Peterson + +from lib2to3 import fixer_base, pytree +from lib2to3.fixer_util import token, syms + + + +class FixSetLiteral(fixer_base.BaseFix): + + BM_compatible = True + explicit = True + + PATTERN = """power< 'set' trailer< '(' + (atom=atom< '[' (items=listmaker< any ((',' any)* [',']) > + | + single=any) ']' > + | + atom< '(' items=testlist_gexp< any ((',' any)* [',']) > ')' > + ) + ')' > > + """ + + def transform(self, node, results): + single = results.get("single") + if single: + # Make a fake listmaker + fake = pytree.Node(syms.listmaker, [single.clone()]) + single.replace(fake) + items = fake + else: + items = results["items"] + + # Build the contents of the literal + literal = [pytree.Leaf(token.LBRACE, "{")] + literal.extend(n.clone() for n in items.children) + literal.append(pytree.Leaf(token.RBRACE, "}")) + # Set the prefix of the right brace to that of the ')' or ']' + literal[-1].prefix = items.next_sibling.prefix + maker = pytree.Node(syms.dictsetmaker, literal) + maker.prefix = node.prefix + + # If the original was a one tuple, we need to remove the extra comma. + if len(maker.children) == 4: + n = maker.children[2] + n.remove() + maker.children[-1].prefix = n.prefix + + # Finally, replace the set call with our shiny new literal. + return maker diff --git a/micromamba_root/envs/pytorch_env/Lib/lib2to3/fixes/fix_standarderror.py b/micromamba_root/envs/pytorch_env/Lib/lib2to3/fixes/fix_standarderror.py new file mode 100644 index 0000000000000000000000000000000000000000..dc742167e6e9d4680afb7afcfc64524f4c14aca3 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/lib2to3/fixes/fix_standarderror.py @@ -0,0 +1,18 @@ +# Copyright 2007 Google, Inc. All Rights Reserved. +# Licensed to PSF under a Contributor Agreement. + +"""Fixer for StandardError -> Exception.""" + +# Local imports +from .. import fixer_base +from ..fixer_util import Name + + +class FixStandarderror(fixer_base.BaseFix): + BM_compatible = True + PATTERN = """ + 'StandardError' + """ + + def transform(self, node, results): + return Name("Exception", prefix=node.prefix) diff --git a/micromamba_root/envs/pytorch_env/Lib/lib2to3/fixes/fix_sys_exc.py b/micromamba_root/envs/pytorch_env/Lib/lib2to3/fixes/fix_sys_exc.py new file mode 100644 index 0000000000000000000000000000000000000000..f6039690374ab26d383bc8e0309438c051d0d405 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/lib2to3/fixes/fix_sys_exc.py @@ -0,0 +1,30 @@ +"""Fixer for sys.exc_{type, value, traceback} + +sys.exc_type -> sys.exc_info()[0] +sys.exc_value -> sys.exc_info()[1] +sys.exc_traceback -> sys.exc_info()[2] +""" + +# By Jeff Balogh and Benjamin Peterson + +# Local imports +from .. import fixer_base +from ..fixer_util import Attr, Call, Name, Number, Subscript, Node, syms + +class FixSysExc(fixer_base.BaseFix): + # This order matches the ordering of sys.exc_info(). + exc_info = ["exc_type", "exc_value", "exc_traceback"] + BM_compatible = True + PATTERN = """ + power< 'sys' trailer< dot='.' attribute=(%s) > > + """ % '|'.join("'%s'" % e for e in exc_info) + + def transform(self, node, results): + sys_attr = results["attribute"][0] + index = Number(self.exc_info.index(sys_attr.value)) + + call = Call(Name("exc_info"), prefix=sys_attr.prefix) + attr = Attr(Name("sys"), call) + attr[1].children[0].prefix = results["dot"].prefix + attr.append(Subscript(index)) + return Node(syms.power, attr, prefix=node.prefix) diff --git a/micromamba_root/envs/pytorch_env/Lib/lib2to3/fixes/fix_throw.py b/micromamba_root/envs/pytorch_env/Lib/lib2to3/fixes/fix_throw.py new file mode 100644 index 0000000000000000000000000000000000000000..aac29169b4e98e26d0aa78c3fbce641742b04952 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/lib2to3/fixes/fix_throw.py @@ -0,0 +1,56 @@ +"""Fixer for generator.throw(E, V, T). + +g.throw(E) -> g.throw(E) +g.throw(E, V) -> g.throw(E(V)) +g.throw(E, V, T) -> g.throw(E(V).with_traceback(T)) + +g.throw("foo"[, V[, T]]) will warn about string exceptions.""" +# Author: Collin Winter + +# Local imports +from .. import pytree +from ..pgen2 import token +from .. import fixer_base +from ..fixer_util import Name, Call, ArgList, Attr, is_tuple + +class FixThrow(fixer_base.BaseFix): + BM_compatible = True + PATTERN = """ + power< any trailer< '.' 'throw' > + trailer< '(' args=arglist< exc=any ',' val=any [',' tb=any] > ')' > + > + | + power< any trailer< '.' 'throw' > trailer< '(' exc=any ')' > > + """ + + def transform(self, node, results): + syms = self.syms + + exc = results["exc"].clone() + if exc.type is token.STRING: + self.cannot_convert(node, "Python 3 does not support string exceptions") + return + + # Leave "g.throw(E)" alone + val = results.get("val") + if val is None: + return + + val = val.clone() + if is_tuple(val): + args = [c.clone() for c in val.children[1:-1]] + else: + val.prefix = "" + args = [val] + + throw_args = results["args"] + + if "tb" in results: + tb = results["tb"].clone() + tb.prefix = "" + + e = Call(exc, args) + with_tb = Attr(e, Name('with_traceback')) + [ArgList([tb])] + throw_args.replace(pytree.Node(syms.power, with_tb)) + else: + throw_args.replace(Call(exc, args)) diff --git a/micromamba_root/envs/pytorch_env/Lib/lib2to3/fixes/fix_tuple_params.py b/micromamba_root/envs/pytorch_env/Lib/lib2to3/fixes/fix_tuple_params.py new file mode 100644 index 0000000000000000000000000000000000000000..cad755ffdbefb39431b2ffa4f5c8cf3c7a920c06 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/lib2to3/fixes/fix_tuple_params.py @@ -0,0 +1,175 @@ +"""Fixer for function definitions with tuple parameters. + +def func(((a, b), c), d): + ... + + -> + +def func(x, d): + ((a, b), c) = x + ... + +It will also support lambdas: + + lambda (x, y): x + y -> lambda t: t[0] + t[1] + + # The parens are a syntax error in Python 3 + lambda (x): x + y -> lambda x: x + y +""" +# Author: Collin Winter + +# Local imports +from .. import pytree +from ..pgen2 import token +from .. import fixer_base +from ..fixer_util import Assign, Name, Newline, Number, Subscript, syms + +def is_docstring(stmt): + return isinstance(stmt, pytree.Node) and \ + stmt.children[0].type == token.STRING + +class FixTupleParams(fixer_base.BaseFix): + run_order = 4 #use a lower order since lambda is part of other + #patterns + BM_compatible = True + + PATTERN = """ + funcdef< 'def' any parameters< '(' args=any ')' > + ['->' any] ':' suite=any+ > + | + lambda= + lambdef< 'lambda' args=vfpdef< '(' inner=any ')' > + ':' body=any + > + """ + + def transform(self, node, results): + if "lambda" in results: + return self.transform_lambda(node, results) + + new_lines = [] + suite = results["suite"] + args = results["args"] + # This crap is so "def foo(...): x = 5; y = 7" is handled correctly. + # TODO(cwinter): suite-cleanup + if suite[0].children[1].type == token.INDENT: + start = 2 + indent = suite[0].children[1].value + end = Newline() + else: + start = 0 + indent = "; " + end = pytree.Leaf(token.INDENT, "") + + # We need access to self for new_name(), and making this a method + # doesn't feel right. Closing over self and new_lines makes the + # code below cleaner. + def handle_tuple(tuple_arg, add_prefix=False): + n = Name(self.new_name()) + arg = tuple_arg.clone() + arg.prefix = "" + stmt = Assign(arg, n.clone()) + if add_prefix: + n.prefix = " " + tuple_arg.replace(n) + new_lines.append(pytree.Node(syms.simple_stmt, + [stmt, end.clone()])) + + if args.type == syms.tfpdef: + handle_tuple(args) + elif args.type == syms.typedargslist: + for i, arg in enumerate(args.children): + if arg.type == syms.tfpdef: + # Without add_prefix, the emitted code is correct, + # just ugly. + handle_tuple(arg, add_prefix=(i > 0)) + + if not new_lines: + return + + # This isn't strictly necessary, but it plays nicely with other fixers. + # TODO(cwinter) get rid of this when children becomes a smart list + for line in new_lines: + line.parent = suite[0] + + # TODO(cwinter) suite-cleanup + after = start + if start == 0: + new_lines[0].prefix = " " + elif is_docstring(suite[0].children[start]): + new_lines[0].prefix = indent + after = start + 1 + + for line in new_lines: + line.parent = suite[0] + suite[0].children[after:after] = new_lines + for i in range(after+1, after+len(new_lines)+1): + suite[0].children[i].prefix = indent + suite[0].changed() + + def transform_lambda(self, node, results): + args = results["args"] + body = results["body"] + inner = simplify_args(results["inner"]) + + # Replace lambda ((((x)))): x with lambda x: x + if inner.type == token.NAME: + inner = inner.clone() + inner.prefix = " " + args.replace(inner) + return + + params = find_params(args) + to_index = map_to_index(params) + tup_name = self.new_name(tuple_name(params)) + + new_param = Name(tup_name, prefix=" ") + args.replace(new_param.clone()) + for n in body.post_order(): + if n.type == token.NAME and n.value in to_index: + subscripts = [c.clone() for c in to_index[n.value]] + new = pytree.Node(syms.power, + [new_param.clone()] + subscripts) + new.prefix = n.prefix + n.replace(new) + + +### Helper functions for transform_lambda() + +def simplify_args(node): + if node.type in (syms.vfplist, token.NAME): + return node + elif node.type == syms.vfpdef: + # These look like vfpdef< '(' x ')' > where x is NAME + # or another vfpdef instance (leading to recursion). + while node.type == syms.vfpdef: + node = node.children[1] + return node + raise RuntimeError("Received unexpected node %s" % node) + +def find_params(node): + if node.type == syms.vfpdef: + return find_params(node.children[1]) + elif node.type == token.NAME: + return node.value + return [find_params(c) for c in node.children if c.type != token.COMMA] + +def map_to_index(param_list, prefix=[], d=None): + if d is None: + d = {} + for i, obj in enumerate(param_list): + trailer = [Subscript(Number(str(i)))] + if isinstance(obj, list): + map_to_index(obj, trailer, d=d) + else: + d[obj] = prefix + trailer + return d + +def tuple_name(param_list): + l = [] + for obj in param_list: + if isinstance(obj, list): + l.append(tuple_name(obj)) + else: + l.append(obj) + return "_".join(l) diff --git a/micromamba_root/envs/pytorch_env/Lib/lib2to3/fixes/fix_types.py b/micromamba_root/envs/pytorch_env/Lib/lib2to3/fixes/fix_types.py new file mode 100644 index 0000000000000000000000000000000000000000..67bf51f2f5b85a6a2f6a4c6427a5d9893f0c4350 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/lib2to3/fixes/fix_types.py @@ -0,0 +1,61 @@ +# Copyright 2007 Google, Inc. All Rights Reserved. +# Licensed to PSF under a Contributor Agreement. + +"""Fixer for removing uses of the types module. + +These work for only the known names in the types module. The forms above +can include types. or not. ie, It is assumed the module is imported either as: + + import types + from types import ... # either * or specific types + +The import statements are not modified. + +There should be another fixer that handles at least the following constants: + + type([]) -> list + type(()) -> tuple + type('') -> str + +""" + +# Local imports +from .. import fixer_base +from ..fixer_util import Name + +_TYPE_MAPPING = { + 'BooleanType' : 'bool', + 'BufferType' : 'memoryview', + 'ClassType' : 'type', + 'ComplexType' : 'complex', + 'DictType': 'dict', + 'DictionaryType' : 'dict', + 'EllipsisType' : 'type(Ellipsis)', + #'FileType' : 'io.IOBase', + 'FloatType': 'float', + 'IntType': 'int', + 'ListType': 'list', + 'LongType': 'int', + 'ObjectType' : 'object', + 'NoneType': 'type(None)', + 'NotImplementedType' : 'type(NotImplemented)', + 'SliceType' : 'slice', + 'StringType': 'bytes', # XXX ? + 'StringTypes' : '(str,)', # XXX ? + 'TupleType': 'tuple', + 'TypeType' : 'type', + 'UnicodeType': 'str', + 'XRangeType' : 'range', + } + +_pats = ["power< 'types' trailer< '.' name='%s' > >" % t for t in _TYPE_MAPPING] + +class FixTypes(fixer_base.BaseFix): + BM_compatible = True + PATTERN = '|'.join(_pats) + + def transform(self, node, results): + new_value = _TYPE_MAPPING.get(results["name"].value) + if new_value: + return Name(new_value, prefix=node.prefix) + return None diff --git a/micromamba_root/envs/pytorch_env/Lib/lib2to3/fixes/fix_unicode.py b/micromamba_root/envs/pytorch_env/Lib/lib2to3/fixes/fix_unicode.py new file mode 100644 index 0000000000000000000000000000000000000000..c7982c2b97c3e1cacf5812a9ddd9d20fdda66496 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/lib2to3/fixes/fix_unicode.py @@ -0,0 +1,42 @@ +r"""Fixer for unicode. + +* Changes unicode to str and unichr to chr. + +* If "...\u..." is not unicode literal change it into "...\\u...". + +* Change u"..." into "...". + +""" + +from ..pgen2 import token +from .. import fixer_base + +_mapping = {"unichr" : "chr", "unicode" : "str"} + +class FixUnicode(fixer_base.BaseFix): + BM_compatible = True + PATTERN = "STRING | 'unicode' | 'unichr'" + + def start_tree(self, tree, filename): + super(FixUnicode, self).start_tree(tree, filename) + self.unicode_literals = 'unicode_literals' in tree.future_features + + def transform(self, node, results): + if node.type == token.NAME: + new = node.clone() + new.value = _mapping[node.value] + return new + elif node.type == token.STRING: + val = node.value + if not self.unicode_literals and val[0] in '\'"' and '\\' in val: + val = r'\\'.join([ + v.replace('\\u', r'\\u').replace('\\U', r'\\U') + for v in val.split(r'\\') + ]) + if val[0] in 'uU': + val = val[1:] + if val == node.value: + return node + new = node.clone() + new.value = val + return new diff --git a/micromamba_root/envs/pytorch_env/Lib/lib2to3/fixes/fix_urllib.py b/micromamba_root/envs/pytorch_env/Lib/lib2to3/fixes/fix_urllib.py new file mode 100644 index 0000000000000000000000000000000000000000..ab892bc52494c25bf5b46f92ca862965b4d99e5c --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/lib2to3/fixes/fix_urllib.py @@ -0,0 +1,196 @@ +"""Fix changes imports of urllib which are now incompatible. + This is rather similar to fix_imports, but because of the more + complex nature of the fixing for urllib, it has its own fixer. +""" +# Author: Nick Edds + +# Local imports +from lib2to3.fixes.fix_imports import alternates, FixImports +from lib2to3.fixer_util import (Name, Comma, FromImport, Newline, + find_indentation, Node, syms) + +MAPPING = {"urllib": [ + ("urllib.request", + ["URLopener", "FancyURLopener", "urlretrieve", + "_urlopener", "urlopen", "urlcleanup", + "pathname2url", "url2pathname", "getproxies"]), + ("urllib.parse", + ["quote", "quote_plus", "unquote", "unquote_plus", + "urlencode", "splitattr", "splithost", "splitnport", + "splitpasswd", "splitport", "splitquery", "splittag", + "splittype", "splituser", "splitvalue", ]), + ("urllib.error", + ["ContentTooShortError"])], + "urllib2" : [ + ("urllib.request", + ["urlopen", "install_opener", "build_opener", + "Request", "OpenerDirector", "BaseHandler", + "HTTPDefaultErrorHandler", "HTTPRedirectHandler", + "HTTPCookieProcessor", "ProxyHandler", + "HTTPPasswordMgr", + "HTTPPasswordMgrWithDefaultRealm", + "AbstractBasicAuthHandler", + "HTTPBasicAuthHandler", "ProxyBasicAuthHandler", + "AbstractDigestAuthHandler", + "HTTPDigestAuthHandler", "ProxyDigestAuthHandler", + "HTTPHandler", "HTTPSHandler", "FileHandler", + "FTPHandler", "CacheFTPHandler", + "UnknownHandler"]), + ("urllib.error", + ["URLError", "HTTPError"]), + ] +} + +# Duplicate the url parsing functions for urllib2. +MAPPING["urllib2"].append(MAPPING["urllib"][1]) + + +def build_pattern(): + bare = set() + for old_module, changes in MAPPING.items(): + for change in changes: + new_module, members = change + members = alternates(members) + yield """import_name< 'import' (module=%r + | dotted_as_names< any* module=%r any* >) > + """ % (old_module, old_module) + yield """import_from< 'from' mod_member=%r 'import' + ( member=%s | import_as_name< member=%s 'as' any > | + import_as_names< members=any* >) > + """ % (old_module, members, members) + yield """import_from< 'from' module_star=%r 'import' star='*' > + """ % old_module + yield """import_name< 'import' + dotted_as_name< module_as=%r 'as' any > > + """ % old_module + # bare_with_attr has a special significance for FixImports.match(). + yield """power< bare_with_attr=%r trailer< '.' member=%s > any* > + """ % (old_module, members) + + +class FixUrllib(FixImports): + + def build_pattern(self): + return "|".join(build_pattern()) + + def transform_import(self, node, results): + """Transform for the basic import case. Replaces the old + import name with a comma separated list of its + replacements. + """ + import_mod = results.get("module") + pref = import_mod.prefix + + names = [] + + # create a Node list of the replacement modules + for name in MAPPING[import_mod.value][:-1]: + names.extend([Name(name[0], prefix=pref), Comma()]) + names.append(Name(MAPPING[import_mod.value][-1][0], prefix=pref)) + import_mod.replace(names) + + def transform_member(self, node, results): + """Transform for imports of specific module elements. Replaces + the module to be imported from with the appropriate new + module. + """ + mod_member = results.get("mod_member") + pref = mod_member.prefix + member = results.get("member") + + # Simple case with only a single member being imported + if member: + # this may be a list of length one, or just a node + if isinstance(member, list): + member = member[0] + new_name = None + for change in MAPPING[mod_member.value]: + if member.value in change[1]: + new_name = change[0] + break + if new_name: + mod_member.replace(Name(new_name, prefix=pref)) + else: + self.cannot_convert(node, "This is an invalid module element") + + # Multiple members being imported + else: + # a dictionary for replacements, order matters + modules = [] + mod_dict = {} + members = results["members"] + for member in members: + # we only care about the actual members + if member.type == syms.import_as_name: + as_name = member.children[2].value + member_name = member.children[0].value + else: + member_name = member.value + as_name = None + if member_name != ",": + for change in MAPPING[mod_member.value]: + if member_name in change[1]: + if change[0] not in mod_dict: + modules.append(change[0]) + mod_dict.setdefault(change[0], []).append(member) + + new_nodes = [] + indentation = find_indentation(node) + first = True + def handle_name(name, prefix): + if name.type == syms.import_as_name: + kids = [Name(name.children[0].value, prefix=prefix), + name.children[1].clone(), + name.children[2].clone()] + return [Node(syms.import_as_name, kids)] + return [Name(name.value, prefix=prefix)] + for module in modules: + elts = mod_dict[module] + names = [] + for elt in elts[:-1]: + names.extend(handle_name(elt, pref)) + names.append(Comma()) + names.extend(handle_name(elts[-1], pref)) + new = FromImport(module, names) + if not first or node.parent.prefix.endswith(indentation): + new.prefix = indentation + new_nodes.append(new) + first = False + if new_nodes: + nodes = [] + for new_node in new_nodes[:-1]: + nodes.extend([new_node, Newline()]) + nodes.append(new_nodes[-1]) + node.replace(nodes) + else: + self.cannot_convert(node, "All module elements are invalid") + + def transform_dot(self, node, results): + """Transform for calls to module members in code.""" + module_dot = results.get("bare_with_attr") + member = results.get("member") + new_name = None + if isinstance(member, list): + member = member[0] + for change in MAPPING[module_dot.value]: + if member.value in change[1]: + new_name = change[0] + break + if new_name: + module_dot.replace(Name(new_name, + prefix=module_dot.prefix)) + else: + self.cannot_convert(node, "This is an invalid module element") + + def transform(self, node, results): + if results.get("module"): + self.transform_import(node, results) + elif results.get("mod_member"): + self.transform_member(node, results) + elif results.get("bare_with_attr"): + self.transform_dot(node, results) + # Renaming and star imports are not supported for these modules. + elif results.get("module_star"): + self.cannot_convert(node, "Cannot handle star imports.") + elif results.get("module_as"): + self.cannot_convert(node, "This module is now multiple modules") diff --git a/micromamba_root/envs/pytorch_env/Lib/lib2to3/fixes/fix_ws_comma.py b/micromamba_root/envs/pytorch_env/Lib/lib2to3/fixes/fix_ws_comma.py new file mode 100644 index 0000000000000000000000000000000000000000..a54a376c472afbff3f23f011d329af24813e5760 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/lib2to3/fixes/fix_ws_comma.py @@ -0,0 +1,39 @@ +"""Fixer that changes 'a ,b' into 'a, b'. + +This also changes '{a :b}' into '{a: b}', but does not touch other +uses of colons. It does not touch other uses of whitespace. + +""" + +from .. import pytree +from ..pgen2 import token +from .. import fixer_base + +class FixWsComma(fixer_base.BaseFix): + + explicit = True # The user must ask for this fixers + + PATTERN = """ + any<(not(',') any)+ ',' ((not(',') any)+ ',')* [not(',') any]> + """ + + COMMA = pytree.Leaf(token.COMMA, ",") + COLON = pytree.Leaf(token.COLON, ":") + SEPS = (COMMA, COLON) + + def transform(self, node, results): + new = node.clone() + comma = False + for child in new.children: + if child in self.SEPS: + prefix = child.prefix + if prefix.isspace() and "\n" not in prefix: + child.prefix = "" + comma = True + else: + if comma: + prefix = child.prefix + if not prefix: + child.prefix = " " + comma = False + return new diff --git a/micromamba_root/envs/pytorch_env/Lib/lib2to3/fixes/fix_xrange.py b/micromamba_root/envs/pytorch_env/Lib/lib2to3/fixes/fix_xrange.py new file mode 100644 index 0000000000000000000000000000000000000000..1e491e166a3f1c4223d306b9ad5817bc31fab2ee --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/lib2to3/fixes/fix_xrange.py @@ -0,0 +1,73 @@ +# Copyright 2007 Google, Inc. All Rights Reserved. +# Licensed to PSF under a Contributor Agreement. + +"""Fixer that changes xrange(...) into range(...).""" + +# Local imports +from .. import fixer_base +from ..fixer_util import Name, Call, consuming_calls +from .. import patcomp + + +class FixXrange(fixer_base.BaseFix): + BM_compatible = True + PATTERN = """ + power< + (name='range'|name='xrange') trailer< '(' args=any ')' > + rest=any* > + """ + + def start_tree(self, tree, filename): + super(FixXrange, self).start_tree(tree, filename) + self.transformed_xranges = set() + + def finish_tree(self, tree, filename): + self.transformed_xranges = None + + def transform(self, node, results): + name = results["name"] + if name.value == "xrange": + return self.transform_xrange(node, results) + elif name.value == "range": + return self.transform_range(node, results) + else: + raise ValueError(repr(name)) + + def transform_xrange(self, node, results): + name = results["name"] + name.replace(Name("range", prefix=name.prefix)) + # This prevents the new range call from being wrapped in a list later. + self.transformed_xranges.add(id(node)) + + def transform_range(self, node, results): + if (id(node) not in self.transformed_xranges and + not self.in_special_context(node)): + range_call = Call(Name("range"), [results["args"].clone()]) + # Encase the range call in list(). + list_call = Call(Name("list"), [range_call], + prefix=node.prefix) + # Put things that were after the range() call after the list call. + for n in results["rest"]: + list_call.append_child(n) + return list_call + + P1 = "power< func=NAME trailer< '(' node=any ')' > any* >" + p1 = patcomp.compile_pattern(P1) + + P2 = """for_stmt< 'for' any 'in' node=any ':' any* > + | comp_for< 'for' any 'in' node=any any* > + | comparison< any 'in' node=any any*> + """ + p2 = patcomp.compile_pattern(P2) + + def in_special_context(self, node): + if node.parent is None: + return False + results = {} + if (node.parent.parent is not None and + self.p1.match(node.parent.parent, results) and + results["node"] is node): + # list(d.keys()) -> list(d.keys()), etc. + return results["func"].value in consuming_calls + # for ... in d.iterkeys() -> for ... in d.keys(), etc. + return self.p2.match(node.parent, results) and results["node"] is node diff --git a/micromamba_root/envs/pytorch_env/Lib/lib2to3/fixes/fix_xreadlines.py b/micromamba_root/envs/pytorch_env/Lib/lib2to3/fixes/fix_xreadlines.py new file mode 100644 index 0000000000000000000000000000000000000000..3e3f71ab045573d9438bcbe5da6115b77dc3d7e9 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/lib2to3/fixes/fix_xreadlines.py @@ -0,0 +1,25 @@ +"""Fix "for x in f.xreadlines()" -> "for x in f". + +This fixer will also convert g(f.xreadlines) into g(f.__iter__).""" +# Author: Collin Winter + +# Local imports +from .. import fixer_base +from ..fixer_util import Name + + +class FixXreadlines(fixer_base.BaseFix): + BM_compatible = True + PATTERN = """ + power< call=any+ trailer< '.' 'xreadlines' > trailer< '(' ')' > > + | + power< any+ trailer< '.' no_call='xreadlines' > > + """ + + def transform(self, node, results): + no_call = results.get("no_call") + + if no_call: + no_call.replace(Name("__iter__", prefix=no_call.prefix)) + else: + node.replace([x.clone() for x in results["call"]]) diff --git a/micromamba_root/envs/pytorch_env/Lib/lib2to3/fixes/fix_zip.py b/micromamba_root/envs/pytorch_env/Lib/lib2to3/fixes/fix_zip.py new file mode 100644 index 0000000000000000000000000000000000000000..52c28df6aab411ad1ea64af74b14edf35e80b5bb --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/lib2to3/fixes/fix_zip.py @@ -0,0 +1,46 @@ +""" +Fixer that changes zip(seq0, seq1, ...) into list(zip(seq0, seq1, ...) +unless there exists a 'from future_builtins import zip' statement in the +top-level namespace. + +We avoid the transformation if the zip() call is directly contained in +iter(<>), list(<>), tuple(<>), sorted(<>), ...join(<>), or for V in <>:. +""" + +# Local imports +from .. import fixer_base +from ..pytree import Node +from ..pygram import python_symbols as syms +from ..fixer_util import Name, ArgList, in_special_context + + +class FixZip(fixer_base.ConditionalFix): + + BM_compatible = True + PATTERN = """ + power< 'zip' args=trailer< '(' [any] ')' > [trailers=trailer*] + > + """ + + skip_on = "future_builtins.zip" + + def transform(self, node, results): + if self.should_skip(node): + return + + if in_special_context(node): + return None + + args = results['args'].clone() + args.prefix = "" + + trailers = [] + if 'trailers' in results: + trailers = [n.clone() for n in results['trailers']] + for n in trailers: + n.prefix = "" + + new = Node(syms.power, [Name("zip"), args], prefix="") + new = Node(syms.power, [Name("list"), ArgList([new])] + trailers) + new.prefix = node.prefix + return new diff --git a/micromamba_root/envs/pytorch_env/Lib/lib2to3/pgen2/__init__.py b/micromamba_root/envs/pytorch_env/Lib/lib2to3/pgen2/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..af390484528d87bfb78377b228b47480d2284ea5 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/lib2to3/pgen2/__init__.py @@ -0,0 +1,4 @@ +# Copyright 2004-2005 Elemental Security, Inc. All Rights Reserved. +# Licensed to PSF under a Contributor Agreement. + +"""The pgen2 package.""" diff --git a/micromamba_root/envs/pytorch_env/Lib/lib2to3/pgen2/__pycache__/__init__.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/lib2to3/pgen2/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b5fe75e2075c25da96c2e2234e097065bba0b17f Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/lib2to3/pgen2/__pycache__/__init__.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/lib2to3/pgen2/__pycache__/conv.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/lib2to3/pgen2/__pycache__/conv.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b2bc50af7b793336ed7970abb1cdbd3d4ffa1ecc Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/lib2to3/pgen2/__pycache__/conv.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/lib2to3/pgen2/__pycache__/driver.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/lib2to3/pgen2/__pycache__/driver.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b6ba9d259ed1bece0d51f1c5fa43a1dd618039d1 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/lib2to3/pgen2/__pycache__/driver.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/lib2to3/pgen2/__pycache__/grammar.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/lib2to3/pgen2/__pycache__/grammar.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0dc193f55d42be6618193c43d55f3813e1053449 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/lib2to3/pgen2/__pycache__/grammar.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/lib2to3/pgen2/__pycache__/literals.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/lib2to3/pgen2/__pycache__/literals.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7c7074f818e5be48a658e9ed9d330ba3fcc00dd0 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/lib2to3/pgen2/__pycache__/literals.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/lib2to3/pgen2/__pycache__/parse.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/lib2to3/pgen2/__pycache__/parse.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..471811dde8a87c0d34fa6691f6a3985b0f3f6457 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/lib2to3/pgen2/__pycache__/parse.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/lib2to3/pgen2/__pycache__/pgen.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/lib2to3/pgen2/__pycache__/pgen.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..63b6a8277bbb9cc328eef27868835df32bc8cca8 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/lib2to3/pgen2/__pycache__/pgen.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/lib2to3/pgen2/__pycache__/token.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/lib2to3/pgen2/__pycache__/token.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..be0a2f08ee0f56347271eeb0bbb70cc4174c00c2 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/lib2to3/pgen2/__pycache__/token.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/lib2to3/pgen2/__pycache__/tokenize.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/lib2to3/pgen2/__pycache__/tokenize.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..75d01645775126498bdbcb8e6a79481b39007b76 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/lib2to3/pgen2/__pycache__/tokenize.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/lib2to3/pgen2/conv.py b/micromamba_root/envs/pytorch_env/Lib/lib2to3/pgen2/conv.py new file mode 100644 index 0000000000000000000000000000000000000000..ed0cac532e424952b460788a1d6f54d279627af6 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/lib2to3/pgen2/conv.py @@ -0,0 +1,257 @@ +# Copyright 2004-2005 Elemental Security, Inc. All Rights Reserved. +# Licensed to PSF under a Contributor Agreement. + +"""Convert graminit.[ch] spit out by pgen to Python code. + +Pgen is the Python parser generator. It is useful to quickly create a +parser from a grammar file in Python's grammar notation. But I don't +want my parsers to be written in C (yet), so I'm translating the +parsing tables to Python data structures and writing a Python parse +engine. + +Note that the token numbers are constants determined by the standard +Python tokenizer. The standard token module defines these numbers and +their names (the names are not used much). The token numbers are +hardcoded into the Python tokenizer and into pgen. A Python +implementation of the Python tokenizer is also available, in the +standard tokenize module. + +On the other hand, symbol numbers (representing the grammar's +non-terminals) are assigned by pgen based on the actual grammar +input. + +Note: this module is pretty much obsolete; the pgen module generates +equivalent grammar tables directly from the Grammar.txt input file +without having to invoke the Python pgen C program. + +""" + +# Python imports +import re + +# Local imports +from pgen2 import grammar, token + + +class Converter(grammar.Grammar): + """Grammar subclass that reads classic pgen output files. + + The run() method reads the tables as produced by the pgen parser + generator, typically contained in two C files, graminit.h and + graminit.c. The other methods are for internal use only. + + See the base class for more documentation. + + """ + + def run(self, graminit_h, graminit_c): + """Load the grammar tables from the text files written by pgen.""" + self.parse_graminit_h(graminit_h) + self.parse_graminit_c(graminit_c) + self.finish_off() + + def parse_graminit_h(self, filename): + """Parse the .h file written by pgen. (Internal) + + This file is a sequence of #define statements defining the + nonterminals of the grammar as numbers. We build two tables + mapping the numbers to names and back. + + """ + try: + f = open(filename) + except OSError as err: + print("Can't open %s: %s" % (filename, err)) + return False + self.symbol2number = {} + self.number2symbol = {} + lineno = 0 + for line in f: + lineno += 1 + mo = re.match(r"^#define\s+(\w+)\s+(\d+)$", line) + if not mo and line.strip(): + print("%s(%s): can't parse %s" % (filename, lineno, + line.strip())) + else: + symbol, number = mo.groups() + number = int(number) + assert symbol not in self.symbol2number + assert number not in self.number2symbol + self.symbol2number[symbol] = number + self.number2symbol[number] = symbol + return True + + def parse_graminit_c(self, filename): + """Parse the .c file written by pgen. (Internal) + + The file looks as follows. The first two lines are always this: + + #include "pgenheaders.h" + #include "grammar.h" + + After that come four blocks: + + 1) one or more state definitions + 2) a table defining dfas + 3) a table defining labels + 4) a struct defining the grammar + + A state definition has the following form: + - one or more arc arrays, each of the form: + static arc arcs__[] = { + {, }, + ... + }; + - followed by a state array, of the form: + static state states_[] = { + {, arcs__}, + ... + }; + + """ + try: + f = open(filename) + except OSError as err: + print("Can't open %s: %s" % (filename, err)) + return False + # The code below essentially uses f's iterator-ness! + lineno = 0 + + # Expect the two #include lines + lineno, line = lineno+1, next(f) + assert line == '#include "pgenheaders.h"\n', (lineno, line) + lineno, line = lineno+1, next(f) + assert line == '#include "grammar.h"\n', (lineno, line) + + # Parse the state definitions + lineno, line = lineno+1, next(f) + allarcs = {} + states = [] + while line.startswith("static arc "): + while line.startswith("static arc "): + mo = re.match(r"static arc arcs_(\d+)_(\d+)\[(\d+)\] = {$", + line) + assert mo, (lineno, line) + n, m, k = list(map(int, mo.groups())) + arcs = [] + for _ in range(k): + lineno, line = lineno+1, next(f) + mo = re.match(r"\s+{(\d+), (\d+)},$", line) + assert mo, (lineno, line) + i, j = list(map(int, mo.groups())) + arcs.append((i, j)) + lineno, line = lineno+1, next(f) + assert line == "};\n", (lineno, line) + allarcs[(n, m)] = arcs + lineno, line = lineno+1, next(f) + mo = re.match(r"static state states_(\d+)\[(\d+)\] = {$", line) + assert mo, (lineno, line) + s, t = list(map(int, mo.groups())) + assert s == len(states), (lineno, line) + state = [] + for _ in range(t): + lineno, line = lineno+1, next(f) + mo = re.match(r"\s+{(\d+), arcs_(\d+)_(\d+)},$", line) + assert mo, (lineno, line) + k, n, m = list(map(int, mo.groups())) + arcs = allarcs[n, m] + assert k == len(arcs), (lineno, line) + state.append(arcs) + states.append(state) + lineno, line = lineno+1, next(f) + assert line == "};\n", (lineno, line) + lineno, line = lineno+1, next(f) + self.states = states + + # Parse the dfas + dfas = {} + mo = re.match(r"static dfa dfas\[(\d+)\] = {$", line) + assert mo, (lineno, line) + ndfas = int(mo.group(1)) + for i in range(ndfas): + lineno, line = lineno+1, next(f) + mo = re.match(r'\s+{(\d+), "(\w+)", (\d+), (\d+), states_(\d+),$', + line) + assert mo, (lineno, line) + symbol = mo.group(2) + number, x, y, z = list(map(int, mo.group(1, 3, 4, 5))) + assert self.symbol2number[symbol] == number, (lineno, line) + assert self.number2symbol[number] == symbol, (lineno, line) + assert x == 0, (lineno, line) + state = states[z] + assert y == len(state), (lineno, line) + lineno, line = lineno+1, next(f) + mo = re.match(r'\s+("(?:\\\d\d\d)*")},$', line) + assert mo, (lineno, line) + first = {} + rawbitset = eval(mo.group(1)) + for i, c in enumerate(rawbitset): + byte = ord(c) + for j in range(8): + if byte & (1<= os.path.getmtime(b) + + +def load_packaged_grammar(package, grammar_source): + """Normally, loads a pickled grammar by doing + pkgutil.get_data(package, pickled_grammar) + where *pickled_grammar* is computed from *grammar_source* by adding the + Python version and using a ``.pickle`` extension. + + However, if *grammar_source* is an extant file, load_grammar(grammar_source) + is called instead. This facilitates using a packaged grammar file when needed + but preserves load_grammar's automatic regeneration behavior when possible. + + """ + if os.path.isfile(grammar_source): + return load_grammar(grammar_source) + pickled_name = _generate_pickle_name(os.path.basename(grammar_source)) + data = pkgutil.get_data(package, pickled_name) + g = grammar.Grammar() + g.loads(data) + return g + + +def main(*args): + """Main program, when run as a script: produce grammar pickle files. + + Calls load_grammar for each argument, a path to a grammar text file. + """ + if not args: + args = sys.argv[1:] + logging.basicConfig(level=logging.INFO, stream=sys.stdout, + format='%(message)s') + for gt in args: + load_grammar(gt, save=True, force=True) + return True + +if __name__ == "__main__": + sys.exit(int(not main())) diff --git a/micromamba_root/envs/pytorch_env/Lib/lib2to3/pgen2/grammar.py b/micromamba_root/envs/pytorch_env/Lib/lib2to3/pgen2/grammar.py new file mode 100644 index 0000000000000000000000000000000000000000..5d550aeb65e8dd10bb286267a7132ae380bbd038 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/lib2to3/pgen2/grammar.py @@ -0,0 +1,189 @@ +# Copyright 2004-2005 Elemental Security, Inc. All Rights Reserved. +# Licensed to PSF under a Contributor Agreement. + +"""This module defines the data structures used to represent a grammar. + +These are a bit arcane because they are derived from the data +structures used by Python's 'pgen' parser generator. + +There's also a table here mapping operators to their names in the +token module; the Python tokenize module reports all operators as the +fallback token code OP, but the parser needs the actual token code. + +""" + +# Python imports +import pickle + +# Local imports +from . import token + + +class Grammar(object): + """Pgen parsing tables conversion class. + + Once initialized, this class supplies the grammar tables for the + parsing engine implemented by parse.py. The parsing engine + accesses the instance variables directly. The class here does not + provide initialization of the tables; several subclasses exist to + do this (see the conv and pgen modules). + + The load() method reads the tables from a pickle file, which is + much faster than the other ways offered by subclasses. The pickle + file is written by calling dump() (after loading the grammar + tables using a subclass). The report() method prints a readable + representation of the tables to stdout, for debugging. + + The instance variables are as follows: + + symbol2number -- a dict mapping symbol names to numbers. Symbol + numbers are always 256 or higher, to distinguish + them from token numbers, which are between 0 and + 255 (inclusive). + + number2symbol -- a dict mapping numbers to symbol names; + these two are each other's inverse. + + states -- a list of DFAs, where each DFA is a list of + states, each state is a list of arcs, and each + arc is a (i, j) pair where i is a label and j is + a state number. The DFA number is the index into + this list. (This name is slightly confusing.) + Final states are represented by a special arc of + the form (0, j) where j is its own state number. + + dfas -- a dict mapping symbol numbers to (DFA, first) + pairs, where DFA is an item from the states list + above, and first is a set of tokens that can + begin this grammar rule (represented by a dict + whose values are always 1). + + labels -- a list of (x, y) pairs where x is either a token + number or a symbol number, and y is either None + or a string; the strings are keywords. The label + number is the index in this list; label numbers + are used to mark state transitions (arcs) in the + DFAs. + + start -- the number of the grammar's start symbol. + + keywords -- a dict mapping keyword strings to arc labels. + + tokens -- a dict mapping token numbers to arc labels. + + """ + + def __init__(self): + self.symbol2number = {} + self.number2symbol = {} + self.states = [] + self.dfas = {} + self.labels = [(0, "EMPTY")] + self.keywords = {} + self.tokens = {} + self.symbol2label = {} + self.start = 256 + + def dump(self, filename): + """Dump the grammar tables to a pickle file.""" + with open(filename, "wb") as f: + pickle.dump(self.__dict__, f, pickle.HIGHEST_PROTOCOL) + + def load(self, filename): + """Load the grammar tables from a pickle file.""" + with open(filename, "rb") as f: + d = pickle.load(f) + self.__dict__.update(d) + + def loads(self, pkl): + """Load the grammar tables from a pickle bytes object.""" + self.__dict__.update(pickle.loads(pkl)) + + def copy(self): + """ + Copy the grammar. + """ + new = self.__class__() + for dict_attr in ("symbol2number", "number2symbol", "dfas", "keywords", + "tokens", "symbol2label"): + setattr(new, dict_attr, getattr(self, dict_attr).copy()) + new.labels = self.labels[:] + new.states = self.states[:] + new.start = self.start + return new + + def report(self): + """Dump the grammar tables to standard output, for debugging.""" + from pprint import pprint + print("s2n") + pprint(self.symbol2number) + print("n2s") + pprint(self.number2symbol) + print("states") + pprint(self.states) + print("dfas") + pprint(self.dfas) + print("labels") + pprint(self.labels) + print("start", self.start) + + +# Map from operator to number (since tokenize doesn't do this) + +opmap_raw = """ +( LPAR +) RPAR +[ LSQB +] RSQB +: COLON +, COMMA +; SEMI ++ PLUS +- MINUS +* STAR +/ SLASH +| VBAR +& AMPER +< LESS +> GREATER += EQUAL +. DOT +% PERCENT +` BACKQUOTE +{ LBRACE +} RBRACE +@ AT +@= ATEQUAL +== EQEQUAL +!= NOTEQUAL +<> NOTEQUAL +<= LESSEQUAL +>= GREATEREQUAL +~ TILDE +^ CIRCUMFLEX +<< LEFTSHIFT +>> RIGHTSHIFT +** DOUBLESTAR ++= PLUSEQUAL +-= MINEQUAL +*= STAREQUAL +/= SLASHEQUAL +%= PERCENTEQUAL +&= AMPEREQUAL +|= VBAREQUAL +^= CIRCUMFLEXEQUAL +<<= LEFTSHIFTEQUAL +>>= RIGHTSHIFTEQUAL +**= DOUBLESTAREQUAL +// DOUBLESLASH +//= DOUBLESLASHEQUAL +-> RARROW +:= COLONEQUAL +""" + +opmap = {} +for line in opmap_raw.splitlines(): + if line: + op, name = line.split() + opmap[op] = getattr(token, name) +del line, op, name diff --git a/micromamba_root/envs/pytorch_env/Lib/lib2to3/pgen2/literals.py b/micromamba_root/envs/pytorch_env/Lib/lib2to3/pgen2/literals.py new file mode 100644 index 0000000000000000000000000000000000000000..b9b63e6e5572c1bc35526c6126db2b31b798d270 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/lib2to3/pgen2/literals.py @@ -0,0 +1,60 @@ +# Copyright 2004-2005 Elemental Security, Inc. All Rights Reserved. +# Licensed to PSF under a Contributor Agreement. + +"""Safely evaluate Python string literals without using eval().""" + +import re + +simple_escapes = {"a": "\a", + "b": "\b", + "f": "\f", + "n": "\n", + "r": "\r", + "t": "\t", + "v": "\v", + "'": "'", + '"': '"', + "\\": "\\"} + +def escape(m): + all, tail = m.group(0, 1) + assert all.startswith("\\") + esc = simple_escapes.get(tail) + if esc is not None: + return esc + if tail.startswith("x"): + hexes = tail[1:] + if len(hexes) < 2: + raise ValueError("invalid hex string escape ('\\%s')" % tail) + try: + i = int(hexes, 16) + except ValueError: + raise ValueError("invalid hex string escape ('\\%s')" % tail) from None + else: + try: + i = int(tail, 8) + except ValueError: + raise ValueError("invalid octal string escape ('\\%s')" % tail) from None + return chr(i) + +def evalString(s): + assert s.startswith("'") or s.startswith('"'), repr(s[:1]) + q = s[0] + if s[:3] == q*3: + q = q*3 + assert s.endswith(q), repr(s[-len(q):]) + assert len(s) >= 2*len(q) + s = s[len(q):-len(q)] + return re.sub(r"\\(\'|\"|\\|[abfnrtv]|x.{0,2}|[0-7]{1,3})", escape, s) + +def test(): + for i in range(256): + c = chr(i) + s = repr(c) + e = evalString(s) + if e != c: + print(i, c, s, e) + + +if __name__ == "__main__": + test() diff --git a/micromamba_root/envs/pytorch_env/Lib/lib2to3/pgen2/parse.py b/micromamba_root/envs/pytorch_env/Lib/lib2to3/pgen2/parse.py new file mode 100644 index 0000000000000000000000000000000000000000..cf3fcf7e99fd11d55fa5567801632f73629ba58c --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/lib2to3/pgen2/parse.py @@ -0,0 +1,204 @@ +# Copyright 2004-2005 Elemental Security, Inc. All Rights Reserved. +# Licensed to PSF under a Contributor Agreement. + +"""Parser engine for the grammar tables generated by pgen. + +The grammar table must be loaded first. + +See Parser/parser.c in the Python distribution for additional info on +how this parsing engine works. + +""" + +# Local imports +from . import token + +class ParseError(Exception): + """Exception to signal the parser is stuck.""" + + def __init__(self, msg, type, value, context): + Exception.__init__(self, "%s: type=%r, value=%r, context=%r" % + (msg, type, value, context)) + self.msg = msg + self.type = type + self.value = value + self.context = context + + def __reduce__(self): + return type(self), (self.msg, self.type, self.value, self.context) + +class Parser(object): + """Parser engine. + + The proper usage sequence is: + + p = Parser(grammar, [converter]) # create instance + p.setup([start]) # prepare for parsing + : + if p.addtoken(...): # parse a token; may raise ParseError + break + root = p.rootnode # root of abstract syntax tree + + A Parser instance may be reused by calling setup() repeatedly. + + A Parser instance contains state pertaining to the current token + sequence, and should not be used concurrently by different threads + to parse separate token sequences. + + See driver.py for how to get input tokens by tokenizing a file or + string. + + Parsing is complete when addtoken() returns True; the root of the + abstract syntax tree can then be retrieved from the rootnode + instance variable. When a syntax error occurs, addtoken() raises + the ParseError exception. There is no error recovery; the parser + cannot be used after a syntax error was reported (but it can be + reinitialized by calling setup()). + + """ + + def __init__(self, grammar, convert=None): + """Constructor. + + The grammar argument is a grammar.Grammar instance; see the + grammar module for more information. + + The parser is not ready yet for parsing; you must call the + setup() method to get it started. + + The optional convert argument is a function mapping concrete + syntax tree nodes to abstract syntax tree nodes. If not + given, no conversion is done and the syntax tree produced is + the concrete syntax tree. If given, it must be a function of + two arguments, the first being the grammar (a grammar.Grammar + instance), and the second being the concrete syntax tree node + to be converted. The syntax tree is converted from the bottom + up. + + A concrete syntax tree node is a (type, value, context, nodes) + tuple, where type is the node type (a token or symbol number), + value is None for symbols and a string for tokens, context is + None or an opaque value used for error reporting (typically a + (lineno, offset) pair), and nodes is a list of children for + symbols, and None for tokens. + + An abstract syntax tree node may be anything; this is entirely + up to the converter function. + + """ + self.grammar = grammar + self.convert = convert or (lambda grammar, node: node) + + def setup(self, start=None): + """Prepare for parsing. + + This *must* be called before starting to parse. + + The optional argument is an alternative start symbol; it + defaults to the grammar's start symbol. + + You can use a Parser instance to parse any number of programs; + each time you call setup() the parser is reset to an initial + state determined by the (implicit or explicit) start symbol. + + """ + if start is None: + start = self.grammar.start + # Each stack entry is a tuple: (dfa, state, node). + # A node is a tuple: (type, value, context, children), + # where children is a list of nodes or None, and context may be None. + newnode = (start, None, None, []) + stackentry = (self.grammar.dfas[start], 0, newnode) + self.stack = [stackentry] + self.rootnode = None + self.used_names = set() # Aliased to self.rootnode.used_names in pop() + + def addtoken(self, type, value, context): + """Add a token; return True iff this is the end of the program.""" + # Map from token to label + ilabel = self.classify(type, value, context) + # Loop until the token is shifted; may raise exceptions + while True: + dfa, state, node = self.stack[-1] + states, first = dfa + arcs = states[state] + # Look for a state with this label + for i, newstate in arcs: + t, v = self.grammar.labels[i] + if ilabel == i: + # Look it up in the list of labels + assert t < 256 + # Shift a token; we're done with it + self.shift(type, value, newstate, context) + # Pop while we are in an accept-only state + state = newstate + while states[state] == [(0, state)]: + self.pop() + if not self.stack: + # Done parsing! + return True + dfa, state, node = self.stack[-1] + states, first = dfa + # Done with this token + return False + elif t >= 256: + # See if it's a symbol and if we're in its first set + itsdfa = self.grammar.dfas[t] + itsstates, itsfirst = itsdfa + if ilabel in itsfirst: + # Push a symbol + self.push(t, self.grammar.dfas[t], newstate, context) + break # To continue the outer while loop + else: + if (0, state) in arcs: + # An accepting state, pop it and try something else + self.pop() + if not self.stack: + # Done parsing, but another token is input + raise ParseError("too much input", + type, value, context) + else: + # No success finding a transition + raise ParseError("bad input", type, value, context) + + def classify(self, type, value, context): + """Turn a token into a label. (Internal)""" + if type == token.NAME: + # Keep a listing of all used names + self.used_names.add(value) + # Check for reserved words + ilabel = self.grammar.keywords.get(value) + if ilabel is not None: + return ilabel + ilabel = self.grammar.tokens.get(type) + if ilabel is None: + raise ParseError("bad token", type, value, context) + return ilabel + + def shift(self, type, value, newstate, context): + """Shift a token. (Internal)""" + dfa, state, node = self.stack[-1] + newnode = (type, value, context, None) + newnode = self.convert(self.grammar, newnode) + if newnode is not None: + node[-1].append(newnode) + self.stack[-1] = (dfa, newstate, node) + + def push(self, type, newdfa, newstate, context): + """Push a nonterminal. (Internal)""" + dfa, state, node = self.stack[-1] + newnode = (type, None, context, []) + self.stack[-1] = (dfa, newstate, node) + self.stack.append((newdfa, 0, newnode)) + + def pop(self): + """Pop a nonterminal. (Internal)""" + popdfa, popstate, popnode = self.stack.pop() + newnode = self.convert(self.grammar, popnode) + if newnode is not None: + if self.stack: + dfa, state, node = self.stack[-1] + node[-1].append(newnode) + else: + self.rootnode = newnode + self.rootnode.used_names = self.used_names diff --git a/micromamba_root/envs/pytorch_env/Lib/lib2to3/pgen2/pgen.py b/micromamba_root/envs/pytorch_env/Lib/lib2to3/pgen2/pgen.py new file mode 100644 index 0000000000000000000000000000000000000000..7abd5cef1c36bb90f340fa6d308672537292ef1f --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/lib2to3/pgen2/pgen.py @@ -0,0 +1,386 @@ +# Copyright 2004-2005 Elemental Security, Inc. All Rights Reserved. +# Licensed to PSF under a Contributor Agreement. + +# Pgen imports +from . import grammar, token, tokenize + +class PgenGrammar(grammar.Grammar): + pass + +class ParserGenerator(object): + + def __init__(self, filename, stream=None): + close_stream = None + if stream is None: + stream = open(filename, encoding="utf-8") + close_stream = stream.close + self.filename = filename + self.stream = stream + self.generator = tokenize.generate_tokens(stream.readline) + self.gettoken() # Initialize lookahead + self.dfas, self.startsymbol = self.parse() + if close_stream is not None: + close_stream() + self.first = {} # map from symbol name to set of tokens + self.addfirstsets() + + def make_grammar(self): + c = PgenGrammar() + names = list(self.dfas.keys()) + names.sort() + names.remove(self.startsymbol) + names.insert(0, self.startsymbol) + for name in names: + i = 256 + len(c.symbol2number) + c.symbol2number[name] = i + c.number2symbol[i] = name + for name in names: + dfa = self.dfas[name] + states = [] + for state in dfa: + arcs = [] + for label, next in sorted(state.arcs.items()): + arcs.append((self.make_label(c, label), dfa.index(next))) + if state.isfinal: + arcs.append((0, dfa.index(state))) + states.append(arcs) + c.states.append(states) + c.dfas[c.symbol2number[name]] = (states, self.make_first(c, name)) + c.start = c.symbol2number[self.startsymbol] + return c + + def make_first(self, c, name): + rawfirst = self.first[name] + first = {} + for label in sorted(rawfirst): + ilabel = self.make_label(c, label) + ##assert ilabel not in first # XXX failed on <> ... != + first[ilabel] = 1 + return first + + def make_label(self, c, label): + # XXX Maybe this should be a method on a subclass of converter? + ilabel = len(c.labels) + if label[0].isalpha(): + # Either a symbol name or a named token + if label in c.symbol2number: + # A symbol name (a non-terminal) + if label in c.symbol2label: + return c.symbol2label[label] + else: + c.labels.append((c.symbol2number[label], None)) + c.symbol2label[label] = ilabel + return ilabel + else: + # A named token (NAME, NUMBER, STRING) + itoken = getattr(token, label, None) + assert isinstance(itoken, int), label + assert itoken in token.tok_name, label + if itoken in c.tokens: + return c.tokens[itoken] + else: + c.labels.append((itoken, None)) + c.tokens[itoken] = ilabel + return ilabel + else: + # Either a keyword or an operator + assert label[0] in ('"', "'"), label + value = eval(label) + if value[0].isalpha(): + # A keyword + if value in c.keywords: + return c.keywords[value] + else: + c.labels.append((token.NAME, value)) + c.keywords[value] = ilabel + return ilabel + else: + # An operator (any non-numeric token) + itoken = grammar.opmap[value] # Fails if unknown token + if itoken in c.tokens: + return c.tokens[itoken] + else: + c.labels.append((itoken, None)) + c.tokens[itoken] = ilabel + return ilabel + + def addfirstsets(self): + names = list(self.dfas.keys()) + names.sort() + for name in names: + if name not in self.first: + self.calcfirst(name) + #print name, self.first[name].keys() + + def calcfirst(self, name): + dfa = self.dfas[name] + self.first[name] = None # dummy to detect left recursion + state = dfa[0] + totalset = {} + overlapcheck = {} + for label, next in state.arcs.items(): + if label in self.dfas: + if label in self.first: + fset = self.first[label] + if fset is None: + raise ValueError("recursion for rule %r" % name) + else: + self.calcfirst(label) + fset = self.first[label] + totalset.update(fset) + overlapcheck[label] = fset + else: + totalset[label] = 1 + overlapcheck[label] = {label: 1} + inverse = {} + for label, itsfirst in overlapcheck.items(): + for symbol in itsfirst: + if symbol in inverse: + raise ValueError("rule %s is ambiguous; %s is in the" + " first sets of %s as well as %s" % + (name, symbol, label, inverse[symbol])) + inverse[symbol] = label + self.first[name] = totalset + + def parse(self): + dfas = {} + startsymbol = None + # MSTART: (NEWLINE | RULE)* ENDMARKER + while self.type != token.ENDMARKER: + while self.type == token.NEWLINE: + self.gettoken() + # RULE: NAME ':' RHS NEWLINE + name = self.expect(token.NAME) + self.expect(token.OP, ":") + a, z = self.parse_rhs() + self.expect(token.NEWLINE) + #self.dump_nfa(name, a, z) + dfa = self.make_dfa(a, z) + #self.dump_dfa(name, dfa) + oldlen = len(dfa) + self.simplify_dfa(dfa) + newlen = len(dfa) + dfas[name] = dfa + #print name, oldlen, newlen + if startsymbol is None: + startsymbol = name + return dfas, startsymbol + + def make_dfa(self, start, finish): + # To turn an NFA into a DFA, we define the states of the DFA + # to correspond to *sets* of states of the NFA. Then do some + # state reduction. Let's represent sets as dicts with 1 for + # values. + assert isinstance(start, NFAState) + assert isinstance(finish, NFAState) + def closure(state): + base = {} + addclosure(state, base) + return base + def addclosure(state, base): + assert isinstance(state, NFAState) + if state in base: + return + base[state] = 1 + for label, next in state.arcs: + if label is None: + addclosure(next, base) + states = [DFAState(closure(start), finish)] + for state in states: # NB states grows while we're iterating + arcs = {} + for nfastate in state.nfaset: + for label, next in nfastate.arcs: + if label is not None: + addclosure(next, arcs.setdefault(label, {})) + for label, nfaset in sorted(arcs.items()): + for st in states: + if st.nfaset == nfaset: + break + else: + st = DFAState(nfaset, finish) + states.append(st) + state.addarc(st, label) + return states # List of DFAState instances; first one is start + + def dump_nfa(self, name, start, finish): + print("Dump of NFA for", name) + todo = [start] + for i, state in enumerate(todo): + print(" State", i, state is finish and "(final)" or "") + for label, next in state.arcs: + if next in todo: + j = todo.index(next) + else: + j = len(todo) + todo.append(next) + if label is None: + print(" -> %d" % j) + else: + print(" %s -> %d" % (label, j)) + + def dump_dfa(self, name, dfa): + print("Dump of DFA for", name) + for i, state in enumerate(dfa): + print(" State", i, state.isfinal and "(final)" or "") + for label, next in sorted(state.arcs.items()): + print(" %s -> %d" % (label, dfa.index(next))) + + def simplify_dfa(self, dfa): + # This is not theoretically optimal, but works well enough. + # Algorithm: repeatedly look for two states that have the same + # set of arcs (same labels pointing to the same nodes) and + # unify them, until things stop changing. + + # dfa is a list of DFAState instances + changes = True + while changes: + changes = False + for i, state_i in enumerate(dfa): + for j in range(i+1, len(dfa)): + state_j = dfa[j] + if state_i == state_j: + #print " unify", i, j + del dfa[j] + for state in dfa: + state.unifystate(state_j, state_i) + changes = True + break + + def parse_rhs(self): + # RHS: ALT ('|' ALT)* + a, z = self.parse_alt() + if self.value != "|": + return a, z + else: + aa = NFAState() + zz = NFAState() + aa.addarc(a) + z.addarc(zz) + while self.value == "|": + self.gettoken() + a, z = self.parse_alt() + aa.addarc(a) + z.addarc(zz) + return aa, zz + + def parse_alt(self): + # ALT: ITEM+ + a, b = self.parse_item() + while (self.value in ("(", "[") or + self.type in (token.NAME, token.STRING)): + c, d = self.parse_item() + b.addarc(c) + b = d + return a, b + + def parse_item(self): + # ITEM: '[' RHS ']' | ATOM ['+' | '*'] + if self.value == "[": + self.gettoken() + a, z = self.parse_rhs() + self.expect(token.OP, "]") + a.addarc(z) + return a, z + else: + a, z = self.parse_atom() + value = self.value + if value not in ("+", "*"): + return a, z + self.gettoken() + z.addarc(a) + if value == "+": + return a, z + else: + return a, a + + def parse_atom(self): + # ATOM: '(' RHS ')' | NAME | STRING + if self.value == "(": + self.gettoken() + a, z = self.parse_rhs() + self.expect(token.OP, ")") + return a, z + elif self.type in (token.NAME, token.STRING): + a = NFAState() + z = NFAState() + a.addarc(z, self.value) + self.gettoken() + return a, z + else: + self.raise_error("expected (...) or NAME or STRING, got %s/%s", + self.type, self.value) + + def expect(self, type, value=None): + if self.type != type or (value is not None and self.value != value): + self.raise_error("expected %s/%s, got %s/%s", + type, value, self.type, self.value) + value = self.value + self.gettoken() + return value + + def gettoken(self): + tup = next(self.generator) + while tup[0] in (tokenize.COMMENT, tokenize.NL): + tup = next(self.generator) + self.type, self.value, self.begin, self.end, self.line = tup + #print token.tok_name[self.type], repr(self.value) + + def raise_error(self, msg, *args): + if args: + try: + msg = msg % args + except: + msg = " ".join([msg] + list(map(str, args))) + raise SyntaxError(msg, (self.filename, self.end[0], + self.end[1], self.line)) + +class NFAState(object): + + def __init__(self): + self.arcs = [] # list of (label, NFAState) pairs + + def addarc(self, next, label=None): + assert label is None or isinstance(label, str) + assert isinstance(next, NFAState) + self.arcs.append((label, next)) + +class DFAState(object): + + def __init__(self, nfaset, final): + assert isinstance(nfaset, dict) + assert isinstance(next(iter(nfaset)), NFAState) + assert isinstance(final, NFAState) + self.nfaset = nfaset + self.isfinal = final in nfaset + self.arcs = {} # map from label to DFAState + + def addarc(self, next, label): + assert isinstance(label, str) + assert label not in self.arcs + assert isinstance(next, DFAState) + self.arcs[label] = next + + def unifystate(self, old, new): + for label, next in self.arcs.items(): + if next is old: + self.arcs[label] = new + + def __eq__(self, other): + # Equality test -- ignore the nfaset instance variable + assert isinstance(other, DFAState) + if self.isfinal != other.isfinal: + return False + # Can't just return self.arcs == other.arcs, because that + # would invoke this method recursively, with cycles... + if len(self.arcs) != len(other.arcs): + return False + for label, next in self.arcs.items(): + if next is not other.arcs.get(label): + return False + return True + + __hash__ = None # For Py3 compatibility. + +def generate_grammar(filename="Grammar.txt"): + p = ParserGenerator(filename) + return p.make_grammar() diff --git a/micromamba_root/envs/pytorch_env/Lib/lib2to3/pgen2/token.py b/micromamba_root/envs/pytorch_env/Lib/lib2to3/pgen2/token.py new file mode 100644 index 0000000000000000000000000000000000000000..5f6612f5b30681dab79e4f71800850202c43a9aa --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/lib2to3/pgen2/token.py @@ -0,0 +1,86 @@ +#! /usr/bin/env python3 + +"""Token constants (from "token.h").""" + +# Taken from Python (r53757) and modified to include some tokens +# originally monkeypatched in by pgen2.tokenize + +#--start constants-- +ENDMARKER = 0 +NAME = 1 +NUMBER = 2 +STRING = 3 +NEWLINE = 4 +INDENT = 5 +DEDENT = 6 +LPAR = 7 +RPAR = 8 +LSQB = 9 +RSQB = 10 +COLON = 11 +COMMA = 12 +SEMI = 13 +PLUS = 14 +MINUS = 15 +STAR = 16 +SLASH = 17 +VBAR = 18 +AMPER = 19 +LESS = 20 +GREATER = 21 +EQUAL = 22 +DOT = 23 +PERCENT = 24 +BACKQUOTE = 25 +LBRACE = 26 +RBRACE = 27 +EQEQUAL = 28 +NOTEQUAL = 29 +LESSEQUAL = 30 +GREATEREQUAL = 31 +TILDE = 32 +CIRCUMFLEX = 33 +LEFTSHIFT = 34 +RIGHTSHIFT = 35 +DOUBLESTAR = 36 +PLUSEQUAL = 37 +MINEQUAL = 38 +STAREQUAL = 39 +SLASHEQUAL = 40 +PERCENTEQUAL = 41 +AMPEREQUAL = 42 +VBAREQUAL = 43 +CIRCUMFLEXEQUAL = 44 +LEFTSHIFTEQUAL = 45 +RIGHTSHIFTEQUAL = 46 +DOUBLESTAREQUAL = 47 +DOUBLESLASH = 48 +DOUBLESLASHEQUAL = 49 +AT = 50 +ATEQUAL = 51 +OP = 52 +COMMENT = 53 +NL = 54 +RARROW = 55 +AWAIT = 56 +ASYNC = 57 +ERRORTOKEN = 58 +COLONEQUAL = 59 +N_TOKENS = 60 +NT_OFFSET = 256 +#--end constants-- + +tok_name = {} +for _name, _value in list(globals().items()): + if type(_value) is type(0): + tok_name[_value] = _name + + +def ISTERMINAL(x): + return x < NT_OFFSET + +def ISNONTERMINAL(x): + return x >= NT_OFFSET + +def ISEOF(x): + return x == ENDMARKER diff --git a/micromamba_root/envs/pytorch_env/Lib/lib2to3/pgen2/tokenize.py b/micromamba_root/envs/pytorch_env/Lib/lib2to3/pgen2/tokenize.py new file mode 100644 index 0000000000000000000000000000000000000000..099dfa7798afd44b3e819e971bf4e9f376d765d4 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/lib2to3/pgen2/tokenize.py @@ -0,0 +1,564 @@ +# Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006 Python Software Foundation. +# All rights reserved. + +"""Tokenization help for Python programs. + +generate_tokens(readline) is a generator that breaks a stream of +text into Python tokens. It accepts a readline-like method which is called +repeatedly to get the next line of input (or "" for EOF). It generates +5-tuples with these members: + + the token type (see token.py) + the token (a string) + the starting (row, column) indices of the token (a 2-tuple of ints) + the ending (row, column) indices of the token (a 2-tuple of ints) + the original line (string) + +It is designed to match the working of the Python tokenizer exactly, except +that it produces COMMENT tokens for comments and gives type OP for all +operators + +Older entry points + tokenize_loop(readline, tokeneater) + tokenize(readline, tokeneater=printtoken) +are the same, except instead of generating tokens, tokeneater is a callback +function to which the 5 fields described above are passed as 5 arguments, +each time a new token is found.""" + +__author__ = 'Ka-Ping Yee ' +__credits__ = \ + 'GvR, ESR, Tim Peters, Thomas Wouters, Fred Drake, Skip Montanaro' + +import string, re +from codecs import BOM_UTF8, lookup +from lib2to3.pgen2.token import * + +from . import token +__all__ = [x for x in dir(token) if x[0] != '_'] + ["tokenize", + "generate_tokens", "untokenize"] +del token + +try: + bytes +except NameError: + # Support bytes type in Python <= 2.5, so 2to3 turns itself into + # valid Python 3 code. + bytes = str + +def group(*choices): return '(' + '|'.join(choices) + ')' +def any(*choices): return group(*choices) + '*' +def maybe(*choices): return group(*choices) + '?' +def _combinations(*l): + return set( + x + y for x in l for y in l + ("",) if x.casefold() != y.casefold() + ) + +Whitespace = r'[ \f\t]*' +Comment = r'#[^\r\n]*' +Ignore = Whitespace + any(r'\\\r?\n' + Whitespace) + maybe(Comment) +Name = r'\w+' + +Binnumber = r'0[bB]_?[01]+(?:_[01]+)*' +Hexnumber = r'0[xX]_?[\da-fA-F]+(?:_[\da-fA-F]+)*[lL]?' +Octnumber = r'0[oO]?_?[0-7]+(?:_[0-7]+)*[lL]?' +Decnumber = group(r'[1-9]\d*(?:_\d+)*[lL]?', '0[lL]?') +Intnumber = group(Binnumber, Hexnumber, Octnumber, Decnumber) +Exponent = r'[eE][-+]?\d+(?:_\d+)*' +Pointfloat = group(r'\d+(?:_\d+)*\.(?:\d+(?:_\d+)*)?', r'\.\d+(?:_\d+)*') + maybe(Exponent) +Expfloat = r'\d+(?:_\d+)*' + Exponent +Floatnumber = group(Pointfloat, Expfloat) +Imagnumber = group(r'\d+(?:_\d+)*[jJ]', Floatnumber + r'[jJ]') +Number = group(Imagnumber, Floatnumber, Intnumber) + +# Tail end of ' string. +Single = r"[^'\\]*(?:\\.[^'\\]*)*'" +# Tail end of " string. +Double = r'[^"\\]*(?:\\.[^"\\]*)*"' +# Tail end of ''' string. +Single3 = r"[^'\\]*(?:(?:\\.|'(?!''))[^'\\]*)*'''" +# Tail end of """ string. +Double3 = r'[^"\\]*(?:(?:\\.|"(?!""))[^"\\]*)*"""' +_litprefix = r"(?:[uUrRbBfF]|[rR][fFbB]|[fFbBuU][rR])?" +Triple = group(_litprefix + "'''", _litprefix + '"""') +# Single-line ' or " string. +String = group(_litprefix + r"'[^\n'\\]*(?:\\.[^\n'\\]*)*'", + _litprefix + r'"[^\n"\\]*(?:\\.[^\n"\\]*)*"') + +# Because of leftmost-then-longest match semantics, be sure to put the +# longest operators first (e.g., if = came before ==, == would get +# recognized as two instances of =). +Operator = group(r"\*\*=?", r">>=?", r"<<=?", r"<>", r"!=", + r"//=?", r"->", + r"[+\-*/%&@|^=<>]=?", + r"~") + +Bracket = '[][(){}]' +Special = group(r'\r?\n', r':=', r'[:;.,`@]') +Funny = group(Operator, Bracket, Special) + +PlainToken = group(Number, Funny, String, Name) +Token = Ignore + PlainToken + +# First (or only) line of ' or " string. +ContStr = group(_litprefix + r"'[^\n'\\]*(?:\\.[^\n'\\]*)*" + + group("'", r'\\\r?\n'), + _litprefix + r'"[^\n"\\]*(?:\\.[^\n"\\]*)*' + + group('"', r'\\\r?\n')) +PseudoExtras = group(r'\\\r?\n', Comment, Triple) +PseudoToken = Whitespace + group(PseudoExtras, Number, Funny, ContStr, Name) + +tokenprog, pseudoprog, single3prog, double3prog = map( + re.compile, (Token, PseudoToken, Single3, Double3)) + +_strprefixes = ( + _combinations('r', 'R', 'f', 'F') | + _combinations('r', 'R', 'b', 'B') | + {'u', 'U', 'ur', 'uR', 'Ur', 'UR'} +) + +endprogs = {"'": re.compile(Single), '"': re.compile(Double), + "'''": single3prog, '"""': double3prog, + **{f"{prefix}'''": single3prog for prefix in _strprefixes}, + **{f'{prefix}"""': double3prog for prefix in _strprefixes}, + **{prefix: None for prefix in _strprefixes}} + +triple_quoted = ( + {"'''", '"""'} | + {f"{prefix}'''" for prefix in _strprefixes} | + {f'{prefix}"""' for prefix in _strprefixes} +) +single_quoted = ( + {"'", '"'} | + {f"{prefix}'" for prefix in _strprefixes} | + {f'{prefix}"' for prefix in _strprefixes} +) + +tabsize = 8 + +class TokenError(Exception): pass + +class StopTokenizing(Exception): pass + +def printtoken(type, token, xxx_todo_changeme, xxx_todo_changeme1, line): # for testing + (srow, scol) = xxx_todo_changeme + (erow, ecol) = xxx_todo_changeme1 + print("%d,%d-%d,%d:\t%s\t%s" % \ + (srow, scol, erow, ecol, tok_name[type], repr(token))) + +def tokenize(readline, tokeneater=printtoken): + """ + The tokenize() function accepts two parameters: one representing the + input stream, and one providing an output mechanism for tokenize(). + + The first parameter, readline, must be a callable object which provides + the same interface as the readline() method of built-in file objects. + Each call to the function should return one line of input as a string. + + The second parameter, tokeneater, must also be a callable object. It is + called once for each token, with five arguments, corresponding to the + tuples generated by generate_tokens(). + """ + try: + tokenize_loop(readline, tokeneater) + except StopTokenizing: + pass + +# backwards compatible interface +def tokenize_loop(readline, tokeneater): + for token_info in generate_tokens(readline): + tokeneater(*token_info) + +class Untokenizer: + + def __init__(self): + self.tokens = [] + self.prev_row = 1 + self.prev_col = 0 + + def add_whitespace(self, start): + row, col = start + assert row <= self.prev_row + col_offset = col - self.prev_col + if col_offset: + self.tokens.append(" " * col_offset) + + def untokenize(self, iterable): + for t in iterable: + if len(t) == 2: + self.compat(t, iterable) + break + tok_type, token, start, end, line = t + self.add_whitespace(start) + self.tokens.append(token) + self.prev_row, self.prev_col = end + if tok_type in (NEWLINE, NL): + self.prev_row += 1 + self.prev_col = 0 + return "".join(self.tokens) + + def compat(self, token, iterable): + startline = False + indents = [] + toks_append = self.tokens.append + toknum, tokval = token + if toknum in (NAME, NUMBER): + tokval += ' ' + if toknum in (NEWLINE, NL): + startline = True + for tok in iterable: + toknum, tokval = tok[:2] + + if toknum in (NAME, NUMBER, ASYNC, AWAIT): + tokval += ' ' + + if toknum == INDENT: + indents.append(tokval) + continue + elif toknum == DEDENT: + indents.pop() + continue + elif toknum in (NEWLINE, NL): + startline = True + elif startline and indents: + toks_append(indents[-1]) + startline = False + toks_append(tokval) + +cookie_re = re.compile(r'^[ \t\f]*#.*?coding[:=][ \t]*([-\w.]+)', re.ASCII) +blank_re = re.compile(br'^[ \t\f]*(?:[#\r\n]|$)', re.ASCII) + +def _get_normal_name(orig_enc): + """Imitates get_normal_name in tokenizer.c.""" + # Only care about the first 12 characters. + enc = orig_enc[:12].lower().replace("_", "-") + if enc == "utf-8" or enc.startswith("utf-8-"): + return "utf-8" + if enc in ("latin-1", "iso-8859-1", "iso-latin-1") or \ + enc.startswith(("latin-1-", "iso-8859-1-", "iso-latin-1-")): + return "iso-8859-1" + return orig_enc + +def detect_encoding(readline): + """ + The detect_encoding() function is used to detect the encoding that should + be used to decode a Python source file. It requires one argument, readline, + in the same way as the tokenize() generator. + + It will call readline a maximum of twice, and return the encoding used + (as a string) and a list of any lines (left as bytes) it has read + in. + + It detects the encoding from the presence of a utf-8 bom or an encoding + cookie as specified in pep-0263. If both a bom and a cookie are present, but + disagree, a SyntaxError will be raised. If the encoding cookie is an invalid + charset, raise a SyntaxError. Note that if a utf-8 bom is found, + 'utf-8-sig' is returned. + + If no encoding is specified, then the default of 'utf-8' will be returned. + """ + bom_found = False + encoding = None + default = 'utf-8' + def read_or_stop(): + try: + return readline() + except StopIteration: + return bytes() + + def find_cookie(line): + try: + line_string = line.decode('ascii') + except UnicodeDecodeError: + return None + match = cookie_re.match(line_string) + if not match: + return None + encoding = _get_normal_name(match.group(1)) + try: + codec = lookup(encoding) + except LookupError: + # This behaviour mimics the Python interpreter + raise SyntaxError("unknown encoding: " + encoding) + + if bom_found: + if codec.name != 'utf-8': + # This behaviour mimics the Python interpreter + raise SyntaxError('encoding problem: utf-8') + encoding += '-sig' + return encoding + + first = read_or_stop() + if first.startswith(BOM_UTF8): + bom_found = True + first = first[3:] + default = 'utf-8-sig' + if not first: + return default, [] + + encoding = find_cookie(first) + if encoding: + return encoding, [first] + if not blank_re.match(first): + return default, [first] + + second = read_or_stop() + if not second: + return default, [first] + + encoding = find_cookie(second) + if encoding: + return encoding, [first, second] + + return default, [first, second] + +def untokenize(iterable): + """Transform tokens back into Python source code. + + Each element returned by the iterable must be a token sequence + with at least two elements, a token number and token value. If + only two tokens are passed, the resulting output is poor. + + Round-trip invariant for full input: + Untokenized source will match input source exactly + + Round-trip invariant for limited input: + # Output text will tokenize the back to the input + t1 = [tok[:2] for tok in generate_tokens(f.readline)] + newcode = untokenize(t1) + readline = iter(newcode.splitlines(1)).next + t2 = [tok[:2] for tokin generate_tokens(readline)] + assert t1 == t2 + """ + ut = Untokenizer() + return ut.untokenize(iterable) + +def generate_tokens(readline): + """ + The generate_tokens() generator requires one argument, readline, which + must be a callable object which provides the same interface as the + readline() method of built-in file objects. Each call to the function + should return one line of input as a string. Alternately, readline + can be a callable function terminating with StopIteration: + readline = open(myfile).next # Example of alternate readline + + The generator produces 5-tuples with these members: the token type; the + token string; a 2-tuple (srow, scol) of ints specifying the row and + column where the token begins in the source; a 2-tuple (erow, ecol) of + ints specifying the row and column where the token ends in the source; + and the line on which the token was found. The line passed is the + physical line. + """ + lnum = parenlev = continued = 0 + contstr, needcont = '', 0 + contline = None + indents = [0] + + # 'stashed' and 'async_*' are used for async/await parsing + stashed = None + async_def = False + async_def_indent = 0 + async_def_nl = False + + while 1: # loop over lines in stream + try: + line = readline() + except StopIteration: + line = '' + lnum = lnum + 1 + pos, max = 0, len(line) + + if contstr: # continued string + if not line: + raise TokenError("EOF in multi-line string", strstart) + endmatch = endprog.match(line) + if endmatch: + pos = end = endmatch.end(0) + yield (STRING, contstr + line[:end], + strstart, (lnum, end), contline + line) + contstr, needcont = '', 0 + contline = None + elif needcont and line[-2:] != '\\\n' and line[-3:] != '\\\r\n': + yield (ERRORTOKEN, contstr + line, + strstart, (lnum, len(line)), contline) + contstr = '' + contline = None + continue + else: + contstr = contstr + line + contline = contline + line + continue + + elif parenlev == 0 and not continued: # new statement + if not line: break + column = 0 + while pos < max: # measure leading whitespace + if line[pos] == ' ': column = column + 1 + elif line[pos] == '\t': column = (column//tabsize + 1)*tabsize + elif line[pos] == '\f': column = 0 + else: break + pos = pos + 1 + if pos == max: break + + if stashed: + yield stashed + stashed = None + + if line[pos] in '#\r\n': # skip comments or blank lines + if line[pos] == '#': + comment_token = line[pos:].rstrip('\r\n') + nl_pos = pos + len(comment_token) + yield (COMMENT, comment_token, + (lnum, pos), (lnum, pos + len(comment_token)), line) + yield (NL, line[nl_pos:], + (lnum, nl_pos), (lnum, len(line)), line) + else: + yield ((NL, COMMENT)[line[pos] == '#'], line[pos:], + (lnum, pos), (lnum, len(line)), line) + continue + + if column > indents[-1]: # count indents or dedents + indents.append(column) + yield (INDENT, line[:pos], (lnum, 0), (lnum, pos), line) + while column < indents[-1]: + if column not in indents: + raise IndentationError( + "unindent does not match any outer indentation level", + ("", lnum, pos, line)) + indents = indents[:-1] + + if async_def and async_def_indent >= indents[-1]: + async_def = False + async_def_nl = False + async_def_indent = 0 + + yield (DEDENT, '', (lnum, pos), (lnum, pos), line) + + if async_def and async_def_nl and async_def_indent >= indents[-1]: + async_def = False + async_def_nl = False + async_def_indent = 0 + + else: # continued statement + if not line: + raise TokenError("EOF in multi-line statement", (lnum, 0)) + continued = 0 + + while pos < max: + pseudomatch = pseudoprog.match(line, pos) + if pseudomatch: # scan for tokens + start, end = pseudomatch.span(1) + spos, epos, pos = (lnum, start), (lnum, end), end + token, initial = line[start:end], line[start] + + if initial in string.digits or \ + (initial == '.' and token != '.'): # ordinary number + yield (NUMBER, token, spos, epos, line) + elif initial in '\r\n': + newline = NEWLINE + if parenlev > 0: + newline = NL + elif async_def: + async_def_nl = True + if stashed: + yield stashed + stashed = None + yield (newline, token, spos, epos, line) + + elif initial == '#': + assert not token.endswith("\n") + if stashed: + yield stashed + stashed = None + yield (COMMENT, token, spos, epos, line) + elif token in triple_quoted: + endprog = endprogs[token] + endmatch = endprog.match(line, pos) + if endmatch: # all on one line + pos = endmatch.end(0) + token = line[start:pos] + if stashed: + yield stashed + stashed = None + yield (STRING, token, spos, (lnum, pos), line) + else: + strstart = (lnum, start) # multiple lines + contstr = line[start:] + contline = line + break + elif initial in single_quoted or \ + token[:2] in single_quoted or \ + token[:3] in single_quoted: + if token[-1] == '\n': # continued string + strstart = (lnum, start) + endprog = (endprogs[initial] or endprogs[token[1]] or + endprogs[token[2]]) + contstr, needcont = line[start:], 1 + contline = line + break + else: # ordinary string + if stashed: + yield stashed + stashed = None + yield (STRING, token, spos, epos, line) + elif initial.isidentifier(): # ordinary name + if token in ('async', 'await'): + if async_def: + yield (ASYNC if token == 'async' else AWAIT, + token, spos, epos, line) + continue + + tok = (NAME, token, spos, epos, line) + if token == 'async' and not stashed: + stashed = tok + continue + + if token in ('def', 'for'): + if (stashed + and stashed[0] == NAME + and stashed[1] == 'async'): + + if token == 'def': + async_def = True + async_def_indent = indents[-1] + + yield (ASYNC, stashed[1], + stashed[2], stashed[3], + stashed[4]) + stashed = None + + if stashed: + yield stashed + stashed = None + + yield tok + elif initial == '\\': # continued stmt + # This yield is new; needed for better idempotency: + if stashed: + yield stashed + stashed = None + yield (NL, token, spos, (lnum, pos), line) + continued = 1 + else: + if initial in '([{': parenlev = parenlev + 1 + elif initial in ')]}': parenlev = parenlev - 1 + if stashed: + yield stashed + stashed = None + yield (OP, token, spos, epos, line) + else: + yield (ERRORTOKEN, line[pos], + (lnum, pos), (lnum, pos+1), line) + pos = pos + 1 + + if stashed: + yield stashed + stashed = None + + for indent in indents[1:]: # pop remaining indent levels + yield (DEDENT, '', (lnum, 0), (lnum, 0), '') + yield (ENDMARKER, '', (lnum, 0), (lnum, 0), '') + +if __name__ == '__main__': # testing + import sys + if len(sys.argv) > 1: tokenize(open(sys.argv[1]).readline) + else: tokenize(sys.stdin.readline) diff --git a/micromamba_root/envs/pytorch_env/Lib/logging/__pycache__/__init__.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/logging/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2a6033ae6eadb89a8ca1a1a9eb2cc48f6210ec74 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/logging/__pycache__/__init__.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/logging/__pycache__/config.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/logging/__pycache__/config.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..27b0d2d634cae854aa951475ff8d5424955cedd7 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/logging/__pycache__/config.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/logging/__pycache__/handlers.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/logging/__pycache__/handlers.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d45da46e3751b6d3d672c2637cc9ada959692b3d Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/logging/__pycache__/handlers.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/msilib/__pycache__/__init__.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/msilib/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2cd3fca4b1761e9ca4ecf75d70f7bf9e6390e497 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/msilib/__pycache__/__init__.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/msilib/__pycache__/schema.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/msilib/__pycache__/schema.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3e66026669acae3da3a3918d813d4c30362420c1 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/msilib/__pycache__/schema.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/msilib/__pycache__/sequence.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/msilib/__pycache__/sequence.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1624a22da1cc9954b5be3e98b479c1bf0c89cde7 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/msilib/__pycache__/sequence.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/msilib/__pycache__/text.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/msilib/__pycache__/text.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9cc8dc5934d583778e332887471d9f43ad3e3568 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/msilib/__pycache__/text.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/multiprocessing/__pycache__/__init__.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/multiprocessing/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0628e80718141e28bcf3bae0de12d6bd75a4e18b Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/multiprocessing/__pycache__/__init__.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/multiprocessing/__pycache__/connection.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/multiprocessing/__pycache__/connection.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..83b8daa4ab1682eee713555a3e7750f6d1d0b201 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/multiprocessing/__pycache__/connection.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/multiprocessing/__pycache__/context.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/multiprocessing/__pycache__/context.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3ff077678fccdb29de032273f9c4b4f3ad5d6058 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/multiprocessing/__pycache__/context.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/multiprocessing/__pycache__/forkserver.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/multiprocessing/__pycache__/forkserver.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0dd07e1d775248ed3cfbb167fccbada02c123d0a Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/multiprocessing/__pycache__/forkserver.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/multiprocessing/__pycache__/heap.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/multiprocessing/__pycache__/heap.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6460de71af85d0ae128dfb3ffeeb6079d16b9ad9 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/multiprocessing/__pycache__/heap.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/multiprocessing/__pycache__/managers.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/multiprocessing/__pycache__/managers.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..39a416f41ae9a48a378fbe5ea4b2626e2566e094 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/multiprocessing/__pycache__/managers.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/multiprocessing/__pycache__/pool.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/multiprocessing/__pycache__/pool.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ff37b1ec8d6952f61b53428edeb3fe923c8a98f8 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/multiprocessing/__pycache__/pool.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/multiprocessing/__pycache__/popen_fork.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/multiprocessing/__pycache__/popen_fork.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8a783f4a1c521efd6d9c9d8145820959fdb4c065 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/multiprocessing/__pycache__/popen_fork.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/multiprocessing/__pycache__/popen_forkserver.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/multiprocessing/__pycache__/popen_forkserver.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..213303b2c363acdd1a793278fef59963a31f4c92 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/multiprocessing/__pycache__/popen_forkserver.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/multiprocessing/__pycache__/popen_spawn_posix.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/multiprocessing/__pycache__/popen_spawn_posix.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a7b4016d3397d16acffce46da4fd3b319bda265f Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/multiprocessing/__pycache__/popen_spawn_posix.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/multiprocessing/__pycache__/popen_spawn_win32.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/multiprocessing/__pycache__/popen_spawn_win32.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9f01ce687fa87b0286d3896585f3430855806a0c Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/multiprocessing/__pycache__/popen_spawn_win32.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/multiprocessing/__pycache__/process.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/multiprocessing/__pycache__/process.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..840206fe2a77c14b5593409cb9b3fd800831bc13 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/multiprocessing/__pycache__/process.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/multiprocessing/__pycache__/queues.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/multiprocessing/__pycache__/queues.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d6620501ae6794a1d69592ec17c16d8a8a9c5b9d Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/multiprocessing/__pycache__/queues.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/multiprocessing/__pycache__/reduction.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/multiprocessing/__pycache__/reduction.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..476171b5b8d5f6c04eda8d1386c453aa0b75a3c9 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/multiprocessing/__pycache__/reduction.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/multiprocessing/__pycache__/resource_sharer.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/multiprocessing/__pycache__/resource_sharer.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2e3135502ea702f3a74da121edbf7252d505f5aa Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/multiprocessing/__pycache__/resource_sharer.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/multiprocessing/__pycache__/resource_tracker.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/multiprocessing/__pycache__/resource_tracker.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b7862e91556734847b203b77888290a02463e7ae Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/multiprocessing/__pycache__/resource_tracker.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/multiprocessing/__pycache__/shared_memory.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/multiprocessing/__pycache__/shared_memory.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..57e0ab12212ea39142e18992ba50910f4961b420 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/multiprocessing/__pycache__/shared_memory.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/multiprocessing/__pycache__/sharedctypes.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/multiprocessing/__pycache__/sharedctypes.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7f0a900ea40265f93613b4c6c7e16a3d542c65b3 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/multiprocessing/__pycache__/sharedctypes.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/multiprocessing/__pycache__/spawn.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/multiprocessing/__pycache__/spawn.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ca4e90e597a646478247cbcd826e7d1cb4f54f63 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/multiprocessing/__pycache__/spawn.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/multiprocessing/__pycache__/synchronize.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/multiprocessing/__pycache__/synchronize.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1ad85bcb08a5f47e64f0ee02a9e7bfdba8a947ba Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/multiprocessing/__pycache__/synchronize.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/multiprocessing/__pycache__/util.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/multiprocessing/__pycache__/util.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..381fd832eeee186137223eefd49aaf8154468d23 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/multiprocessing/__pycache__/util.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/multiprocessing/dummy/__init__.py b/micromamba_root/envs/pytorch_env/Lib/multiprocessing/dummy/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..6a1468609e347b3a0b9281e5c9e6ec311fcb37e5 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/multiprocessing/dummy/__init__.py @@ -0,0 +1,126 @@ +# +# Support for the API of the multiprocessing package using threads +# +# multiprocessing/dummy/__init__.py +# +# Copyright (c) 2006-2008, R Oudkerk +# Licensed to PSF under a Contributor Agreement. +# + +__all__ = [ + 'Process', 'current_process', 'active_children', 'freeze_support', + 'Lock', 'RLock', 'Semaphore', 'BoundedSemaphore', 'Condition', + 'Event', 'Barrier', 'Queue', 'Manager', 'Pipe', 'Pool', 'JoinableQueue' + ] + +# +# Imports +# + +import threading +import sys +import weakref +import array + +from .connection import Pipe +from threading import Lock, RLock, Semaphore, BoundedSemaphore +from threading import Event, Condition, Barrier +from queue import Queue + +# +# +# + +class DummyProcess(threading.Thread): + + def __init__(self, group=None, target=None, name=None, args=(), kwargs={}): + threading.Thread.__init__(self, group, target, name, args, kwargs) + self._pid = None + self._children = weakref.WeakKeyDictionary() + self._start_called = False + self._parent = current_process() + + def start(self): + if self._parent is not current_process(): + raise RuntimeError( + "Parent is {0!r} but current_process is {1!r}".format( + self._parent, current_process())) + self._start_called = True + if hasattr(self._parent, '_children'): + self._parent._children[self] = None + threading.Thread.start(self) + + @property + def exitcode(self): + if self._start_called and not self.is_alive(): + return 0 + else: + return None + +# +# +# + +Process = DummyProcess +current_process = threading.current_thread +current_process()._children = weakref.WeakKeyDictionary() + +def active_children(): + children = current_process()._children + for p in list(children): + if not p.is_alive(): + children.pop(p, None) + return list(children) + +def freeze_support(): + pass + +# +# +# + +class Namespace(object): + def __init__(self, /, **kwds): + self.__dict__.update(kwds) + def __repr__(self): + items = list(self.__dict__.items()) + temp = [] + for name, value in items: + if not name.startswith('_'): + temp.append('%s=%r' % (name, value)) + temp.sort() + return '%s(%s)' % (self.__class__.__name__, ', '.join(temp)) + +dict = dict +list = list + +def Array(typecode, sequence, lock=True): + return array.array(typecode, sequence) + +class Value(object): + def __init__(self, typecode, value, lock=True): + self._typecode = typecode + self._value = value + + @property + def value(self): + return self._value + + @value.setter + def value(self, value): + self._value = value + + def __repr__(self): + return '<%s(%r, %r)>'%(type(self).__name__,self._typecode,self._value) + +def Manager(): + return sys.modules[__name__] + +def shutdown(): + pass + +def Pool(processes=None, initializer=None, initargs=()): + from ..pool import ThreadPool + return ThreadPool(processes, initializer, initargs) + +JoinableQueue = Queue diff --git a/micromamba_root/envs/pytorch_env/Lib/multiprocessing/dummy/__pycache__/__init__.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/multiprocessing/dummy/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e099a18be286241f3418713d935ba614596d62fe Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/multiprocessing/dummy/__pycache__/__init__.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/multiprocessing/dummy/__pycache__/connection.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/multiprocessing/dummy/__pycache__/connection.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ee71682ed47a344b21fc3ed84ff5c077cc760b21 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/multiprocessing/dummy/__pycache__/connection.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/multiprocessing/dummy/connection.py b/micromamba_root/envs/pytorch_env/Lib/multiprocessing/dummy/connection.py new file mode 100644 index 0000000000000000000000000000000000000000..f0ce320fcf514083f3a6477e87abf40e9719285a --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/multiprocessing/dummy/connection.py @@ -0,0 +1,75 @@ +# +# Analogue of `multiprocessing.connection` which uses queues instead of sockets +# +# multiprocessing/dummy/connection.py +# +# Copyright (c) 2006-2008, R Oudkerk +# Licensed to PSF under a Contributor Agreement. +# + +__all__ = [ 'Client', 'Listener', 'Pipe' ] + +from queue import Queue + + +families = [None] + + +class Listener(object): + + def __init__(self, address=None, family=None, backlog=1): + self._backlog_queue = Queue(backlog) + + def accept(self): + return Connection(*self._backlog_queue.get()) + + def close(self): + self._backlog_queue = None + + @property + def address(self): + return self._backlog_queue + + def __enter__(self): + return self + + def __exit__(self, exc_type, exc_value, exc_tb): + self.close() + + +def Client(address): + _in, _out = Queue(), Queue() + address.put((_out, _in)) + return Connection(_in, _out) + + +def Pipe(duplex=True): + a, b = Queue(), Queue() + return Connection(a, b), Connection(b, a) + + +class Connection(object): + + def __init__(self, _in, _out): + self._out = _out + self._in = _in + self.send = self.send_bytes = _out.put + self.recv = self.recv_bytes = _in.get + + def poll(self, timeout=0.0): + if self._in.qsize() > 0: + return True + if timeout <= 0.0: + return False + with self._in.not_empty: + self._in.not_empty.wait(timeout) + return self._in.qsize() > 0 + + def close(self): + pass + + def __enter__(self): + return self + + def __exit__(self, exc_type, exc_value, exc_tb): + self.close() diff --git a/micromamba_root/envs/pytorch_env/Lib/pydoc_data/__pycache__/__init__.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/pydoc_data/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..646e567e63ec93a413eca686ed22473de737c10f Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/pydoc_data/__pycache__/__init__.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/re/__pycache__/__init__.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/re/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a969b9efc7a41d3d8e68c9c3236b6e7d5d19509a Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/re/__pycache__/__init__.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/re/__pycache__/_casefix.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/re/__pycache__/_casefix.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3c6a0ff006b3338cad180968bad7dd5b168cf6d7 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/re/__pycache__/_casefix.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/re/__pycache__/_compiler.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/re/__pycache__/_compiler.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9c4c9812ce1f126126527a38b73a4c069af17686 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/re/__pycache__/_compiler.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/re/__pycache__/_constants.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/re/__pycache__/_constants.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ab6d1ce9fd39fa4c356196e4fe2222b302b9ad77 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/re/__pycache__/_constants.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/re/__pycache__/_parser.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/re/__pycache__/_parser.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..25dc707764d3578539d096cabda538af4593d1da Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/re/__pycache__/_parser.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/aiohappyeyeballs/__pycache__/__init__.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/aiohappyeyeballs/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b8772e52882d11361ab079b799e5048e2d9ffb97 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/aiohappyeyeballs/__pycache__/__init__.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/aiohappyeyeballs/__pycache__/_staggered.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/aiohappyeyeballs/__pycache__/_staggered.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..74b7101634a0fb38c3273e74e54c85b1ad46cc6d Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/aiohappyeyeballs/__pycache__/_staggered.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/aiohappyeyeballs/__pycache__/impl.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/aiohappyeyeballs/__pycache__/impl.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f1f0a5ccecdf934cdb17e5347fd0342506f1c3c4 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/aiohappyeyeballs/__pycache__/impl.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/aiohappyeyeballs/__pycache__/types.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/aiohappyeyeballs/__pycache__/types.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..45c80d9722d8dd7c1cfd2998ff68742b784fd4e4 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/aiohappyeyeballs/__pycache__/types.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/aiohappyeyeballs/__pycache__/utils.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/aiohappyeyeballs/__pycache__/utils.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b7bf56c2245063d38edb78f579a5724213fd5954 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/aiohappyeyeballs/__pycache__/utils.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/aiohttp-3.13.5.dist-info/licenses/LICENSE.txt b/micromamba_root/envs/pytorch_env/Lib/site-packages/aiohttp-3.13.5.dist-info/licenses/LICENSE.txt new file mode 100644 index 0000000000000000000000000000000000000000..aa2bc24043c1dddac90e74eba3ff92b848515898 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/aiohttp-3.13.5.dist-info/licenses/LICENSE.txt @@ -0,0 +1,13 @@ + Copyright aio-libs contributors. + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/aiohttp-3.13.5.dist-info/licenses/vendor/llhttp/LICENSE b/micromamba_root/envs/pytorch_env/Lib/site-packages/aiohttp-3.13.5.dist-info/licenses/vendor/llhttp/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..ea78c2ce8e7ed1ecc147ee70e9b87ae7e2589032 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/aiohttp-3.13.5.dist-info/licenses/vendor/llhttp/LICENSE @@ -0,0 +1,22 @@ +This software is licensed under the MIT License. + +Copyright Fedor Indutny, 2018. + +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/micromamba_root/envs/pytorch_env/Lib/site-packages/aiohttp/.hash/_cparser.pxd.hash b/micromamba_root/envs/pytorch_env/Lib/site-packages/aiohttp/.hash/_cparser.pxd.hash new file mode 100644 index 0000000000000000000000000000000000000000..532200984381857fef80d3876a69beb4ed47bf56 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/aiohttp/.hash/_cparser.pxd.hash @@ -0,0 +1 @@ +18fd18f4da996101a426d4bcd570f353bd1eeeb44c6f7e1347bc86326c79ff3b *D:/a/aiohttp/aiohttp/aiohttp/_cparser.pxd diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/aiohttp/.hash/_find_header.pxd.hash b/micromamba_root/envs/pytorch_env/Lib/site-packages/aiohttp/.hash/_find_header.pxd.hash new file mode 100644 index 0000000000000000000000000000000000000000..8af9f81d71e4e4ee436f4bf3e6f95940e5f3666e --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/aiohttp/.hash/_find_header.pxd.hash @@ -0,0 +1 @@ +0455129b185e981b5b96ac738f31f7c74dc57f1696953cae0083b3f18679fe73 *D:/a/aiohttp/aiohttp/aiohttp/_find_header.pxd diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/aiohttp/.hash/_http_parser.pyx.hash b/micromamba_root/envs/pytorch_env/Lib/site-packages/aiohttp/.hash/_http_parser.pyx.hash new file mode 100644 index 0000000000000000000000000000000000000000..2c1168340a655fe41977aef4d9914074ea2c2deb --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/aiohttp/.hash/_http_parser.pyx.hash @@ -0,0 +1 @@ +9e16082d2392b4371d43132603b1a419b785a9b023b0a5d3e36887f21deee2b7 *D:/a/aiohttp/aiohttp/aiohttp/_http_parser.pyx diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/aiohttp/.hash/_http_writer.pyx.hash b/micromamba_root/envs/pytorch_env/Lib/site-packages/aiohttp/.hash/_http_writer.pyx.hash new file mode 100644 index 0000000000000000000000000000000000000000..70535a58830645e4963096259dfbb8e943c97a52 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/aiohttp/.hash/_http_writer.pyx.hash @@ -0,0 +1 @@ +dc6d27fe46580e824474374833c8df8ce117c905cc4cff74ad99ec1a1918bf1c *D:/a/aiohttp/aiohttp/aiohttp/_http_writer.pyx diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/aiohttp/.hash/hdrs.py.hash b/micromamba_root/envs/pytorch_env/Lib/site-packages/aiohttp/.hash/hdrs.py.hash new file mode 100644 index 0000000000000000000000000000000000000000..e4f3c29cbe63e8a58f5406efa6bb550f60d2c537 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/aiohttp/.hash/hdrs.py.hash @@ -0,0 +1 @@ +ee1b6686067213d1ea59b3e9c47534afb90021d4f692939741ad4069d0e1d96f *D:/a/aiohttp/aiohttp/aiohttp/hdrs.py diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/aiohttp/__pycache__/__init__.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/aiohttp/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0d5b7e3407e1fa5675c09fbdc722e58de2aca552 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/aiohttp/__pycache__/__init__.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/aiohttp/__pycache__/_cookie_helpers.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/aiohttp/__pycache__/_cookie_helpers.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..449bf2ef768b19b3ce3278f71c968e6519402db6 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/aiohttp/__pycache__/_cookie_helpers.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/aiohttp/__pycache__/abc.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/aiohttp/__pycache__/abc.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..29f75ea322f13d36367f851884767e1c434bb59e Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/aiohttp/__pycache__/abc.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/aiohttp/__pycache__/base_protocol.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/aiohttp/__pycache__/base_protocol.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..eb33de3227a948e1daca289f3ae16406f7d06d90 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/aiohttp/__pycache__/base_protocol.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/aiohttp/__pycache__/client.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/aiohttp/__pycache__/client.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d8ef8165e401b48dcd906083d9dc332660324737 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/aiohttp/__pycache__/client.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/aiohttp/__pycache__/client_exceptions.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/aiohttp/__pycache__/client_exceptions.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..45d7290711df3aa914550542b20b8fe732d8dd42 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/aiohttp/__pycache__/client_exceptions.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/aiohttp/__pycache__/client_middleware_digest_auth.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/aiohttp/__pycache__/client_middleware_digest_auth.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..62cfa7780f51845babc7755af679b56070ccacda Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/aiohttp/__pycache__/client_middleware_digest_auth.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/aiohttp/__pycache__/client_middlewares.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/aiohttp/__pycache__/client_middlewares.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..15d8fb316d319bd8116635ceb78dba44cbbfd27a Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/aiohttp/__pycache__/client_middlewares.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/aiohttp/__pycache__/client_proto.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/aiohttp/__pycache__/client_proto.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5cd43ab0ef5270a838d2031c0df63a043ac6424d Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/aiohttp/__pycache__/client_proto.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/aiohttp/__pycache__/client_reqrep.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/aiohttp/__pycache__/client_reqrep.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9ab8de6d476d61eab0e488fe9afe2270e2c69b88 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/aiohttp/__pycache__/client_reqrep.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/aiohttp/__pycache__/client_ws.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/aiohttp/__pycache__/client_ws.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9a06db3d40dbcf5546b5c7083401f7c772a4c07f Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/aiohttp/__pycache__/client_ws.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/aiohttp/__pycache__/compression_utils.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/aiohttp/__pycache__/compression_utils.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8a9db5836401a9055b697b87a58d6c32f23d2eab Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/aiohttp/__pycache__/compression_utils.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/aiohttp/__pycache__/connector.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/aiohttp/__pycache__/connector.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..46c4ca2446ea7160d5df9e2601b674463d49d679 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/aiohttp/__pycache__/connector.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/aiohttp/__pycache__/cookiejar.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/aiohttp/__pycache__/cookiejar.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5187e8f02aa89fa295e92724d8b18eacd832232f Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/aiohttp/__pycache__/cookiejar.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/aiohttp/__pycache__/formdata.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/aiohttp/__pycache__/formdata.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b93ab861aa85bbf5e587f57fa5da1f349d2ffcb6 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/aiohttp/__pycache__/formdata.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/aiohttp/__pycache__/hdrs.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/aiohttp/__pycache__/hdrs.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6742ae86914cb4e62756a18025b0b99771384fda Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/aiohttp/__pycache__/hdrs.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/aiohttp/__pycache__/helpers.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/aiohttp/__pycache__/helpers.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..62737245a8a3787cbae44f94c6ef83131d7b405a Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/aiohttp/__pycache__/helpers.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/aiohttp/__pycache__/http.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/aiohttp/__pycache__/http.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..87f0205dd91a321b7ed94aea1bd18619beab9f1f Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/aiohttp/__pycache__/http.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/aiohttp/__pycache__/http_exceptions.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/aiohttp/__pycache__/http_exceptions.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e3a0ac1066b26f77e6ef6462163534b7b074eaf0 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/aiohttp/__pycache__/http_exceptions.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/aiohttp/__pycache__/http_parser.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/aiohttp/__pycache__/http_parser.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e490a1354c77abbe8d094a66c9a7a5966a612fb9 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/aiohttp/__pycache__/http_parser.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/aiohttp/__pycache__/http_websocket.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/aiohttp/__pycache__/http_websocket.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ffc7ed1efed019fb908893ff077aeb8019ba24f6 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/aiohttp/__pycache__/http_websocket.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/aiohttp/__pycache__/http_writer.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/aiohttp/__pycache__/http_writer.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..183875c4df717febd5ea2ca7bcf078e615003d7e Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/aiohttp/__pycache__/http_writer.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/aiohttp/__pycache__/log.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/aiohttp/__pycache__/log.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..692dfff8535366bf90d827dbd6952cd6c8ce9803 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/aiohttp/__pycache__/log.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/aiohttp/__pycache__/multipart.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/aiohttp/__pycache__/multipart.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..697031ce90831345289b74085d2ecaadcda24605 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/aiohttp/__pycache__/multipart.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/aiohttp/__pycache__/payload.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/aiohttp/__pycache__/payload.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..66713e3b04807261f0817d2beac0527df555a567 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/aiohttp/__pycache__/payload.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/aiohttp/__pycache__/payload_streamer.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/aiohttp/__pycache__/payload_streamer.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..50f0d6441bea50f698911d9171c4febd5cf3aef6 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/aiohttp/__pycache__/payload_streamer.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/aiohttp/__pycache__/pytest_plugin.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/aiohttp/__pycache__/pytest_plugin.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e71c9fcee5ad5c5953740cb5156ef476eb9db50c Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/aiohttp/__pycache__/pytest_plugin.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/aiohttp/__pycache__/resolver.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/aiohttp/__pycache__/resolver.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..407215c7ca031a865caf6dac477e9fabba21696a Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/aiohttp/__pycache__/resolver.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/aiohttp/__pycache__/streams.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/aiohttp/__pycache__/streams.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c7c9d17e6e5f21db699f4655a13db0a4e95026d4 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/aiohttp/__pycache__/streams.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/aiohttp/__pycache__/tcp_helpers.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/aiohttp/__pycache__/tcp_helpers.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..74905eb9d1bbfcbb290ffec67db94f8409f66b9c Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/aiohttp/__pycache__/tcp_helpers.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/aiohttp/__pycache__/test_utils.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/aiohttp/__pycache__/test_utils.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..527ff9e83f2c60c8e9ecb093f49f03237ccc3536 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/aiohttp/__pycache__/test_utils.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/aiohttp/__pycache__/tracing.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/aiohttp/__pycache__/tracing.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..107e5a2fc07693bb1a97f6330ff2aeaef71f136b Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/aiohttp/__pycache__/tracing.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/aiohttp/__pycache__/typedefs.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/aiohttp/__pycache__/typedefs.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0e6be51519700867b633c617431d8bd08c43aa74 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/aiohttp/__pycache__/typedefs.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/aiohttp/__pycache__/web.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/aiohttp/__pycache__/web.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ffa8ae8b5c317061f2b0c872fdbcf2658adecc9f Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/aiohttp/__pycache__/web.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/aiohttp/__pycache__/web_app.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/aiohttp/__pycache__/web_app.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ecdaae93f2b39b07a31350de3c2713717fab5273 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/aiohttp/__pycache__/web_app.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/aiohttp/__pycache__/web_exceptions.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/aiohttp/__pycache__/web_exceptions.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1e661bf76d9133b194658820e8be71191cfb64ae Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/aiohttp/__pycache__/web_exceptions.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/aiohttp/__pycache__/web_fileresponse.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/aiohttp/__pycache__/web_fileresponse.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e057d4af125f9c49007cb98ca311cc4de5be8992 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/aiohttp/__pycache__/web_fileresponse.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/aiohttp/__pycache__/web_log.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/aiohttp/__pycache__/web_log.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1c0fe1d8a79dab93a4d4085093582121deefd741 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/aiohttp/__pycache__/web_log.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/aiohttp/__pycache__/web_middlewares.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/aiohttp/__pycache__/web_middlewares.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f7e776d059d5bedc36b2aedee40347959e87e838 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/aiohttp/__pycache__/web_middlewares.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/aiohttp/__pycache__/web_protocol.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/aiohttp/__pycache__/web_protocol.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1c9604c83fe31f890e97a891c6ed65922be0603c Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/aiohttp/__pycache__/web_protocol.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/aiohttp/__pycache__/web_request.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/aiohttp/__pycache__/web_request.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9a49b7ab66fe61f93bc1a697984d15a9a91b5c60 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/aiohttp/__pycache__/web_request.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/aiohttp/__pycache__/web_response.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/aiohttp/__pycache__/web_response.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..56c4ab39c3e0402ad1ade776b91e9a1cdbd217a0 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/aiohttp/__pycache__/web_response.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/aiohttp/__pycache__/web_routedef.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/aiohttp/__pycache__/web_routedef.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..240accfeeafefbb430088a4d1e88d1ce3486d45d Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/aiohttp/__pycache__/web_routedef.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/aiohttp/__pycache__/web_runner.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/aiohttp/__pycache__/web_runner.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6f378aa39a73756aa51a0b6264f4f98a0394eb88 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/aiohttp/__pycache__/web_runner.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/aiohttp/__pycache__/web_server.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/aiohttp/__pycache__/web_server.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f88352599860487d67eccd99122fe52f676f8977 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/aiohttp/__pycache__/web_server.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/aiohttp/__pycache__/web_urldispatcher.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/aiohttp/__pycache__/web_urldispatcher.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1a65f2147b1de6a8df2c768f07caa085e6012032 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/aiohttp/__pycache__/web_urldispatcher.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/aiohttp/__pycache__/web_ws.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/aiohttp/__pycache__/web_ws.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..93e637cbde9f2e84b7ca4fde31c6856c65139404 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/aiohttp/__pycache__/web_ws.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/aiohttp/__pycache__/worker.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/aiohttp/__pycache__/worker.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..dd239049540b761100d57d6f96135d1424ebd359 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/aiohttp/__pycache__/worker.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/aiohttp/_websocket/.hash/mask.pxd.hash b/micromamba_root/envs/pytorch_env/Lib/site-packages/aiohttp/_websocket/.hash/mask.pxd.hash new file mode 100644 index 0000000000000000000000000000000000000000..59ec1233e51ca80d766bc036bbfcc1fded2bb7dc --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/aiohttp/_websocket/.hash/mask.pxd.hash @@ -0,0 +1 @@ +e354dd499be171b6125bf56bc3b6c5e2bff2a28af69e3b5d699ddb9af2bafa3c *D:/a/aiohttp/aiohttp/aiohttp/_websocket/mask.pxd diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/aiohttp/_websocket/.hash/mask.pyx.hash b/micromamba_root/envs/pytorch_env/Lib/site-packages/aiohttp/_websocket/.hash/mask.pyx.hash new file mode 100644 index 0000000000000000000000000000000000000000..025189ec4bd962d7b10b160b40f6faab3db37c9b --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/aiohttp/_websocket/.hash/mask.pyx.hash @@ -0,0 +1 @@ +468edd38ebf8dc7000a8d333df1c82035d69a5c9febc0448be3c9c4ad4c4630c *D:/a/aiohttp/aiohttp/aiohttp/_websocket/mask.pyx diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/aiohttp/_websocket/.hash/reader_c.pxd.hash b/micromamba_root/envs/pytorch_env/Lib/site-packages/aiohttp/_websocket/.hash/reader_c.pxd.hash new file mode 100644 index 0000000000000000000000000000000000000000..0f260dc6af7e9b6d667dae196c00eee6d6689f62 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/aiohttp/_websocket/.hash/reader_c.pxd.hash @@ -0,0 +1 @@ +1cd3a5e20456b4d04d11835b2bd3c639f14443052a2467b105b0ca07fdb4b25d *D:/a/aiohttp/aiohttp/aiohttp/_websocket/reader_c.pxd diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/aiohttp/_websocket/__init__.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/aiohttp/_websocket/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..a00ebcf833d69d49c9f0b2167f1b31623c6cf6d1 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/aiohttp/_websocket/__init__.py @@ -0,0 +1 @@ +"""WebSocket protocol versions 13 and 8.""" diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/aiohttp/_websocket/__pycache__/__init__.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/aiohttp/_websocket/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b32de17c20de411a0939c7ccfe83bfcb20743d63 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/aiohttp/_websocket/__pycache__/__init__.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/aiohttp/_websocket/__pycache__/helpers.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/aiohttp/_websocket/__pycache__/helpers.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9b2e5382d2378a262f199249d7203f1bffc781b3 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/aiohttp/_websocket/__pycache__/helpers.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/aiohttp/_websocket/__pycache__/models.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/aiohttp/_websocket/__pycache__/models.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..451d277bbb6274397706b969684e7278eacd26ee Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/aiohttp/_websocket/__pycache__/models.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/aiohttp/_websocket/__pycache__/reader.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/aiohttp/_websocket/__pycache__/reader.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e6f93a4b46c1e5e35b830b3cfb102464c74f7847 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/aiohttp/_websocket/__pycache__/reader.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/aiohttp/_websocket/__pycache__/reader_c.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/aiohttp/_websocket/__pycache__/reader_c.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..77b1e25caafcfb0ae84ba20f596a204a0b253473 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/aiohttp/_websocket/__pycache__/reader_c.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/aiohttp/_websocket/__pycache__/reader_py.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/aiohttp/_websocket/__pycache__/reader_py.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8e255e2f427beae698bab19bba042be51a3c0955 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/aiohttp/_websocket/__pycache__/reader_py.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/aiohttp/_websocket/__pycache__/writer.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/aiohttp/_websocket/__pycache__/writer.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ab0da5f20fd9278dd85f3ca4f62fe006a4890071 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/aiohttp/_websocket/__pycache__/writer.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/aiohttp/_websocket/helpers.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/aiohttp/_websocket/helpers.py new file mode 100644 index 0000000000000000000000000000000000000000..3f96ed1760f377ac2d514113aba2a7bdab9a300f --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/aiohttp/_websocket/helpers.py @@ -0,0 +1,147 @@ +"""Helpers for WebSocket protocol versions 13 and 8.""" + +import functools +import re +from struct import Struct +from typing import TYPE_CHECKING, Final, List, Optional, Pattern, Tuple + +from ..helpers import NO_EXTENSIONS +from .models import WSHandshakeError + +UNPACK_LEN3 = Struct("!Q").unpack_from +UNPACK_CLOSE_CODE = Struct("!H").unpack +PACK_LEN1 = Struct("!BB").pack +PACK_LEN2 = Struct("!BBH").pack +PACK_LEN3 = Struct("!BBQ").pack +PACK_CLOSE_CODE = Struct("!H").pack +PACK_RANDBITS = Struct("!L").pack +MSG_SIZE: Final[int] = 2**14 +MASK_LEN: Final[int] = 4 + +WS_KEY: Final[bytes] = b"258EAFA5-E914-47DA-95CA-C5AB0DC85B11" + + +# Used by _websocket_mask_python +@functools.lru_cache +def _xor_table() -> List[bytes]: + return [bytes(a ^ b for a in range(256)) for b in range(256)] + + +def _websocket_mask_python(mask: bytes, data: bytearray) -> None: + """Websocket masking function. + + `mask` is a `bytes` object of length 4; `data` is a `bytearray` + object of any length. The contents of `data` are masked with `mask`, + as specified in section 5.3 of RFC 6455. + + Note that this function mutates the `data` argument. + + This pure-python implementation may be replaced by an optimized + version when available. + + """ + assert isinstance(data, bytearray), data + assert len(mask) == 4, mask + + if data: + _XOR_TABLE = _xor_table() + a, b, c, d = (_XOR_TABLE[n] for n in mask) + data[::4] = data[::4].translate(a) + data[1::4] = data[1::4].translate(b) + data[2::4] = data[2::4].translate(c) + data[3::4] = data[3::4].translate(d) + + +if TYPE_CHECKING or NO_EXTENSIONS: # pragma: no cover + websocket_mask = _websocket_mask_python +else: + try: + from .mask import _websocket_mask_cython # type: ignore[import-not-found] + + websocket_mask = _websocket_mask_cython + except ImportError: # pragma: no cover + websocket_mask = _websocket_mask_python + + +_WS_EXT_RE: Final[Pattern[str]] = re.compile( + r"^(?:;\s*(?:" + r"(server_no_context_takeover)|" + r"(client_no_context_takeover)|" + r"(server_max_window_bits(?:=(\d+))?)|" + r"(client_max_window_bits(?:=(\d+))?)))*$" +) + +_WS_EXT_RE_SPLIT: Final[Pattern[str]] = re.compile(r"permessage-deflate([^,]+)?") + + +def ws_ext_parse(extstr: Optional[str], isserver: bool = False) -> Tuple[int, bool]: + if not extstr: + return 0, False + + compress = 0 + notakeover = False + for ext in _WS_EXT_RE_SPLIT.finditer(extstr): + defext = ext.group(1) + # Return compress = 15 when get `permessage-deflate` + if not defext: + compress = 15 + break + match = _WS_EXT_RE.match(defext) + if match: + compress = 15 + if isserver: + # Server never fail to detect compress handshake. + # Server does not need to send max wbit to client + if match.group(4): + compress = int(match.group(4)) + # Group3 must match if group4 matches + # Compress wbit 8 does not support in zlib + # If compress level not support, + # CONTINUE to next extension + if compress > 15 or compress < 9: + compress = 0 + continue + if match.group(1): + notakeover = True + # Ignore regex group 5 & 6 for client_max_window_bits + break + else: + if match.group(6): + compress = int(match.group(6)) + # Group5 must match if group6 matches + # Compress wbit 8 does not support in zlib + # If compress level not support, + # FAIL the parse progress + if compress > 15 or compress < 9: + raise WSHandshakeError("Invalid window size") + if match.group(2): + notakeover = True + # Ignore regex group 5 & 6 for client_max_window_bits + break + # Return Fail if client side and not match + elif not isserver: + raise WSHandshakeError("Extension for deflate not supported" + ext.group(1)) + + return compress, notakeover + + +def ws_ext_gen( + compress: int = 15, isserver: bool = False, server_notakeover: bool = False +) -> str: + # client_notakeover=False not used for server + # compress wbit 8 does not support in zlib + if compress < 9 or compress > 15: + raise ValueError( + "Compress wbits must between 9 and 15, zlib does not support wbits=8" + ) + enabledext = ["permessage-deflate"] + if not isserver: + enabledext.append("client_max_window_bits") + + if compress < 15: + enabledext.append("server_max_window_bits=" + str(compress)) + if server_notakeover: + enabledext.append("server_no_context_takeover") + # if client_notakeover: + # enabledext.append('client_no_context_takeover') + return "; ".join(enabledext) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/aiohttp/_websocket/mask.cp311-win_amd64.pyd b/micromamba_root/envs/pytorch_env/Lib/site-packages/aiohttp/_websocket/mask.cp311-win_amd64.pyd new file mode 100644 index 0000000000000000000000000000000000000000..521b0957087a048952621718eeb7492045e03c13 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/aiohttp/_websocket/mask.cp311-win_amd64.pyd differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/aiohttp/_websocket/mask.pxd b/micromamba_root/envs/pytorch_env/Lib/site-packages/aiohttp/_websocket/mask.pxd new file mode 100644 index 0000000000000000000000000000000000000000..90ab78fd06aa6cd4639795f06f15eb07f5404834 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/aiohttp/_websocket/mask.pxd @@ -0,0 +1,3 @@ +"""Cython declarations for websocket masking.""" + +cpdef void _websocket_mask_cython(bytes mask, bytearray data) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/aiohttp/_websocket/mask.pyx b/micromamba_root/envs/pytorch_env/Lib/site-packages/aiohttp/_websocket/mask.pyx new file mode 100644 index 0000000000000000000000000000000000000000..ef61b76217b5cf9071f716aeedee377a3bbb7517 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/aiohttp/_websocket/mask.pyx @@ -0,0 +1,48 @@ +from cpython cimport PyBytes_AsString + + +#from cpython cimport PyByteArray_AsString # cython still not exports that +cdef extern from "Python.h": + char* PyByteArray_AsString(bytearray ba) except NULL + +from libc.stdint cimport uint32_t, uint64_t, uintmax_t + + +cpdef void _websocket_mask_cython(bytes mask, bytearray data): + """Note, this function mutates its `data` argument + """ + cdef: + Py_ssize_t data_len, i + # bit operations on signed integers are implementation-specific + unsigned char * in_buf + const unsigned char * mask_buf + uint32_t uint32_msk + uint64_t uint64_msk + + assert len(mask) == 4 + + data_len = len(data) + in_buf = PyByteArray_AsString(data) + mask_buf = PyBytes_AsString(mask) + uint32_msk = (mask_buf)[0] + + # TODO: align in_data ptr to achieve even faster speeds + # does it need in python ?! malloc() always aligns to sizeof(long) bytes + + if sizeof(size_t) >= 8: + uint64_msk = uint32_msk + uint64_msk = (uint64_msk << 32) | uint32_msk + + while data_len >= 8: + (in_buf)[0] ^= uint64_msk + in_buf += 8 + data_len -= 8 + + + while data_len >= 4: + (in_buf)[0] ^= uint32_msk + in_buf += 4 + data_len -= 4 + + for i in range(0, data_len): + in_buf[i] ^= mask_buf[i] diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/aiohttp/_websocket/models.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/aiohttp/_websocket/models.py new file mode 100644 index 0000000000000000000000000000000000000000..27945b3bef95f1f6e230ed63197d0e54acaca171 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/aiohttp/_websocket/models.py @@ -0,0 +1,84 @@ +"""Models for WebSocket protocol versions 13 and 8.""" + +import json +from enum import IntEnum +from typing import Any, Callable, Final, NamedTuple, Optional, cast + +WS_DEFLATE_TRAILING: Final[bytes] = bytes([0x00, 0x00, 0xFF, 0xFF]) + + +class WSCloseCode(IntEnum): + OK = 1000 + GOING_AWAY = 1001 + PROTOCOL_ERROR = 1002 + UNSUPPORTED_DATA = 1003 + ABNORMAL_CLOSURE = 1006 + INVALID_TEXT = 1007 + POLICY_VIOLATION = 1008 + MESSAGE_TOO_BIG = 1009 + MANDATORY_EXTENSION = 1010 + INTERNAL_ERROR = 1011 + SERVICE_RESTART = 1012 + TRY_AGAIN_LATER = 1013 + BAD_GATEWAY = 1014 + + +class WSMsgType(IntEnum): + # websocket spec types + CONTINUATION = 0x0 + TEXT = 0x1 + BINARY = 0x2 + PING = 0x9 + PONG = 0xA + CLOSE = 0x8 + + # aiohttp specific types + CLOSING = 0x100 + CLOSED = 0x101 + ERROR = 0x102 + + text = TEXT + binary = BINARY + ping = PING + pong = PONG + close = CLOSE + closing = CLOSING + closed = CLOSED + error = ERROR + + +class WSMessage(NamedTuple): + type: WSMsgType + # To type correctly, this would need some kind of tagged union for each type. + data: Any + extra: Optional[str] + + def json(self, *, loads: Callable[[Any], Any] = json.loads) -> Any: + """Return parsed JSON data. + + .. versionadded:: 0.22 + """ + return loads(self.data) + + +# Constructing the tuple directly to avoid the overhead of +# the lambda and arg processing since NamedTuples are constructed +# with a run time built lambda +# https://github.com/python/cpython/blob/d83fcf8371f2f33c7797bc8f5423a8bca8c46e5c/Lib/collections/__init__.py#L441 +WS_CLOSED_MESSAGE = tuple.__new__(WSMessage, (WSMsgType.CLOSED, None, None)) +WS_CLOSING_MESSAGE = tuple.__new__(WSMessage, (WSMsgType.CLOSING, None, None)) + + +class WebSocketError(Exception): + """WebSocket protocol parser error.""" + + def __init__(self, code: int, message: str) -> None: + self.code = code + super().__init__(code, message) + + def __str__(self) -> str: + return cast(str, self.args[1]) + + +class WSHandshakeError(Exception): + """WebSocket protocol handshake error.""" diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/aiohttp/_websocket/reader.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/aiohttp/_websocket/reader.py new file mode 100644 index 0000000000000000000000000000000000000000..e70858d3d5c49cb94b56d1d911aada5f150f63c7 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/aiohttp/_websocket/reader.py @@ -0,0 +1,31 @@ +"""Reader for WebSocket protocol versions 13 and 8.""" + +from typing import TYPE_CHECKING + +from ..helpers import NO_EXTENSIONS + +if TYPE_CHECKING or NO_EXTENSIONS: # pragma: no cover + from .reader_py import ( + WebSocketDataQueue as WebSocketDataQueuePython, + WebSocketReader as WebSocketReaderPython, + ) + + WebSocketReader = WebSocketReaderPython + WebSocketDataQueue = WebSocketDataQueuePython +else: + try: + from .reader_c import ( # type: ignore[import-not-found] + WebSocketDataQueue as WebSocketDataQueueCython, + WebSocketReader as WebSocketReaderCython, + ) + + WebSocketReader = WebSocketReaderCython + WebSocketDataQueue = WebSocketDataQueueCython + except ImportError: # pragma: no cover + from .reader_py import ( + WebSocketDataQueue as WebSocketDataQueuePython, + WebSocketReader as WebSocketReaderPython, + ) + + WebSocketReader = WebSocketReaderPython + WebSocketDataQueue = WebSocketDataQueuePython diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/aiohttp/_websocket/reader_c.pxd b/micromamba_root/envs/pytorch_env/Lib/site-packages/aiohttp/_websocket/reader_c.pxd new file mode 100644 index 0000000000000000000000000000000000000000..5752947217e93fb82684cea7eb78118b18bf6b6a --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/aiohttp/_websocket/reader_c.pxd @@ -0,0 +1,110 @@ +import cython + +from .mask cimport _websocket_mask_cython as websocket_mask + + +cdef unsigned int READ_HEADER +cdef unsigned int READ_PAYLOAD_LENGTH +cdef unsigned int READ_PAYLOAD_MASK +cdef unsigned int READ_PAYLOAD + +cdef int OP_CODE_NOT_SET +cdef int OP_CODE_CONTINUATION +cdef int OP_CODE_TEXT +cdef int OP_CODE_BINARY +cdef int OP_CODE_CLOSE +cdef int OP_CODE_PING +cdef int OP_CODE_PONG + +cdef int COMPRESSED_NOT_SET +cdef int COMPRESSED_FALSE +cdef int COMPRESSED_TRUE + +cdef object UNPACK_LEN3 +cdef object UNPACK_CLOSE_CODE +cdef object TUPLE_NEW + +cdef object WSMsgType +cdef object WSMessage + +cdef object WS_MSG_TYPE_TEXT +cdef object WS_MSG_TYPE_BINARY + +cdef set ALLOWED_CLOSE_CODES +cdef set MESSAGE_TYPES_WITH_CONTENT + +cdef tuple EMPTY_FRAME +cdef tuple EMPTY_FRAME_ERROR + +cdef class WebSocketDataQueue: + + cdef unsigned int _size + cdef public object _protocol + cdef unsigned int _limit + cdef object _loop + cdef bint _eof + cdef object _waiter + cdef object _exception + cdef public object _buffer + cdef object _get_buffer + cdef object _put_buffer + + cdef void _release_waiter(self) + + cpdef void feed_data(self, object data, unsigned int size) + + @cython.locals(size="unsigned int") + cdef _read_from_buffer(self) + +cdef class WebSocketReader: + + cdef WebSocketDataQueue queue + cdef unsigned int _max_msg_size + + cdef Exception _exc + cdef bytearray _partial + cdef unsigned int _state + + cdef int _opcode + cdef bint _frame_fin + cdef int _frame_opcode + cdef list _payload_fragments + cdef Py_ssize_t _frame_payload_len + + cdef bytes _tail + cdef bint _has_mask + cdef bytes _frame_mask + cdef Py_ssize_t _payload_bytes_to_read + cdef unsigned int _payload_len_flag + cdef int _compressed + cdef object _decompressobj + cdef bint _compress + + cpdef tuple feed_data(self, object data) + + @cython.locals( + is_continuation=bint, + fin=bint, + has_partial=bint, + payload_merged=bytes, + ) + cpdef void _handle_frame(self, bint fin, int opcode, object payload, int compressed) except * + + @cython.locals( + start_pos=Py_ssize_t, + data_len=Py_ssize_t, + length=Py_ssize_t, + chunk_size=Py_ssize_t, + chunk_len=Py_ssize_t, + data_len=Py_ssize_t, + data_cstr="const unsigned char *", + first_byte="unsigned char", + second_byte="unsigned char", + f_start_pos=Py_ssize_t, + f_end_pos=Py_ssize_t, + has_mask=bint, + fin=bint, + had_fragments=Py_ssize_t, + payload_bytearray=bytearray, + ) + cpdef void _feed_data(self, bytes data) except * diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/aiohttp/_websocket/reader_c.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/aiohttp/_websocket/reader_c.py new file mode 100644 index 0000000000000000000000000000000000000000..f7d44d6228322aaa3ed89a78411c17a7ae511585 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/aiohttp/_websocket/reader_c.py @@ -0,0 +1,478 @@ +"""Reader for WebSocket protocol versions 13 and 8.""" + +import asyncio +import builtins +from collections import deque +from typing import Deque, Final, Optional, Set, Tuple, Union + +from ..base_protocol import BaseProtocol +from ..compression_utils import ZLibDecompressor +from ..helpers import _EXC_SENTINEL, set_exception +from ..streams import EofStream +from .helpers import UNPACK_CLOSE_CODE, UNPACK_LEN3, websocket_mask +from .models import ( + WS_DEFLATE_TRAILING, + WebSocketError, + WSCloseCode, + WSMessage, + WSMsgType, +) + +ALLOWED_CLOSE_CODES: Final[Set[int]] = {int(i) for i in WSCloseCode} + +# States for the reader, used to parse the WebSocket frame +# integer values are used so they can be cythonized +READ_HEADER = 1 +READ_PAYLOAD_LENGTH = 2 +READ_PAYLOAD_MASK = 3 +READ_PAYLOAD = 4 + +WS_MSG_TYPE_BINARY = WSMsgType.BINARY +WS_MSG_TYPE_TEXT = WSMsgType.TEXT + +# WSMsgType values unpacked so they can by cythonized to ints +OP_CODE_NOT_SET = -1 +OP_CODE_CONTINUATION = WSMsgType.CONTINUATION.value +OP_CODE_TEXT = WSMsgType.TEXT.value +OP_CODE_BINARY = WSMsgType.BINARY.value +OP_CODE_CLOSE = WSMsgType.CLOSE.value +OP_CODE_PING = WSMsgType.PING.value +OP_CODE_PONG = WSMsgType.PONG.value + +EMPTY_FRAME_ERROR = (True, b"") +EMPTY_FRAME = (False, b"") + +COMPRESSED_NOT_SET = -1 +COMPRESSED_FALSE = 0 +COMPRESSED_TRUE = 1 + +TUPLE_NEW = tuple.__new__ + +cython_int = int # Typed to int in Python, but cython with use a signed int in the pxd + + +class WebSocketDataQueue: + """WebSocketDataQueue resumes and pauses an underlying stream. + + It is a destination for WebSocket data. + """ + + def __init__( + self, protocol: BaseProtocol, limit: int, *, loop: asyncio.AbstractEventLoop + ) -> None: + self._size = 0 + self._protocol = protocol + self._limit = limit * 2 + self._loop = loop + self._eof = False + self._waiter: Optional[asyncio.Future[None]] = None + self._exception: Union[BaseException, None] = None + self._buffer: Deque[Tuple[WSMessage, int]] = deque() + self._get_buffer = self._buffer.popleft + self._put_buffer = self._buffer.append + + def is_eof(self) -> bool: + return self._eof + + def exception(self) -> Optional[BaseException]: + return self._exception + + def set_exception( + self, + exc: BaseException, + exc_cause: builtins.BaseException = _EXC_SENTINEL, + ) -> None: + self._eof = True + self._exception = exc + if (waiter := self._waiter) is not None: + self._waiter = None + set_exception(waiter, exc, exc_cause) + + def _release_waiter(self) -> None: + if (waiter := self._waiter) is None: + return + self._waiter = None + if not waiter.done(): + waiter.set_result(None) + + def feed_eof(self) -> None: + self._eof = True + self._release_waiter() + self._exception = None # Break cyclic references + + def feed_data(self, data: "WSMessage", size: "cython_int") -> None: + self._size += size + self._put_buffer((data, size)) + self._release_waiter() + if self._size > self._limit and not self._protocol._reading_paused: + self._protocol.pause_reading() + + async def read(self) -> WSMessage: + if not self._buffer and not self._eof: + assert not self._waiter + self._waiter = self._loop.create_future() + try: + await self._waiter + except (asyncio.CancelledError, asyncio.TimeoutError): + self._waiter = None + raise + return self._read_from_buffer() + + def _read_from_buffer(self) -> WSMessage: + if self._buffer: + data, size = self._get_buffer() + self._size -= size + if self._size < self._limit and self._protocol._reading_paused: + self._protocol.resume_reading() + return data + if self._exception is not None: + raise self._exception + raise EofStream + + +class WebSocketReader: + def __init__( + self, queue: WebSocketDataQueue, max_msg_size: int, compress: bool = True + ) -> None: + self.queue = queue + self._max_msg_size = max_msg_size + + self._exc: Optional[Exception] = None + self._partial = bytearray() + self._state = READ_HEADER + + self._opcode: int = OP_CODE_NOT_SET + self._frame_fin = False + self._frame_opcode: int = OP_CODE_NOT_SET + self._payload_fragments: list[bytes] = [] + self._frame_payload_len = 0 + + self._tail: bytes = b"" + self._has_mask = False + self._frame_mask: Optional[bytes] = None + self._payload_bytes_to_read = 0 + self._payload_len_flag = 0 + self._compressed: int = COMPRESSED_NOT_SET + self._decompressobj: Optional[ZLibDecompressor] = None + self._compress = compress + + def feed_eof(self) -> None: + self.queue.feed_eof() + + # data can be bytearray on Windows because proactor event loop uses bytearray + # and asyncio types this to Union[bytes, bytearray, memoryview] so we need + # coerce data to bytes if it is not + def feed_data( + self, data: Union[bytes, bytearray, memoryview] + ) -> Tuple[bool, bytes]: + if type(data) is not bytes: + data = bytes(data) + + if self._exc is not None: + return True, data + + try: + self._feed_data(data) + except Exception as exc: + self._exc = exc + set_exception(self.queue, exc) + return EMPTY_FRAME_ERROR + + return EMPTY_FRAME + + def _handle_frame( + self, + fin: bool, + opcode: Union[int, cython_int], # Union intended: Cython pxd uses C int + payload: Union[bytes, bytearray], + compressed: Union[int, cython_int], # Union intended: Cython pxd uses C int + ) -> None: + msg: WSMessage + if opcode in {OP_CODE_TEXT, OP_CODE_BINARY, OP_CODE_CONTINUATION}: + # Validate continuation frames before processing + if opcode == OP_CODE_CONTINUATION and self._opcode == OP_CODE_NOT_SET: + raise WebSocketError( + WSCloseCode.PROTOCOL_ERROR, + "Continuation frame for non started message", + ) + + # load text/binary + if not fin: + # got partial frame payload + if opcode != OP_CODE_CONTINUATION: + self._opcode = opcode + self._partial += payload + if self._max_msg_size and len(self._partial) >= self._max_msg_size: + raise WebSocketError( + WSCloseCode.MESSAGE_TOO_BIG, + f"Message size {len(self._partial)} " + f"exceeds limit {self._max_msg_size}", + ) + return + + has_partial = bool(self._partial) + if opcode == OP_CODE_CONTINUATION: + opcode = self._opcode + self._opcode = OP_CODE_NOT_SET + # previous frame was non finished + # we should get continuation opcode + elif has_partial: + raise WebSocketError( + WSCloseCode.PROTOCOL_ERROR, + "The opcode in non-fin frame is expected " + f"to be zero, got {opcode!r}", + ) + + assembled_payload: Union[bytes, bytearray] + if has_partial: + assembled_payload = self._partial + payload + self._partial.clear() + else: + assembled_payload = payload + + if self._max_msg_size and len(assembled_payload) >= self._max_msg_size: + raise WebSocketError( + WSCloseCode.MESSAGE_TOO_BIG, + f"Message size {len(assembled_payload)} " + f"exceeds limit {self._max_msg_size}", + ) + + # Decompress process must to be done after all packets + # received. + if compressed: + if not self._decompressobj: + self._decompressobj = ZLibDecompressor(suppress_deflate_header=True) + # XXX: It's possible that the zlib backend (isal is known to + # do this, maybe others too?) will return max_length bytes, + # but internally buffer more data such that the payload is + # >max_length, so we return one extra byte and if we're able + # to do that, then the message is too big. + payload_merged = self._decompressobj.decompress_sync( + assembled_payload + WS_DEFLATE_TRAILING, + ( + self._max_msg_size + 1 + if self._max_msg_size + else self._max_msg_size + ), + ) + if self._max_msg_size and len(payload_merged) > self._max_msg_size: + raise WebSocketError( + WSCloseCode.MESSAGE_TOO_BIG, + f"Decompressed message exceeds size limit {self._max_msg_size}", + ) + elif type(assembled_payload) is bytes: + payload_merged = assembled_payload + else: + payload_merged = bytes(assembled_payload) + + if opcode == OP_CODE_TEXT: + try: + text = payload_merged.decode("utf-8") + except UnicodeDecodeError as exc: + raise WebSocketError( + WSCloseCode.INVALID_TEXT, "Invalid UTF-8 text message" + ) from exc + + # XXX: The Text and Binary messages here can be a performance + # bottleneck, so we use tuple.__new__ to improve performance. + # This is not type safe, but many tests should fail in + # test_client_ws_functional.py if this is wrong. + self.queue.feed_data( + TUPLE_NEW(WSMessage, (WS_MSG_TYPE_TEXT, text, "")), + len(payload_merged), + ) + else: + self.queue.feed_data( + TUPLE_NEW(WSMessage, (WS_MSG_TYPE_BINARY, payload_merged, "")), + len(payload_merged), + ) + elif opcode == OP_CODE_CLOSE: + if len(payload) >= 2: + close_code = UNPACK_CLOSE_CODE(payload[:2])[0] + if close_code < 3000 and close_code not in ALLOWED_CLOSE_CODES: + raise WebSocketError( + WSCloseCode.PROTOCOL_ERROR, + f"Invalid close code: {close_code}", + ) + try: + close_message = payload[2:].decode("utf-8") + except UnicodeDecodeError as exc: + raise WebSocketError( + WSCloseCode.INVALID_TEXT, "Invalid UTF-8 text message" + ) from exc + msg = TUPLE_NEW(WSMessage, (WSMsgType.CLOSE, close_code, close_message)) + elif payload: + raise WebSocketError( + WSCloseCode.PROTOCOL_ERROR, + f"Invalid close frame: {fin} {opcode} {payload!r}", + ) + else: + msg = TUPLE_NEW(WSMessage, (WSMsgType.CLOSE, 0, "")) + + self.queue.feed_data(msg, 0) + elif opcode == OP_CODE_PING: + msg = TUPLE_NEW(WSMessage, (WSMsgType.PING, payload, "")) + self.queue.feed_data(msg, len(payload)) + elif opcode == OP_CODE_PONG: + msg = TUPLE_NEW(WSMessage, (WSMsgType.PONG, payload, "")) + self.queue.feed_data(msg, len(payload)) + else: + raise WebSocketError( + WSCloseCode.PROTOCOL_ERROR, f"Unexpected opcode={opcode!r}" + ) + + def _feed_data(self, data: bytes) -> None: + """Return the next frame from the socket.""" + if self._tail: + data, self._tail = self._tail + data, b"" + + start_pos: int = 0 + data_len = len(data) + data_cstr = data + + while True: + # read header + if self._state == READ_HEADER: + if data_len - start_pos < 2: + break + first_byte = data_cstr[start_pos] + second_byte = data_cstr[start_pos + 1] + start_pos += 2 + + fin = (first_byte >> 7) & 1 + rsv1 = (first_byte >> 6) & 1 + rsv2 = (first_byte >> 5) & 1 + rsv3 = (first_byte >> 4) & 1 + opcode = first_byte & 0xF + + # frame-fin = %x0 ; more frames of this message follow + # / %x1 ; final frame of this message + # frame-rsv1 = %x0 ; + # 1 bit, MUST be 0 unless negotiated otherwise + # frame-rsv2 = %x0 ; + # 1 bit, MUST be 0 unless negotiated otherwise + # frame-rsv3 = %x0 ; + # 1 bit, MUST be 0 unless negotiated otherwise + # + # Remove rsv1 from this test for deflate development + if rsv2 or rsv3 or (rsv1 and not self._compress): + raise WebSocketError( + WSCloseCode.PROTOCOL_ERROR, + "Received frame with non-zero reserved bits", + ) + + if opcode > 0x7 and fin == 0: + raise WebSocketError( + WSCloseCode.PROTOCOL_ERROR, + "Received fragmented control frame", + ) + + has_mask = (second_byte >> 7) & 1 + length = second_byte & 0x7F + + # Control frames MUST have a payload + # length of 125 bytes or less + if opcode > 0x7 and length > 125: + raise WebSocketError( + WSCloseCode.PROTOCOL_ERROR, + "Control frame payload cannot be larger than 125 bytes", + ) + + # Set compress status if last package is FIN + # OR set compress status if this is first fragment + # Raise error if not first fragment with rsv1 = 0x1 + if self._frame_fin or self._compressed == COMPRESSED_NOT_SET: + self._compressed = COMPRESSED_TRUE if rsv1 else COMPRESSED_FALSE + elif rsv1: + raise WebSocketError( + WSCloseCode.PROTOCOL_ERROR, + "Received frame with non-zero reserved bits", + ) + + self._frame_fin = bool(fin) + self._frame_opcode = opcode + self._has_mask = bool(has_mask) + self._payload_len_flag = length + self._state = READ_PAYLOAD_LENGTH + + # read payload length + if self._state == READ_PAYLOAD_LENGTH: + len_flag = self._payload_len_flag + if len_flag == 126: + if data_len - start_pos < 2: + break + first_byte = data_cstr[start_pos] + second_byte = data_cstr[start_pos + 1] + start_pos += 2 + self._payload_bytes_to_read = first_byte << 8 | second_byte + elif len_flag > 126: + if data_len - start_pos < 8: + break + self._payload_bytes_to_read = UNPACK_LEN3(data, start_pos)[0] + start_pos += 8 + else: + self._payload_bytes_to_read = len_flag + + self._state = READ_PAYLOAD_MASK if self._has_mask else READ_PAYLOAD + + # read payload mask + if self._state == READ_PAYLOAD_MASK: + if data_len - start_pos < 4: + break + self._frame_mask = data_cstr[start_pos : start_pos + 4] + start_pos += 4 + self._state = READ_PAYLOAD + + if self._state == READ_PAYLOAD: + chunk_len = data_len - start_pos + if self._payload_bytes_to_read >= chunk_len: + f_end_pos = data_len + self._payload_bytes_to_read -= chunk_len + else: + f_end_pos = start_pos + self._payload_bytes_to_read + self._payload_bytes_to_read = 0 + + had_fragments = self._frame_payload_len + self._frame_payload_len += f_end_pos - start_pos + f_start_pos = start_pos + start_pos = f_end_pos + + if self._payload_bytes_to_read != 0: + # If we don't have a complete frame, we need to save the + # data for the next call to feed_data. + self._payload_fragments.append(data_cstr[f_start_pos:f_end_pos]) + break + + payload: Union[bytes, bytearray] + if had_fragments: + # We have to join the payload fragments get the payload + self._payload_fragments.append(data_cstr[f_start_pos:f_end_pos]) + if self._has_mask: + assert self._frame_mask is not None + payload_bytearray = bytearray(b"".join(self._payload_fragments)) + websocket_mask(self._frame_mask, payload_bytearray) + payload = payload_bytearray + else: + payload = b"".join(self._payload_fragments) + self._payload_fragments.clear() + elif self._has_mask: + assert self._frame_mask is not None + payload_bytearray = data_cstr[f_start_pos:f_end_pos] # type: ignore[assignment] + if type(payload_bytearray) is not bytearray: # pragma: no branch + # Cython will do the conversion for us + # but we need to do it for Python and we + # will always get here in Python + payload_bytearray = bytearray(payload_bytearray) + websocket_mask(self._frame_mask, payload_bytearray) + payload = payload_bytearray + else: + payload = data_cstr[f_start_pos:f_end_pos] + + self._handle_frame( + self._frame_fin, self._frame_opcode, payload, self._compressed + ) + self._frame_payload_len = 0 + self._state = READ_HEADER + + # XXX: Cython needs slices to be bounded, so we can't omit the slice end here. + self._tail = data_cstr[start_pos:data_len] if start_pos < data_len else b"" diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/aiohttp/_websocket/reader_py.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/aiohttp/_websocket/reader_py.py new file mode 100644 index 0000000000000000000000000000000000000000..f7d44d6228322aaa3ed89a78411c17a7ae511585 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/aiohttp/_websocket/reader_py.py @@ -0,0 +1,478 @@ +"""Reader for WebSocket protocol versions 13 and 8.""" + +import asyncio +import builtins +from collections import deque +from typing import Deque, Final, Optional, Set, Tuple, Union + +from ..base_protocol import BaseProtocol +from ..compression_utils import ZLibDecompressor +from ..helpers import _EXC_SENTINEL, set_exception +from ..streams import EofStream +from .helpers import UNPACK_CLOSE_CODE, UNPACK_LEN3, websocket_mask +from .models import ( + WS_DEFLATE_TRAILING, + WebSocketError, + WSCloseCode, + WSMessage, + WSMsgType, +) + +ALLOWED_CLOSE_CODES: Final[Set[int]] = {int(i) for i in WSCloseCode} + +# States for the reader, used to parse the WebSocket frame +# integer values are used so they can be cythonized +READ_HEADER = 1 +READ_PAYLOAD_LENGTH = 2 +READ_PAYLOAD_MASK = 3 +READ_PAYLOAD = 4 + +WS_MSG_TYPE_BINARY = WSMsgType.BINARY +WS_MSG_TYPE_TEXT = WSMsgType.TEXT + +# WSMsgType values unpacked so they can by cythonized to ints +OP_CODE_NOT_SET = -1 +OP_CODE_CONTINUATION = WSMsgType.CONTINUATION.value +OP_CODE_TEXT = WSMsgType.TEXT.value +OP_CODE_BINARY = WSMsgType.BINARY.value +OP_CODE_CLOSE = WSMsgType.CLOSE.value +OP_CODE_PING = WSMsgType.PING.value +OP_CODE_PONG = WSMsgType.PONG.value + +EMPTY_FRAME_ERROR = (True, b"") +EMPTY_FRAME = (False, b"") + +COMPRESSED_NOT_SET = -1 +COMPRESSED_FALSE = 0 +COMPRESSED_TRUE = 1 + +TUPLE_NEW = tuple.__new__ + +cython_int = int # Typed to int in Python, but cython with use a signed int in the pxd + + +class WebSocketDataQueue: + """WebSocketDataQueue resumes and pauses an underlying stream. + + It is a destination for WebSocket data. + """ + + def __init__( + self, protocol: BaseProtocol, limit: int, *, loop: asyncio.AbstractEventLoop + ) -> None: + self._size = 0 + self._protocol = protocol + self._limit = limit * 2 + self._loop = loop + self._eof = False + self._waiter: Optional[asyncio.Future[None]] = None + self._exception: Union[BaseException, None] = None + self._buffer: Deque[Tuple[WSMessage, int]] = deque() + self._get_buffer = self._buffer.popleft + self._put_buffer = self._buffer.append + + def is_eof(self) -> bool: + return self._eof + + def exception(self) -> Optional[BaseException]: + return self._exception + + def set_exception( + self, + exc: BaseException, + exc_cause: builtins.BaseException = _EXC_SENTINEL, + ) -> None: + self._eof = True + self._exception = exc + if (waiter := self._waiter) is not None: + self._waiter = None + set_exception(waiter, exc, exc_cause) + + def _release_waiter(self) -> None: + if (waiter := self._waiter) is None: + return + self._waiter = None + if not waiter.done(): + waiter.set_result(None) + + def feed_eof(self) -> None: + self._eof = True + self._release_waiter() + self._exception = None # Break cyclic references + + def feed_data(self, data: "WSMessage", size: "cython_int") -> None: + self._size += size + self._put_buffer((data, size)) + self._release_waiter() + if self._size > self._limit and not self._protocol._reading_paused: + self._protocol.pause_reading() + + async def read(self) -> WSMessage: + if not self._buffer and not self._eof: + assert not self._waiter + self._waiter = self._loop.create_future() + try: + await self._waiter + except (asyncio.CancelledError, asyncio.TimeoutError): + self._waiter = None + raise + return self._read_from_buffer() + + def _read_from_buffer(self) -> WSMessage: + if self._buffer: + data, size = self._get_buffer() + self._size -= size + if self._size < self._limit and self._protocol._reading_paused: + self._protocol.resume_reading() + return data + if self._exception is not None: + raise self._exception + raise EofStream + + +class WebSocketReader: + def __init__( + self, queue: WebSocketDataQueue, max_msg_size: int, compress: bool = True + ) -> None: + self.queue = queue + self._max_msg_size = max_msg_size + + self._exc: Optional[Exception] = None + self._partial = bytearray() + self._state = READ_HEADER + + self._opcode: int = OP_CODE_NOT_SET + self._frame_fin = False + self._frame_opcode: int = OP_CODE_NOT_SET + self._payload_fragments: list[bytes] = [] + self._frame_payload_len = 0 + + self._tail: bytes = b"" + self._has_mask = False + self._frame_mask: Optional[bytes] = None + self._payload_bytes_to_read = 0 + self._payload_len_flag = 0 + self._compressed: int = COMPRESSED_NOT_SET + self._decompressobj: Optional[ZLibDecompressor] = None + self._compress = compress + + def feed_eof(self) -> None: + self.queue.feed_eof() + + # data can be bytearray on Windows because proactor event loop uses bytearray + # and asyncio types this to Union[bytes, bytearray, memoryview] so we need + # coerce data to bytes if it is not + def feed_data( + self, data: Union[bytes, bytearray, memoryview] + ) -> Tuple[bool, bytes]: + if type(data) is not bytes: + data = bytes(data) + + if self._exc is not None: + return True, data + + try: + self._feed_data(data) + except Exception as exc: + self._exc = exc + set_exception(self.queue, exc) + return EMPTY_FRAME_ERROR + + return EMPTY_FRAME + + def _handle_frame( + self, + fin: bool, + opcode: Union[int, cython_int], # Union intended: Cython pxd uses C int + payload: Union[bytes, bytearray], + compressed: Union[int, cython_int], # Union intended: Cython pxd uses C int + ) -> None: + msg: WSMessage + if opcode in {OP_CODE_TEXT, OP_CODE_BINARY, OP_CODE_CONTINUATION}: + # Validate continuation frames before processing + if opcode == OP_CODE_CONTINUATION and self._opcode == OP_CODE_NOT_SET: + raise WebSocketError( + WSCloseCode.PROTOCOL_ERROR, + "Continuation frame for non started message", + ) + + # load text/binary + if not fin: + # got partial frame payload + if opcode != OP_CODE_CONTINUATION: + self._opcode = opcode + self._partial += payload + if self._max_msg_size and len(self._partial) >= self._max_msg_size: + raise WebSocketError( + WSCloseCode.MESSAGE_TOO_BIG, + f"Message size {len(self._partial)} " + f"exceeds limit {self._max_msg_size}", + ) + return + + has_partial = bool(self._partial) + if opcode == OP_CODE_CONTINUATION: + opcode = self._opcode + self._opcode = OP_CODE_NOT_SET + # previous frame was non finished + # we should get continuation opcode + elif has_partial: + raise WebSocketError( + WSCloseCode.PROTOCOL_ERROR, + "The opcode in non-fin frame is expected " + f"to be zero, got {opcode!r}", + ) + + assembled_payload: Union[bytes, bytearray] + if has_partial: + assembled_payload = self._partial + payload + self._partial.clear() + else: + assembled_payload = payload + + if self._max_msg_size and len(assembled_payload) >= self._max_msg_size: + raise WebSocketError( + WSCloseCode.MESSAGE_TOO_BIG, + f"Message size {len(assembled_payload)} " + f"exceeds limit {self._max_msg_size}", + ) + + # Decompress process must to be done after all packets + # received. + if compressed: + if not self._decompressobj: + self._decompressobj = ZLibDecompressor(suppress_deflate_header=True) + # XXX: It's possible that the zlib backend (isal is known to + # do this, maybe others too?) will return max_length bytes, + # but internally buffer more data such that the payload is + # >max_length, so we return one extra byte and if we're able + # to do that, then the message is too big. + payload_merged = self._decompressobj.decompress_sync( + assembled_payload + WS_DEFLATE_TRAILING, + ( + self._max_msg_size + 1 + if self._max_msg_size + else self._max_msg_size + ), + ) + if self._max_msg_size and len(payload_merged) > self._max_msg_size: + raise WebSocketError( + WSCloseCode.MESSAGE_TOO_BIG, + f"Decompressed message exceeds size limit {self._max_msg_size}", + ) + elif type(assembled_payload) is bytes: + payload_merged = assembled_payload + else: + payload_merged = bytes(assembled_payload) + + if opcode == OP_CODE_TEXT: + try: + text = payload_merged.decode("utf-8") + except UnicodeDecodeError as exc: + raise WebSocketError( + WSCloseCode.INVALID_TEXT, "Invalid UTF-8 text message" + ) from exc + + # XXX: The Text and Binary messages here can be a performance + # bottleneck, so we use tuple.__new__ to improve performance. + # This is not type safe, but many tests should fail in + # test_client_ws_functional.py if this is wrong. + self.queue.feed_data( + TUPLE_NEW(WSMessage, (WS_MSG_TYPE_TEXT, text, "")), + len(payload_merged), + ) + else: + self.queue.feed_data( + TUPLE_NEW(WSMessage, (WS_MSG_TYPE_BINARY, payload_merged, "")), + len(payload_merged), + ) + elif opcode == OP_CODE_CLOSE: + if len(payload) >= 2: + close_code = UNPACK_CLOSE_CODE(payload[:2])[0] + if close_code < 3000 and close_code not in ALLOWED_CLOSE_CODES: + raise WebSocketError( + WSCloseCode.PROTOCOL_ERROR, + f"Invalid close code: {close_code}", + ) + try: + close_message = payload[2:].decode("utf-8") + except UnicodeDecodeError as exc: + raise WebSocketError( + WSCloseCode.INVALID_TEXT, "Invalid UTF-8 text message" + ) from exc + msg = TUPLE_NEW(WSMessage, (WSMsgType.CLOSE, close_code, close_message)) + elif payload: + raise WebSocketError( + WSCloseCode.PROTOCOL_ERROR, + f"Invalid close frame: {fin} {opcode} {payload!r}", + ) + else: + msg = TUPLE_NEW(WSMessage, (WSMsgType.CLOSE, 0, "")) + + self.queue.feed_data(msg, 0) + elif opcode == OP_CODE_PING: + msg = TUPLE_NEW(WSMessage, (WSMsgType.PING, payload, "")) + self.queue.feed_data(msg, len(payload)) + elif opcode == OP_CODE_PONG: + msg = TUPLE_NEW(WSMessage, (WSMsgType.PONG, payload, "")) + self.queue.feed_data(msg, len(payload)) + else: + raise WebSocketError( + WSCloseCode.PROTOCOL_ERROR, f"Unexpected opcode={opcode!r}" + ) + + def _feed_data(self, data: bytes) -> None: + """Return the next frame from the socket.""" + if self._tail: + data, self._tail = self._tail + data, b"" + + start_pos: int = 0 + data_len = len(data) + data_cstr = data + + while True: + # read header + if self._state == READ_HEADER: + if data_len - start_pos < 2: + break + first_byte = data_cstr[start_pos] + second_byte = data_cstr[start_pos + 1] + start_pos += 2 + + fin = (first_byte >> 7) & 1 + rsv1 = (first_byte >> 6) & 1 + rsv2 = (first_byte >> 5) & 1 + rsv3 = (first_byte >> 4) & 1 + opcode = first_byte & 0xF + + # frame-fin = %x0 ; more frames of this message follow + # / %x1 ; final frame of this message + # frame-rsv1 = %x0 ; + # 1 bit, MUST be 0 unless negotiated otherwise + # frame-rsv2 = %x0 ; + # 1 bit, MUST be 0 unless negotiated otherwise + # frame-rsv3 = %x0 ; + # 1 bit, MUST be 0 unless negotiated otherwise + # + # Remove rsv1 from this test for deflate development + if rsv2 or rsv3 or (rsv1 and not self._compress): + raise WebSocketError( + WSCloseCode.PROTOCOL_ERROR, + "Received frame with non-zero reserved bits", + ) + + if opcode > 0x7 and fin == 0: + raise WebSocketError( + WSCloseCode.PROTOCOL_ERROR, + "Received fragmented control frame", + ) + + has_mask = (second_byte >> 7) & 1 + length = second_byte & 0x7F + + # Control frames MUST have a payload + # length of 125 bytes or less + if opcode > 0x7 and length > 125: + raise WebSocketError( + WSCloseCode.PROTOCOL_ERROR, + "Control frame payload cannot be larger than 125 bytes", + ) + + # Set compress status if last package is FIN + # OR set compress status if this is first fragment + # Raise error if not first fragment with rsv1 = 0x1 + if self._frame_fin or self._compressed == COMPRESSED_NOT_SET: + self._compressed = COMPRESSED_TRUE if rsv1 else COMPRESSED_FALSE + elif rsv1: + raise WebSocketError( + WSCloseCode.PROTOCOL_ERROR, + "Received frame with non-zero reserved bits", + ) + + self._frame_fin = bool(fin) + self._frame_opcode = opcode + self._has_mask = bool(has_mask) + self._payload_len_flag = length + self._state = READ_PAYLOAD_LENGTH + + # read payload length + if self._state == READ_PAYLOAD_LENGTH: + len_flag = self._payload_len_flag + if len_flag == 126: + if data_len - start_pos < 2: + break + first_byte = data_cstr[start_pos] + second_byte = data_cstr[start_pos + 1] + start_pos += 2 + self._payload_bytes_to_read = first_byte << 8 | second_byte + elif len_flag > 126: + if data_len - start_pos < 8: + break + self._payload_bytes_to_read = UNPACK_LEN3(data, start_pos)[0] + start_pos += 8 + else: + self._payload_bytes_to_read = len_flag + + self._state = READ_PAYLOAD_MASK if self._has_mask else READ_PAYLOAD + + # read payload mask + if self._state == READ_PAYLOAD_MASK: + if data_len - start_pos < 4: + break + self._frame_mask = data_cstr[start_pos : start_pos + 4] + start_pos += 4 + self._state = READ_PAYLOAD + + if self._state == READ_PAYLOAD: + chunk_len = data_len - start_pos + if self._payload_bytes_to_read >= chunk_len: + f_end_pos = data_len + self._payload_bytes_to_read -= chunk_len + else: + f_end_pos = start_pos + self._payload_bytes_to_read + self._payload_bytes_to_read = 0 + + had_fragments = self._frame_payload_len + self._frame_payload_len += f_end_pos - start_pos + f_start_pos = start_pos + start_pos = f_end_pos + + if self._payload_bytes_to_read != 0: + # If we don't have a complete frame, we need to save the + # data for the next call to feed_data. + self._payload_fragments.append(data_cstr[f_start_pos:f_end_pos]) + break + + payload: Union[bytes, bytearray] + if had_fragments: + # We have to join the payload fragments get the payload + self._payload_fragments.append(data_cstr[f_start_pos:f_end_pos]) + if self._has_mask: + assert self._frame_mask is not None + payload_bytearray = bytearray(b"".join(self._payload_fragments)) + websocket_mask(self._frame_mask, payload_bytearray) + payload = payload_bytearray + else: + payload = b"".join(self._payload_fragments) + self._payload_fragments.clear() + elif self._has_mask: + assert self._frame_mask is not None + payload_bytearray = data_cstr[f_start_pos:f_end_pos] # type: ignore[assignment] + if type(payload_bytearray) is not bytearray: # pragma: no branch + # Cython will do the conversion for us + # but we need to do it for Python and we + # will always get here in Python + payload_bytearray = bytearray(payload_bytearray) + websocket_mask(self._frame_mask, payload_bytearray) + payload = payload_bytearray + else: + payload = data_cstr[f_start_pos:f_end_pos] + + self._handle_frame( + self._frame_fin, self._frame_opcode, payload, self._compressed + ) + self._frame_payload_len = 0 + self._state = READ_HEADER + + # XXX: Cython needs slices to be bounded, so we can't omit the slice end here. + self._tail = data_cstr[start_pos:data_len] if start_pos < data_len else b"" diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/aiohttp/_websocket/writer.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/aiohttp/_websocket/writer.py new file mode 100644 index 0000000000000000000000000000000000000000..621d389a24dc50b811e2a476174e2df25613beb0 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/aiohttp/_websocket/writer.py @@ -0,0 +1,262 @@ +"""WebSocket protocol versions 13 and 8.""" + +import asyncio +import random +import sys +from functools import partial +from typing import Final, Optional, Set, Union + +from ..base_protocol import BaseProtocol +from ..client_exceptions import ClientConnectionResetError +from ..compression_utils import ZLibBackend, ZLibCompressor +from .helpers import ( + MASK_LEN, + MSG_SIZE, + PACK_CLOSE_CODE, + PACK_LEN1, + PACK_LEN2, + PACK_LEN3, + PACK_RANDBITS, + websocket_mask, +) +from .models import WS_DEFLATE_TRAILING, WSMsgType + +DEFAULT_LIMIT: Final[int] = 2**16 + +# WebSocket opcode boundary: opcodes 0-7 are data frames, 8-15 are control frames +# Control frames (ping, pong, close) are never compressed +WS_CONTROL_FRAME_OPCODE: Final[int] = 8 + +# For websockets, keeping latency low is extremely important as implementations +# generally expect to be able to send and receive messages quickly. We use a +# larger chunk size to reduce the number of executor calls and avoid task +# creation overhead, since both are significant sources of latency when chunks +# are small. A size of 16KiB was chosen as a balance between avoiding task +# overhead and not blocking the event loop too long with synchronous compression. + +WEBSOCKET_MAX_SYNC_CHUNK_SIZE = 16 * 1024 + + +class WebSocketWriter: + """WebSocket writer. + + The writer is responsible for sending messages to the client. It is + created by the protocol when a connection is established. The writer + should avoid implementing any application logic and should only be + concerned with the low-level details of the WebSocket protocol. + """ + + def __init__( + self, + protocol: BaseProtocol, + transport: asyncio.Transport, + *, + use_mask: bool = False, + limit: int = DEFAULT_LIMIT, + random: random.Random = random.Random(), + compress: int = 0, + notakeover: bool = False, + ) -> None: + """Initialize a WebSocket writer.""" + self.protocol = protocol + self.transport = transport + self.use_mask = use_mask + self.get_random_bits = partial(random.getrandbits, 32) + self.compress = compress + self.notakeover = notakeover + self._closing = False + self._limit = limit + self._output_size = 0 + self._compressobj: Optional[ZLibCompressor] = None + self._send_lock = asyncio.Lock() + self._background_tasks: Set[asyncio.Task[None]] = set() + + async def send_frame( + self, message: bytes, opcode: int, compress: Optional[int] = None + ) -> None: + """Send a frame over the websocket with message as its payload.""" + if self._closing and not (opcode & WSMsgType.CLOSE): + raise ClientConnectionResetError("Cannot write to closing transport") + + if not (compress or self.compress) or opcode >= WS_CONTROL_FRAME_OPCODE: + # Non-compressed frames don't need lock or shield + self._write_websocket_frame(message, opcode, 0) + elif len(message) <= WEBSOCKET_MAX_SYNC_CHUNK_SIZE: + # Small compressed payloads - compress synchronously in event loop + # We need the lock even though sync compression has no await points. + # This prevents small frames from interleaving with large frames that + # compress in the executor, avoiding compressor state corruption. + async with self._send_lock: + self._send_compressed_frame_sync(message, opcode, compress) + else: + # Large compressed frames need shield to prevent corruption + # For large compressed frames, the entire compress+send + # operation must be atomic. If cancelled after compression but + # before send, the compressor state would be advanced but data + # not sent, corrupting subsequent frames. + # Create a task to shield from cancellation + # The lock is acquired inside the shielded task so the entire + # operation (lock + compress + send) completes atomically. + # Use eager_start on Python 3.12+ to avoid scheduling overhead + loop = asyncio.get_running_loop() + coro = self._send_compressed_frame_async_locked(message, opcode, compress) + if sys.version_info >= (3, 12): + send_task = asyncio.Task(coro, loop=loop, eager_start=True) + else: + send_task = loop.create_task(coro) + # Keep a strong reference to prevent garbage collection + self._background_tasks.add(send_task) + send_task.add_done_callback(self._background_tasks.discard) + await asyncio.shield(send_task) + + # It is safe to return control to the event loop when using compression + # after this point as we have already sent or buffered all the data. + # Once we have written output_size up to the limit, we call the + # drain helper which waits for the transport to be ready to accept + # more data. This is a flow control mechanism to prevent the buffer + # from growing too large. The drain helper will return right away + # if the writer is not paused. + if self._output_size > self._limit: + self._output_size = 0 + if self.protocol._paused: + await self.protocol._drain_helper() + + def _write_websocket_frame(self, message: bytes, opcode: int, rsv: int) -> None: + """ + Write a websocket frame to the transport. + + This method handles frame header construction, masking, and writing to transport. + It does not handle compression or flow control - those are the responsibility + of the caller. + """ + msg_length = len(message) + + use_mask = self.use_mask + mask_bit = 0x80 if use_mask else 0 + + # Depending on the message length, the header is assembled differently. + # The first byte is reserved for the opcode and the RSV bits. + first_byte = 0x80 | rsv | opcode + if msg_length < 126: + header = PACK_LEN1(first_byte, msg_length | mask_bit) + header_len = 2 + elif msg_length < 65536: + header = PACK_LEN2(first_byte, 126 | mask_bit, msg_length) + header_len = 4 + else: + header = PACK_LEN3(first_byte, 127 | mask_bit, msg_length) + header_len = 10 + + if self.transport.is_closing(): + raise ClientConnectionResetError("Cannot write to closing transport") + + # https://datatracker.ietf.org/doc/html/rfc6455#section-5.3 + # If we are using a mask, we need to generate it randomly + # and apply it to the message before sending it. A mask is + # a 32-bit value that is applied to the message using a + # bitwise XOR operation. It is used to prevent certain types + # of attacks on the websocket protocol. The mask is only used + # when aiohttp is acting as a client. Servers do not use a mask. + if use_mask: + mask = PACK_RANDBITS(self.get_random_bits()) + message = bytearray(message) + websocket_mask(mask, message) + self.transport.write(header + mask + message) + self._output_size += MASK_LEN + elif msg_length > MSG_SIZE: + self.transport.write(header) + self.transport.write(message) + else: + self.transport.write(header + message) + + self._output_size += header_len + msg_length + + def _get_compressor(self, compress: Optional[int]) -> ZLibCompressor: + """Get or create a compressor object for the given compression level.""" + if compress: + # Do not set self._compress if compressing is for this frame + return ZLibCompressor( + level=ZLibBackend.Z_BEST_SPEED, + wbits=-compress, + max_sync_chunk_size=WEBSOCKET_MAX_SYNC_CHUNK_SIZE, + ) + if not self._compressobj: + self._compressobj = ZLibCompressor( + level=ZLibBackend.Z_BEST_SPEED, + wbits=-self.compress, + max_sync_chunk_size=WEBSOCKET_MAX_SYNC_CHUNK_SIZE, + ) + return self._compressobj + + def _send_compressed_frame_sync( + self, message: bytes, opcode: int, compress: Optional[int] + ) -> None: + """ + Synchronous send for small compressed frames. + + This is used for small compressed payloads that compress synchronously in the event loop. + Since there are no await points, this is inherently cancellation-safe. + """ + # RSV are the reserved bits in the frame header. They are used to + # indicate that the frame is using an extension. + # https://datatracker.ietf.org/doc/html/rfc6455#section-5.2 + compressobj = self._get_compressor(compress) + # (0x40) RSV1 is set for compressed frames + # https://datatracker.ietf.org/doc/html/rfc7692#section-7.2.3.1 + self._write_websocket_frame( + ( + compressobj.compress_sync(message) + + compressobj.flush( + ZLibBackend.Z_FULL_FLUSH + if self.notakeover + else ZLibBackend.Z_SYNC_FLUSH + ) + ).removesuffix(WS_DEFLATE_TRAILING), + opcode, + 0x40, + ) + + async def _send_compressed_frame_async_locked( + self, message: bytes, opcode: int, compress: Optional[int] + ) -> None: + """ + Async send for large compressed frames with lock. + + Acquires the lock and compresses large payloads asynchronously in + the executor. The lock is held for the entire operation to ensure + the compressor state is not corrupted by concurrent sends. + + MUST be run shielded from cancellation. If cancelled after + compression but before sending, the compressor state would be + advanced but data not sent, corrupting subsequent frames. + """ + async with self._send_lock: + # RSV are the reserved bits in the frame header. They are used to + # indicate that the frame is using an extension. + # https://datatracker.ietf.org/doc/html/rfc6455#section-5.2 + compressobj = self._get_compressor(compress) + # (0x40) RSV1 is set for compressed frames + # https://datatracker.ietf.org/doc/html/rfc7692#section-7.2.3.1 + self._write_websocket_frame( + ( + await compressobj.compress(message) + + compressobj.flush( + ZLibBackend.Z_FULL_FLUSH + if self.notakeover + else ZLibBackend.Z_SYNC_FLUSH + ) + ).removesuffix(WS_DEFLATE_TRAILING), + opcode, + 0x40, + ) + + async def close(self, code: int = 1000, message: Union[bytes, str] = b"") -> None: + """Close the websocket, sending the specified code and message.""" + if isinstance(message, str): + message = message.encode("utf-8") + try: + await self.send_frame( + PACK_CLOSE_CODE(code) + message, opcode=WSMsgType.CLOSE + ) + finally: + self._closing = True diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/aiosignal-1.4.0.dist-info/licenses/LICENSE b/micromamba_root/envs/pytorch_env/Lib/site-packages/aiosignal-1.4.0.dist-info/licenses/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..7082a2d5b9047bfc09589f387053e24ea490bc54 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/aiosignal-1.4.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/micromamba_root/envs/pytorch_env/Lib/site-packages/aiosignal/__pycache__/__init__.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/aiosignal/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..289c84d9e33645747f1cb097eb87ccdff43e1c5c Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/aiosignal/__pycache__/__init__.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/annotated_doc-0.0.4.dist-info/licenses/LICENSE b/micromamba_root/envs/pytorch_env/Lib/site-packages/annotated_doc-0.0.4.dist-info/licenses/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..7a254464cc78ccea32b3ded00513c44c4e4da412 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/annotated_doc-0.0.4.dist-info/licenses/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2025 Sebastián Ramírez + +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/micromamba_root/envs/pytorch_env/Lib/site-packages/annotated_doc/__pycache__/__init__.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/annotated_doc/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..22d25a7c4b58f5d50c38906864ab557bf53dc9e8 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/annotated_doc/__pycache__/__init__.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/annotated_doc/__pycache__/main.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/annotated_doc/__pycache__/main.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8be1a439751ffae1b5ca19d4c096df45d0ce0b02 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/annotated_doc/__pycache__/main.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/annotated_types-0.7.0.dist-info/licenses/LICENSE b/micromamba_root/envs/pytorch_env/Lib/site-packages/annotated_types-0.7.0.dist-info/licenses/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..d99323a9965f146d5b0888c4ca1bf0727e12b04f --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/annotated_types-0.7.0.dist-info/licenses/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2022 the 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/micromamba_root/envs/pytorch_env/Lib/site-packages/annotated_types/__pycache__/__init__.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/annotated_types/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f323afb8ea1a08d66080bf13ce4cd27d22667276 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/annotated_types/__pycache__/__init__.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/annotated_types/__pycache__/test_cases.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/annotated_types/__pycache__/test_cases.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a84fc28436a2d9ee8ec96f1b2ee380c95514a1c8 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/annotated_types/__pycache__/test_cases.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/anyio-4.13.0.dist-info/licenses/LICENSE b/micromamba_root/envs/pytorch_env/Lib/site-packages/anyio-4.13.0.dist-info/licenses/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..104eebf5a3002fccdaceef3a4cb936173c1c2035 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/anyio-4.13.0.dist-info/licenses/LICENSE @@ -0,0 +1,20 @@ +The MIT License (MIT) + +Copyright (c) 2018 Alex Grönholm + +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/micromamba_root/envs/pytorch_env/Lib/site-packages/anyio/__pycache__/__init__.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/anyio/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..526a11d08293648797e79428579c546fb728e2df Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/anyio/__pycache__/__init__.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/anyio/__pycache__/from_thread.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/anyio/__pycache__/from_thread.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..90a254a46e05a9e5286197ee9d70a19470436e9d Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/anyio/__pycache__/from_thread.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/anyio/__pycache__/functools.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/anyio/__pycache__/functools.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3c1dbb25f3bee3aaa250fcba9c488c4a4dd48cc0 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/anyio/__pycache__/functools.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/anyio/__pycache__/lowlevel.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/anyio/__pycache__/lowlevel.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5de71a6421f3180fa292997c89656e330ce871e8 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/anyio/__pycache__/lowlevel.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/anyio/__pycache__/pytest_plugin.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/anyio/__pycache__/pytest_plugin.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..011a5dcd49ec0ced46cf39f8a0b28c98012fc933 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/anyio/__pycache__/pytest_plugin.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/anyio/__pycache__/to_interpreter.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/anyio/__pycache__/to_interpreter.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..708ff6641c9a159af880c1cf1a531f5fbe67f54b Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/anyio/__pycache__/to_interpreter.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/anyio/__pycache__/to_process.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/anyio/__pycache__/to_process.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6cceb3242839a661f45efd230e22257a019dd999 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/anyio/__pycache__/to_process.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/anyio/__pycache__/to_thread.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/anyio/__pycache__/to_thread.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..86f9882e6682aaeced0d60562cc2bd9bc4407566 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/anyio/__pycache__/to_thread.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/anyio/_backends/__init__.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/anyio/_backends/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/anyio/_backends/__pycache__/__init__.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/anyio/_backends/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d14ae56e1af6a5180cc6af3ed3b1509443f22626 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/anyio/_backends/__pycache__/__init__.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/anyio/_backends/__pycache__/_trio.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/anyio/_backends/__pycache__/_trio.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6c01ca7ecee5a9573fb701df85b9e9e59697412f Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/anyio/_backends/__pycache__/_trio.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/anyio/_backends/_asyncio.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/anyio/_backends/_asyncio.py new file mode 100644 index 0000000000000000000000000000000000000000..9f1ddc242c778588bfc48c0d3ec8a2db49b666c7 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/anyio/_backends/_asyncio.py @@ -0,0 +1,2996 @@ +from __future__ import annotations + +import array +import asyncio +import concurrent.futures +import contextvars +import math +import os +import socket +import sys +import threading +import weakref +from asyncio import ( + AbstractEventLoop, + CancelledError, + all_tasks, + create_task, + current_task, + get_running_loop, + sleep, +) +from asyncio.base_events import _run_until_complete_cb # type: ignore[attr-defined] +from collections import OrderedDict, deque +from collections.abc import ( + AsyncGenerator, + AsyncIterator, + Awaitable, + Callable, + Collection, + Coroutine, + Iterable, + Sequence, +) +from concurrent.futures import Future +from contextlib import AbstractContextManager, suppress +from contextvars import Context, copy_context +from dataclasses import dataclass, field +from functools import partial, wraps +from inspect import ( + CORO_RUNNING, + CORO_SUSPENDED, + getcoroutinestate, + iscoroutine, +) +from io import IOBase +from os import PathLike +from queue import Queue +from signal import Signals +from socket import AddressFamily, SocketKind +from threading import Thread +from types import CodeType, TracebackType +from typing import ( + IO, + TYPE_CHECKING, + Any, + ParamSpec, + TypeVar, + cast, +) +from weakref import WeakKeyDictionary + +from .. import ( + CapacityLimiterStatistics, + EventStatistics, + LockStatistics, + TaskInfo, + abc, +) +from .._core._eventloop import ( + claim_worker_thread, + set_current_async_library, + threadlocals, +) +from .._core._exceptions import ( + BrokenResourceError, + BusyResourceError, + ClosedResourceError, + EndOfStream, + RunFinishedError, + WouldBlock, +) +from .._core._sockets import convert_ipv6_sockaddr +from .._core._streams import create_memory_object_stream +from .._core._synchronization import ( + CapacityLimiter as BaseCapacityLimiter, +) +from .._core._synchronization import Event as BaseEvent +from .._core._synchronization import Lock as BaseLock +from .._core._synchronization import ( + ResourceGuard, + SemaphoreStatistics, +) +from .._core._synchronization import Semaphore as BaseSemaphore +from .._core._tasks import CancelScope as BaseCancelScope +from ..abc import ( + AsyncBackend, + IPSockAddrType, + SocketListener, + UDPPacketType, + UNIXDatagramPacketType, +) +from ..abc._eventloop import StrOrBytesPath +from ..lowlevel import RunVar +from ..streams.memory import MemoryObjectReceiveStream, MemoryObjectSendStream + +if TYPE_CHECKING: + from _typeshed import FileDescriptorLike +else: + FileDescriptorLike = object + +if sys.version_info >= (3, 11): + from asyncio import Runner + from typing import TypeVarTuple, Unpack +else: + import contextvars + import enum + import signal + from asyncio import coroutines, events, exceptions, tasks + + from exceptiongroup import BaseExceptionGroup + from typing_extensions import TypeVarTuple, Unpack + + class _State(enum.Enum): + CREATED = "created" + INITIALIZED = "initialized" + CLOSED = "closed" + + class Runner: + # Copied from CPython 3.11 + def __init__( + self, + *, + debug: bool | None = None, + loop_factory: Callable[[], AbstractEventLoop] | None = None, + ): + self._state = _State.CREATED + self._debug = debug + self._loop_factory = loop_factory + self._loop: AbstractEventLoop | None = None + self._context = None + self._interrupt_count = 0 + self._set_event_loop = False + + def __enter__(self) -> Runner: + self._lazy_init() + return self + + def __exit__( + self, + exc_type: type[BaseException] | None, + exc_val: BaseException | None, + exc_tb: TracebackType | None, + ) -> None: + self.close() + + def close(self) -> None: + """Shutdown and close event loop.""" + loop = self._loop + if self._state is not _State.INITIALIZED or loop is None: + return + try: + _cancel_all_tasks(loop) + loop.run_until_complete(loop.shutdown_asyncgens()) + if hasattr(loop, "shutdown_default_executor"): + loop.run_until_complete(loop.shutdown_default_executor()) + else: + loop.run_until_complete(_shutdown_default_executor(loop)) + finally: + if self._set_event_loop: + events.set_event_loop(None) + loop.close() + self._loop = None + self._state = _State.CLOSED + + def get_loop(self) -> AbstractEventLoop: + """Return embedded event loop.""" + self._lazy_init() + return self._loop + + def run(self, coro: Coroutine[T_Retval], *, context=None) -> T_Retval: + """Run a coroutine inside the embedded event loop.""" + if not coroutines.iscoroutine(coro): + raise ValueError(f"a coroutine was expected, got {coro!r}") + + if events._get_running_loop() is not None: + # fail fast with short traceback + raise RuntimeError( + "Runner.run() cannot be called from a running event loop" + ) + + self._lazy_init() + + if context is None: + context = self._context + task = context.run(self._loop.create_task, coro) + + if ( + threading.current_thread() is threading.main_thread() + and signal.getsignal(signal.SIGINT) is signal.default_int_handler + ): + sigint_handler = partial(self._on_sigint, main_task=task) + try: + signal.signal(signal.SIGINT, sigint_handler) + except ValueError: + # `signal.signal` may throw if `threading.main_thread` does + # not support signals (e.g. embedded interpreter with signals + # not registered - see gh-91880) + sigint_handler = None + else: + sigint_handler = None + + self._interrupt_count = 0 + try: + return self._loop.run_until_complete(task) + except exceptions.CancelledError: + if self._interrupt_count > 0: + uncancel = getattr(task, "uncancel", None) + if uncancel is not None and uncancel() == 0: + raise KeyboardInterrupt # noqa: B904 + raise # CancelledError + finally: + if ( + sigint_handler is not None + and signal.getsignal(signal.SIGINT) is sigint_handler + ): + signal.signal(signal.SIGINT, signal.default_int_handler) + + def _lazy_init(self) -> None: + if self._state is _State.CLOSED: + raise RuntimeError("Runner is closed") + if self._state is _State.INITIALIZED: + return + if self._loop_factory is None: + self._loop = events.new_event_loop() + if not self._set_event_loop: + # Call set_event_loop only once to avoid calling + # attach_loop multiple times on child watchers + events.set_event_loop(self._loop) + self._set_event_loop = True + else: + self._loop = self._loop_factory() + if self._debug is not None: + self._loop.set_debug(self._debug) + self._context = contextvars.copy_context() + self._state = _State.INITIALIZED + + def _on_sigint(self, signum, frame, main_task: asyncio.Task) -> None: + self._interrupt_count += 1 + if self._interrupt_count == 1 and not main_task.done(): + main_task.cancel() + # wakeup loop if it is blocked by select() with long timeout + self._loop.call_soon_threadsafe(lambda: None) + return + raise KeyboardInterrupt() + + def _cancel_all_tasks(loop: AbstractEventLoop) -> None: + to_cancel = tasks.all_tasks(loop) + if not to_cancel: + return + + for task in to_cancel: + task.cancel() + + loop.run_until_complete(tasks.gather(*to_cancel, return_exceptions=True)) + + for task in to_cancel: + if task.cancelled(): + continue + if task.exception() is not None: + loop.call_exception_handler( + { + "message": "unhandled exception during asyncio.run() shutdown", + "exception": task.exception(), + "task": task, + } + ) + + async def _shutdown_default_executor(loop: AbstractEventLoop) -> None: + """Schedule the shutdown of the default executor.""" + + def _do_shutdown(future: asyncio.futures.Future) -> None: + try: + loop._default_executor.shutdown(wait=True) # type: ignore[attr-defined] + loop.call_soon_threadsafe(future.set_result, None) + except Exception as ex: + loop.call_soon_threadsafe(future.set_exception, ex) + + loop._executor_shutdown_called = True + if loop._default_executor is None: + return + future = loop.create_future() + thread = threading.Thread(target=_do_shutdown, args=(future,)) + thread.start() + try: + await future + finally: + thread.join() + + +T_Retval = TypeVar("T_Retval") +T_contra = TypeVar("T_contra", contravariant=True) +PosArgsT = TypeVarTuple("PosArgsT") +P = ParamSpec("P") + +_root_task: RunVar[asyncio.Task | None] = RunVar("_root_task") + + +def find_root_task() -> asyncio.Task: + root_task = _root_task.get(None) + if root_task is not None and not root_task.done(): + return root_task + + # Look for a task that has been started via run_until_complete() + for task in all_tasks(): + if task._callbacks and not task.done(): + callbacks = [cb for cb, context in task._callbacks] + for cb in callbacks: + if ( + cb is _run_until_complete_cb + or getattr(cb, "__module__", None) == "uvloop.loop" + ): + _root_task.set(task) + return task + + # Look up the topmost task in the AnyIO task tree, if possible + task = cast(asyncio.Task, current_task()) + state = _task_states.get(task) + if state: + cancel_scope = state.cancel_scope + while cancel_scope and cancel_scope._parent_scope is not None: + cancel_scope = cancel_scope._parent_scope + + if cancel_scope is not None: + return cast(asyncio.Task, cancel_scope._host_task) + + return task + + +def get_callable_name(func: Callable) -> str: + module = getattr(func, "__module__", None) + qualname = getattr(func, "__qualname__", None) + return ".".join([x for x in (module, qualname) if x]) + + +# +# Event loop +# + +_run_vars: WeakKeyDictionary[asyncio.AbstractEventLoop, Any] = WeakKeyDictionary() + + +def _task_started(task: asyncio.Task) -> bool: + """Return ``True`` if the task has been started and has not finished.""" + # The task coro should never be None here, as we never add finished tasks to the + # task list + coro = task.get_coro() + assert coro is not None + try: + return getcoroutinestate(coro) in (CORO_RUNNING, CORO_SUSPENDED) + except AttributeError: + # task coro is async_genenerator_asend https://bugs.python.org/issue37771 + raise Exception(f"Cannot determine if task {task} has started or not") from None + + +# +# Timeouts and cancellation +# + + +def is_anyio_cancellation(exc: CancelledError) -> bool: + # Sometimes third party frameworks catch a CancelledError and raise a new one, so as + # a workaround we have to look at the previous ones in __context__ too for a + # matching cancel message + while True: + if ( + exc.args + and isinstance(exc.args[0], str) + and exc.args[0].startswith("Cancelled via cancel scope ") + ): + return True + + if isinstance(exc.__context__, CancelledError): + exc = exc.__context__ + continue + + return False + + +class CancelScope(BaseCancelScope): + def __new__( + cls, *, deadline: float = math.inf, shield: bool = False + ) -> CancelScope: + return object.__new__(cls) + + def __init__(self, deadline: float = math.inf, shield: bool = False): + self._deadline = deadline + self._shield = shield + self._parent_scope: CancelScope | None = None + self._child_scopes: set[CancelScope] = set() + self._cancel_called = False + self._cancel_reason: str | None = None + self._cancelled_caught = False + self._active = False + self._timeout_handle: asyncio.TimerHandle | None = None + self._cancel_handle: asyncio.Handle | None = None + self._tasks: set[asyncio.Task] = set() + self._host_task: asyncio.Task | None = None + if sys.version_info >= (3, 11): + self._pending_uncancellations: int | None = 0 + else: + self._pending_uncancellations = None + + def __enter__(self) -> CancelScope: + if self._active: + raise RuntimeError( + "Each CancelScope may only be used for a single 'with' block" + ) + + self._host_task = host_task = cast(asyncio.Task, current_task()) + self._tasks.add(host_task) + try: + task_state = _task_states[host_task] + except KeyError: + task_state = TaskState(None, self) + _task_states[host_task] = task_state + else: + self._parent_scope = task_state.cancel_scope + task_state.cancel_scope = self + if self._parent_scope is not None: + # If using an eager task factory, the parent scope may not even contain + # the host task + self._parent_scope._child_scopes.add(self) + self._parent_scope._tasks.discard(host_task) + + self._timeout() + self._active = True + + # Start cancelling the host task if the scope was cancelled before entering + if self._cancel_called: + self._deliver_cancellation(self) + + return self + + def __exit__( + self, + exc_type: type[BaseException] | None, + exc_val: BaseException | None, + exc_tb: TracebackType | None, + ) -> bool: + del exc_tb + + if not self._active: + raise RuntimeError("This cancel scope is not active") + if current_task() is not self._host_task: + raise RuntimeError( + "Attempted to exit cancel scope in a different task than it was " + "entered in" + ) + + assert self._host_task is not None + host_task_state = _task_states.get(self._host_task) + if host_task_state is None or host_task_state.cancel_scope is not self: + raise RuntimeError( + "Attempted to exit a cancel scope that isn't the current tasks's " + "current cancel scope" + ) + + try: + self._active = False + if self._timeout_handle: + self._timeout_handle.cancel() + self._timeout_handle = None + + self._tasks.remove(self._host_task) + if self._parent_scope is not None: + self._parent_scope._child_scopes.remove(self) + self._parent_scope._tasks.add(self._host_task) + + host_task_state.cancel_scope = self._parent_scope + + # Restart the cancellation effort in the closest visible, cancelled parent + # scope if necessary + self._restart_cancellation_in_parent() + + # We only swallow the exception iff it was an AnyIO CancelledError, either + # directly as exc_val or inside an exception group and there are no cancelled + # parent cancel scopes visible to us here + if self._cancel_called and not self._parent_cancellation_is_visible_to_us: + # For each level-cancel() call made on the host task, call uncancel() + while self._pending_uncancellations: + self._host_task.uncancel() + self._pending_uncancellations -= 1 + + # Update cancelled_caught and check for exceptions we must not swallow + if isinstance(exc_val, BaseExceptionGroup): + cancelleds_caught, remaining = exc_val.split( + lambda exc: ( + isinstance(exc, CancelledError) + and is_anyio_cancellation(exc) + ) + ) + + if cancelleds_caught is None: + return False + + self._cancelled_caught = True + + if remaining is None: + return True + + context = remaining.__context__ + try: + # Preserve __cause__ and __suppress_context__ by avoiding `raise + # ... from ...` + raise remaining + finally: + # Preserve __context__ + remaining.__context__ = context + del context + else: + if isinstance(exc_val, CancelledError) and is_anyio_cancellation( + exc_val + ): + self._cancelled_caught = True + return True + else: + return False + else: + if self._pending_uncancellations: + assert self._parent_scope is not None + assert self._parent_scope._pending_uncancellations is not None + self._parent_scope._pending_uncancellations += ( + self._pending_uncancellations + ) + self._pending_uncancellations = 0 + + return False + finally: + self._host_task = None + del exc_val + + @property + def _effectively_cancelled(self) -> bool: + cancel_scope: CancelScope | None = self + while cancel_scope is not None: + if cancel_scope._cancel_called: + return True + + if cancel_scope.shield: + return False + + cancel_scope = cancel_scope._parent_scope + + return False + + @property + def _parent_cancellation_is_visible_to_us(self) -> bool: + return ( + self._parent_scope is not None + and not self.shield + and self._parent_scope._effectively_cancelled + ) + + def _timeout(self) -> None: + if self._deadline != math.inf: + loop = get_running_loop() + if loop.time() >= self._deadline: + self.cancel("deadline exceeded") + else: + self._timeout_handle = loop.call_at(self._deadline, self._timeout) + + def _deliver_cancellation(self, origin: CancelScope) -> bool: + """ + Deliver cancellation to directly contained tasks and nested cancel scopes. + + Schedule another run at the end if we still have tasks eligible for + cancellation. + + :param origin: the cancel scope that originated the cancellation + :return: ``True`` if the delivery needs to be retried on the next cycle + + """ + should_retry = False + current = current_task() + for task in self._tasks: + should_retry = True + if task._must_cancel: # type: ignore[attr-defined] + continue + + # The task is eligible for cancellation if it has started + if task is not current and (task is self._host_task or _task_started(task)): + waiter = task._fut_waiter # type: ignore[attr-defined] + if not isinstance(waiter, asyncio.Future) or not waiter.done(): + task.cancel(origin._cancel_reason) + if ( + task is origin._host_task + and origin._pending_uncancellations is not None + ): + origin._pending_uncancellations += 1 + + # Deliver cancellation to child scopes that aren't shielded or running their own + # cancellation callbacks + for scope in self._child_scopes: + if not scope._shield and not scope.cancel_called: + should_retry = scope._deliver_cancellation(origin) or should_retry + + # Schedule another callback if there are still tasks left + if origin is self: + if should_retry: + self._cancel_handle = get_running_loop().call_soon( + self._deliver_cancellation, origin + ) + else: + self._cancel_handle = None + + return should_retry + + def _restart_cancellation_in_parent(self) -> None: + """ + Restart the cancellation effort in the closest directly cancelled parent scope. + + """ + scope = self._parent_scope + while scope is not None: + if scope._cancel_called: + if scope._cancel_handle is None: + scope._deliver_cancellation(scope) + + break + + # No point in looking beyond any shielded scope + if scope._shield: + break + + scope = scope._parent_scope + + def cancel(self, reason: str | None = None) -> None: + if not self._cancel_called: + if self._timeout_handle: + self._timeout_handle.cancel() + self._timeout_handle = None + + self._cancel_called = True + self._cancel_reason = f"Cancelled via cancel scope {id(self):x}" + if task := current_task(): + self._cancel_reason += f" by {task}" + + if reason: + self._cancel_reason += f"; reason: {reason}" + + if self._host_task is not None: + self._deliver_cancellation(self) + + @property + def deadline(self) -> float: + return self._deadline + + @deadline.setter + def deadline(self, value: float) -> None: + self._deadline = float(value) + if self._timeout_handle is not None: + self._timeout_handle.cancel() + self._timeout_handle = None + + if self._active and not self._cancel_called: + self._timeout() + + @property + def cancel_called(self) -> bool: + return self._cancel_called + + @property + def cancelled_caught(self) -> bool: + return self._cancelled_caught + + @property + def shield(self) -> bool: + return self._shield + + @shield.setter + def shield(self, value: bool) -> None: + if self._shield != value: + self._shield = value + if not value: + self._restart_cancellation_in_parent() + + +# +# Task states +# + + +class TaskState: + """ + Encapsulates auxiliary task information that cannot be added to the Task instance + itself because there are no guarantees about its implementation. + """ + + __slots__ = "parent_id", "cancel_scope", "__weakref__" + + def __init__(self, parent_id: int | None, cancel_scope: CancelScope | None): + self.parent_id = parent_id + self.cancel_scope = cancel_scope + + +_task_states: WeakKeyDictionary[asyncio.Task, TaskState] = WeakKeyDictionary() + + +# +# Task groups +# + + +class _AsyncioTaskStatus(abc.TaskStatus): + def __init__(self, future: asyncio.Future, parent_id: int): + self._future = future + self._parent_id = parent_id + + def started(self, value: T_contra | None = None) -> None: + try: + self._future.set_result(value) + except asyncio.InvalidStateError: + if not self._future.cancelled(): + raise RuntimeError( + "called 'started' twice on the same task status" + ) from None + + task = cast(asyncio.Task, current_task()) + _task_states[task].parent_id = self._parent_id + + +if sys.version_info >= (3, 12): + _eager_task_factory_code: CodeType | None = asyncio.eager_task_factory.__code__ +else: + _eager_task_factory_code = None + + +class TaskGroup(abc.TaskGroup): + def __init__(self) -> None: + self.cancel_scope: CancelScope = CancelScope() + self._active = False + self._exceptions: list[BaseException] = [] + self._tasks: set[asyncio.Task] = set() + self._on_completed_fut: asyncio.Future[None] | None = None + + async def __aenter__(self) -> TaskGroup: + self.cancel_scope.__enter__() + self._active = True + return self + + async def __aexit__( + self, + exc_type: type[BaseException] | None, + exc_val: BaseException | None, + exc_tb: TracebackType | None, + ) -> bool: + try: + if exc_val is not None: + self.cancel_scope.cancel() + if not isinstance(exc_val, CancelledError): + self._exceptions.append(exc_val) + + loop = get_running_loop() + try: + if self._tasks: + with CancelScope() as wait_scope: + while self._tasks: + self._on_completed_fut = loop.create_future() + + try: + await self._on_completed_fut + except CancelledError as exc: + # Shield the scope against further cancellation attempts, + # as they're not productive (#695) + wait_scope.shield = True + self.cancel_scope.cancel() + + # Set exc_val from the cancellation exception if it was + # previously unset. However, we should not replace a native + # cancellation exception with one raise by a cancel scope. + if exc_val is None or ( + isinstance(exc_val, CancelledError) + and not is_anyio_cancellation(exc) + ): + exc_val = exc + + self._on_completed_fut = None + else: + # If there are no child tasks to wait on, run at least one checkpoint + # anyway + await AsyncIOBackend.cancel_shielded_checkpoint() + + self._active = False + if self._exceptions: + # The exception that got us here should already have been + # added to self._exceptions so it's ok to break exception + # chaining and avoid adding a "During handling of above..." + # for each nesting level. + raise BaseExceptionGroup( + "unhandled errors in a TaskGroup", self._exceptions + ) from None + elif exc_val: + raise exc_val + except BaseException as exc: + if self.cancel_scope.__exit__(type(exc), exc, exc.__traceback__): + return True + + raise + + return self.cancel_scope.__exit__(exc_type, exc_val, exc_tb) + finally: + del exc_val, exc_tb, self._exceptions + + def _spawn( + self, + func: Callable[[Unpack[PosArgsT]], Awaitable[Any]], + args: tuple[Unpack[PosArgsT]], + name: object, + task_status_future: asyncio.Future | None = None, + ) -> asyncio.Task: + def task_done(_task: asyncio.Task) -> None: + if sys.version_info >= (3, 14) and self.cancel_scope._host_task is not None: + asyncio.future_discard_from_awaited_by( + _task, self.cancel_scope._host_task + ) + + task_state = _task_states[_task] + assert task_state.cancel_scope is not None + assert _task in task_state.cancel_scope._tasks + task_state.cancel_scope._tasks.remove(_task) + self._tasks.remove(task) + del _task_states[_task] + + if self._on_completed_fut is not None and not self._tasks: + try: + self._on_completed_fut.set_result(None) + except asyncio.InvalidStateError: + pass + + try: + exc = _task.exception() + except CancelledError as e: + while isinstance(e.__context__, CancelledError): + e = e.__context__ + + exc = e + + if exc is not None: + # The future can only be in the cancelled state if the host task was + # cancelled, so return immediately instead of adding one more + # CancelledError to the exceptions list + if task_status_future is not None and task_status_future.cancelled(): + return + + if task_status_future is None or task_status_future.done(): + if not isinstance(exc, CancelledError): + self._exceptions.append(exc) + + if not self.cancel_scope._effectively_cancelled: + self.cancel_scope.cancel() + else: + task_status_future.set_exception(exc) + elif task_status_future is not None and not task_status_future.done(): + task_status_future.set_exception( + RuntimeError("Child exited without calling task_status.started()") + ) + + if not self._active: + raise RuntimeError( + "This task group is not active; no new tasks can be started." + ) + + kwargs = {} + if task_status_future: + parent_id = id(current_task()) + kwargs["task_status"] = _AsyncioTaskStatus( + task_status_future, id(self.cancel_scope._host_task) + ) + else: + parent_id = id(self.cancel_scope._host_task) + + coro = func(*args, **kwargs) + if not iscoroutine(coro): + prefix = f"{func.__module__}." if hasattr(func, "__module__") else "" + raise TypeError( + f"Expected {prefix}{func.__qualname__}() to return a coroutine, but " + f"the return value ({coro!r}) is not a coroutine object" + ) + + name = get_callable_name(func) if name is None else str(name) + loop = asyncio.get_running_loop() + if ( + (factory := loop.get_task_factory()) + and getattr(factory, "__code__", None) is _eager_task_factory_code + and (closure := getattr(factory, "__closure__", None)) + ): + custom_task_constructor = closure[0].cell_contents + task = custom_task_constructor(coro, loop=loop, name=name) + else: + task = create_task(coro, name=name) + + # Make the spawned task inherit the task group's cancel scope + _task_states[task] = TaskState( + parent_id=parent_id, cancel_scope=self.cancel_scope + ) + self.cancel_scope._tasks.add(task) + self._tasks.add(task) + if sys.version_info >= (3, 14) and self.cancel_scope._host_task is not None: + asyncio.future_add_to_awaited_by(task, self.cancel_scope._host_task) + + task.add_done_callback(task_done) + return task + + def start_soon( + self, + func: Callable[[Unpack[PosArgsT]], Awaitable[Any]], + *args: Unpack[PosArgsT], + name: object = None, + ) -> None: + self._spawn(func, args, name) + + async def start( + self, func: Callable[..., Awaitable[Any]], *args: object, name: object = None + ) -> Any: + future: asyncio.Future = asyncio.Future() + task = self._spawn(func, args, name, future) + + # If the task raises an exception after sending a start value without a switch + # point between, the task group is cancelled and this method never proceeds to + # process the completed future. That's why we have to have a shielded cancel + # scope here. + try: + return await future + except CancelledError: + # Cancel the task and wait for it to exit before returning + task.cancel() + with CancelScope(shield=True), suppress(CancelledError): + await task + + raise + + +# +# Threads +# + +_Retval_Queue_Type = tuple[T_Retval | None, BaseException | None] + + +class WorkerThread(Thread): + MAX_IDLE_TIME = 10 # seconds + + def __init__( + self, + root_task: asyncio.Task, + workers: set[WorkerThread], + idle_workers: deque[WorkerThread], + ): + super().__init__(name="AnyIO worker thread") + self.root_task = root_task + self.workers = workers + self.idle_workers = idle_workers + self.loop = root_task._loop + self.queue: Queue[ + tuple[Context, Callable, tuple, asyncio.Future, CancelScope] | None + ] = Queue(2) + self.idle_since = AsyncIOBackend.current_time() + self.stopping = False + + def _report_result( + self, future: asyncio.Future, result: Any, exc: BaseException | None + ) -> None: + self.idle_since = AsyncIOBackend.current_time() + if not self.stopping: + self.idle_workers.append(self) + + if not future.cancelled(): + if exc is not None: + if isinstance(exc, StopIteration): + new_exc = RuntimeError("coroutine raised StopIteration") + new_exc.__cause__ = exc + exc = new_exc + + future.set_exception(exc) + else: + future.set_result(result) + + def run(self) -> None: + with claim_worker_thread(AsyncIOBackend, self.loop): + while True: + item = self.queue.get() + if item is None: + # Shutdown command received + return + + context, func, args, future, cancel_scope = item + if not future.cancelled(): + result = None + exception: BaseException | None = None + threadlocals.current_cancel_scope = cancel_scope + try: + result = context.run(func, *args) + except BaseException as exc: + exception = exc + finally: + del threadlocals.current_cancel_scope + + if not self.loop.is_closed(): + self.loop.call_soon_threadsafe( + self._report_result, future, result, exception + ) + + del result, exception + + self.queue.task_done() + del item, context, func, args, future, cancel_scope + + def stop(self, f: asyncio.Task | None = None) -> None: + self.stopping = True + self.queue.put_nowait(None) + self.workers.discard(self) + try: + self.idle_workers.remove(self) + except ValueError: + pass + + +_threadpool_idle_workers: RunVar[deque[WorkerThread]] = RunVar( + "_threadpool_idle_workers" +) +_threadpool_workers: RunVar[set[WorkerThread]] = RunVar("_threadpool_workers") + + +# +# Subprocesses +# + + +@dataclass(eq=False) +class StreamReaderWrapper(abc.ByteReceiveStream): + _stream: asyncio.StreamReader + + async def receive(self, max_bytes: int = 65536) -> bytes: + data = await self._stream.read(max_bytes) + if data: + return data + else: + raise EndOfStream + + async def aclose(self) -> None: + self._stream.set_exception(ClosedResourceError()) + await AsyncIOBackend.checkpoint() + + +@dataclass(eq=False) +class StreamWriterWrapper(abc.ByteSendStream): + _stream: asyncio.StreamWriter + _closed: bool = field(init=False, default=False) + + async def send(self, item: bytes) -> None: + await AsyncIOBackend.checkpoint_if_cancelled() + stream_paused = self._stream._protocol._paused # type: ignore[attr-defined] + try: + self._stream.write(item) + await self._stream.drain() + except (ConnectionResetError, BrokenPipeError, RuntimeError) as exc: + # If closed by us and/or the peer: + # * on stdlib, drain() raises ConnectionResetError or BrokenPipeError + # * on uvloop and Winloop, write() eventually starts raising RuntimeError + if self._closed: + raise ClosedResourceError from exc + elif self._stream.is_closing(): + raise BrokenResourceError from exc + + raise + + if not stream_paused: + await AsyncIOBackend.cancel_shielded_checkpoint() + + async def aclose(self) -> None: + self._closed = True + self._stream.close() + await AsyncIOBackend.checkpoint() + + +@dataclass(eq=False) +class Process(abc.Process): + _process: asyncio.subprocess.Process + _stdin: StreamWriterWrapper | None + _stdout: StreamReaderWrapper | None + _stderr: StreamReaderWrapper | None + + async def aclose(self) -> None: + with CancelScope(shield=True) as scope: + if self._stdin: + await self._stdin.aclose() + if self._stdout: + await self._stdout.aclose() + if self._stderr: + await self._stderr.aclose() + + scope.shield = False + try: + await self.wait() + except BaseException: + scope.shield = True + self.kill() + await self.wait() + raise + + async def wait(self) -> int: + return await self._process.wait() + + def terminate(self) -> None: + self._process.terminate() + + def kill(self) -> None: + self._process.kill() + + def send_signal(self, signal: int) -> None: + self._process.send_signal(signal) + + @property + def pid(self) -> int: + return self._process.pid + + @property + def returncode(self) -> int | None: + return self._process.returncode + + @property + def stdin(self) -> abc.ByteSendStream | None: + return self._stdin + + @property + def stdout(self) -> abc.ByteReceiveStream | None: + return self._stdout + + @property + def stderr(self) -> abc.ByteReceiveStream | None: + return self._stderr + + +def _forcibly_shutdown_process_pool_on_exit( + workers: set[Process], _task: object +) -> None: + """ + Forcibly shuts down worker processes belonging to this event loop.""" + child_watcher: asyncio.AbstractChildWatcher | None = None # type: ignore[name-defined] + if sys.version_info < (3, 12): + try: + child_watcher = asyncio.get_event_loop_policy().get_child_watcher() + except NotImplementedError: + pass + + # Close as much as possible (w/o async/await) to avoid warnings + for process in workers.copy(): + if process.returncode is not None: + continue + + process._stdin._stream._transport.close() # type: ignore[union-attr] + process._stdout._stream._transport.close() # type: ignore[union-attr] + process._stderr._stream._transport.close() # type: ignore[union-attr] + process.kill() + if child_watcher: + child_watcher.remove_child_handler(process.pid) + + +async def _shutdown_process_pool_on_exit(workers: set[abc.Process]) -> None: + """ + Shuts down worker processes belonging to this event loop. + + NOTE: this only works when the event loop was started using asyncio.run() or + anyio.run(). + + """ + process: abc.Process + try: + await sleep(math.inf) + except asyncio.CancelledError: + workers = workers.copy() + for process in workers: + if process.returncode is None: + process.kill() + + for process in workers: + await process.aclose() + + +# +# Sockets and networking +# + + +class StreamProtocol(asyncio.Protocol): + read_queue: deque[bytes] + read_event: asyncio.Event + write_event: asyncio.Event + exception: Exception | None = None + is_at_eof: bool = False + + def connection_made(self, transport: asyncio.BaseTransport) -> None: + self.read_queue = deque() + self.read_event = asyncio.Event() + self.write_event = asyncio.Event() + self.write_event.set() + cast(asyncio.Transport, transport).set_write_buffer_limits(0) + + def connection_lost(self, exc: Exception | None) -> None: + if exc: + self.exception = exc + + self.read_event.set() + self.write_event.set() + + def data_received(self, data: bytes) -> None: + # ProactorEventloop sometimes sends bytearray instead of bytes + self.read_queue.append(bytes(data)) + self.read_event.set() + + def eof_received(self) -> bool | None: + self.is_at_eof = True + self.read_event.set() + return True + + def pause_writing(self) -> None: + self.write_event = asyncio.Event() + + def resume_writing(self) -> None: + self.write_event.set() + + +class DatagramProtocol(asyncio.DatagramProtocol): + read_queue: deque[tuple[bytes, IPSockAddrType]] + read_event: asyncio.Event + write_event: asyncio.Event + exception: Exception | None = None + + def connection_made(self, transport: asyncio.BaseTransport) -> None: + self.read_queue = deque(maxlen=100) # arbitrary value + self.read_event = asyncio.Event() + self.write_event = asyncio.Event() + self.write_event.set() + + def connection_lost(self, exc: Exception | None) -> None: + self.read_event.set() + self.write_event.set() + + def datagram_received(self, data: bytes, addr: IPSockAddrType) -> None: + addr = convert_ipv6_sockaddr(addr) + self.read_queue.append((data, addr)) + self.read_event.set() + + def error_received(self, exc: Exception) -> None: + self.exception = exc + + def pause_writing(self) -> None: + self.write_event.clear() + + def resume_writing(self) -> None: + self.write_event.set() + + +class SocketStream(abc.SocketStream): + def __init__(self, transport: asyncio.Transport, protocol: StreamProtocol): + self._transport = transport + self._protocol = protocol + self._receive_guard = ResourceGuard("reading from") + self._send_guard = ResourceGuard("writing to") + self._closed = False + + @property + def _raw_socket(self) -> socket.socket: + return self._transport.get_extra_info("socket") + + async def receive(self, max_bytes: int = 65536) -> bytes: + with self._receive_guard: + if ( + not self._protocol.read_event.is_set() + and not self._transport.is_closing() + and not self._protocol.is_at_eof + ): + self._transport.resume_reading() + await self._protocol.read_event.wait() + self._transport.pause_reading() + else: + await AsyncIOBackend.checkpoint() + + try: + chunk = self._protocol.read_queue.popleft() + except IndexError: + if self._closed: + raise ClosedResourceError from None + elif self._protocol.exception: + raise BrokenResourceError from self._protocol.exception + else: + raise EndOfStream from None + + if len(chunk) > max_bytes: + # Split the oversized chunk + chunk, leftover = chunk[:max_bytes], chunk[max_bytes:] + self._protocol.read_queue.appendleft(leftover) + + # If the read queue is empty, clear the flag so that the next call will + # block until data is available + if not self._protocol.read_queue: + self._protocol.read_event.clear() + + return chunk + + async def send(self, item: bytes) -> None: + with self._send_guard: + await AsyncIOBackend.checkpoint() + + if self._closed: + raise ClosedResourceError + elif self._protocol.exception is not None: + raise BrokenResourceError from self._protocol.exception + + try: + self._transport.write(item) + except RuntimeError as exc: + if self._transport.is_closing(): + raise BrokenResourceError from exc + else: + raise + + await self._protocol.write_event.wait() + + async def send_eof(self) -> None: + try: + self._transport.write_eof() + except OSError: + pass + + async def aclose(self) -> None: + self._closed = True + if not self._transport.is_closing(): + try: + self._transport.write_eof() + except OSError: + pass + + self._transport.close() + await sleep(0) + self._transport.abort() + + +class _RawSocketMixin: + _receive_future: asyncio.Future | None = None + _send_future: asyncio.Future | None = None + _closing = False + + def __init__(self, raw_socket: socket.socket): + self.__raw_socket = raw_socket + self._receive_guard = ResourceGuard("reading from") + self._send_guard = ResourceGuard("writing to") + + @property + def _raw_socket(self) -> socket.socket: + return self.__raw_socket + + def _wait_until_readable(self, loop: asyncio.AbstractEventLoop) -> asyncio.Future: + def callback(f: object) -> None: + del self._receive_future + loop.remove_reader(self.__raw_socket) + + f = self._receive_future = asyncio.Future() + loop.add_reader(self.__raw_socket, f.set_result, None) + f.add_done_callback(callback) + return f + + def _wait_until_writable(self, loop: asyncio.AbstractEventLoop) -> asyncio.Future: + def callback(f: object) -> None: + del self._send_future + loop.remove_writer(self.__raw_socket) + + f = self._send_future = asyncio.Future() + loop.add_writer(self.__raw_socket, f.set_result, None) + f.add_done_callback(callback) + return f + + async def aclose(self) -> None: + if not self._closing: + self._closing = True + if self.__raw_socket.fileno() != -1: + self.__raw_socket.close() + + if self._receive_future: + self._receive_future.set_result(None) + if self._send_future: + self._send_future.set_result(None) + + +class UNIXSocketStream(_RawSocketMixin, abc.UNIXSocketStream): + async def send_eof(self) -> None: + with self._send_guard: + self._raw_socket.shutdown(socket.SHUT_WR) + + async def receive(self, max_bytes: int = 65536) -> bytes: + loop = get_running_loop() + await AsyncIOBackend.checkpoint() + with self._receive_guard: + while True: + try: + data = self._raw_socket.recv(max_bytes) + except BlockingIOError: + await self._wait_until_readable(loop) + except OSError as exc: + if self._closing: + raise ClosedResourceError from None + else: + raise BrokenResourceError from exc + else: + if not data: + raise EndOfStream + + return data + + async def send(self, item: bytes) -> None: + loop = get_running_loop() + await AsyncIOBackend.checkpoint() + with self._send_guard: + view = memoryview(item) + while view: + try: + bytes_sent = self._raw_socket.send(view) + except BlockingIOError: + await self._wait_until_writable(loop) + except OSError as exc: + if self._closing: + raise ClosedResourceError from None + else: + raise BrokenResourceError from exc + else: + view = view[bytes_sent:] + + async def receive_fds(self, msglen: int, maxfds: int) -> tuple[bytes, list[int]]: + if not isinstance(msglen, int) or msglen < 0: + raise ValueError("msglen must be a non-negative integer") + if not isinstance(maxfds, int) or maxfds < 1: + raise ValueError("maxfds must be a positive integer") + + loop = get_running_loop() + fds = array.array("i") + await AsyncIOBackend.checkpoint() + with self._receive_guard: + while True: + try: + message, ancdata, flags, addr = self._raw_socket.recvmsg( + msglen, socket.CMSG_LEN(maxfds * fds.itemsize) + ) + except BlockingIOError: + await self._wait_until_readable(loop) + except OSError as exc: + if self._closing: + raise ClosedResourceError from None + else: + raise BrokenResourceError from exc + else: + if not message and not ancdata: + raise EndOfStream + + break + + for cmsg_level, cmsg_type, cmsg_data in ancdata: + if cmsg_level != socket.SOL_SOCKET or cmsg_type != socket.SCM_RIGHTS: + raise RuntimeError( + f"Received unexpected ancillary data; message = {message!r}, " + f"cmsg_level = {cmsg_level}, cmsg_type = {cmsg_type}" + ) + + fds.frombytes(cmsg_data[: len(cmsg_data) - (len(cmsg_data) % fds.itemsize)]) + + return message, list(fds) + + async def send_fds(self, message: bytes, fds: Collection[int | IOBase]) -> None: + if not message: + raise ValueError("message must not be empty") + if not fds: + raise ValueError("fds must not be empty") + + loop = get_running_loop() + filenos: list[int] = [] + for fd in fds: + if isinstance(fd, int): + filenos.append(fd) + elif isinstance(fd, IOBase): + filenos.append(fd.fileno()) + + fdarray = array.array("i", filenos) + await AsyncIOBackend.checkpoint() + with self._send_guard: + while True: + try: + # The ignore can be removed after mypy picks up + # https://github.com/python/typeshed/pull/5545 + self._raw_socket.sendmsg( + [message], [(socket.SOL_SOCKET, socket.SCM_RIGHTS, fdarray)] + ) + break + except BlockingIOError: + await self._wait_until_writable(loop) + except OSError as exc: + if self._closing: + raise ClosedResourceError from None + else: + raise BrokenResourceError from exc + + +class TCPSocketListener(abc.SocketListener): + _accept_scope: CancelScope | None = None + _closed = False + + def __init__(self, raw_socket: socket.socket): + self.__raw_socket = raw_socket + self._loop = cast(asyncio.BaseEventLoop, get_running_loop()) + self._accept_guard = ResourceGuard("accepting connections from") + + @property + def _raw_socket(self) -> socket.socket: + return self.__raw_socket + + async def accept(self) -> abc.SocketStream: + if self._closed: + raise ClosedResourceError + + with self._accept_guard: + await AsyncIOBackend.checkpoint() + with CancelScope() as self._accept_scope: + try: + client_sock, _addr = await self._loop.sock_accept(self._raw_socket) + except asyncio.CancelledError: + # Workaround for https://bugs.python.org/issue41317 + try: + self._loop.remove_reader(self._raw_socket) + except (ValueError, NotImplementedError): + pass + + if self._closed: + raise ClosedResourceError from None + + raise + finally: + self._accept_scope = None + + client_sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1) + transport, protocol = await self._loop.connect_accepted_socket( + StreamProtocol, client_sock + ) + return SocketStream(transport, protocol) + + async def aclose(self) -> None: + if self._closed: + return + + self._closed = True + if self._accept_scope: + # Workaround for https://bugs.python.org/issue41317 + try: + self._loop.remove_reader(self._raw_socket) + except (ValueError, NotImplementedError): + pass + + self._accept_scope.cancel() + await sleep(0) + + self._raw_socket.close() + + +class UNIXSocketListener(abc.SocketListener): + def __init__(self, raw_socket: socket.socket): + self.__raw_socket = raw_socket + self._loop = get_running_loop() + self._accept_guard = ResourceGuard("accepting connections from") + self._closed = False + + async def accept(self) -> abc.SocketStream: + await AsyncIOBackend.checkpoint() + with self._accept_guard: + while True: + try: + client_sock, _ = self.__raw_socket.accept() + client_sock.setblocking(False) + return UNIXSocketStream(client_sock) + except BlockingIOError: + f: asyncio.Future = asyncio.Future() + self._loop.add_reader(self.__raw_socket, f.set_result, None) + f.add_done_callback( + lambda _: self._loop.remove_reader(self.__raw_socket) + ) + await f + except OSError as exc: + if self._closed: + raise ClosedResourceError from None + else: + raise BrokenResourceError from exc + + async def aclose(self) -> None: + self._closed = True + self.__raw_socket.close() + + @property + def _raw_socket(self) -> socket.socket: + return self.__raw_socket + + +class UDPSocket(abc.UDPSocket): + def __init__( + self, transport: asyncio.DatagramTransport, protocol: DatagramProtocol + ): + self._transport = transport + self._protocol = protocol + self._receive_guard = ResourceGuard("reading from") + self._send_guard = ResourceGuard("writing to") + self._closed = False + + @property + def _raw_socket(self) -> socket.socket: + return self._transport.get_extra_info("socket") + + async def aclose(self) -> None: + self._closed = True + if not self._transport.is_closing(): + self._transport.close() + + async def receive(self) -> tuple[bytes, IPSockAddrType]: + with self._receive_guard: + await AsyncIOBackend.checkpoint() + + # If the buffer is empty, ask for more data + if not self._protocol.read_queue and not self._transport.is_closing(): + self._protocol.read_event.clear() + await self._protocol.read_event.wait() + + try: + return self._protocol.read_queue.popleft() + except IndexError: + if self._closed: + raise ClosedResourceError from None + else: + raise BrokenResourceError from None + + async def send(self, item: UDPPacketType) -> None: + with self._send_guard: + await AsyncIOBackend.checkpoint() + await self._protocol.write_event.wait() + if self._closed: + raise ClosedResourceError + elif self._transport.is_closing(): + raise BrokenResourceError + else: + self._transport.sendto(*item) + + +class ConnectedUDPSocket(abc.ConnectedUDPSocket): + def __init__( + self, transport: asyncio.DatagramTransport, protocol: DatagramProtocol + ): + self._transport = transport + self._protocol = protocol + self._receive_guard = ResourceGuard("reading from") + self._send_guard = ResourceGuard("writing to") + self._closed = False + + @property + def _raw_socket(self) -> socket.socket: + return self._transport.get_extra_info("socket") + + async def aclose(self) -> None: + self._closed = True + if not self._transport.is_closing(): + self._transport.close() + + async def receive(self) -> bytes: + with self._receive_guard: + await AsyncIOBackend.checkpoint() + + # If the buffer is empty, ask for more data + if not self._protocol.read_queue and not self._transport.is_closing(): + self._protocol.read_event.clear() + await self._protocol.read_event.wait() + + try: + packet = self._protocol.read_queue.popleft() + except IndexError: + if self._closed: + raise ClosedResourceError from None + else: + raise BrokenResourceError from None + + return packet[0] + + async def send(self, item: bytes) -> None: + with self._send_guard: + await AsyncIOBackend.checkpoint() + await self._protocol.write_event.wait() + if self._closed: + raise ClosedResourceError + elif self._transport.is_closing(): + raise BrokenResourceError + else: + self._transport.sendto(item) + + +class UNIXDatagramSocket(_RawSocketMixin, abc.UNIXDatagramSocket): + async def receive(self) -> UNIXDatagramPacketType: + loop = get_running_loop() + await AsyncIOBackend.checkpoint() + with self._receive_guard: + while True: + try: + data = self._raw_socket.recvfrom(65536) + except BlockingIOError: + await self._wait_until_readable(loop) + except OSError as exc: + if self._closing: + raise ClosedResourceError from None + else: + raise BrokenResourceError from exc + else: + return data + + async def send(self, item: UNIXDatagramPacketType) -> None: + loop = get_running_loop() + await AsyncIOBackend.checkpoint() + with self._send_guard: + while True: + try: + self._raw_socket.sendto(*item) + except BlockingIOError: + await self._wait_until_writable(loop) + except OSError as exc: + if self._closing: + raise ClosedResourceError from None + else: + raise BrokenResourceError from exc + else: + return + + +class ConnectedUNIXDatagramSocket(_RawSocketMixin, abc.ConnectedUNIXDatagramSocket): + async def receive(self) -> bytes: + loop = get_running_loop() + await AsyncIOBackend.checkpoint() + with self._receive_guard: + while True: + try: + data = self._raw_socket.recv(65536) + except BlockingIOError: + await self._wait_until_readable(loop) + except OSError as exc: + if self._closing: + raise ClosedResourceError from None + else: + raise BrokenResourceError from exc + else: + return data + + async def send(self, item: bytes) -> None: + loop = get_running_loop() + await AsyncIOBackend.checkpoint() + with self._send_guard: + while True: + try: + self._raw_socket.send(item) + except BlockingIOError: + await self._wait_until_writable(loop) + except OSError as exc: + if self._closing: + raise ClosedResourceError from None + else: + raise BrokenResourceError from exc + else: + return + + +_read_events: RunVar[dict[int, asyncio.Future[bool]]] = RunVar("read_events") +_write_events: RunVar[dict[int, asyncio.Future[bool]]] = RunVar("write_events") + + +# +# Synchronization +# + + +class Event(BaseEvent): + def __new__(cls) -> Event: + return object.__new__(cls) + + def __init__(self) -> None: + self._event = asyncio.Event() + + def set(self) -> None: + self._event.set() + + def is_set(self) -> bool: + return self._event.is_set() + + async def wait(self) -> None: + if self.is_set(): + await AsyncIOBackend.checkpoint() + else: + await self._event.wait() + + def statistics(self) -> EventStatistics: + return EventStatistics(len(self._event._waiters)) + + +class Lock(BaseLock): + def __new__(cls, *, fast_acquire: bool = False) -> Lock: + return object.__new__(cls) + + def __init__(self, *, fast_acquire: bool = False) -> None: + self._fast_acquire = fast_acquire + self._owner_task: asyncio.Task | None = None + self._waiters: deque[tuple[asyncio.Task, asyncio.Future]] = deque() + + async def acquire(self) -> None: + task = cast(asyncio.Task, current_task()) + if self._owner_task is None and not self._waiters: + await AsyncIOBackend.checkpoint_if_cancelled() + self._owner_task = task + + # Unless on the "fast path", yield control of the event loop so that other + # tasks can run too + if not self._fast_acquire: + try: + await AsyncIOBackend.cancel_shielded_checkpoint() + except CancelledError: + self.release() + raise + + return + + if self._owner_task == task: + raise RuntimeError("Attempted to acquire an already held Lock") + + fut: asyncio.Future[None] = asyncio.Future() + item = task, fut + self._waiters.append(item) + try: + await fut + except CancelledError: + self._waiters.remove(item) + if self._owner_task is task: + self.release() + + raise + + self._waiters.remove(item) + + def acquire_nowait(self) -> None: + task = cast(asyncio.Task, current_task()) + if self._owner_task is None and not self._waiters: + self._owner_task = task + return + + if self._owner_task is task: + raise RuntimeError("Attempted to acquire an already held Lock") + + raise WouldBlock + + def locked(self) -> bool: + return self._owner_task is not None + + def release(self) -> None: + if self._owner_task != current_task(): + raise RuntimeError("The current task is not holding this lock") + + for task, fut in self._waiters: + if not fut.cancelled(): + self._owner_task = task + fut.set_result(None) + return + + self._owner_task = None + + def statistics(self) -> LockStatistics: + task_info = AsyncIOTaskInfo(self._owner_task) if self._owner_task else None + return LockStatistics(self.locked(), task_info, len(self._waiters)) + + +class Semaphore(BaseSemaphore): + def __new__( + cls, + initial_value: int, + *, + max_value: int | None = None, + fast_acquire: bool = False, + ) -> Semaphore: + return object.__new__(cls) + + def __init__( + self, + initial_value: int, + *, + max_value: int | None = None, + fast_acquire: bool = False, + ): + super().__init__(initial_value, max_value=max_value) + self._value = initial_value + self._max_value = max_value + self._fast_acquire = fast_acquire + self._waiters: deque[asyncio.Future[None]] = deque() + + async def acquire(self) -> None: + if self._value > 0 and not self._waiters: + await AsyncIOBackend.checkpoint_if_cancelled() + self._value -= 1 + + # Unless on the "fast path", yield control of the event loop so that other + # tasks can run too + if not self._fast_acquire: + try: + await AsyncIOBackend.cancel_shielded_checkpoint() + except CancelledError: + self.release() + raise + + return + + fut: asyncio.Future[None] = asyncio.Future() + self._waiters.append(fut) + try: + await fut + except CancelledError: + try: + self._waiters.remove(fut) + except ValueError: + self.release() + + raise + + def acquire_nowait(self) -> None: + if self._value == 0: + raise WouldBlock + + self._value -= 1 + + def release(self) -> None: + if self._max_value is not None and self._value == self._max_value: + raise ValueError("semaphore released too many times") + + for fut in self._waiters: + if not fut.cancelled(): + fut.set_result(None) + self._waiters.remove(fut) + return + + self._value += 1 + + @property + def value(self) -> int: + return self._value + + @property + def max_value(self) -> int | None: + return self._max_value + + def statistics(self) -> SemaphoreStatistics: + return SemaphoreStatistics(len(self._waiters)) + + +class CapacityLimiter(BaseCapacityLimiter): + _total_tokens: float = 0 + + def __new__(cls, total_tokens: float) -> CapacityLimiter: + return object.__new__(cls) + + def __init__(self, total_tokens: float): + self._borrowers: set[Any] = set() + self._wait_queue: OrderedDict[Any, asyncio.Event] = OrderedDict() + self.total_tokens = total_tokens + + async def __aenter__(self) -> None: + await self.acquire() + + async def __aexit__( + self, + exc_type: type[BaseException] | None, + exc_val: BaseException | None, + exc_tb: TracebackType | None, + ) -> None: + self.release() + + @property + def total_tokens(self) -> float: + return self._total_tokens + + @total_tokens.setter + def total_tokens(self, value: float) -> None: + if not isinstance(value, int) and not math.isinf(value): + raise TypeError("total_tokens must be an int or math.inf") + + if value < 0: + raise ValueError("total_tokens must be >= 0") + + waiters_to_notify = max(value - self._total_tokens, 0) + self._total_tokens = value + + # Notify waiting tasks that they have acquired the limiter + while self._wait_queue and waiters_to_notify: + event = self._wait_queue.popitem(last=False)[1] + event.set() + waiters_to_notify -= 1 + + @property + def borrowed_tokens(self) -> int: + return len(self._borrowers) + + @property + def available_tokens(self) -> float: + return self._total_tokens - len(self._borrowers) + + def _notify_next_waiter(self) -> None: + """Notify the next task in line if this limiter has free capacity now.""" + if self._wait_queue and len(self._borrowers) < self._total_tokens: + event = self._wait_queue.popitem(last=False)[1] + event.set() + + def acquire_nowait(self) -> None: + self.acquire_on_behalf_of_nowait(current_task()) + + def acquire_on_behalf_of_nowait(self, borrower: object) -> None: + if borrower in self._borrowers: + raise RuntimeError( + "this borrower is already holding one of this CapacityLimiter's tokens" + ) + + if self._wait_queue or len(self._borrowers) >= self._total_tokens: + raise WouldBlock + + self._borrowers.add(borrower) + + async def acquire(self) -> None: + return await self.acquire_on_behalf_of(current_task()) + + async def acquire_on_behalf_of(self, borrower: object) -> None: + await AsyncIOBackend.checkpoint_if_cancelled() + try: + self.acquire_on_behalf_of_nowait(borrower) + except WouldBlock: + event = asyncio.Event() + self._wait_queue[borrower] = event + try: + await event.wait() + except BaseException: + self._wait_queue.pop(borrower, None) + if event.is_set(): + self._notify_next_waiter() + + raise + + self._borrowers.add(borrower) + else: + try: + await AsyncIOBackend.cancel_shielded_checkpoint() + except BaseException: + self.release() + raise + + def release(self) -> None: + self.release_on_behalf_of(current_task()) + + def release_on_behalf_of(self, borrower: object) -> None: + try: + self._borrowers.remove(borrower) + except KeyError: + raise RuntimeError( + "this borrower isn't holding any of this CapacityLimiter's tokens" + ) from None + + self._notify_next_waiter() + + def statistics(self) -> CapacityLimiterStatistics: + return CapacityLimiterStatistics( + self.borrowed_tokens, + self.total_tokens, + tuple(self._borrowers), + len(self._wait_queue), + ) + + +_default_thread_limiter: RunVar[CapacityLimiter] = RunVar("_default_thread_limiter") + + +# +# Operating system signals +# + + +class _SignalReceiver: + def __init__(self, signals: tuple[Signals, ...]): + self._signals = signals + self._loop = get_running_loop() + self._signal_queue: deque[Signals] = deque() + self._future: asyncio.Future = asyncio.Future() + self._handled_signals: set[Signals] = set() + + def _deliver(self, signum: Signals) -> None: + self._signal_queue.append(signum) + if not self._future.done(): + self._future.set_result(None) + + def __enter__(self) -> _SignalReceiver: + for sig in set(self._signals): + self._loop.add_signal_handler(sig, self._deliver, sig) + self._handled_signals.add(sig) + + return self + + def __exit__( + self, + exc_type: type[BaseException] | None, + exc_val: BaseException | None, + exc_tb: TracebackType | None, + ) -> None: + for sig in self._handled_signals: + self._loop.remove_signal_handler(sig) + + def __aiter__(self) -> _SignalReceiver: + return self + + async def __anext__(self) -> Signals: + await AsyncIOBackend.checkpoint() + if not self._signal_queue: + self._future = asyncio.Future() + await self._future + + return self._signal_queue.popleft() + + +# +# Testing and debugging +# + + +class AsyncIOTaskInfo(TaskInfo): + def __init__(self, task: asyncio.Task): + task_state = _task_states.get(task) + if task_state is None: + parent_id = None + else: + parent_id = task_state.parent_id + + coro = task.get_coro() + assert coro is not None, "created TaskInfo from a completed Task" + super().__init__(id(task), parent_id, task.get_name(), coro) + self._task = weakref.ref(task) + + def has_pending_cancellation(self) -> bool: + if not (task := self._task()): + # If the task isn't around anymore, it won't have a pending cancellation + return False + + if task._must_cancel: # type: ignore[attr-defined] + return True + elif ( + isinstance(task._fut_waiter, asyncio.Future) # type: ignore[attr-defined] + and task._fut_waiter.cancelled() # type: ignore[attr-defined] + ): + return True + + if task_state := _task_states.get(task): + if cancel_scope := task_state.cancel_scope: + return cancel_scope._effectively_cancelled + + return False + + +class TestRunner(abc.TestRunner): + _send_stream: MemoryObjectSendStream[tuple[Awaitable[Any], asyncio.Future[Any]]] + + def __init__( + self, + *, + debug: bool | None = None, + use_uvloop: bool = False, + loop_factory: Callable[[], AbstractEventLoop] | None = None, + ) -> None: + if use_uvloop and loop_factory is None: + if sys.platform != "win32": + import uvloop + + loop_factory = uvloop.new_event_loop + else: + import winloop + + loop_factory = winloop.new_event_loop + + self._runner = Runner(debug=debug, loop_factory=loop_factory) + self._exceptions: list[BaseException] = [] + self._runner_task: asyncio.Task | None = None + + def __enter__(self) -> TestRunner: + self._runner.__enter__() + self.get_loop().set_exception_handler(self._exception_handler) + return self + + def __exit__( + self, + exc_type: type[BaseException] | None, + exc_val: BaseException | None, + exc_tb: TracebackType | None, + ) -> None: + self._runner.__exit__(exc_type, exc_val, exc_tb) + + def get_loop(self) -> AbstractEventLoop: + return self._runner.get_loop() + + def _exception_handler( + self, loop: asyncio.AbstractEventLoop, context: dict[str, Any] + ) -> None: + if isinstance(context.get("exception"), Exception): + self._exceptions.append(context["exception"]) + else: + loop.default_exception_handler(context) + + def _raise_async_exceptions(self) -> None: + # Re-raise any exceptions raised in asynchronous callbacks + if self._exceptions: + exceptions, self._exceptions = self._exceptions, [] + if len(exceptions) == 1: + raise exceptions[0] + elif exceptions: + raise BaseExceptionGroup( + "Multiple exceptions occurred in asynchronous callbacks", exceptions + ) + + async def _run_tests_and_fixtures( + self, + receive_stream: MemoryObjectReceiveStream[ + tuple[Awaitable[T_Retval], asyncio.Future[T_Retval]] + ], + ) -> None: + from _pytest.outcomes import OutcomeException + + with receive_stream, self._send_stream: + async for coro, future in receive_stream: + try: + retval = await coro + except CancelledError as exc: + if not future.cancelled(): + future.cancel(*exc.args) + + raise + except BaseException as exc: + if not future.cancelled(): + future.set_exception(exc) + + if not isinstance(exc, (Exception, OutcomeException)): + raise + else: + if not future.cancelled(): + future.set_result(retval) + + async def _call_in_runner_task( + self, + func: Callable[P, Awaitable[T_Retval]], + /, + *args: P.args, + **kwargs: P.kwargs, + ) -> T_Retval: + if not self._runner_task: + self._send_stream, receive_stream = create_memory_object_stream[ + tuple[Awaitable[Any], asyncio.Future] + ](1) + self._runner_task = self.get_loop().create_task( + self._run_tests_and_fixtures(receive_stream) + ) + + coro = func(*args, **kwargs) + future: asyncio.Future[T_Retval] = self.get_loop().create_future() + self._send_stream.send_nowait((coro, future)) + return await future + + def run_asyncgen_fixture( + self, + fixture_func: Callable[..., AsyncGenerator[T_Retval, Any]], + kwargs: dict[str, Any], + ) -> Iterable[T_Retval]: + asyncgen = fixture_func(**kwargs) + fixturevalue: T_Retval = self.get_loop().run_until_complete( + self._call_in_runner_task(asyncgen.asend, None) + ) + self._raise_async_exceptions() + + yield fixturevalue + + try: + self.get_loop().run_until_complete( + self._call_in_runner_task(asyncgen.asend, None) + ) + except StopAsyncIteration: + self._raise_async_exceptions() + else: + self.get_loop().run_until_complete(asyncgen.aclose()) + raise RuntimeError("Async generator fixture did not stop") + + def run_fixture( + self, + fixture_func: Callable[..., Coroutine[Any, Any, T_Retval]], + kwargs: dict[str, Any], + ) -> T_Retval: + retval = self.get_loop().run_until_complete( + self._call_in_runner_task(fixture_func, **kwargs) + ) + self._raise_async_exceptions() + return retval + + def run_test( + self, test_func: Callable[..., Coroutine[Any, Any, Any]], kwargs: dict[str, Any] + ) -> None: + try: + self.get_loop().run_until_complete( + self._call_in_runner_task(test_func, **kwargs) + ) + except Exception as exc: + self._exceptions.append(exc) + + self._raise_async_exceptions() + + +class AsyncIOBackend(AsyncBackend): + @classmethod + def run( + cls, + func: Callable[[Unpack[PosArgsT]], Awaitable[T_Retval]], + args: tuple[Unpack[PosArgsT]], + kwargs: dict[str, Any], + options: dict[str, Any], + ) -> T_Retval: + @wraps(func) + async def wrapper() -> T_Retval: + task = cast(asyncio.Task, current_task()) + task.set_name(get_callable_name(func)) + _task_states[task] = TaskState(None, None) + + try: + return await func(*args) + finally: + del _task_states[task] + + debug = options.get("debug", None) + loop_factory = options.get("loop_factory", None) + if loop_factory is None and options.get("use_uvloop", False): + if sys.platform != "win32": + import uvloop + + loop_factory = uvloop.new_event_loop + else: + import winloop + + loop_factory = winloop.new_event_loop + + with Runner(debug=debug, loop_factory=loop_factory) as runner: + return runner.run(wrapper()) + + @classmethod + def current_token(cls) -> object: + return get_running_loop() + + @classmethod + def current_time(cls) -> float: + return get_running_loop().time() + + @classmethod + def cancelled_exception_class(cls) -> type[BaseException]: + return CancelledError + + @classmethod + async def checkpoint(cls) -> None: + await sleep(0) + + @classmethod + async def checkpoint_if_cancelled(cls) -> None: + task = current_task() + if task is None: + return + + try: + cancel_scope = _task_states[task].cancel_scope + except KeyError: + return + + while cancel_scope: + if cancel_scope.cancel_called: + await sleep(0) + elif cancel_scope.shield: + break + else: + cancel_scope = cancel_scope._parent_scope + + @classmethod + async def cancel_shielded_checkpoint(cls) -> None: + with CancelScope(shield=True): + await sleep(0) + + @classmethod + async def sleep(cls, delay: float) -> None: + await sleep(delay) + + @classmethod + def create_cancel_scope( + cls, *, deadline: float = math.inf, shield: bool = False + ) -> CancelScope: + return CancelScope(deadline=deadline, shield=shield) + + @classmethod + def current_effective_deadline(cls) -> float: + if (task := current_task()) is None: + return math.inf + + try: + cancel_scope = _task_states[task].cancel_scope + except KeyError: + return math.inf + + deadline = math.inf + while cancel_scope: + deadline = min(deadline, cancel_scope.deadline) + if cancel_scope._cancel_called: + deadline = -math.inf + break + elif cancel_scope.shield: + break + else: + cancel_scope = cancel_scope._parent_scope + + return deadline + + @classmethod + def create_task_group(cls) -> abc.TaskGroup: + return TaskGroup() + + @classmethod + def create_event(cls) -> abc.Event: + return Event() + + @classmethod + def create_lock(cls, *, fast_acquire: bool) -> abc.Lock: + return Lock(fast_acquire=fast_acquire) + + @classmethod + def create_semaphore( + cls, + initial_value: int, + *, + max_value: int | None = None, + fast_acquire: bool = False, + ) -> abc.Semaphore: + return Semaphore(initial_value, max_value=max_value, fast_acquire=fast_acquire) + + @classmethod + def create_capacity_limiter(cls, total_tokens: float) -> abc.CapacityLimiter: + return CapacityLimiter(total_tokens) + + @classmethod + async def run_sync_in_worker_thread( # type: ignore[return] + cls, + func: Callable[[Unpack[PosArgsT]], T_Retval], + args: tuple[Unpack[PosArgsT]], + abandon_on_cancel: bool = False, + limiter: abc.CapacityLimiter | None = None, + ) -> T_Retval: + await cls.checkpoint() + + # If this is the first run in this event loop thread, set up the necessary + # variables + try: + idle_workers = _threadpool_idle_workers.get() + workers = _threadpool_workers.get() + except LookupError: + idle_workers = deque() + workers = set() + _threadpool_idle_workers.set(idle_workers) + _threadpool_workers.set(workers) + + async with limiter or cls.current_default_thread_limiter(): + with CancelScope(shield=not abandon_on_cancel) as scope: + future = asyncio.Future[T_Retval]() + root_task = find_root_task() + if not idle_workers: + worker = WorkerThread(root_task, workers, idle_workers) + worker.start() + workers.add(worker) + root_task.add_done_callback( + worker.stop, context=contextvars.Context() + ) + else: + worker = idle_workers.pop() + + # Prune any other workers that have been idle for MAX_IDLE_TIME + # seconds or longer + now = cls.current_time() + while idle_workers: + if ( + now - idle_workers[0].idle_since + < WorkerThread.MAX_IDLE_TIME + ): + break + + expired_worker = idle_workers.popleft() + expired_worker.root_task.remove_done_callback( + expired_worker.stop + ) + expired_worker.stop() + + context = copy_context() + context.run(set_current_async_library, None) + if abandon_on_cancel or scope._parent_scope is None: + worker_scope = scope + else: + worker_scope = scope._parent_scope + + worker.queue.put_nowait((context, func, args, future, worker_scope)) + return await future + + @classmethod + def check_cancelled(cls) -> None: + scope: CancelScope | None = threadlocals.current_cancel_scope + while scope is not None: + if scope.cancel_called: + raise CancelledError(f"Cancelled by cancel scope {id(scope):x}") + + if scope.shield: + return + + scope = scope._parent_scope + + @classmethod + def run_async_from_thread( + cls, + func: Callable[[Unpack[PosArgsT]], Awaitable[T_Retval]], + args: tuple[Unpack[PosArgsT]], + token: object, + ) -> T_Retval: + async def task_wrapper() -> T_Retval: + __tracebackhide__ = True + if scope is not None: + task = cast(asyncio.Task, current_task()) + _task_states[task] = TaskState(None, scope) + scope._tasks.add(task) + try: + return await func(*args) + except CancelledError as exc: + raise concurrent.futures.CancelledError(str(exc)) from None + finally: + if scope is not None: + scope._tasks.discard(task) + + loop = cast( + "AbstractEventLoop", token or threadlocals.current_token.native_token + ) + if loop.is_closed(): + raise RunFinishedError + + context = copy_context() + context.run(set_current_async_library, "asyncio") + scope = getattr(threadlocals, "current_cancel_scope", None) + f: concurrent.futures.Future[T_Retval] = context.run( + asyncio.run_coroutine_threadsafe, task_wrapper(), loop=loop + ) + return f.result() + + @classmethod + def run_sync_from_thread( + cls, + func: Callable[[Unpack[PosArgsT]], T_Retval], + args: tuple[Unpack[PosArgsT]], + token: object, + ) -> T_Retval: + @wraps(func) + def wrapper() -> None: + try: + set_current_async_library("asyncio") + f.set_result(func(*args)) + except BaseException as exc: + f.set_exception(exc) + if not isinstance(exc, Exception): + raise + + loop = cast( + "AbstractEventLoop", token or threadlocals.current_token.native_token + ) + if loop.is_closed(): + raise RunFinishedError + + f: concurrent.futures.Future[T_Retval] = Future() + loop.call_soon_threadsafe(wrapper) + return f.result() + + @classmethod + async def open_process( + cls, + command: StrOrBytesPath | Sequence[StrOrBytesPath], + *, + stdin: int | IO[Any] | None, + stdout: int | IO[Any] | None, + stderr: int | IO[Any] | None, + **kwargs: Any, + ) -> Process: + await cls.checkpoint() + if isinstance(command, PathLike): + command = os.fspath(command) + + if isinstance(command, (str, bytes)): + process = await asyncio.create_subprocess_shell( + command, + stdin=stdin, + stdout=stdout, + stderr=stderr, + **kwargs, + ) + else: + process = await asyncio.create_subprocess_exec( + *command, + stdin=stdin, + stdout=stdout, + stderr=stderr, + **kwargs, + ) + + stdin_stream = StreamWriterWrapper(process.stdin) if process.stdin else None + stdout_stream = StreamReaderWrapper(process.stdout) if process.stdout else None + stderr_stream = StreamReaderWrapper(process.stderr) if process.stderr else None + return Process(process, stdin_stream, stdout_stream, stderr_stream) + + @classmethod + def setup_process_pool_exit_at_shutdown(cls, workers: set[abc.Process]) -> None: + create_task( + _shutdown_process_pool_on_exit(workers), + name="AnyIO process pool shutdown task", + ) + find_root_task().add_done_callback( + partial(_forcibly_shutdown_process_pool_on_exit, workers) # type:ignore[arg-type] + ) + + @classmethod + async def connect_tcp( + cls, host: str, port: int, local_address: IPSockAddrType | None = None + ) -> abc.SocketStream: + transport, protocol = cast( + tuple[asyncio.Transport, StreamProtocol], + await get_running_loop().create_connection( + StreamProtocol, host, port, local_addr=local_address + ), + ) + transport.pause_reading() + return SocketStream(transport, protocol) + + @classmethod + async def connect_unix(cls, path: str | bytes) -> abc.UNIXSocketStream: + await cls.checkpoint() + loop = get_running_loop() + raw_socket = socket.socket(socket.AF_UNIX) + raw_socket.setblocking(False) + while True: + try: + raw_socket.connect(path) + except BlockingIOError: + f: asyncio.Future = asyncio.Future() + loop.add_writer(raw_socket, f.set_result, None) + f.add_done_callback(lambda _: loop.remove_writer(raw_socket)) + await f + except BaseException: + raw_socket.close() + raise + else: + return UNIXSocketStream(raw_socket) + + @classmethod + def create_tcp_listener(cls, sock: socket.socket) -> SocketListener: + return TCPSocketListener(sock) + + @classmethod + def create_unix_listener(cls, sock: socket.socket) -> SocketListener: + return UNIXSocketListener(sock) + + @classmethod + async def create_udp_socket( + cls, + family: AddressFamily, + local_address: IPSockAddrType | None, + remote_address: IPSockAddrType | None, + reuse_port: bool, + ) -> UDPSocket | ConnectedUDPSocket: + transport, protocol = await get_running_loop().create_datagram_endpoint( + DatagramProtocol, + local_addr=local_address, + remote_addr=remote_address, + family=family, + reuse_port=reuse_port, + ) + if protocol.exception: + transport.close() + raise protocol.exception + + if not remote_address: + return UDPSocket(transport, protocol) + else: + return ConnectedUDPSocket(transport, protocol) + + @classmethod + async def create_unix_datagram_socket( # type: ignore[override] + cls, raw_socket: socket.socket, remote_path: str | bytes | None + ) -> abc.UNIXDatagramSocket | abc.ConnectedUNIXDatagramSocket: + await cls.checkpoint() + loop = get_running_loop() + + if remote_path: + while True: + try: + raw_socket.connect(remote_path) + except BlockingIOError: + f: asyncio.Future = asyncio.Future() + loop.add_writer(raw_socket, f.set_result, None) + f.add_done_callback(lambda _: loop.remove_writer(raw_socket)) + await f + except BaseException: + raw_socket.close() + raise + else: + return ConnectedUNIXDatagramSocket(raw_socket) + else: + return UNIXDatagramSocket(raw_socket) + + @classmethod + async def getaddrinfo( + cls, + host: bytes | str | None, + port: str | int | None, + *, + family: int | AddressFamily = 0, + type: int | SocketKind = 0, + proto: int = 0, + flags: int = 0, + ) -> Sequence[ + tuple[ + AddressFamily, + SocketKind, + int, + str, + tuple[str, int] | tuple[str, int, int, int] | tuple[int, bytes], + ] + ]: + return await get_running_loop().getaddrinfo( + host, port, family=family, type=type, proto=proto, flags=flags + ) + + @classmethod + async def getnameinfo( + cls, sockaddr: IPSockAddrType, flags: int = 0 + ) -> tuple[str, str]: + return await get_running_loop().getnameinfo(sockaddr, flags) + + @classmethod + async def wait_readable(cls, obj: FileDescriptorLike) -> None: + try: + read_events = _read_events.get() + except LookupError: + read_events = {} + _read_events.set(read_events) + + fd = obj if isinstance(obj, int) else obj.fileno() + if read_events.get(fd): + raise BusyResourceError("reading from") + + loop = get_running_loop() + fut: asyncio.Future[bool] = loop.create_future() + + def cb() -> None: + try: + del read_events[fd] + except KeyError: + pass + else: + remove_reader(fd) + + try: + fut.set_result(True) + except asyncio.InvalidStateError: + pass + + try: + loop.add_reader(fd, cb) + except NotImplementedError: + from anyio._core._asyncio_selector_thread import get_selector + + selector = get_selector() + selector.add_reader(fd, cb) + remove_reader = selector.remove_reader + else: + remove_reader = loop.remove_reader + + read_events[fd] = fut + try: + success = await fut + finally: + try: + del read_events[fd] + except KeyError: + pass + else: + remove_reader(fd) + + if not success: + raise ClosedResourceError + + @classmethod + async def wait_writable(cls, obj: FileDescriptorLike) -> None: + try: + write_events = _write_events.get() + except LookupError: + write_events = {} + _write_events.set(write_events) + + fd = obj if isinstance(obj, int) else obj.fileno() + if write_events.get(fd): + raise BusyResourceError("writing to") + + loop = get_running_loop() + fut: asyncio.Future[bool] = loop.create_future() + + def cb() -> None: + try: + del write_events[fd] + except KeyError: + pass + else: + remove_writer(fd) + + try: + fut.set_result(True) + except asyncio.InvalidStateError: + pass + + try: + loop.add_writer(fd, cb) + except NotImplementedError: + from anyio._core._asyncio_selector_thread import get_selector + + selector = get_selector() + selector.add_writer(fd, cb) + remove_writer = selector.remove_writer + else: + remove_writer = loop.remove_writer + + write_events[fd] = fut + try: + success = await fut + finally: + try: + del write_events[fd] + except KeyError: + pass + else: + remove_writer(fd) + + if not success: + raise ClosedResourceError + + @classmethod + def notify_closing(cls, obj: FileDescriptorLike) -> None: + fd = obj if isinstance(obj, int) else obj.fileno() + loop = get_running_loop() + + try: + write_events = _write_events.get() + except LookupError: + pass + else: + try: + fut = write_events.pop(fd) + except KeyError: + pass + else: + try: + fut.set_result(False) + except asyncio.InvalidStateError: + pass + + try: + loop.remove_writer(fd) + except NotImplementedError: + from anyio._core._asyncio_selector_thread import get_selector + + get_selector().remove_writer(fd) + + try: + read_events = _read_events.get() + except LookupError: + pass + else: + try: + fut = read_events.pop(fd) + except KeyError: + pass + else: + try: + fut.set_result(False) + except asyncio.InvalidStateError: + pass + + try: + loop.remove_reader(fd) + except NotImplementedError: + from anyio._core._asyncio_selector_thread import get_selector + + get_selector().remove_reader(fd) + + @classmethod + async def wrap_listener_socket(cls, sock: socket.socket) -> SocketListener: + return TCPSocketListener(sock) + + @classmethod + async def wrap_stream_socket(cls, sock: socket.socket) -> SocketStream: + transport, protocol = await get_running_loop().create_connection( + StreamProtocol, sock=sock + ) + return SocketStream(transport, protocol) + + @classmethod + async def wrap_unix_stream_socket(cls, sock: socket.socket) -> UNIXSocketStream: + return UNIXSocketStream(sock) + + @classmethod + async def wrap_udp_socket(cls, sock: socket.socket) -> UDPSocket: + transport, protocol = await get_running_loop().create_datagram_endpoint( + DatagramProtocol, sock=sock + ) + return UDPSocket(transport, protocol) + + @classmethod + async def wrap_connected_udp_socket(cls, sock: socket.socket) -> ConnectedUDPSocket: + transport, protocol = await get_running_loop().create_datagram_endpoint( + DatagramProtocol, sock=sock + ) + return ConnectedUDPSocket(transport, protocol) + + @classmethod + async def wrap_unix_datagram_socket(cls, sock: socket.socket) -> UNIXDatagramSocket: + return UNIXDatagramSocket(sock) + + @classmethod + async def wrap_connected_unix_datagram_socket( + cls, sock: socket.socket + ) -> ConnectedUNIXDatagramSocket: + return ConnectedUNIXDatagramSocket(sock) + + @classmethod + def current_default_thread_limiter(cls) -> CapacityLimiter: + try: + return _default_thread_limiter.get() + except LookupError: + limiter = CapacityLimiter(40) + _default_thread_limiter.set(limiter) + return limiter + + @classmethod + def open_signal_receiver( + cls, *signals: Signals + ) -> AbstractContextManager[AsyncIterator[Signals]]: + return _SignalReceiver(signals) + + @classmethod + def get_current_task(cls) -> TaskInfo: + return AsyncIOTaskInfo(current_task()) # type: ignore[arg-type] + + @classmethod + def get_running_tasks(cls) -> Sequence[TaskInfo]: + return [AsyncIOTaskInfo(task) for task in all_tasks() if not task.done()] + + @classmethod + async def wait_all_tasks_blocked(cls) -> None: + await cls.checkpoint() + this_task = current_task() + while True: + for task in all_tasks(): + if task is this_task: + continue + + waiter = task._fut_waiter # type: ignore[attr-defined] + if waiter is None or waiter.done(): + await sleep(0.1) + break + else: + return + + @classmethod + def create_test_runner(cls, options: dict[str, Any]) -> TestRunner: + return TestRunner(**options) + + +backend_class = AsyncIOBackend diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/anyio/_backends/_trio.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/anyio/_backends/_trio.py new file mode 100644 index 0000000000000000000000000000000000000000..b85a10a13a0149e12718eea95f9269aed75449b6 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/anyio/_backends/_trio.py @@ -0,0 +1,1343 @@ +from __future__ import annotations + +import array +import math +import os +import socket +import sys +import types +import weakref +from collections.abc import ( + AsyncGenerator, + AsyncIterator, + Awaitable, + Callable, + Collection, + Coroutine, + Iterable, + Sequence, +) +from contextlib import AbstractContextManager +from dataclasses import dataclass +from io import IOBase +from os import PathLike +from signal import Signals +from socket import AddressFamily, SocketKind +from types import TracebackType +from typing import ( + IO, + TYPE_CHECKING, + Any, + Generic, + NoReturn, + ParamSpec, + TypeVar, + cast, + overload, +) + +import trio.from_thread +import trio.lowlevel +from outcome import Error, Outcome, Value +from trio.lowlevel import ( + current_root_task, + current_task, + notify_closing, + wait_readable, + wait_writable, +) +from trio.socket import SocketType as TrioSocketType +from trio.to_thread import run_sync + +from .. import ( + CapacityLimiterStatistics, + EventStatistics, + LockStatistics, + RunFinishedError, + TaskInfo, + WouldBlock, + abc, +) +from .._core._eventloop import claim_worker_thread +from .._core._exceptions import ( + BrokenResourceError, + BusyResourceError, + ClosedResourceError, + EndOfStream, +) +from .._core._sockets import convert_ipv6_sockaddr +from .._core._streams import create_memory_object_stream +from .._core._synchronization import ( + CapacityLimiter as BaseCapacityLimiter, +) +from .._core._synchronization import Event as BaseEvent +from .._core._synchronization import Lock as BaseLock +from .._core._synchronization import ( + ResourceGuard, + SemaphoreStatistics, +) +from .._core._synchronization import Semaphore as BaseSemaphore +from .._core._tasks import CancelScope as BaseCancelScope +from ..abc import IPSockAddrType, UDPPacketType, UNIXDatagramPacketType +from ..abc._eventloop import AsyncBackend, StrOrBytesPath +from ..streams.memory import MemoryObjectSendStream + +if TYPE_CHECKING: + from _typeshed import FileDescriptorLike + +if sys.version_info >= (3, 11): + from typing import TypeVarTuple, Unpack +else: + from exceptiongroup import BaseExceptionGroup + from typing_extensions import TypeVarTuple, Unpack + +T = TypeVar("T") +T_Retval = TypeVar("T_Retval") +T_SockAddr = TypeVar("T_SockAddr", str, IPSockAddrType) +PosArgsT = TypeVarTuple("PosArgsT") +P = ParamSpec("P") + + +# +# Event loop +# + +RunVar = trio.lowlevel.RunVar + + +# +# Timeouts and cancellation +# + + +class CancelScope(BaseCancelScope): + def __new__( + cls, original: trio.CancelScope | None = None, **kwargs: object + ) -> CancelScope: + return object.__new__(cls) + + def __init__(self, original: trio.CancelScope | None = None, **kwargs: Any) -> None: + self.__original = original or trio.CancelScope(**kwargs) + + def __enter__(self) -> CancelScope: + self.__original.__enter__() + return self + + def __exit__( + self, + exc_type: type[BaseException] | None, + exc_val: BaseException | None, + exc_tb: TracebackType | None, + ) -> bool: + return self.__original.__exit__(exc_type, exc_val, exc_tb) + + def cancel(self, reason: str | None = None) -> None: + self.__original.cancel(reason) + + @property + def deadline(self) -> float: + return self.__original.deadline + + @deadline.setter + def deadline(self, value: float) -> None: + self.__original.deadline = value + + @property + def cancel_called(self) -> bool: + return self.__original.cancel_called + + @property + def cancelled_caught(self) -> bool: + return self.__original.cancelled_caught + + @property + def shield(self) -> bool: + return self.__original.shield + + @shield.setter + def shield(self, value: bool) -> None: + self.__original.shield = value + + +# +# Task groups +# + + +class TaskGroup(abc.TaskGroup): + def __init__(self) -> None: + self._active = False + self._nursery_manager = trio.open_nursery(strict_exception_groups=True) + self.cancel_scope = None # type: ignore[assignment] + + async def __aenter__(self) -> TaskGroup: + self._active = True + self._nursery = await self._nursery_manager.__aenter__() + self.cancel_scope = CancelScope(self._nursery.cancel_scope) + return self + + async def __aexit__( + self, + exc_type: type[BaseException] | None, + exc_val: BaseException | None, + exc_tb: TracebackType | None, + ) -> bool: + try: + # trio.Nursery.__exit__ returns bool; .open_nursery has wrong type + return await self._nursery_manager.__aexit__(exc_type, exc_val, exc_tb) # type: ignore[return-value] + except BaseExceptionGroup as exc: + if not exc.split(trio.Cancelled)[1]: + raise trio.Cancelled._create() from exc + + raise + finally: + del exc_val, exc_tb + self._active = False + + def start_soon( + self, + func: Callable[[Unpack[PosArgsT]], Awaitable[Any]], + *args: Unpack[PosArgsT], + name: object = None, + ) -> None: + if not self._active: + raise RuntimeError( + "This task group is not active; no new tasks can be started." + ) + + self._nursery.start_soon(func, *args, name=name) + + async def start( + self, func: Callable[..., Awaitable[Any]], *args: object, name: object = None + ) -> Any: + if not self._active: + raise RuntimeError( + "This task group is not active; no new tasks can be started." + ) + + return await self._nursery.start(func, *args, name=name) + + +# +# Subprocesses +# + + +@dataclass(eq=False) +class ReceiveStreamWrapper(abc.ByteReceiveStream): + _stream: trio.abc.ReceiveStream + + async def receive(self, max_bytes: int | None = None) -> bytes: + try: + data = await self._stream.receive_some(max_bytes) + except trio.ClosedResourceError as exc: + raise ClosedResourceError from exc.__cause__ + except trio.BrokenResourceError as exc: + raise BrokenResourceError from exc.__cause__ + + if data: + return bytes(data) + else: + raise EndOfStream + + async def aclose(self) -> None: + await self._stream.aclose() + + +@dataclass(eq=False) +class SendStreamWrapper(abc.ByteSendStream): + _stream: trio.abc.SendStream + + async def send(self, item: bytes) -> None: + try: + await self._stream.send_all(item) + except trio.ClosedResourceError as exc: + raise ClosedResourceError from exc.__cause__ + except trio.BrokenResourceError as exc: + raise BrokenResourceError from exc.__cause__ + + async def aclose(self) -> None: + await self._stream.aclose() + + +@dataclass(eq=False) +class Process(abc.Process): + _process: trio.Process + _stdin: abc.ByteSendStream | None + _stdout: abc.ByteReceiveStream | None + _stderr: abc.ByteReceiveStream | None + + async def aclose(self) -> None: + with CancelScope(shield=True): + if self._stdin: + await self._stdin.aclose() + if self._stdout: + await self._stdout.aclose() + if self._stderr: + await self._stderr.aclose() + + try: + await self.wait() + except BaseException: + self.kill() + with CancelScope(shield=True): + await self.wait() + raise + + async def wait(self) -> int: + return await self._process.wait() + + def terminate(self) -> None: + self._process.terminate() + + def kill(self) -> None: + self._process.kill() + + def send_signal(self, signal: Signals) -> None: + self._process.send_signal(signal) + + @property + def pid(self) -> int: + return self._process.pid + + @property + def returncode(self) -> int | None: + return self._process.returncode + + @property + def stdin(self) -> abc.ByteSendStream | None: + return self._stdin + + @property + def stdout(self) -> abc.ByteReceiveStream | None: + return self._stdout + + @property + def stderr(self) -> abc.ByteReceiveStream | None: + return self._stderr + + +class _ProcessPoolShutdownInstrument(trio.abc.Instrument): + def after_run(self) -> None: + super().after_run() + + +current_default_worker_process_limiter: trio.lowlevel.RunVar = RunVar( + "current_default_worker_process_limiter" +) + + +async def _shutdown_process_pool(workers: set[abc.Process]) -> None: + try: + await trio.sleep(math.inf) + except trio.Cancelled: + for process in workers: + if process.returncode is None: + process.kill() + + with CancelScope(shield=True): + for process in workers: + await process.aclose() + + +# +# Sockets and networking +# + + +class _TrioSocketMixin(Generic[T_SockAddr]): + def __init__(self, trio_socket: TrioSocketType) -> None: + self._trio_socket = trio_socket + self._closed = False + + def _check_closed(self) -> None: + if self._closed: + raise ClosedResourceError + if self._trio_socket.fileno() < 0: + raise BrokenResourceError + + @property + def _raw_socket(self) -> socket.socket: + return self._trio_socket._sock # type: ignore[attr-defined] + + async def aclose(self) -> None: + if self._trio_socket.fileno() >= 0: + self._closed = True + self._trio_socket.close() + + def _convert_socket_error(self, exc: BaseException) -> NoReturn: + if isinstance(exc, trio.ClosedResourceError): + raise ClosedResourceError from exc + elif self._trio_socket.fileno() < 0 and self._closed: + raise ClosedResourceError from None + elif isinstance(exc, OSError): + raise BrokenResourceError from exc + else: + raise exc + + +class SocketStream(_TrioSocketMixin, abc.SocketStream): + def __init__(self, trio_socket: TrioSocketType) -> None: + super().__init__(trio_socket) + self._receive_guard = ResourceGuard("reading from") + self._send_guard = ResourceGuard("writing to") + + async def receive(self, max_bytes: int = 65536) -> bytes: + with self._receive_guard: + try: + data = await self._trio_socket.recv(max_bytes) + except BaseException as exc: + self._convert_socket_error(exc) + + if data: + return data + else: + raise EndOfStream + + async def send(self, item: bytes) -> None: + with self._send_guard: + view = memoryview(item) + while view: + try: + bytes_sent = await self._trio_socket.send(view) + except BaseException as exc: + self._convert_socket_error(exc) + + view = view[bytes_sent:] + + async def send_eof(self) -> None: + self._trio_socket.shutdown(socket.SHUT_WR) + + +class UNIXSocketStream(SocketStream, abc.UNIXSocketStream): + async def receive_fds(self, msglen: int, maxfds: int) -> tuple[bytes, list[int]]: + if not isinstance(msglen, int) or msglen < 0: + raise ValueError("msglen must be a non-negative integer") + if not isinstance(maxfds, int) or maxfds < 1: + raise ValueError("maxfds must be a positive integer") + + fds = array.array("i") + await trio.lowlevel.checkpoint() + with self._receive_guard: + while True: + try: + message, ancdata, flags, addr = await self._trio_socket.recvmsg( + msglen, socket.CMSG_LEN(maxfds * fds.itemsize) + ) + except BaseException as exc: + self._convert_socket_error(exc) + else: + if not message and not ancdata: + raise EndOfStream + + break + + for cmsg_level, cmsg_type, cmsg_data in ancdata: + if cmsg_level != socket.SOL_SOCKET or cmsg_type != socket.SCM_RIGHTS: + raise RuntimeError( + f"Received unexpected ancillary data; message = {message!r}, " + f"cmsg_level = {cmsg_level}, cmsg_type = {cmsg_type}" + ) + + fds.frombytes(cmsg_data[: len(cmsg_data) - (len(cmsg_data) % fds.itemsize)]) + + return message, list(fds) + + async def send_fds(self, message: bytes, fds: Collection[int | IOBase]) -> None: + if not message: + raise ValueError("message must not be empty") + if not fds: + raise ValueError("fds must not be empty") + + filenos: list[int] = [] + for fd in fds: + if isinstance(fd, int): + filenos.append(fd) + elif isinstance(fd, IOBase): + filenos.append(fd.fileno()) + + fdarray = array.array("i", filenos) + await trio.lowlevel.checkpoint() + with self._send_guard: + while True: + try: + await self._trio_socket.sendmsg( + [message], + [ + ( + socket.SOL_SOCKET, + socket.SCM_RIGHTS, + fdarray, + ) + ], + ) + break + except BaseException as exc: + self._convert_socket_error(exc) + + +class TCPSocketListener(_TrioSocketMixin, abc.SocketListener): + def __init__(self, raw_socket: socket.socket): + super().__init__(trio.socket.from_stdlib_socket(raw_socket)) + self._accept_guard = ResourceGuard("accepting connections from") + + async def accept(self) -> SocketStream: + with self._accept_guard: + try: + trio_socket, _addr = await self._trio_socket.accept() + except BaseException as exc: + self._convert_socket_error(exc) + + trio_socket.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1) + return SocketStream(trio_socket) + + +class UNIXSocketListener(_TrioSocketMixin, abc.SocketListener): + def __init__(self, raw_socket: socket.socket): + super().__init__(trio.socket.from_stdlib_socket(raw_socket)) + self._accept_guard = ResourceGuard("accepting connections from") + + async def accept(self) -> UNIXSocketStream: + with self._accept_guard: + try: + trio_socket, _addr = await self._trio_socket.accept() + except BaseException as exc: + self._convert_socket_error(exc) + + return UNIXSocketStream(trio_socket) + + +class UDPSocket(_TrioSocketMixin[IPSockAddrType], abc.UDPSocket): + def __init__(self, trio_socket: TrioSocketType) -> None: + super().__init__(trio_socket) + self._receive_guard = ResourceGuard("reading from") + self._send_guard = ResourceGuard("writing to") + + async def receive(self) -> tuple[bytes, IPSockAddrType]: + with self._receive_guard: + try: + data, addr = await self._trio_socket.recvfrom(65536) + return data, convert_ipv6_sockaddr(addr) + except BaseException as exc: + self._convert_socket_error(exc) + + async def send(self, item: UDPPacketType) -> None: + with self._send_guard: + try: + await self._trio_socket.sendto(*item) + except BaseException as exc: + self._convert_socket_error(exc) + + +class ConnectedUDPSocket(_TrioSocketMixin[IPSockAddrType], abc.ConnectedUDPSocket): + def __init__(self, trio_socket: TrioSocketType) -> None: + super().__init__(trio_socket) + self._receive_guard = ResourceGuard("reading from") + self._send_guard = ResourceGuard("writing to") + + async def receive(self) -> bytes: + with self._receive_guard: + try: + return await self._trio_socket.recv(65536) + except BaseException as exc: + self._convert_socket_error(exc) + + async def send(self, item: bytes) -> None: + with self._send_guard: + try: + await self._trio_socket.send(item) + except BaseException as exc: + self._convert_socket_error(exc) + + +class UNIXDatagramSocket(_TrioSocketMixin[str], abc.UNIXDatagramSocket): + def __init__(self, trio_socket: TrioSocketType) -> None: + super().__init__(trio_socket) + self._receive_guard = ResourceGuard("reading from") + self._send_guard = ResourceGuard("writing to") + + async def receive(self) -> UNIXDatagramPacketType: + with self._receive_guard: + try: + data, addr = await self._trio_socket.recvfrom(65536) + return data, addr + except BaseException as exc: + self._convert_socket_error(exc) + + async def send(self, item: UNIXDatagramPacketType) -> None: + with self._send_guard: + try: + await self._trio_socket.sendto(*item) + except BaseException as exc: + self._convert_socket_error(exc) + + +class ConnectedUNIXDatagramSocket( + _TrioSocketMixin[str], abc.ConnectedUNIXDatagramSocket +): + def __init__(self, trio_socket: TrioSocketType) -> None: + super().__init__(trio_socket) + self._receive_guard = ResourceGuard("reading from") + self._send_guard = ResourceGuard("writing to") + + async def receive(self) -> bytes: + with self._receive_guard: + try: + return await self._trio_socket.recv(65536) + except BaseException as exc: + self._convert_socket_error(exc) + + async def send(self, item: bytes) -> None: + with self._send_guard: + try: + await self._trio_socket.send(item) + except BaseException as exc: + self._convert_socket_error(exc) + + +# +# Synchronization +# + + +class Event(BaseEvent): + def __new__(cls) -> Event: + return object.__new__(cls) + + def __init__(self) -> None: + self.__original = trio.Event() + + def is_set(self) -> bool: + return self.__original.is_set() + + async def wait(self) -> None: + return await self.__original.wait() + + def statistics(self) -> EventStatistics: + orig_statistics = self.__original.statistics() + return EventStatistics(tasks_waiting=orig_statistics.tasks_waiting) + + def set(self) -> None: + self.__original.set() + + +class Lock(BaseLock): + def __new__(cls, *, fast_acquire: bool = False) -> Lock: + return object.__new__(cls) + + def __init__(self, *, fast_acquire: bool = False) -> None: + self._fast_acquire = fast_acquire + self.__original = trio.Lock() + + @staticmethod + def _convert_runtime_error_msg(exc: RuntimeError) -> None: + if exc.args == ("attempt to re-acquire an already held Lock",): + exc.args = ("Attempted to acquire an already held Lock",) + + async def acquire(self) -> None: + if not self._fast_acquire: + try: + await self.__original.acquire() + except RuntimeError as exc: + self._convert_runtime_error_msg(exc) + raise + + return + + # This is the "fast path" where we don't let other tasks run + await trio.lowlevel.checkpoint_if_cancelled() + try: + self.__original.acquire_nowait() + except trio.WouldBlock: + await self.__original._lot.park() + except RuntimeError as exc: + self._convert_runtime_error_msg(exc) + raise + + def acquire_nowait(self) -> None: + try: + self.__original.acquire_nowait() + except trio.WouldBlock: + raise WouldBlock from None + except RuntimeError as exc: + self._convert_runtime_error_msg(exc) + raise + + def locked(self) -> bool: + return self.__original.locked() + + def release(self) -> None: + self.__original.release() + + def statistics(self) -> LockStatistics: + orig_statistics = self.__original.statistics() + owner = TrioTaskInfo(orig_statistics.owner) if orig_statistics.owner else None + return LockStatistics( + orig_statistics.locked, owner, orig_statistics.tasks_waiting + ) + + +class Semaphore(BaseSemaphore): + def __new__( + cls, + initial_value: int, + *, + max_value: int | None = None, + fast_acquire: bool = False, + ) -> Semaphore: + return object.__new__(cls) + + def __init__( + self, + initial_value: int, + *, + max_value: int | None = None, + fast_acquire: bool = False, + ) -> None: + super().__init__(initial_value, max_value=max_value, fast_acquire=fast_acquire) + self.__original = trio.Semaphore(initial_value, max_value=max_value) + + async def acquire(self) -> None: + if not self._fast_acquire: + await self.__original.acquire() + return + + # This is the "fast path" where we don't let other tasks run + await trio.lowlevel.checkpoint_if_cancelled() + try: + self.__original.acquire_nowait() + except trio.WouldBlock: + await self.__original._lot.park() + + def acquire_nowait(self) -> None: + try: + self.__original.acquire_nowait() + except trio.WouldBlock: + raise WouldBlock from None + + @property + def max_value(self) -> int | None: + return self.__original.max_value + + @property + def value(self) -> int: + return self.__original.value + + def release(self) -> None: + self.__original.release() + + def statistics(self) -> SemaphoreStatistics: + orig_statistics = self.__original.statistics() + return SemaphoreStatistics(orig_statistics.tasks_waiting) + + +class CapacityLimiter(BaseCapacityLimiter): + def __new__( + cls, + total_tokens: float | None = None, + *, + original: trio.CapacityLimiter | None = None, + ) -> CapacityLimiter: + return object.__new__(cls) + + def __init__( + self, + total_tokens: float | None = None, + *, + original: trio.CapacityLimiter | None = None, + ) -> None: + if original is not None: + self.__original = original + else: + assert total_tokens is not None + self.__original = trio.CapacityLimiter(total_tokens) + + async def __aenter__(self) -> None: + return await self.__original.__aenter__() + + async def __aexit__( + self, + exc_type: type[BaseException] | None, + exc_val: BaseException | None, + exc_tb: TracebackType | None, + ) -> None: + await self.__original.__aexit__(exc_type, exc_val, exc_tb) + + @property + def total_tokens(self) -> float: + return self.__original.total_tokens + + @total_tokens.setter + def total_tokens(self, value: float) -> None: + self.__original.total_tokens = value + + @property + def borrowed_tokens(self) -> int: + return self.__original.borrowed_tokens + + @property + def available_tokens(self) -> float: + return self.__original.available_tokens + + def acquire_nowait(self) -> None: + self.__original.acquire_nowait() + + def acquire_on_behalf_of_nowait(self, borrower: object) -> None: + self.__original.acquire_on_behalf_of_nowait(borrower) + + async def acquire(self) -> None: + await self.__original.acquire() + + async def acquire_on_behalf_of(self, borrower: object) -> None: + await self.__original.acquire_on_behalf_of(borrower) + + def release(self) -> None: + return self.__original.release() + + def release_on_behalf_of(self, borrower: object) -> None: + return self.__original.release_on_behalf_of(borrower) + + def statistics(self) -> CapacityLimiterStatistics: + orig = self.__original.statistics() + return CapacityLimiterStatistics( + borrowed_tokens=orig.borrowed_tokens, + total_tokens=orig.total_tokens, + borrowers=tuple(orig.borrowers), + tasks_waiting=orig.tasks_waiting, + ) + + +_capacity_limiter_wrapper: trio.lowlevel.RunVar = RunVar("_capacity_limiter_wrapper") + + +# +# Signal handling +# + + +class _SignalReceiver: + _iterator: AsyncIterator[int] + + def __init__(self, signals: tuple[Signals, ...]): + self._signals = signals + + def __enter__(self) -> _SignalReceiver: + self._cm = trio.open_signal_receiver(*self._signals) + self._iterator = self._cm.__enter__() + return self + + def __exit__( + self, + exc_type: type[BaseException] | None, + exc_val: BaseException | None, + exc_tb: TracebackType | None, + ) -> bool | None: + return self._cm.__exit__(exc_type, exc_val, exc_tb) + + def __aiter__(self) -> _SignalReceiver: + return self + + async def __anext__(self) -> Signals: + signum = await self._iterator.__anext__() + return Signals(signum) + + +# +# Testing and debugging +# + + +class TestRunner(abc.TestRunner): + def __init__(self, **options: Any) -> None: + from queue import Queue + + self._call_queue: Queue[Callable[[], object]] = Queue() + self._send_stream: MemoryObjectSendStream | None = None + self._options = options + + def __exit__( + self, + exc_type: type[BaseException] | None, + exc_val: BaseException | None, + exc_tb: types.TracebackType | None, + ) -> None: + if self._send_stream: + self._send_stream.close() + while self._send_stream is not None: + self._call_queue.get()() + + async def _run_tests_and_fixtures(self) -> None: + self._send_stream, receive_stream = create_memory_object_stream(1) + with receive_stream: + async for coro, outcome_holder in receive_stream: + try: + retval = await coro + except BaseException as exc: + outcome_holder.append(Error(exc)) + else: + outcome_holder.append(Value(retval)) + + def _main_task_finished(self, outcome: object) -> None: + self._send_stream = None + + def _call_in_runner_task( + self, + func: Callable[P, Awaitable[T_Retval]], + /, + *args: P.args, + **kwargs: P.kwargs, + ) -> T_Retval: + if self._send_stream is None: + trio.lowlevel.start_guest_run( + self._run_tests_and_fixtures, + run_sync_soon_threadsafe=self._call_queue.put, + done_callback=self._main_task_finished, + **self._options, + ) + while self._send_stream is None: + self._call_queue.get()() + + outcome_holder: list[Outcome] = [] + self._send_stream.send_nowait((func(*args, **kwargs), outcome_holder)) + while not outcome_holder: + self._call_queue.get()() + + return outcome_holder[0].unwrap() + + def run_asyncgen_fixture( + self, + fixture_func: Callable[..., AsyncGenerator[T_Retval, Any]], + kwargs: dict[str, Any], + ) -> Iterable[T_Retval]: + asyncgen = fixture_func(**kwargs) + fixturevalue: T_Retval = self._call_in_runner_task(asyncgen.asend, None) + + yield fixturevalue + + try: + self._call_in_runner_task(asyncgen.asend, None) + except StopAsyncIteration: + pass + else: + self._call_in_runner_task(asyncgen.aclose) + raise RuntimeError("Async generator fixture did not stop") + + def run_fixture( + self, + fixture_func: Callable[..., Coroutine[Any, Any, T_Retval]], + kwargs: dict[str, Any], + ) -> T_Retval: + return self._call_in_runner_task(fixture_func, **kwargs) + + def run_test( + self, test_func: Callable[..., Coroutine[Any, Any, Any]], kwargs: dict[str, Any] + ) -> None: + self._call_in_runner_task(test_func, **kwargs) + + +class TrioTaskInfo(TaskInfo): + def __init__(self, task: trio.lowlevel.Task): + parent_id = None + if task.parent_nursery and task.parent_nursery.parent_task: + parent_id = id(task.parent_nursery.parent_task) + + super().__init__(id(task), parent_id, task.name, task.coro) + self._task = weakref.proxy(task) + + def has_pending_cancellation(self) -> bool: + try: + return self._task._cancel_status.effectively_cancelled + except ReferenceError: + # If the task is no longer around, it surely doesn't have a cancellation + # pending + return False + + +class TrioBackend(AsyncBackend): + @classmethod + def run( + cls, + func: Callable[[Unpack[PosArgsT]], Awaitable[T_Retval]], + args: tuple[Unpack[PosArgsT]], + kwargs: dict[str, Any], + options: dict[str, Any], + ) -> T_Retval: + return trio.run(func, *args) + + @classmethod + def current_token(cls) -> object: + return trio.lowlevel.current_trio_token() + + @classmethod + def current_time(cls) -> float: + return trio.current_time() + + @classmethod + def cancelled_exception_class(cls) -> type[BaseException]: + return trio.Cancelled + + @classmethod + async def checkpoint(cls) -> None: + await trio.lowlevel.checkpoint() + + @classmethod + async def checkpoint_if_cancelled(cls) -> None: + await trio.lowlevel.checkpoint_if_cancelled() + + @classmethod + async def cancel_shielded_checkpoint(cls) -> None: + await trio.lowlevel.cancel_shielded_checkpoint() + + @classmethod + async def sleep(cls, delay: float) -> None: + await trio.sleep(delay) + + @classmethod + def create_cancel_scope( + cls, *, deadline: float = math.inf, shield: bool = False + ) -> abc.CancelScope: + return CancelScope(deadline=deadline, shield=shield) + + @classmethod + def current_effective_deadline(cls) -> float: + return trio.current_effective_deadline() + + @classmethod + def create_task_group(cls) -> abc.TaskGroup: + return TaskGroup() + + @classmethod + def create_event(cls) -> abc.Event: + return Event() + + @classmethod + def create_lock(cls, *, fast_acquire: bool) -> Lock: + return Lock(fast_acquire=fast_acquire) + + @classmethod + def create_semaphore( + cls, + initial_value: int, + *, + max_value: int | None = None, + fast_acquire: bool = False, + ) -> abc.Semaphore: + return Semaphore(initial_value, max_value=max_value, fast_acquire=fast_acquire) + + @classmethod + def create_capacity_limiter(cls, total_tokens: float) -> CapacityLimiter: + return CapacityLimiter(total_tokens) + + @classmethod + async def run_sync_in_worker_thread( + cls, + func: Callable[[Unpack[PosArgsT]], T_Retval], + args: tuple[Unpack[PosArgsT]], + abandon_on_cancel: bool = False, + limiter: abc.CapacityLimiter | None = None, + ) -> T_Retval: + def wrapper() -> T_Retval: + with claim_worker_thread(TrioBackend, token): + return func(*args) + + token = TrioBackend.current_token() + return await run_sync( + wrapper, + abandon_on_cancel=abandon_on_cancel, + limiter=cast(trio.CapacityLimiter, limiter), + ) + + @classmethod + def check_cancelled(cls) -> None: + trio.from_thread.check_cancelled() + + @classmethod + def run_async_from_thread( + cls, + func: Callable[[Unpack[PosArgsT]], Awaitable[T_Retval]], + args: tuple[Unpack[PosArgsT]], + token: object, + ) -> T_Retval: + trio_token = cast("trio.lowlevel.TrioToken | None", token) + try: + return trio.from_thread.run(func, *args, trio_token=trio_token) + except trio.RunFinishedError: + raise RunFinishedError from None + + @classmethod + def run_sync_from_thread( + cls, + func: Callable[[Unpack[PosArgsT]], T_Retval], + args: tuple[Unpack[PosArgsT]], + token: object, + ) -> T_Retval: + trio_token = cast("trio.lowlevel.TrioToken | None", token) + try: + return trio.from_thread.run_sync(func, *args, trio_token=trio_token) + except trio.RunFinishedError: + raise RunFinishedError from None + + @classmethod + async def open_process( + cls, + command: StrOrBytesPath | Sequence[StrOrBytesPath], + *, + stdin: int | IO[Any] | None, + stdout: int | IO[Any] | None, + stderr: int | IO[Any] | None, + **kwargs: Any, + ) -> Process: + def convert_item(item: StrOrBytesPath) -> str: + str_or_bytes = os.fspath(item) + if isinstance(str_or_bytes, str): + return str_or_bytes + else: + return os.fsdecode(str_or_bytes) + + if isinstance(command, (str, bytes, PathLike)): + process = await trio.lowlevel.open_process( + convert_item(command), + stdin=stdin, + stdout=stdout, + stderr=stderr, + shell=True, + **kwargs, + ) + else: + process = await trio.lowlevel.open_process( + [convert_item(item) for item in command], + stdin=stdin, + stdout=stdout, + stderr=stderr, + shell=False, + **kwargs, + ) + + stdin_stream = SendStreamWrapper(process.stdin) if process.stdin else None + stdout_stream = ReceiveStreamWrapper(process.stdout) if process.stdout else None + stderr_stream = ReceiveStreamWrapper(process.stderr) if process.stderr else None + return Process(process, stdin_stream, stdout_stream, stderr_stream) + + @classmethod + def setup_process_pool_exit_at_shutdown(cls, workers: set[abc.Process]) -> None: + trio.lowlevel.spawn_system_task(_shutdown_process_pool, workers) + + @classmethod + async def connect_tcp( + cls, host: str, port: int, local_address: IPSockAddrType | None = None + ) -> SocketStream: + family = socket.AF_INET6 if ":" in host else socket.AF_INET + trio_socket = trio.socket.socket(family) + trio_socket.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1) + if local_address: + await trio_socket.bind(local_address) + + try: + await trio_socket.connect((host, port)) + except BaseException: + trio_socket.close() + raise + + return SocketStream(trio_socket) + + @classmethod + async def connect_unix(cls, path: str | bytes) -> abc.UNIXSocketStream: + trio_socket = trio.socket.socket(socket.AF_UNIX) + try: + await trio_socket.connect(path) + except BaseException: + trio_socket.close() + raise + + return UNIXSocketStream(trio_socket) + + @classmethod + def create_tcp_listener(cls, sock: socket.socket) -> abc.SocketListener: + return TCPSocketListener(sock) + + @classmethod + def create_unix_listener(cls, sock: socket.socket) -> abc.SocketListener: + return UNIXSocketListener(sock) + + @classmethod + async def create_udp_socket( + cls, + family: socket.AddressFamily, + local_address: IPSockAddrType | None, + remote_address: IPSockAddrType | None, + reuse_port: bool, + ) -> UDPSocket | ConnectedUDPSocket: + trio_socket = trio.socket.socket(family=family, type=socket.SOCK_DGRAM) + + if reuse_port: + trio_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT, 1) + + if local_address: + await trio_socket.bind(local_address) + + if remote_address: + await trio_socket.connect(remote_address) + return ConnectedUDPSocket(trio_socket) + else: + return UDPSocket(trio_socket) + + @classmethod + @overload + async def create_unix_datagram_socket( + cls, raw_socket: socket.socket, remote_path: None + ) -> abc.UNIXDatagramSocket: ... + + @classmethod + @overload + async def create_unix_datagram_socket( + cls, raw_socket: socket.socket, remote_path: str | bytes + ) -> abc.ConnectedUNIXDatagramSocket: ... + + @classmethod + async def create_unix_datagram_socket( + cls, raw_socket: socket.socket, remote_path: str | bytes | None + ) -> abc.UNIXDatagramSocket | abc.ConnectedUNIXDatagramSocket: + trio_socket = trio.socket.from_stdlib_socket(raw_socket) + + if remote_path: + await trio_socket.connect(remote_path) + return ConnectedUNIXDatagramSocket(trio_socket) + else: + return UNIXDatagramSocket(trio_socket) + + @classmethod + async def getaddrinfo( + cls, + host: bytes | str | None, + port: str | int | None, + *, + family: int | AddressFamily = 0, + type: int | SocketKind = 0, + proto: int = 0, + flags: int = 0, + ) -> Sequence[ + tuple[ + AddressFamily, + SocketKind, + int, + str, + tuple[str, int] | tuple[str, int, int, int] | tuple[int, bytes], + ] + ]: + return await trio.socket.getaddrinfo(host, port, family, type, proto, flags) + + @classmethod + async def getnameinfo( + cls, sockaddr: IPSockAddrType, flags: int = 0 + ) -> tuple[str, str]: + return await trio.socket.getnameinfo(sockaddr, flags) + + @classmethod + async def wait_readable(cls, obj: FileDescriptorLike) -> None: + try: + await wait_readable(obj) + except trio.ClosedResourceError as exc: + raise ClosedResourceError().with_traceback(exc.__traceback__) from None + except trio.BusyResourceError: + raise BusyResourceError("reading from") from None + + @classmethod + async def wait_writable(cls, obj: FileDescriptorLike) -> None: + try: + await wait_writable(obj) + except trio.ClosedResourceError as exc: + raise ClosedResourceError().with_traceback(exc.__traceback__) from None + except trio.BusyResourceError: + raise BusyResourceError("writing to") from None + + @classmethod + def notify_closing(cls, obj: FileDescriptorLike) -> None: + notify_closing(obj) + + @classmethod + async def wrap_listener_socket(cls, sock: socket.socket) -> abc.SocketListener: + return TCPSocketListener(sock) + + @classmethod + async def wrap_stream_socket(cls, sock: socket.socket) -> SocketStream: + trio_sock = trio.socket.from_stdlib_socket(sock) + return SocketStream(trio_sock) + + @classmethod + async def wrap_unix_stream_socket(cls, sock: socket.socket) -> UNIXSocketStream: + trio_sock = trio.socket.from_stdlib_socket(sock) + return UNIXSocketStream(trio_sock) + + @classmethod + async def wrap_udp_socket(cls, sock: socket.socket) -> UDPSocket: + trio_sock = trio.socket.from_stdlib_socket(sock) + return UDPSocket(trio_sock) + + @classmethod + async def wrap_connected_udp_socket(cls, sock: socket.socket) -> ConnectedUDPSocket: + trio_sock = trio.socket.from_stdlib_socket(sock) + return ConnectedUDPSocket(trio_sock) + + @classmethod + async def wrap_unix_datagram_socket(cls, sock: socket.socket) -> UNIXDatagramSocket: + trio_sock = trio.socket.from_stdlib_socket(sock) + return UNIXDatagramSocket(trio_sock) + + @classmethod + async def wrap_connected_unix_datagram_socket( + cls, sock: socket.socket + ) -> ConnectedUNIXDatagramSocket: + trio_sock = trio.socket.from_stdlib_socket(sock) + return ConnectedUNIXDatagramSocket(trio_sock) + + @classmethod + def current_default_thread_limiter(cls) -> CapacityLimiter: + try: + return _capacity_limiter_wrapper.get() + except LookupError: + limiter = CapacityLimiter( + original=trio.to_thread.current_default_thread_limiter() + ) + _capacity_limiter_wrapper.set(limiter) + return limiter + + @classmethod + def open_signal_receiver( + cls, *signals: Signals + ) -> AbstractContextManager[AsyncIterator[Signals]]: + return _SignalReceiver(signals) + + @classmethod + def get_current_task(cls) -> TaskInfo: + task = current_task() + return TrioTaskInfo(task) + + @classmethod + def get_running_tasks(cls) -> Sequence[TaskInfo]: + root_task = current_root_task() + assert root_task + task_infos = [TrioTaskInfo(root_task)] + nurseries = root_task.child_nurseries + while nurseries: + new_nurseries: list[trio.Nursery] = [] + for nursery in nurseries: + for task in nursery.child_tasks: + task_infos.append(TrioTaskInfo(task)) + new_nurseries.extend(task.child_nurseries) + + nurseries = new_nurseries + + return task_infos + + @classmethod + async def wait_all_tasks_blocked(cls) -> None: + from trio.testing import wait_all_tasks_blocked + + await wait_all_tasks_blocked() + + @classmethod + def create_test_runner(cls, options: dict[str, Any]) -> TestRunner: + return TestRunner(**options) + + +backend_class = TrioBackend diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/anyio/_core/__init__.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/anyio/_core/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/anyio/_core/__pycache__/__init__.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/anyio/_core/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1c5aa4805139213dab45184f15a0f76769b66436 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/anyio/_core/__pycache__/__init__.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/anyio/_core/__pycache__/_asyncio_selector_thread.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/anyio/_core/__pycache__/_asyncio_selector_thread.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e84110ced8a3605d66b83d664b97f6556a967d6b Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/anyio/_core/__pycache__/_asyncio_selector_thread.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/anyio/_core/__pycache__/_contextmanagers.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/anyio/_core/__pycache__/_contextmanagers.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6574fc870fd36ac8117dabcf94e9c958dceaf645 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/anyio/_core/__pycache__/_contextmanagers.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/anyio/_core/__pycache__/_eventloop.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/anyio/_core/__pycache__/_eventloop.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8029ccc1f684a9dc3202c44f3d95b0d52b448f4e Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/anyio/_core/__pycache__/_eventloop.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/anyio/_core/__pycache__/_exceptions.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/anyio/_core/__pycache__/_exceptions.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..33d6e58d4eaec0c05989761fb1e5f665b2c8954b Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/anyio/_core/__pycache__/_exceptions.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/anyio/_core/__pycache__/_fileio.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/anyio/_core/__pycache__/_fileio.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ed890e103aa974eaa3e199be2142176674513c28 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/anyio/_core/__pycache__/_fileio.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/anyio/_core/__pycache__/_resources.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/anyio/_core/__pycache__/_resources.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..fab669629819d53e257cead331dbf806bdde0576 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/anyio/_core/__pycache__/_resources.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/anyio/_core/__pycache__/_signals.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/anyio/_core/__pycache__/_signals.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..fb78a1236f427aa9964afb88d53adcc4fcb289c3 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/anyio/_core/__pycache__/_signals.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/anyio/_core/__pycache__/_sockets.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/anyio/_core/__pycache__/_sockets.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..042442cf72390bbac6522f1214ec8279e6b458ab Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/anyio/_core/__pycache__/_sockets.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/anyio/_core/__pycache__/_streams.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/anyio/_core/__pycache__/_streams.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9ca35f07b509b3ea769a023144a72adaa8516a7e Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/anyio/_core/__pycache__/_streams.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/anyio/_core/__pycache__/_subprocesses.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/anyio/_core/__pycache__/_subprocesses.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b0ff48cfd205bdcd171832e4ee995fccbdc209f9 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/anyio/_core/__pycache__/_subprocesses.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/anyio/_core/__pycache__/_synchronization.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/anyio/_core/__pycache__/_synchronization.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..826117b86de7b88db8d79de632ca0f7f347fd8c8 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/anyio/_core/__pycache__/_synchronization.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/anyio/_core/__pycache__/_tasks.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/anyio/_core/__pycache__/_tasks.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7317ea63d6a3231139d6e22b3f9d953d9ab6c68b Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/anyio/_core/__pycache__/_tasks.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/anyio/_core/__pycache__/_tempfile.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/anyio/_core/__pycache__/_tempfile.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..951ad9f1214177d69884cbfd0fd18636fe1e8e5e Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/anyio/_core/__pycache__/_tempfile.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/anyio/_core/__pycache__/_testing.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/anyio/_core/__pycache__/_testing.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..884e1b514499c398512881a50021ddff7a7cabc3 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/anyio/_core/__pycache__/_testing.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/anyio/_core/__pycache__/_typedattr.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/anyio/_core/__pycache__/_typedattr.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..050ba327b2f3b442e01e86338127fc2d7bbe1c40 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/anyio/_core/__pycache__/_typedattr.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/anyio/_core/_asyncio_selector_thread.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/anyio/_core/_asyncio_selector_thread.py new file mode 100644 index 0000000000000000000000000000000000000000..9f35bae568e33e6a9e1219761c83cc8350fa0532 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/anyio/_core/_asyncio_selector_thread.py @@ -0,0 +1,167 @@ +from __future__ import annotations + +import asyncio +import socket +import threading +from collections.abc import Callable +from selectors import EVENT_READ, EVENT_WRITE, DefaultSelector +from typing import TYPE_CHECKING, Any + +if TYPE_CHECKING: + from _typeshed import FileDescriptorLike + +_selector_lock = threading.Lock() +_selector: Selector | None = None + + +class Selector: + def __init__(self) -> None: + self._thread = threading.Thread(target=self.run, name="AnyIO socket selector") + self._selector = DefaultSelector() + self._send, self._receive = socket.socketpair() + self._send.setblocking(False) + self._receive.setblocking(False) + # This somewhat reduces the amount of memory wasted queueing up data + # for wakeups. With these settings, maximum number of 1-byte sends + # before getting BlockingIOError: + # Linux 4.8: 6 + # macOS (darwin 15.5): 1 + # Windows 10: 525347 + # Windows you're weird. (And on Windows setting SNDBUF to 0 makes send + # blocking, even on non-blocking sockets, so don't do that.) + self._receive.setsockopt(socket.SOL_SOCKET, socket.SO_RCVBUF, 1) + self._send.setsockopt(socket.SOL_SOCKET, socket.SO_SNDBUF, 1) + # On Windows this is a TCP socket so this might matter. On other + # platforms this fails b/c AF_UNIX sockets aren't actually TCP. + try: + self._send.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1) + except OSError: + pass + + self._selector.register(self._receive, EVENT_READ) + self._closed = False + + def start(self) -> None: + self._thread.start() + threading._register_atexit(self._stop) # type: ignore[attr-defined] + + def _stop(self) -> None: + global _selector + self._closed = True + self._notify_self() + self._send.close() + self._thread.join() + self._selector.unregister(self._receive) + self._receive.close() + self._selector.close() + _selector = None + assert not self._selector.get_map(), ( + "selector still has registered file descriptors after shutdown" + ) + + def _notify_self(self) -> None: + try: + self._send.send(b"\x00") + except BlockingIOError: + pass + + def add_reader(self, fd: FileDescriptorLike, callback: Callable[[], Any]) -> None: + loop = asyncio.get_running_loop() + try: + key = self._selector.get_key(fd) + except KeyError: + self._selector.register(fd, EVENT_READ, {EVENT_READ: (loop, callback)}) + else: + if EVENT_READ in key.data: + raise ValueError( + "this file descriptor is already registered for reading" + ) + + key.data[EVENT_READ] = loop, callback + self._selector.modify(fd, key.events | EVENT_READ, key.data) + + self._notify_self() + + def add_writer(self, fd: FileDescriptorLike, callback: Callable[[], Any]) -> None: + loop = asyncio.get_running_loop() + try: + key = self._selector.get_key(fd) + except KeyError: + self._selector.register(fd, EVENT_WRITE, {EVENT_WRITE: (loop, callback)}) + else: + if EVENT_WRITE in key.data: + raise ValueError( + "this file descriptor is already registered for writing" + ) + + key.data[EVENT_WRITE] = loop, callback + self._selector.modify(fd, key.events | EVENT_WRITE, key.data) + + self._notify_self() + + def remove_reader(self, fd: FileDescriptorLike) -> bool: + try: + key = self._selector.get_key(fd) + except KeyError: + return False + + if new_events := key.events ^ EVENT_READ: + del key.data[EVENT_READ] + self._selector.modify(fd, new_events, key.data) + else: + self._selector.unregister(fd) + + return True + + def remove_writer(self, fd: FileDescriptorLike) -> bool: + try: + key = self._selector.get_key(fd) + except KeyError: + return False + + if new_events := key.events ^ EVENT_WRITE: + del key.data[EVENT_WRITE] + self._selector.modify(fd, new_events, key.data) + else: + self._selector.unregister(fd) + + return True + + def run(self) -> None: + while not self._closed: + for key, events in self._selector.select(): + if key.fileobj is self._receive: + try: + while self._receive.recv(4096): + pass + except BlockingIOError: + pass + + continue + + if events & EVENT_READ: + loop, callback = key.data[EVENT_READ] + self.remove_reader(key.fd) + try: + loop.call_soon_threadsafe(callback) + except RuntimeError: + pass # the loop was already closed + + if events & EVENT_WRITE: + loop, callback = key.data[EVENT_WRITE] + self.remove_writer(key.fd) + try: + loop.call_soon_threadsafe(callback) + except RuntimeError: + pass # the loop was already closed + + +def get_selector() -> Selector: + global _selector + + with _selector_lock: + if _selector is None: + _selector = Selector() + _selector.start() + + return _selector diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/anyio/_core/_contextmanagers.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/anyio/_core/_contextmanagers.py new file mode 100644 index 0000000000000000000000000000000000000000..302f32b0c78a7071605b195c55054cfdb0b55f37 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/anyio/_core/_contextmanagers.py @@ -0,0 +1,200 @@ +from __future__ import annotations + +from abc import abstractmethod +from contextlib import AbstractAsyncContextManager, AbstractContextManager +from inspect import isasyncgen, iscoroutine, isgenerator +from types import TracebackType +from typing import Protocol, TypeVar, cast, final + +_T_co = TypeVar("_T_co", covariant=True) +_ExitT_co = TypeVar("_ExitT_co", covariant=True, bound="bool | None") + + +class _SupportsCtxMgr(Protocol[_T_co, _ExitT_co]): + def __contextmanager__(self) -> AbstractContextManager[_T_co, _ExitT_co]: ... + + +class _SupportsAsyncCtxMgr(Protocol[_T_co, _ExitT_co]): + def __asynccontextmanager__( + self, + ) -> AbstractAsyncContextManager[_T_co, _ExitT_co]: ... + + +class ContextManagerMixin: + """ + Mixin class providing context manager functionality via a generator-based + implementation. + + This class allows you to implement a context manager via :meth:`__contextmanager__` + which should return a generator. The mechanics are meant to mirror those of + :func:`@contextmanager `. + + .. note:: Classes using this mix-in are not reentrant as context managers, meaning + that once you enter it, you can't re-enter before first exiting it. + + .. seealso:: :doc:`contextmanagers` + """ + + __cm: AbstractContextManager[object, bool | None] | None = None + + @final + def __enter__(self: _SupportsCtxMgr[_T_co, bool | None]) -> _T_co: + # Needed for mypy to assume self still has the __cm member + assert isinstance(self, ContextManagerMixin) + if self.__cm is not None: + raise RuntimeError( + f"this {self.__class__.__qualname__} has already been entered" + ) + + cm = self.__contextmanager__() + if not isinstance(cm, AbstractContextManager): + if isgenerator(cm): + raise TypeError( + "__contextmanager__() returned a generator object instead of " + "a context manager. Did you forget to add the @contextmanager " + "decorator?" + ) + + raise TypeError( + f"__contextmanager__() did not return a context manager object, " + f"but {cm.__class__!r}" + ) + + if cm is self: + raise TypeError( + f"{self.__class__.__qualname__}.__contextmanager__() returned " + f"self. Did you forget to add the @contextmanager decorator and a " + f"'yield' statement?" + ) + + value = cm.__enter__() + self.__cm = cm + return value + + @final + def __exit__( + self: _SupportsCtxMgr[object, _ExitT_co], + exc_type: type[BaseException] | None, + exc_val: BaseException | None, + exc_tb: TracebackType | None, + ) -> _ExitT_co: + # Needed for mypy to assume self still has the __cm member + assert isinstance(self, ContextManagerMixin) + if self.__cm is None: + raise RuntimeError( + f"this {self.__class__.__qualname__} has not been entered yet" + ) + + # Prevent circular references + cm = self.__cm + del self.__cm + + return cast(_ExitT_co, cm.__exit__(exc_type, exc_val, exc_tb)) + + @abstractmethod + def __contextmanager__(self) -> AbstractContextManager[object, bool | None]: + """ + Implement your context manager logic here. + + This method **must** be decorated with + :func:`@contextmanager `. + + .. note:: Remember that the ``yield`` will raise any exception raised in the + enclosed context block, so use a ``finally:`` block to clean up resources! + + :return: a context manager object + """ + + +class AsyncContextManagerMixin: + """ + Mixin class providing async context manager functionality via a generator-based + implementation. + + This class allows you to implement a context manager via + :meth:`__asynccontextmanager__`. The mechanics are meant to mirror those of + :func:`@asynccontextmanager `. + + .. note:: Classes using this mix-in are not reentrant as context managers, meaning + that once you enter it, you can't re-enter before first exiting it. + + .. seealso:: :doc:`contextmanagers` + """ + + __cm: AbstractAsyncContextManager[object, bool | None] | None = None + + @final + async def __aenter__(self: _SupportsAsyncCtxMgr[_T_co, bool | None]) -> _T_co: + # Needed for mypy to assume self still has the __cm member + assert isinstance(self, AsyncContextManagerMixin) + if self.__cm is not None: + raise RuntimeError( + f"this {self.__class__.__qualname__} has already been entered" + ) + + cm = self.__asynccontextmanager__() + if not isinstance(cm, AbstractAsyncContextManager): + if isasyncgen(cm): + raise TypeError( + "__asynccontextmanager__() returned an async generator instead of " + "an async context manager. Did you forget to add the " + "@asynccontextmanager decorator?" + ) + elif iscoroutine(cm): + cm.close() + raise TypeError( + "__asynccontextmanager__() returned a coroutine object instead of " + "an async context manager. Did you forget to add the " + "@asynccontextmanager decorator and a 'yield' statement?" + ) + + raise TypeError( + f"__asynccontextmanager__() did not return an async context manager, " + f"but {cm.__class__!r}" + ) + + if cm is self: + raise TypeError( + f"{self.__class__.__qualname__}.__asynccontextmanager__() returned " + f"self. Did you forget to add the @asynccontextmanager decorator and a " + f"'yield' statement?" + ) + + value = await cm.__aenter__() + self.__cm = cm + return value + + @final + async def __aexit__( + self: _SupportsAsyncCtxMgr[object, _ExitT_co], + exc_type: type[BaseException] | None, + exc_val: BaseException | None, + exc_tb: TracebackType | None, + ) -> _ExitT_co: + assert isinstance(self, AsyncContextManagerMixin) + if self.__cm is None: + raise RuntimeError( + f"this {self.__class__.__qualname__} has not been entered yet" + ) + + # Prevent circular references + cm = self.__cm + del self.__cm + + return cast(_ExitT_co, await cm.__aexit__(exc_type, exc_val, exc_tb)) + + @abstractmethod + def __asynccontextmanager__( + self, + ) -> AbstractAsyncContextManager[object, bool | None]: + """ + Implement your async context manager logic here. + + This method **must** be decorated with + :func:`@asynccontextmanager `. + + .. note:: Remember that the ``yield`` will raise any exception raised in the + enclosed context block, so use a ``finally:`` block to clean up resources! + + :return: an async context manager object + """ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/anyio/_core/_eventloop.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/anyio/_core/_eventloop.py new file mode 100644 index 0000000000000000000000000000000000000000..59a69ccdf02c2989fb522bcc9af5a23f64e1f3e7 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/anyio/_core/_eventloop.py @@ -0,0 +1,234 @@ +from __future__ import annotations + +import math +import sys +import threading +from collections.abc import Awaitable, Callable, Generator +from contextlib import contextmanager +from contextvars import Token +from importlib import import_module +from typing import TYPE_CHECKING, Any, TypeVar + +from ._exceptions import NoEventLoopError + +if sys.version_info >= (3, 11): + from typing import TypeVarTuple, Unpack +else: + from typing_extensions import TypeVarTuple, Unpack + +sniffio: Any +try: + import sniffio +except ModuleNotFoundError: + sniffio = None + +if TYPE_CHECKING: + from ..abc import AsyncBackend + +# This must be updated when new backends are introduced +BACKENDS = "asyncio", "trio" + +T_Retval = TypeVar("T_Retval") +PosArgsT = TypeVarTuple("PosArgsT") + +threadlocals = threading.local() +loaded_backends: dict[str, type[AsyncBackend]] = {} + + +def run( + func: Callable[[Unpack[PosArgsT]], Awaitable[T_Retval]], + *args: Unpack[PosArgsT], + backend: str = "asyncio", + backend_options: dict[str, Any] | None = None, +) -> T_Retval: + """ + Run the given coroutine function in an asynchronous event loop. + + The current thread must not be already running an event loop. + + :param func: a coroutine function + :param args: positional arguments to ``func`` + :param backend: name of the asynchronous event loop implementation – currently + either ``asyncio`` or ``trio`` + :param backend_options: keyword arguments to call the backend ``run()`` + implementation with (documented :ref:`here `) + :return: the return value of the coroutine function + :raises RuntimeError: if an asynchronous event loop is already running in this + thread + :raises LookupError: if the named backend is not found + + """ + if asynclib_name := current_async_library(): + raise RuntimeError(f"Already running {asynclib_name} in this thread") + + try: + async_backend = get_async_backend(backend) + except ImportError as exc: + raise LookupError(f"No such backend: {backend}") from exc + + token = None + if asynclib_name is None: + # Since we're in control of the event loop, we can cache the name of the async + # library + token = set_current_async_library(backend) + + try: + backend_options = backend_options or {} + return async_backend.run(func, args, {}, backend_options) + finally: + reset_current_async_library(token) + + +async def sleep(delay: float) -> None: + """ + Pause the current task for the specified duration. + + :param delay: the duration, in seconds + + """ + return await get_async_backend().sleep(delay) + + +async def sleep_forever() -> None: + """ + Pause the current task until it's cancelled. + + This is a shortcut for ``sleep(math.inf)``. + + .. versionadded:: 3.1 + + """ + await sleep(math.inf) + + +async def sleep_until(deadline: float) -> None: + """ + Pause the current task until the given time. + + :param deadline: the absolute time to wake up at (according to the internal + monotonic clock of the event loop) + + .. versionadded:: 3.1 + + """ + now = current_time() + await sleep(max(deadline - now, 0)) + + +def current_time() -> float: + """ + Return the current value of the event loop's internal clock. + + :return: the clock value (seconds) + :raises NoEventLoopError: if no supported asynchronous event loop is running in the + current thread + + """ + return get_async_backend().current_time() + + +def get_all_backends() -> tuple[str, ...]: + """Return a tuple of the names of all built-in backends.""" + return BACKENDS + + +def get_available_backends() -> tuple[str, ...]: + """ + Test for the availability of built-in backends. + + :return a tuple of the built-in backend names that were successfully imported + + .. versionadded:: 4.12 + + """ + available_backends: list[str] = [] + for backend_name in get_all_backends(): + try: + get_async_backend(backend_name) + except ImportError: + continue + + available_backends.append(backend_name) + + return tuple(available_backends) + + +def get_cancelled_exc_class() -> type[BaseException]: + """ + Return the current async library's cancellation exception class. + + :raises NoEventLoopError: if no supported asynchronous event loop is running in the + current thread + + """ + return get_async_backend().cancelled_exception_class() + + +# +# Private API +# + + +@contextmanager +def claim_worker_thread( + backend_class: type[AsyncBackend], token: object +) -> Generator[Any, None, None]: + from ..lowlevel import EventLoopToken + + threadlocals.current_token = EventLoopToken(backend_class, token) + try: + yield + finally: + del threadlocals.current_token + + +def get_async_backend(asynclib_name: str | None = None) -> type[AsyncBackend]: + if asynclib_name is None: + asynclib_name = current_async_library() + if not asynclib_name: + raise NoEventLoopError( + f"Not currently running on any asynchronous event loop. " + f"Available async backends: {', '.join(get_all_backends())}" + ) + + # We use our own dict instead of sys.modules to get the already imported back-end + # class because the appropriate modules in sys.modules could potentially be only + # partially initialized + try: + return loaded_backends[asynclib_name] + except KeyError: + module = import_module(f"anyio._backends._{asynclib_name}") + loaded_backends[asynclib_name] = module.backend_class + return module.backend_class + + +def current_async_library() -> str | None: + if sniffio is None: + # If sniffio is not installed, we assume we're either running asyncio or nothing + import asyncio + + try: + asyncio.get_running_loop() + return "asyncio" + except RuntimeError: + pass + else: + try: + return sniffio.current_async_library() + except sniffio.AsyncLibraryNotFoundError: + pass + + return None + + +def set_current_async_library(asynclib_name: str | None) -> Token | None: + # no-op if sniffio is not installed + if sniffio is None: + return None + + return sniffio.current_async_library_cvar.set(asynclib_name) + + +def reset_current_async_library(token: Token | None) -> None: + if token is not None: + sniffio.current_async_library_cvar.reset(token) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/anyio/_core/_exceptions.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/anyio/_core/_exceptions.py new file mode 100644 index 0000000000000000000000000000000000000000..3776bedcd339913d609e41e2e396f3f2fd16ae9d --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/anyio/_core/_exceptions.py @@ -0,0 +1,156 @@ +from __future__ import annotations + +import sys +from collections.abc import Generator +from textwrap import dedent +from typing import Any + +if sys.version_info < (3, 11): + from exceptiongroup import BaseExceptionGroup + + +class BrokenResourceError(Exception): + """ + Raised when trying to use a resource that has been rendered unusable due to external + causes (e.g. a send stream whose peer has disconnected). + """ + + +class BrokenWorkerProcess(Exception): + """ + Raised by :meth:`~anyio.to_process.run_sync` if the worker process terminates abruptly or + otherwise misbehaves. + """ + + +class BrokenWorkerInterpreter(Exception): + """ + Raised by :meth:`~anyio.to_interpreter.run_sync` if an unexpected exception is + raised in the subinterpreter. + """ + + def __init__(self, excinfo: Any): + # This was adapted from concurrent.futures.interpreter.ExecutionFailed + msg = excinfo.formatted + if not msg: + if excinfo.type and excinfo.msg: + msg = f"{excinfo.type.__name__}: {excinfo.msg}" + else: + msg = excinfo.type.__name__ or excinfo.msg + + super().__init__(msg) + self.excinfo = excinfo + + def __str__(self) -> str: + try: + formatted = self.excinfo.errdisplay + except Exception: + return super().__str__() + else: + return dedent( + f""" + {super().__str__()} + + Uncaught in the interpreter: + + {formatted} + """.strip() + ) + + +class BusyResourceError(Exception): + """ + Raised when two tasks are trying to read from or write to the same resource + concurrently. + """ + + def __init__(self, action: str): + super().__init__(f"Another task is already {action} this resource") + + +class ClosedResourceError(Exception): + """Raised when trying to use a resource that has been closed.""" + + +class ConnectionFailed(OSError): + """ + Raised when a connection attempt fails. + + .. note:: This class inherits from :exc:`OSError` for backwards compatibility. + """ + + +def iterate_exceptions( + exception: BaseException, +) -> Generator[BaseException, None, None]: + if isinstance(exception, BaseExceptionGroup): + for exc in exception.exceptions: + yield from iterate_exceptions(exc) + else: + yield exception + + +class DelimiterNotFound(Exception): + """ + Raised during + :meth:`~anyio.streams.buffered.BufferedByteReceiveStream.receive_until` if the + maximum number of bytes has been read without the delimiter being found. + """ + + def __init__(self, max_bytes: int) -> None: + super().__init__( + f"The delimiter was not found among the first {max_bytes} bytes" + ) + + +class EndOfStream(Exception): + """ + Raised when trying to read from a stream that has been closed from the other end. + """ + + +class IncompleteRead(Exception): + """ + Raised during + :meth:`~anyio.streams.buffered.BufferedByteReceiveStream.receive_exactly` or + :meth:`~anyio.streams.buffered.BufferedByteReceiveStream.receive_until` if the + connection is closed before the requested amount of bytes has been read. + """ + + def __init__(self) -> None: + super().__init__( + "The stream was closed before the read operation could be completed" + ) + + +class TypedAttributeLookupError(LookupError): + """ + Raised by :meth:`~anyio.TypedAttributeProvider.extra` when the given typed attribute + is not found and no default value has been given. + """ + + +class WouldBlock(Exception): + """Raised by ``X_nowait`` functions if ``X()`` would block.""" + + +class NoEventLoopError(RuntimeError): + """ + Raised by several functions that require an event loop to be running in the current + thread when there is no running event loop. + + This is also raised by :func:`.from_thread.run` and :func:`.from_thread.run_sync` + if not calling from an AnyIO worker thread, and no ``token`` was passed. + """ + + +class RunFinishedError(RuntimeError): + """ + Raised by :func:`.from_thread.run` and :func:`.from_thread.run_sync` if the event + loop associated with the explicitly passed token has already finished. + """ + + def __init__(self) -> None: + super().__init__( + "The event loop associated with the given token has already finished" + ) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/anyio/_core/_fileio.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/anyio/_core/_fileio.py new file mode 100644 index 0000000000000000000000000000000000000000..3bb8c845690818fbc92de6a3da31997a8da69244 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/anyio/_core/_fileio.py @@ -0,0 +1,799 @@ +from __future__ import annotations + +import os +import pathlib +import sys +from collections.abc import ( + AsyncIterator, + Callable, + Iterable, + Iterator, + Sequence, +) +from dataclasses import dataclass +from functools import partial +from os import PathLike +from typing import ( + IO, + TYPE_CHECKING, + Any, + AnyStr, + ClassVar, + Final, + Generic, + overload, +) + +from .. import to_thread +from ..abc import AsyncResource + +if TYPE_CHECKING: + from types import ModuleType + + from _typeshed import OpenBinaryMode, OpenTextMode, ReadableBuffer, WriteableBuffer +else: + ReadableBuffer = OpenBinaryMode = OpenTextMode = WriteableBuffer = object + + +class AsyncFile(AsyncResource, Generic[AnyStr]): + """ + An asynchronous file object. + + This class wraps a standard file object and provides async friendly versions of the + following blocking methods (where available on the original file object): + + * read + * read1 + * readline + * readlines + * readinto + * readinto1 + * write + * writelines + * truncate + * seek + * tell + * flush + + All other methods are directly passed through. + + This class supports the asynchronous context manager protocol which closes the + underlying file at the end of the context block. + + This class also supports asynchronous iteration:: + + async with await open_file(...) as f: + async for line in f: + print(line) + """ + + def __init__(self, fp: IO[AnyStr]) -> None: + self._fp: Any = fp + + def __getattr__(self, name: str) -> object: + return getattr(self._fp, name) + + @property + def wrapped(self) -> IO[AnyStr]: + """The wrapped file object.""" + return self._fp + + async def __aiter__(self) -> AsyncIterator[AnyStr]: + while True: + line = await self.readline() + if line: + yield line + else: + break + + async def aclose(self) -> None: + return await to_thread.run_sync(self._fp.close) + + async def read(self, size: int = -1) -> AnyStr: + return await to_thread.run_sync(self._fp.read, size) + + async def read1(self: AsyncFile[bytes], size: int = -1) -> bytes: + return await to_thread.run_sync(self._fp.read1, size) + + async def readline(self) -> AnyStr: + return await to_thread.run_sync(self._fp.readline) + + async def readlines(self) -> list[AnyStr]: + return await to_thread.run_sync(self._fp.readlines) + + async def readinto(self: AsyncFile[bytes], b: WriteableBuffer) -> int: + return await to_thread.run_sync(self._fp.readinto, b) + + async def readinto1(self: AsyncFile[bytes], b: WriteableBuffer) -> int: + return await to_thread.run_sync(self._fp.readinto1, b) + + @overload + async def write(self: AsyncFile[bytes], b: ReadableBuffer) -> int: ... + + @overload + async def write(self: AsyncFile[str], b: str) -> int: ... + + async def write(self, b: ReadableBuffer | str) -> int: + return await to_thread.run_sync(self._fp.write, b) + + @overload + async def writelines( + self: AsyncFile[bytes], lines: Iterable[ReadableBuffer] + ) -> None: ... + + @overload + async def writelines(self: AsyncFile[str], lines: Iterable[str]) -> None: ... + + async def writelines(self, lines: Iterable[ReadableBuffer] | Iterable[str]) -> None: + return await to_thread.run_sync(self._fp.writelines, lines) + + async def truncate(self, size: int | None = None) -> int: + return await to_thread.run_sync(self._fp.truncate, size) + + async def seek(self, offset: int, whence: int | None = os.SEEK_SET) -> int: + return await to_thread.run_sync(self._fp.seek, offset, whence) + + async def tell(self) -> int: + return await to_thread.run_sync(self._fp.tell) + + async def flush(self) -> None: + return await to_thread.run_sync(self._fp.flush) + + +@overload +async def open_file( + file: str | PathLike[str] | int, + mode: OpenBinaryMode, + buffering: int = ..., + encoding: str | None = ..., + errors: str | None = ..., + newline: str | None = ..., + closefd: bool = ..., + opener: Callable[[str, int], int] | None = ..., +) -> AsyncFile[bytes]: ... + + +@overload +async def open_file( + file: str | PathLike[str] | int, + mode: OpenTextMode = ..., + buffering: int = ..., + encoding: str | None = ..., + errors: str | None = ..., + newline: str | None = ..., + closefd: bool = ..., + opener: Callable[[str, int], int] | None = ..., +) -> AsyncFile[str]: ... + + +async def open_file( + file: str | PathLike[str] | int, + mode: str = "r", + buffering: int = -1, + encoding: str | None = None, + errors: str | None = None, + newline: str | None = None, + closefd: bool = True, + opener: Callable[[str, int], int] | None = None, +) -> AsyncFile[Any]: + """ + Open a file asynchronously. + + The arguments are exactly the same as for the builtin :func:`open`. + + :return: an asynchronous file object + + """ + fp = await to_thread.run_sync( + open, file, mode, buffering, encoding, errors, newline, closefd, opener + ) + return AsyncFile(fp) + + +def wrap_file(file: IO[AnyStr]) -> AsyncFile[AnyStr]: + """ + Wrap an existing file as an asynchronous file. + + :param file: an existing file-like object + :return: an asynchronous file object + + """ + return AsyncFile(file) + + +@dataclass(eq=False) +class _PathIterator(AsyncIterator["Path"]): + iterator: Iterator[PathLike[str]] + + async def __anext__(self) -> Path: + nextval = await to_thread.run_sync( + next, self.iterator, None, abandon_on_cancel=True + ) + if nextval is None: + raise StopAsyncIteration from None + + return Path(nextval) + + +class Path: + """ + An asynchronous version of :class:`pathlib.Path`. + + This class cannot be substituted for :class:`pathlib.Path` or + :class:`pathlib.PurePath`, but it is compatible with the :class:`os.PathLike` + interface. + + It implements the Python 3.10 version of :class:`pathlib.Path` interface, except for + the deprecated :meth:`~pathlib.Path.link_to` method. + + Some methods may be unavailable or have limited functionality, based on the Python + version: + + * :meth:`~pathlib.Path.copy` (available on Python 3.14 or later) + * :meth:`~pathlib.Path.copy_into` (available on Python 3.14 or later) + * :meth:`~pathlib.Path.from_uri` (available on Python 3.13 or later) + * :meth:`~pathlib.PurePath.full_match` (available on Python 3.13 or later) + * :attr:`~pathlib.Path.info` (available on Python 3.14 or later) + * :meth:`~pathlib.Path.is_junction` (available on Python 3.12 or later) + * :meth:`~pathlib.PurePath.match` (the ``case_sensitive`` parameter is only + available on Python 3.13 or later) + * :meth:`~pathlib.Path.move` (available on Python 3.14 or later) + * :meth:`~pathlib.Path.move_into` (available on Python 3.14 or later) + * :meth:`~pathlib.PurePath.relative_to` (the ``walk_up`` parameter is only available + on Python 3.12 or later) + * :meth:`~pathlib.Path.walk` (available on Python 3.12 or later) + + Any methods that do disk I/O need to be awaited on. These methods are: + + * :meth:`~pathlib.Path.absolute` + * :meth:`~pathlib.Path.chmod` + * :meth:`~pathlib.Path.cwd` + * :meth:`~pathlib.Path.exists` + * :meth:`~pathlib.Path.expanduser` + * :meth:`~pathlib.Path.group` + * :meth:`~pathlib.Path.hardlink_to` + * :meth:`~pathlib.Path.home` + * :meth:`~pathlib.Path.is_block_device` + * :meth:`~pathlib.Path.is_char_device` + * :meth:`~pathlib.Path.is_dir` + * :meth:`~pathlib.Path.is_fifo` + * :meth:`~pathlib.Path.is_file` + * :meth:`~pathlib.Path.is_junction` + * :meth:`~pathlib.Path.is_mount` + * :meth:`~pathlib.Path.is_socket` + * :meth:`~pathlib.Path.is_symlink` + * :meth:`~pathlib.Path.lchmod` + * :meth:`~pathlib.Path.lstat` + * :meth:`~pathlib.Path.mkdir` + * :meth:`~pathlib.Path.open` + * :meth:`~pathlib.Path.owner` + * :meth:`~pathlib.Path.read_bytes` + * :meth:`~pathlib.Path.read_text` + * :meth:`~pathlib.Path.readlink` + * :meth:`~pathlib.Path.rename` + * :meth:`~pathlib.Path.replace` + * :meth:`~pathlib.Path.resolve` + * :meth:`~pathlib.Path.rmdir` + * :meth:`~pathlib.Path.samefile` + * :meth:`~pathlib.Path.stat` + * :meth:`~pathlib.Path.symlink_to` + * :meth:`~pathlib.Path.touch` + * :meth:`~pathlib.Path.unlink` + * :meth:`~pathlib.Path.walk` + * :meth:`~pathlib.Path.write_bytes` + * :meth:`~pathlib.Path.write_text` + + Additionally, the following methods return an async iterator yielding + :class:`~.Path` objects: + + * :meth:`~pathlib.Path.glob` + * :meth:`~pathlib.Path.iterdir` + * :meth:`~pathlib.Path.rglob` + """ + + __slots__ = "_path", "__weakref__" + + __weakref__: Any + + def __init__(self, *args: str | PathLike[str]) -> None: + self._path: Final[pathlib.Path] = pathlib.Path(*args) + + def __fspath__(self) -> str: + return self._path.__fspath__() + + if sys.version_info >= (3, 15): + + def __vfspath__(self) -> str: + return self._path.__vfspath__() + + def __str__(self) -> str: + return self._path.__str__() + + def __repr__(self) -> str: + return f"{self.__class__.__name__}({self.as_posix()!r})" + + def __bytes__(self) -> bytes: + return self._path.__bytes__() + + def __hash__(self) -> int: + return self._path.__hash__() + + def __eq__(self, other: object) -> bool: + target = other._path if isinstance(other, Path) else other + return self._path.__eq__(target) + + def __lt__(self, other: pathlib.PurePath | Path) -> bool: + target = other._path if isinstance(other, Path) else other + return self._path.__lt__(target) + + def __le__(self, other: pathlib.PurePath | Path) -> bool: + target = other._path if isinstance(other, Path) else other + return self._path.__le__(target) + + def __gt__(self, other: pathlib.PurePath | Path) -> bool: + target = other._path if isinstance(other, Path) else other + return self._path.__gt__(target) + + def __ge__(self, other: pathlib.PurePath | Path) -> bool: + target = other._path if isinstance(other, Path) else other + return self._path.__ge__(target) + + def __truediv__(self, other: str | PathLike[str]) -> Path: + return Path(self._path / other) + + def __rtruediv__(self, other: str | PathLike[str]) -> Path: + return Path(other) / self + + @property + def parts(self) -> tuple[str, ...]: + return self._path.parts + + @property + def drive(self) -> str: + return self._path.drive + + @property + def root(self) -> str: + return self._path.root + + @property + def anchor(self) -> str: + return self._path.anchor + + @property + def parents(self) -> Sequence[Path]: + return tuple(Path(p) for p in self._path.parents) + + @property + def parent(self) -> Path: + return Path(self._path.parent) + + @property + def name(self) -> str: + return self._path.name + + @property + def suffix(self) -> str: + return self._path.suffix + + @property + def suffixes(self) -> list[str]: + return self._path.suffixes + + @property + def stem(self) -> str: + return self._path.stem + + async def absolute(self) -> Path: + path = await to_thread.run_sync(self._path.absolute) + return Path(path) + + def as_posix(self) -> str: + return self._path.as_posix() + + def as_uri(self) -> str: + return self._path.as_uri() + + if sys.version_info >= (3, 13): + parser: ClassVar[ModuleType] = pathlib.Path.parser + + @classmethod + def from_uri(cls, uri: str) -> Path: + return Path(pathlib.Path.from_uri(uri)) + + def full_match( + self, path_pattern: str, *, case_sensitive: bool | None = None + ) -> bool: + return self._path.full_match(path_pattern, case_sensitive=case_sensitive) + + def match( + self, path_pattern: str, *, case_sensitive: bool | None = None + ) -> bool: + return self._path.match(path_pattern, case_sensitive=case_sensitive) + else: + + def match(self, path_pattern: str) -> bool: + return self._path.match(path_pattern) + + if sys.version_info >= (3, 14): + + @property + def info(self) -> Any: # TODO: add return type annotation when Typeshed gets it + return self._path.info + + async def copy( + self, + target: str | os.PathLike[str], + *, + follow_symlinks: bool = True, + preserve_metadata: bool = False, + ) -> Path: + func = partial( + self._path.copy, + follow_symlinks=follow_symlinks, + preserve_metadata=preserve_metadata, + ) + return Path(await to_thread.run_sync(func, pathlib.Path(target))) + + async def copy_into( + self, + target_dir: str | os.PathLike[str], + *, + follow_symlinks: bool = True, + preserve_metadata: bool = False, + ) -> Path: + func = partial( + self._path.copy_into, + follow_symlinks=follow_symlinks, + preserve_metadata=preserve_metadata, + ) + return Path(await to_thread.run_sync(func, pathlib.Path(target_dir))) + + async def move(self, target: str | os.PathLike[str]) -> Path: + # Upstream does not handle anyio.Path properly as a PathLike + target = pathlib.Path(target) + return Path(await to_thread.run_sync(self._path.move, target)) + + async def move_into( + self, + target_dir: str | os.PathLike[str], + ) -> Path: + return Path(await to_thread.run_sync(self._path.move_into, target_dir)) + + def is_relative_to(self, other: str | PathLike[str]) -> bool: + try: + self.relative_to(other) + return True + except ValueError: + return False + + async def chmod(self, mode: int, *, follow_symlinks: bool = True) -> None: + func = partial(os.chmod, follow_symlinks=follow_symlinks) + return await to_thread.run_sync(func, self._path, mode) + + @classmethod + async def cwd(cls) -> Path: + path = await to_thread.run_sync(pathlib.Path.cwd) + return cls(path) + + async def exists(self) -> bool: + return await to_thread.run_sync(self._path.exists, abandon_on_cancel=True) + + async def expanduser(self) -> Path: + return Path( + await to_thread.run_sync(self._path.expanduser, abandon_on_cancel=True) + ) + + if sys.version_info < (3, 12): + # Python 3.11 and earlier + def glob(self, pattern: str) -> AsyncIterator[Path]: + gen = self._path.glob(pattern) + return _PathIterator(gen) + elif (3, 12) <= sys.version_info < (3, 13): + # changed in Python 3.12: + # - The case_sensitive parameter was added. + def glob( + self, + pattern: str, + *, + case_sensitive: bool | None = None, + ) -> AsyncIterator[Path]: + gen = self._path.glob(pattern, case_sensitive=case_sensitive) + return _PathIterator(gen) + elif sys.version_info >= (3, 13): + # Changed in Python 3.13: + # - The recurse_symlinks parameter was added. + # - The pattern parameter accepts a path-like object. + def glob( # type: ignore[misc] # mypy doesn't allow for differing signatures in a conditional block + self, + pattern: str | PathLike[str], + *, + case_sensitive: bool | None = None, + recurse_symlinks: bool = False, + ) -> AsyncIterator[Path]: + gen = self._path.glob( + pattern, # type: ignore[arg-type] + case_sensitive=case_sensitive, + recurse_symlinks=recurse_symlinks, + ) + return _PathIterator(gen) + + async def group(self) -> str: + return await to_thread.run_sync(self._path.group, abandon_on_cancel=True) + + async def hardlink_to( + self, target: str | bytes | PathLike[str] | PathLike[bytes] + ) -> None: + if isinstance(target, Path): + target = target._path + + await to_thread.run_sync(os.link, target, self) + + @classmethod + async def home(cls) -> Path: + home_path = await to_thread.run_sync(pathlib.Path.home) + return cls(home_path) + + def is_absolute(self) -> bool: + return self._path.is_absolute() + + async def is_block_device(self) -> bool: + return await to_thread.run_sync( + self._path.is_block_device, abandon_on_cancel=True + ) + + async def is_char_device(self) -> bool: + return await to_thread.run_sync( + self._path.is_char_device, abandon_on_cancel=True + ) + + async def is_dir(self) -> bool: + return await to_thread.run_sync(self._path.is_dir, abandon_on_cancel=True) + + async def is_fifo(self) -> bool: + return await to_thread.run_sync(self._path.is_fifo, abandon_on_cancel=True) + + async def is_file(self) -> bool: + return await to_thread.run_sync(self._path.is_file, abandon_on_cancel=True) + + if sys.version_info >= (3, 12): + + async def is_junction(self) -> bool: + return await to_thread.run_sync(self._path.is_junction) + + async def is_mount(self) -> bool: + return await to_thread.run_sync( + os.path.ismount, self._path, abandon_on_cancel=True + ) + + if sys.version_info < (3, 15): + + def is_reserved(self) -> bool: + return self._path.is_reserved() + + async def is_socket(self) -> bool: + return await to_thread.run_sync(self._path.is_socket, abandon_on_cancel=True) + + async def is_symlink(self) -> bool: + return await to_thread.run_sync(self._path.is_symlink, abandon_on_cancel=True) + + async def iterdir(self) -> AsyncIterator[Path]: + gen = ( + self._path.iterdir() + if sys.version_info < (3, 13) + else await to_thread.run_sync(self._path.iterdir, abandon_on_cancel=True) + ) + async for path in _PathIterator(gen): + yield path + + def joinpath(self, *args: str | PathLike[str]) -> Path: + return Path(self._path.joinpath(*args)) + + async def lchmod(self, mode: int) -> None: + await to_thread.run_sync(self._path.lchmod, mode) + + async def lstat(self) -> os.stat_result: + return await to_thread.run_sync(self._path.lstat, abandon_on_cancel=True) + + async def mkdir( + self, mode: int = 0o777, parents: bool = False, exist_ok: bool = False + ) -> None: + await to_thread.run_sync(self._path.mkdir, mode, parents, exist_ok) + + @overload + async def open( + self, + mode: OpenBinaryMode, + buffering: int = ..., + encoding: str | None = ..., + errors: str | None = ..., + newline: str | None = ..., + ) -> AsyncFile[bytes]: ... + + @overload + async def open( + self, + mode: OpenTextMode = ..., + buffering: int = ..., + encoding: str | None = ..., + errors: str | None = ..., + newline: str | None = ..., + ) -> AsyncFile[str]: ... + + async def open( + self, + mode: str = "r", + buffering: int = -1, + encoding: str | None = None, + errors: str | None = None, + newline: str | None = None, + ) -> AsyncFile[Any]: + fp = await to_thread.run_sync( + self._path.open, mode, buffering, encoding, errors, newline + ) + return AsyncFile(fp) + + async def owner(self) -> str: + return await to_thread.run_sync(self._path.owner, abandon_on_cancel=True) + + async def read_bytes(self) -> bytes: + return await to_thread.run_sync(self._path.read_bytes) + + async def read_text( + self, encoding: str | None = None, errors: str | None = None + ) -> str: + return await to_thread.run_sync(self._path.read_text, encoding, errors) + + if sys.version_info >= (3, 12): + + def relative_to( + self, *other: str | PathLike[str], walk_up: bool = False + ) -> Path: + # relative_to() should work with any PathLike but it doesn't + others = [pathlib.Path(other) for other in other] + return Path(self._path.relative_to(*others, walk_up=walk_up)) + + else: + + def relative_to(self, *other: str | PathLike[str]) -> Path: + return Path(self._path.relative_to(*other)) + + async def readlink(self) -> Path: + target = await to_thread.run_sync(os.readlink, self._path) + return Path(target) + + async def rename(self, target: str | pathlib.PurePath | Path) -> Path: + if isinstance(target, Path): + target = target._path + + await to_thread.run_sync(self._path.rename, target) + return Path(target) + + async def replace(self, target: str | pathlib.PurePath | Path) -> Path: + if isinstance(target, Path): + target = target._path + + await to_thread.run_sync(self._path.replace, target) + return Path(target) + + async def resolve(self, strict: bool = False) -> Path: + func = partial(self._path.resolve, strict=strict) + return Path(await to_thread.run_sync(func, abandon_on_cancel=True)) + + if sys.version_info < (3, 12): + # Pre Python 3.12 + def rglob(self, pattern: str) -> AsyncIterator[Path]: + gen = self._path.rglob(pattern) + return _PathIterator(gen) + elif (3, 12) <= sys.version_info < (3, 13): + # Changed in Python 3.12: + # - The case_sensitive parameter was added. + def rglob( + self, pattern: str, *, case_sensitive: bool | None = None + ) -> AsyncIterator[Path]: + gen = self._path.rglob(pattern, case_sensitive=case_sensitive) + return _PathIterator(gen) + elif sys.version_info >= (3, 13): + # Changed in Python 3.13: + # - The recurse_symlinks parameter was added. + # - The pattern parameter accepts a path-like object. + def rglob( # type: ignore[misc] # mypy doesn't allow for differing signatures in a conditional block + self, + pattern: str | PathLike[str], + *, + case_sensitive: bool | None = None, + recurse_symlinks: bool = False, + ) -> AsyncIterator[Path]: + gen = self._path.rglob( + pattern, # type: ignore[arg-type] + case_sensitive=case_sensitive, + recurse_symlinks=recurse_symlinks, + ) + return _PathIterator(gen) + + async def rmdir(self) -> None: + await to_thread.run_sync(self._path.rmdir) + + async def samefile(self, other_path: str | PathLike[str]) -> bool: + if isinstance(other_path, Path): + other_path = other_path._path + + return await to_thread.run_sync( + self._path.samefile, other_path, abandon_on_cancel=True + ) + + async def stat(self, *, follow_symlinks: bool = True) -> os.stat_result: + func = partial(os.stat, follow_symlinks=follow_symlinks) + return await to_thread.run_sync(func, self._path, abandon_on_cancel=True) + + async def symlink_to( + self, + target: str | bytes | PathLike[str] | PathLike[bytes], + target_is_directory: bool = False, + ) -> None: + if isinstance(target, Path): + target = target._path + + await to_thread.run_sync(self._path.symlink_to, target, target_is_directory) + + async def touch(self, mode: int = 0o666, exist_ok: bool = True) -> None: + await to_thread.run_sync(self._path.touch, mode, exist_ok) + + async def unlink(self, missing_ok: bool = False) -> None: + try: + await to_thread.run_sync(self._path.unlink) + except FileNotFoundError: + if not missing_ok: + raise + + if sys.version_info >= (3, 12): + + async def walk( + self, + top_down: bool = True, + on_error: Callable[[OSError], object] | None = None, + follow_symlinks: bool = False, + ) -> AsyncIterator[tuple[Path, list[str], list[str]]]: + def get_next_value() -> tuple[pathlib.Path, list[str], list[str]] | None: + try: + return next(gen) + except StopIteration: + return None + + gen = self._path.walk(top_down, on_error, follow_symlinks) + while True: + value = await to_thread.run_sync(get_next_value) + if value is None: + return + + root, dirs, paths = value + yield Path(root), dirs, paths + + def with_name(self, name: str) -> Path: + return Path(self._path.with_name(name)) + + def with_stem(self, stem: str) -> Path: + return Path(self._path.with_name(stem + self._path.suffix)) + + def with_suffix(self, suffix: str) -> Path: + return Path(self._path.with_suffix(suffix)) + + def with_segments(self, *pathsegments: str | PathLike[str]) -> Path: + return Path(*pathsegments) + + async def write_bytes(self, data: bytes) -> int: + return await to_thread.run_sync(self._path.write_bytes, data) + + async def write_text( + self, + data: str, + encoding: str | None = None, + errors: str | None = None, + newline: str | None = None, + ) -> int: + return await to_thread.run_sync( + self._path.write_text, data, encoding, errors, newline + ) + + +PathLike.register(Path) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/anyio/_core/_resources.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/anyio/_core/_resources.py new file mode 100644 index 0000000000000000000000000000000000000000..b9a5344aef2962670f9b305a02cd0b11f2087d2f --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/anyio/_core/_resources.py @@ -0,0 +1,18 @@ +from __future__ import annotations + +from ..abc import AsyncResource +from ._tasks import CancelScope + + +async def aclose_forcefully(resource: AsyncResource) -> None: + """ + Close an asynchronous resource in a cancelled scope. + + Doing this closes the resource without waiting on anything. + + :param resource: the resource to close + + """ + with CancelScope() as scope: + scope.cancel() + await resource.aclose() diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/anyio/_core/_signals.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/anyio/_core/_signals.py new file mode 100644 index 0000000000000000000000000000000000000000..e24c79e10d4b76775679f7dd0dbe3f5860150451 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/anyio/_core/_signals.py @@ -0,0 +1,29 @@ +from __future__ import annotations + +from collections.abc import AsyncIterator +from contextlib import AbstractContextManager +from signal import Signals + +from ._eventloop import get_async_backend + + +def open_signal_receiver( + *signals: Signals, +) -> AbstractContextManager[AsyncIterator[Signals]]: + """ + Start receiving operating system signals. + + :param signals: signals to receive (e.g. ``signal.SIGINT``) + :return: an asynchronous context manager for an asynchronous iterator which yields + signal numbers + :raises NoEventLoopError: if no supported asynchronous event loop is running in the + current thread + + .. warning:: Windows does not support signals natively so it is best to avoid + relying on this in cross-platform applications. + + .. warning:: On asyncio, this permanently replaces any previous signal handler for + the given signals, as set via :meth:`~asyncio.loop.add_signal_handler`. + + """ + return get_async_backend().open_signal_receiver(*signals) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/anyio/_core/_sockets.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/anyio/_core/_sockets.py new file mode 100644 index 0000000000000000000000000000000000000000..6c99b3a1c1c7a5beee07aa5cf053149f8b5b9e2f --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/anyio/_core/_sockets.py @@ -0,0 +1,1003 @@ +from __future__ import annotations + +import errno +import os +import socket +import ssl +import stat +import sys +from collections.abc import Awaitable +from dataclasses import dataclass +from ipaddress import IPv4Address, IPv6Address, ip_address +from os import PathLike, chmod +from socket import AddressFamily, SocketKind +from typing import TYPE_CHECKING, Any, Literal, cast, overload + +from .. import ConnectionFailed, to_thread +from ..abc import ( + ByteStreamConnectable, + ConnectedUDPSocket, + ConnectedUNIXDatagramSocket, + IPAddressType, + IPSockAddrType, + SocketListener, + SocketStream, + UDPSocket, + UNIXDatagramSocket, + UNIXSocketStream, +) +from ..streams.stapled import MultiListener +from ..streams.tls import TLSConnectable, TLSStream +from ._eventloop import get_async_backend +from ._resources import aclose_forcefully +from ._synchronization import Event +from ._tasks import create_task_group, move_on_after + +if TYPE_CHECKING: + from _typeshed import FileDescriptorLike +else: + FileDescriptorLike = object + +if sys.version_info < (3, 11): + from exceptiongroup import ExceptionGroup + +if sys.version_info >= (3, 12): + from typing import override +else: + from typing_extensions import override + +if sys.version_info < (3, 13): + from typing_extensions import deprecated +else: + from warnings import deprecated + +IPPROTO_IPV6 = getattr(socket, "IPPROTO_IPV6", 41) # https://bugs.python.org/issue29515 + +AnyIPAddressFamily = Literal[ + AddressFamily.AF_UNSPEC, AddressFamily.AF_INET, AddressFamily.AF_INET6 +] +IPAddressFamily = Literal[AddressFamily.AF_INET, AddressFamily.AF_INET6] + + +# tls_hostname given +@overload +async def connect_tcp( + remote_host: IPAddressType, + remote_port: int, + *, + local_host: IPAddressType | None = ..., + ssl_context: ssl.SSLContext | None = ..., + tls_standard_compatible: bool = ..., + tls_hostname: str, + happy_eyeballs_delay: float = ..., +) -> TLSStream: ... + + +# ssl_context given +@overload +async def connect_tcp( + remote_host: IPAddressType, + remote_port: int, + *, + local_host: IPAddressType | None = ..., + ssl_context: ssl.SSLContext, + tls_standard_compatible: bool = ..., + tls_hostname: str | None = ..., + happy_eyeballs_delay: float = ..., +) -> TLSStream: ... + + +# tls=True +@overload +async def connect_tcp( + remote_host: IPAddressType, + remote_port: int, + *, + local_host: IPAddressType | None = ..., + tls: Literal[True], + ssl_context: ssl.SSLContext | None = ..., + tls_standard_compatible: bool = ..., + tls_hostname: str | None = ..., + happy_eyeballs_delay: float = ..., +) -> TLSStream: ... + + +# tls=False +@overload +async def connect_tcp( + remote_host: IPAddressType, + remote_port: int, + *, + local_host: IPAddressType | None = ..., + tls: Literal[False], + ssl_context: ssl.SSLContext | None = ..., + tls_standard_compatible: bool = ..., + tls_hostname: str | None = ..., + happy_eyeballs_delay: float = ..., +) -> SocketStream: ... + + +# No TLS arguments +@overload +async def connect_tcp( + remote_host: IPAddressType, + remote_port: int, + *, + local_host: IPAddressType | None = ..., + happy_eyeballs_delay: float = ..., +) -> SocketStream: ... + + +async def connect_tcp( + remote_host: IPAddressType, + remote_port: int, + *, + local_host: IPAddressType | None = None, + tls: bool = False, + ssl_context: ssl.SSLContext | None = None, + tls_standard_compatible: bool = True, + tls_hostname: str | None = None, + happy_eyeballs_delay: float = 0.25, +) -> SocketStream | TLSStream: + """ + Connect to a host using the TCP protocol. + + This function implements the stateless version of the Happy Eyeballs algorithm (RFC + 6555). If ``remote_host`` is a host name that resolves to multiple IP addresses, + each one is tried until one connection attempt succeeds. If the first attempt does + not connected within 250 milliseconds, a second attempt is started using the next + address in the list, and so on. On IPv6 enabled systems, an IPv6 address (if + available) is tried first. + + When the connection has been established, a TLS handshake will be done if either + ``ssl_context`` or ``tls_hostname`` is not ``None``, or if ``tls`` is ``True``. + + :param remote_host: the IP address or host name to connect to + :param remote_port: port on the target host to connect to + :param local_host: the interface address or name to bind the socket to before + connecting + :param tls: ``True`` to do a TLS handshake with the connected stream and return a + :class:`~anyio.streams.tls.TLSStream` instead + :param ssl_context: the SSL context object to use (if omitted, a default context is + created) + :param tls_standard_compatible: If ``True``, performs the TLS shutdown handshake + before closing the stream and requires that the server does this as well. + Otherwise, :exc:`~ssl.SSLEOFError` may be raised during reads from the stream. + Some protocols, such as HTTP, require this option to be ``False``. + See :meth:`~ssl.SSLContext.wrap_socket` for details. + :param tls_hostname: host name to check the server certificate against (defaults to + the value of ``remote_host``) + :param happy_eyeballs_delay: delay (in seconds) before starting the next connection + attempt + :return: a socket stream object if no TLS handshake was done, otherwise a TLS stream + :raises ConnectionFailed: if the connection fails + + """ + # Placed here due to https://github.com/python/mypy/issues/7057 + connected_stream: SocketStream | None = None + + async def try_connect(remote_host: str, event: Event) -> None: + nonlocal connected_stream + try: + stream = await asynclib.connect_tcp(remote_host, remote_port, local_address) + except OSError as exc: + oserrors.append(exc) + return + else: + if connected_stream is None: + connected_stream = stream + tg.cancel_scope.cancel() + else: + await stream.aclose() + finally: + event.set() + + asynclib = get_async_backend() + local_address: IPSockAddrType | None = None + family = socket.AF_UNSPEC + if local_host: + gai_res = await getaddrinfo(str(local_host), None) + family, *_, local_address = gai_res[0] + + target_host = str(remote_host) + try: + addr_obj = ip_address(remote_host) + except ValueError: + addr_obj = None + + if addr_obj is not None: + if isinstance(addr_obj, IPv6Address): + target_addrs = [(socket.AF_INET6, addr_obj.compressed)] + else: + target_addrs = [(socket.AF_INET, addr_obj.compressed)] + else: + # getaddrinfo() will raise an exception if name resolution fails + gai_res = await getaddrinfo( + target_host, remote_port, family=family, type=socket.SOCK_STREAM + ) + + # Organize the list so that the first address is an IPv6 address (if available) + # and the second one is an IPv4 addresses. The rest can be in whatever order. + v6_found = v4_found = False + target_addrs = [] + for af, *_, sa in gai_res: + if af == socket.AF_INET6 and not v6_found: + v6_found = True + target_addrs.insert(0, (af, sa[0])) + elif af == socket.AF_INET and not v4_found and v6_found: + v4_found = True + target_addrs.insert(1, (af, sa[0])) + else: + target_addrs.append((af, sa[0])) + + oserrors: list[OSError] = [] + try: + async with create_task_group() as tg: + for _af, addr in target_addrs: + event = Event() + tg.start_soon(try_connect, addr, event) + with move_on_after(happy_eyeballs_delay): + await event.wait() + + if connected_stream is None: + cause = ( + oserrors[0] + if len(oserrors) == 1 + else ExceptionGroup("multiple connection attempts failed", oserrors) + ) + raise OSError("All connection attempts failed") from cause + finally: + oserrors.clear() + + if tls or tls_hostname or ssl_context: + try: + return await TLSStream.wrap( + connected_stream, + server_side=False, + hostname=tls_hostname or str(remote_host), + ssl_context=ssl_context, + standard_compatible=tls_standard_compatible, + ) + except BaseException: + await aclose_forcefully(connected_stream) + raise + + return connected_stream + + +async def connect_unix(path: str | bytes | PathLike[Any]) -> UNIXSocketStream: + """ + Connect to the given UNIX socket. + + Not available on Windows. + + :param path: path to the socket + :return: a socket stream object + :raises ConnectionFailed: if the connection fails + + """ + path = os.fspath(path) + return await get_async_backend().connect_unix(path) + + +async def create_tcp_listener( + *, + local_host: IPAddressType | None = None, + local_port: int = 0, + family: AnyIPAddressFamily = socket.AddressFamily.AF_UNSPEC, + backlog: int = 65536, + reuse_port: bool = False, +) -> MultiListener[SocketStream]: + """ + Create a TCP socket listener. + + :param local_port: port number to listen on + :param local_host: IP address of the interface to listen on. If omitted, listen on + all IPv4 and IPv6 interfaces. To listen on all interfaces on a specific address + family, use ``0.0.0.0`` for IPv4 or ``::`` for IPv6. + :param family: address family (used if ``local_host`` was omitted) + :param backlog: maximum number of queued incoming connections (up to a maximum of + 2**16, or 65536) + :param reuse_port: ``True`` to allow multiple sockets to bind to the same + address/port (not supported on Windows) + :return: a multi-listener object containing one or more socket listeners + :raises OSError: if there's an error creating a socket, or binding to one or more + interfaces failed + + """ + asynclib = get_async_backend() + backlog = min(backlog, 65536) + local_host = str(local_host) if local_host is not None else None + + def setup_raw_socket( + fam: AddressFamily, + bind_addr: tuple[str, int] | tuple[str, int, int, int], + *, + v6only: bool = True, + ) -> socket.socket: + sock = socket.socket(fam) + try: + sock.setblocking(False) + + if fam == AddressFamily.AF_INET6: + sock.setsockopt(IPPROTO_IPV6, socket.IPV6_V6ONLY, v6only) + + # For Windows, enable exclusive address use. For others, enable address + # reuse. + if sys.platform == "win32": + sock.setsockopt(socket.SOL_SOCKET, socket.SO_EXCLUSIVEADDRUSE, 1) + else: + sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) + + if reuse_port: + sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT, 1) + + # Workaround for #554 + if fam == socket.AF_INET6 and "%" in bind_addr[0]: + addr, scope_id = bind_addr[0].split("%", 1) + bind_addr = (addr, bind_addr[1], 0, int(scope_id)) + + sock.bind(bind_addr) + sock.listen(backlog) + except BaseException: + sock.close() + raise + + return sock + + # We passing type=0 on non-Windows platforms as a workaround for a uvloop bug + # where we don't get the correct scope ID for IPv6 link-local addresses when passing + # type=socket.SOCK_STREAM to getaddrinfo(): + # https://github.com/MagicStack/uvloop/issues/539 + gai_res = await getaddrinfo( + local_host, + local_port, + family=family, + type=socket.SOCK_STREAM if sys.platform == "win32" else 0, + flags=socket.AI_PASSIVE | socket.AI_ADDRCONFIG, + ) + + # The set comprehension is here to work around a glibc bug: + # https://sourceware.org/bugzilla/show_bug.cgi?id=14969 + sockaddrs = sorted({res for res in gai_res if res[1] == SocketKind.SOCK_STREAM}) + + # Special case for dual-stack binding on the "any" interface + if ( + local_host is None + and family == AddressFamily.AF_UNSPEC + and socket.has_dualstack_ipv6() + and any(fam == AddressFamily.AF_INET6 for fam, *_ in gai_res) + ): + raw_socket = setup_raw_socket( + AddressFamily.AF_INET6, ("::", local_port), v6only=False + ) + listener = asynclib.create_tcp_listener(raw_socket) + return MultiListener([listener]) + + errors: list[OSError] = [] + try: + for _ in range(len(sockaddrs)): + listeners: list[SocketListener] = [] + bound_ephemeral_port = local_port + try: + for fam, *_, sockaddr in sockaddrs: + sockaddr = sockaddr[0], bound_ephemeral_port, *sockaddr[2:] + raw_socket = setup_raw_socket(fam, sockaddr) + + # Store the assigned port if an ephemeral port was requested, so + # we'll bind to the same port on all interfaces + if local_port == 0 and len(gai_res) > 1: + bound_ephemeral_port = raw_socket.getsockname()[1] + + listeners.append(asynclib.create_tcp_listener(raw_socket)) + except BaseException as exc: + for listener in listeners: + await listener.aclose() + + # If an ephemeral port was requested but binding the assigned port + # failed for another interface, rotate the address list and try again + if ( + isinstance(exc, OSError) + and exc.errno == errno.EADDRINUSE + and local_port == 0 + and bound_ephemeral_port + ): + errors.append(exc) + sockaddrs.append(sockaddrs.pop(0)) + continue + + raise + + return MultiListener(listeners) + + raise OSError( + f"Could not create {len(sockaddrs)} listeners with a consistent port" + ) from ExceptionGroup("Several bind attempts failed", errors) + finally: + del errors # Prevent reference cycles + + +async def create_unix_listener( + path: str | bytes | PathLike[Any], + *, + mode: int | None = None, + backlog: int = 65536, +) -> SocketListener: + """ + Create a UNIX socket listener. + + Not available on Windows. + + :param path: path of the socket + :param mode: permissions to set on the socket + :param backlog: maximum number of queued incoming connections (up to a maximum of + 2**16, or 65536) + :return: a listener object + + .. versionchanged:: 3.0 + If a socket already exists on the file system in the given path, it will be + removed first. + + """ + backlog = min(backlog, 65536) + raw_socket = await setup_unix_local_socket(path, mode, socket.SOCK_STREAM) + try: + raw_socket.listen(backlog) + return get_async_backend().create_unix_listener(raw_socket) + except BaseException: + raw_socket.close() + raise + + +async def create_udp_socket( + family: AnyIPAddressFamily = AddressFamily.AF_UNSPEC, + *, + local_host: IPAddressType | None = None, + local_port: int = 0, + reuse_port: bool = False, +) -> UDPSocket: + """ + Create a UDP socket. + + If ``port`` has been given, the socket will be bound to this port on the local + machine, making this socket suitable for providing UDP based services. + + :param family: address family (``AF_INET`` or ``AF_INET6``) – automatically + determined from ``local_host`` if omitted + :param local_host: IP address or host name of the local interface to bind to + :param local_port: local port to bind to + :param reuse_port: ``True`` to allow multiple sockets to bind to the same + address/port (not supported on Windows) + :return: a UDP socket + + """ + if family is AddressFamily.AF_UNSPEC and not local_host: + raise ValueError('Either "family" or "local_host" must be given') + + if local_host: + gai_res = await getaddrinfo( + str(local_host), + local_port, + family=family, + type=socket.SOCK_DGRAM, + flags=socket.AI_PASSIVE | socket.AI_ADDRCONFIG, + ) + family = cast(AnyIPAddressFamily, gai_res[0][0]) + local_address = gai_res[0][-1] + elif family is AddressFamily.AF_INET6: + local_address = ("::", 0) + else: + local_address = ("0.0.0.0", 0) + + sock = await get_async_backend().create_udp_socket( + family, local_address, None, reuse_port + ) + return cast(UDPSocket, sock) + + +async def create_connected_udp_socket( + remote_host: IPAddressType, + remote_port: int, + *, + family: AnyIPAddressFamily = AddressFamily.AF_UNSPEC, + local_host: IPAddressType | None = None, + local_port: int = 0, + reuse_port: bool = False, +) -> ConnectedUDPSocket: + """ + Create a connected UDP socket. + + Connected UDP sockets can only communicate with the specified remote host/port, an + any packets sent from other sources are dropped. + + :param remote_host: remote host to set as the default target + :param remote_port: port on the remote host to set as the default target + :param family: address family (``AF_INET`` or ``AF_INET6``) – automatically + determined from ``local_host`` or ``remote_host`` if omitted + :param local_host: IP address or host name of the local interface to bind to + :param local_port: local port to bind to + :param reuse_port: ``True`` to allow multiple sockets to bind to the same + address/port (not supported on Windows) + :return: a connected UDP socket + + """ + local_address = None + if local_host: + gai_res = await getaddrinfo( + str(local_host), + local_port, + family=family, + type=socket.SOCK_DGRAM, + flags=socket.AI_PASSIVE | socket.AI_ADDRCONFIG, + ) + family = cast(AnyIPAddressFamily, gai_res[0][0]) + local_address = gai_res[0][-1] + + gai_res = await getaddrinfo( + str(remote_host), remote_port, family=family, type=socket.SOCK_DGRAM + ) + family = cast(AnyIPAddressFamily, gai_res[0][0]) + remote_address = gai_res[0][-1] + + sock = await get_async_backend().create_udp_socket( + family, local_address, remote_address, reuse_port + ) + return cast(ConnectedUDPSocket, sock) + + +async def create_unix_datagram_socket( + *, + local_path: None | str | bytes | PathLike[Any] = None, + local_mode: int | None = None, +) -> UNIXDatagramSocket: + """ + Create a UNIX datagram socket. + + Not available on Windows. + + If ``local_path`` has been given, the socket will be bound to this path, making this + socket suitable for receiving datagrams from other processes. Other processes can + send datagrams to this socket only if ``local_path`` is set. + + If a socket already exists on the file system in the ``local_path``, it will be + removed first. + + :param local_path: the path on which to bind to + :param local_mode: permissions to set on the local socket + :return: a UNIX datagram socket + + """ + raw_socket = await setup_unix_local_socket( + local_path, local_mode, socket.SOCK_DGRAM + ) + return await get_async_backend().create_unix_datagram_socket(raw_socket, None) + + +async def create_connected_unix_datagram_socket( + remote_path: str | bytes | PathLike[Any], + *, + local_path: None | str | bytes | PathLike[Any] = None, + local_mode: int | None = None, +) -> ConnectedUNIXDatagramSocket: + """ + Create a connected UNIX datagram socket. + + Connected datagram sockets can only communicate with the specified remote path. + + If ``local_path`` has been given, the socket will be bound to this path, making + this socket suitable for receiving datagrams from other processes. Other processes + can send datagrams to this socket only if ``local_path`` is set. + + If a socket already exists on the file system in the ``local_path``, it will be + removed first. + + :param remote_path: the path to set as the default target + :param local_path: the path on which to bind to + :param local_mode: permissions to set on the local socket + :return: a connected UNIX datagram socket + + """ + remote_path = os.fspath(remote_path) + raw_socket = await setup_unix_local_socket( + local_path, local_mode, socket.SOCK_DGRAM + ) + return await get_async_backend().create_unix_datagram_socket( + raw_socket, remote_path + ) + + +async def getaddrinfo( + host: bytes | str | None, + port: str | int | None, + *, + family: int | AddressFamily = 0, + type: int | SocketKind = 0, + proto: int = 0, + flags: int = 0, +) -> list[tuple[AddressFamily, SocketKind, int, str, tuple[str, int]]]: + """ + Look up a numeric IP address given a host name. + + Internationalized domain names are translated according to the (non-transitional) + IDNA 2008 standard. + + .. note:: 4-tuple IPv6 socket addresses are automatically converted to 2-tuples of + (host, port), unlike what :func:`socket.getaddrinfo` does. + + :param host: host name + :param port: port number + :param family: socket family (`'AF_INET``, ...) + :param type: socket type (``SOCK_STREAM``, ...) + :param proto: protocol number + :param flags: flags to pass to upstream ``getaddrinfo()`` + :return: list of tuples containing (family, type, proto, canonname, sockaddr) + + .. seealso:: :func:`socket.getaddrinfo` + + """ + # Handle unicode hostnames + if isinstance(host, str): + try: + encoded_host: bytes | None = host.encode("ascii") + except UnicodeEncodeError: + import idna + + encoded_host = idna.encode(host, uts46=True) + else: + encoded_host = host + + gai_res = await get_async_backend().getaddrinfo( + encoded_host, port, family=family, type=type, proto=proto, flags=flags + ) + return [ + (family, type, proto, canonname, convert_ipv6_sockaddr(sockaddr)) + for family, type, proto, canonname, sockaddr in gai_res + # filter out IPv6 results when IPv6 is disabled + if not isinstance(sockaddr[0], int) + ] + + +def getnameinfo(sockaddr: IPSockAddrType, flags: int = 0) -> Awaitable[tuple[str, str]]: + """ + Look up the host name of an IP address. + + :param sockaddr: socket address (e.g. (ipaddress, port) for IPv4) + :param flags: flags to pass to upstream ``getnameinfo()`` + :return: a tuple of (host name, service name) + :raises NoEventLoopError: if no supported asynchronous event loop is running in the + current thread + + .. seealso:: :func:`socket.getnameinfo` + + """ + return get_async_backend().getnameinfo(sockaddr, flags) + + +@deprecated("This function is deprecated; use `wait_readable` instead") +def wait_socket_readable(sock: socket.socket) -> Awaitable[None]: + """ + .. deprecated:: 4.7.0 + Use :func:`wait_readable` instead. + + Wait until the given socket has data to be read. + + .. warning:: Only use this on raw sockets that have not been wrapped by any higher + level constructs like socket streams! + + :param sock: a socket object + :raises ~anyio.ClosedResourceError: if the socket was closed while waiting for the + socket to become readable + :raises ~anyio.BusyResourceError: if another task is already waiting for the socket + to become readable + :raises NoEventLoopError: if no supported asynchronous event loop is running in the + current thread + + """ + return get_async_backend().wait_readable(sock.fileno()) + + +@deprecated("This function is deprecated; use `wait_writable` instead") +def wait_socket_writable(sock: socket.socket) -> Awaitable[None]: + """ + .. deprecated:: 4.7.0 + Use :func:`wait_writable` instead. + + Wait until the given socket can be written to. + + This does **NOT** work on Windows when using the asyncio backend with a proactor + event loop (default on py3.8+). + + .. warning:: Only use this on raw sockets that have not been wrapped by any higher + level constructs like socket streams! + + :param sock: a socket object + :raises ~anyio.ClosedResourceError: if the socket was closed while waiting for the + socket to become writable + :raises ~anyio.BusyResourceError: if another task is already waiting for the socket + to become writable + :raises NoEventLoopError: if no supported asynchronous event loop is running in the + current thread + + """ + return get_async_backend().wait_writable(sock.fileno()) + + +def wait_readable(obj: FileDescriptorLike) -> Awaitable[None]: + """ + Wait until the given object has data to be read. + + On Unix systems, ``obj`` must either be an integer file descriptor, or else an + object with a ``.fileno()`` method which returns an integer file descriptor. Any + kind of file descriptor can be passed, though the exact semantics will depend on + your kernel. For example, this probably won't do anything useful for on-disk files. + + On Windows systems, ``obj`` must either be an integer ``SOCKET`` handle, or else an + object with a ``.fileno()`` method which returns an integer ``SOCKET`` handle. File + descriptors aren't supported, and neither are handles that refer to anything besides + a ``SOCKET``. + + On backends where this functionality is not natively provided (asyncio + ``ProactorEventLoop`` on Windows), it is provided using a separate selector thread + which is set to shut down when the interpreter shuts down. + + .. warning:: Don't use this on raw sockets that have been wrapped by any higher + level constructs like socket streams! + + :param obj: an object with a ``.fileno()`` method or an integer handle + :raises ~anyio.ClosedResourceError: if the object was closed while waiting for the + object to become readable + :raises ~anyio.BusyResourceError: if another task is already waiting for the object + to become readable + :raises NoEventLoopError: if no supported asynchronous event loop is running in the + current thread + + """ + return get_async_backend().wait_readable(obj) + + +def wait_writable(obj: FileDescriptorLike) -> Awaitable[None]: + """ + Wait until the given object can be written to. + + :param obj: an object with a ``.fileno()`` method or an integer handle + :raises ~anyio.ClosedResourceError: if the object was closed while waiting for the + object to become writable + :raises ~anyio.BusyResourceError: if another task is already waiting for the object + to become writable + :raises NoEventLoopError: if no supported asynchronous event loop is running in the + current thread + + .. seealso:: See the documentation of :func:`wait_readable` for the definition of + ``obj`` and notes on backend compatibility. + + .. warning:: Don't use this on raw sockets that have been wrapped by any higher + level constructs like socket streams! + + """ + return get_async_backend().wait_writable(obj) + + +def notify_closing(obj: FileDescriptorLike) -> None: + """ + Call this before closing a file descriptor (on Unix) or socket (on + Windows). This will cause any `wait_readable` or `wait_writable` + calls on the given object to immediately wake up and raise + `~anyio.ClosedResourceError`. + + This doesn't actually close the object – you still have to do that + yourself afterwards. Also, you want to be careful to make sure no + new tasks start waiting on the object in between when you call this + and when it's actually closed. So to close something properly, you + usually want to do these steps in order: + + 1. Explicitly mark the object as closed, so that any new attempts + to use it will abort before they start. + 2. Call `notify_closing` to wake up any already-existing users. + 3. Actually close the object. + + It's also possible to do them in a different order if that's more + convenient, *but only if* you make sure not to have any checkpoints in + between the steps. This way they all happen in a single atomic + step, so other tasks won't be able to tell what order they happened + in anyway. + + :param obj: an object with a ``.fileno()`` method or an integer handle + :raises NoEventLoopError: if no supported asynchronous event loop is running in the + current thread + + """ + get_async_backend().notify_closing(obj) + + +# +# Private API +# + + +def convert_ipv6_sockaddr( + sockaddr: tuple[str, int, int, int] | tuple[str, int], +) -> tuple[str, int]: + """ + Convert a 4-tuple IPv6 socket address to a 2-tuple (address, port) format. + + If the scope ID is nonzero, it is added to the address, separated with ``%``. + Otherwise the flow id and scope id are simply cut off from the tuple. + Any other kinds of socket addresses are returned as-is. + + :param sockaddr: the result of :meth:`~socket.socket.getsockname` + :return: the converted socket address + + """ + # This is more complicated than it should be because of MyPy + if isinstance(sockaddr, tuple) and len(sockaddr) == 4: + host, port, flowinfo, scope_id = sockaddr + if scope_id: + # PyPy (as of v7.3.11) leaves the interface name in the result, so + # we discard it and only get the scope ID from the end + # (https://foss.heptapod.net/pypy/pypy/-/issues/3938) + host = host.split("%")[0] + + # Add scope_id to the address + return f"{host}%{scope_id}", port + else: + return host, port + else: + return sockaddr + + +async def setup_unix_local_socket( + path: None | str | bytes | PathLike[Any], + mode: int | None, + socktype: int, +) -> socket.socket: + """ + Create a UNIX local socket object, deleting the socket at the given path if it + exists. + + Not available on Windows. + + :param path: path of the socket + :param mode: permissions to set on the socket + :param socktype: socket.SOCK_STREAM or socket.SOCK_DGRAM + + """ + path_str: str | None + if path is not None: + path_str = os.fsdecode(path) + + # Linux abstract namespace sockets aren't backed by a concrete file so skip stat call + if not path_str.startswith("\0"): + # Copied from pathlib... + try: + stat_result = os.stat(path) + except OSError as e: + if e.errno not in ( + errno.ENOENT, + errno.ENOTDIR, + errno.EBADF, + errno.ELOOP, + ): + raise + else: + if stat.S_ISSOCK(stat_result.st_mode): + os.unlink(path) + else: + path_str = None + + raw_socket = socket.socket(socket.AF_UNIX, socktype) + raw_socket.setblocking(False) + + if path_str is not None: + try: + await to_thread.run_sync(raw_socket.bind, path_str, abandon_on_cancel=True) + if mode is not None: + await to_thread.run_sync(chmod, path_str, mode, abandon_on_cancel=True) + except BaseException: + raw_socket.close() + raise + + return raw_socket + + +@dataclass +class TCPConnectable(ByteStreamConnectable): + """ + Connects to a TCP server at the given host and port. + + :param host: host name or IP address of the server + :param port: TCP port number of the server + """ + + host: str | IPv4Address | IPv6Address + port: int + + def __post_init__(self) -> None: + if self.port < 1 or self.port > 65535: + raise ValueError("TCP port number out of range") + + @override + async def connect(self) -> SocketStream: + try: + return await connect_tcp(self.host, self.port) + except OSError as exc: + raise ConnectionFailed( + f"error connecting to {self.host}:{self.port}: {exc}" + ) from exc + + +@dataclass +class UNIXConnectable(ByteStreamConnectable): + """ + Connects to a UNIX domain socket at the given path. + + :param path: the file system path of the socket + """ + + path: str | bytes | PathLike[str] | PathLike[bytes] + + @override + async def connect(self) -> UNIXSocketStream: + try: + return await connect_unix(self.path) + except OSError as exc: + raise ConnectionFailed(f"error connecting to {self.path!r}: {exc}") from exc + + +def as_connectable( + remote: ByteStreamConnectable + | tuple[str | IPv4Address | IPv6Address, int] + | str + | bytes + | PathLike[str], + /, + *, + tls: bool = False, + ssl_context: ssl.SSLContext | None = None, + tls_hostname: str | None = None, + tls_standard_compatible: bool = True, +) -> ByteStreamConnectable: + """ + Return a byte stream connectable from the given object. + + If a bytestream connectable is given, it is returned unchanged. + If a tuple of (host, port) is given, a TCP connectable is returned. + If a string or bytes path is given, a UNIX connectable is returned. + + If ``tls=True``, the connectable will be wrapped in a + :class:`~.streams.tls.TLSConnectable`. + + :param remote: a connectable, a tuple of (host, port) or a path to a UNIX socket + :param tls: if ``True``, wrap the plaintext connectable in a + :class:`~.streams.tls.TLSConnectable`, using the provided TLS settings) + :param ssl_context: if ``tls=True``, the SSLContext object to use (if not provided, + a secure default will be created) + :param tls_hostname: if ``tls=True``, host name of the server to use for checking + the server certificate (defaults to the host portion of the address for TCP + connectables) + :param tls_standard_compatible: if ``False`` and ``tls=True``, makes the TLS stream + skip the closing handshake when closing the connection, so it won't raise an + exception if the server does the same + + """ + connectable: TCPConnectable | UNIXConnectable | TLSConnectable + if isinstance(remote, ByteStreamConnectable): + return remote + elif isinstance(remote, tuple) and len(remote) == 2: + connectable = TCPConnectable(*remote) + elif isinstance(remote, (str, bytes, PathLike)): + connectable = UNIXConnectable(remote) + else: + raise TypeError(f"cannot convert {remote!r} to a connectable") + + if tls: + if not tls_hostname and isinstance(connectable, TCPConnectable): + tls_hostname = str(connectable.host) + + connectable = TLSConnectable( + connectable, + ssl_context=ssl_context, + hostname=tls_hostname, + standard_compatible=tls_standard_compatible, + ) + + return connectable diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/anyio/_core/_streams.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/anyio/_core/_streams.py new file mode 100644 index 0000000000000000000000000000000000000000..2b9c7df200f9520357503c754bcdea1c047bdda3 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/anyio/_core/_streams.py @@ -0,0 +1,52 @@ +from __future__ import annotations + +import math +from typing import TypeVar +from warnings import warn + +from ..streams.memory import ( + MemoryObjectReceiveStream, + MemoryObjectSendStream, + _MemoryObjectStreamState, +) + +T_Item = TypeVar("T_Item") + + +class create_memory_object_stream( + tuple[MemoryObjectSendStream[T_Item], MemoryObjectReceiveStream[T_Item]], +): + """ + Create a memory object stream. + + The stream's item type can be annotated like + :func:`create_memory_object_stream[T_Item]`. + + :param max_buffer_size: number of items held in the buffer until ``send()`` starts + blocking + :param item_type: old way of marking the streams with the right generic type for + static typing (does nothing on AnyIO 4) + + .. deprecated:: 4.0 + Use ``create_memory_object_stream[YourItemType](...)`` instead. + :return: a tuple of (send stream, receive stream) + + """ + + def __new__( # type: ignore[misc] + cls, max_buffer_size: float = 0, item_type: object = None + ) -> tuple[MemoryObjectSendStream[T_Item], MemoryObjectReceiveStream[T_Item]]: + if max_buffer_size != math.inf and not isinstance(max_buffer_size, int): + raise ValueError("max_buffer_size must be either an integer or math.inf") + if max_buffer_size < 0: + raise ValueError("max_buffer_size cannot be negative") + if item_type is not None: + warn( + "The item_type argument has been deprecated in AnyIO 4.0. " + "Use create_memory_object_stream[YourItemType](...) instead.", + DeprecationWarning, + stacklevel=2, + ) + + state = _MemoryObjectStreamState[T_Item](max_buffer_size) + return (MemoryObjectSendStream(state), MemoryObjectReceiveStream(state)) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/anyio/_core/_subprocesses.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/anyio/_core/_subprocesses.py new file mode 100644 index 0000000000000000000000000000000000000000..9796f8bb99403616fcb0b764a0f8283792599e45 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/anyio/_core/_subprocesses.py @@ -0,0 +1,196 @@ +from __future__ import annotations + +from collections.abc import AsyncIterable, Iterable, Mapping, Sequence +from io import BytesIO +from os import PathLike +from subprocess import PIPE, CalledProcessError, CompletedProcess +from typing import IO, Any, TypeAlias, cast + +from ..abc import Process +from ._eventloop import get_async_backend +from ._tasks import create_task_group + +StrOrBytesPath: TypeAlias = str | bytes | PathLike[str] | PathLike[bytes] + + +async def run_process( + command: StrOrBytesPath | Sequence[StrOrBytesPath], + *, + input: bytes | None = None, + stdin: int | IO[Any] | None = None, + stdout: int | IO[Any] | None = PIPE, + stderr: int | IO[Any] | None = PIPE, + check: bool = True, + cwd: StrOrBytesPath | None = None, + env: Mapping[str, str] | None = None, + startupinfo: Any = None, + creationflags: int = 0, + start_new_session: bool = False, + pass_fds: Sequence[int] = (), + user: str | int | None = None, + group: str | int | None = None, + extra_groups: Iterable[str | int] | None = None, + umask: int = -1, +) -> CompletedProcess[bytes]: + """ + Run an external command in a subprocess and wait until it completes. + + .. seealso:: :func:`subprocess.run` + + :param command: either a string to pass to the shell, or an iterable of strings + containing the executable name or path and its arguments + :param input: bytes passed to the standard input of the subprocess + :param stdin: one of :data:`subprocess.PIPE`, :data:`subprocess.DEVNULL`, + a file-like object, or `None`; ``input`` overrides this + :param stdout: one of :data:`subprocess.PIPE`, :data:`subprocess.DEVNULL`, + a file-like object, or `None` + :param stderr: one of :data:`subprocess.PIPE`, :data:`subprocess.DEVNULL`, + :data:`subprocess.STDOUT`, a file-like object, or `None` + :param check: if ``True``, raise :exc:`~subprocess.CalledProcessError` if the + process terminates with a return code other than 0 + :param cwd: If not ``None``, change the working directory to this before running the + command + :param env: if not ``None``, this mapping replaces the inherited environment + variables from the parent process + :param startupinfo: an instance of :class:`subprocess.STARTUPINFO` that can be used + to specify process startup parameters (Windows only) + :param creationflags: flags that can be used to control the creation of the + subprocess (see :class:`subprocess.Popen` for the specifics) + :param start_new_session: if ``true`` the setsid() system call will be made in the + child process prior to the execution of the subprocess. (POSIX only) + :param pass_fds: sequence of file descriptors to keep open between the parent and + child processes. (POSIX only) + :param user: effective user to run the process as (Python >= 3.9, POSIX only) + :param group: effective group to run the process as (Python >= 3.9, POSIX only) + :param extra_groups: supplementary groups to set in the subprocess (Python >= 3.9, + POSIX only) + :param umask: if not negative, this umask is applied in the child process before + running the given command (Python >= 3.9, POSIX only) + :return: an object representing the completed process + :raises ~subprocess.CalledProcessError: if ``check`` is ``True`` and the process + exits with a nonzero return code + + """ + + async def drain_stream(stream: AsyncIterable[bytes], index: int) -> None: + buffer = BytesIO() + async for chunk in stream: + buffer.write(chunk) + + stream_contents[index] = buffer.getvalue() + + if stdin is not None and input is not None: + raise ValueError("only one of stdin and input is allowed") + + async with await open_process( + command, + stdin=PIPE if input else stdin, + stdout=stdout, + stderr=stderr, + cwd=cwd, + env=env, + startupinfo=startupinfo, + creationflags=creationflags, + start_new_session=start_new_session, + pass_fds=pass_fds, + user=user, + group=group, + extra_groups=extra_groups, + umask=umask, + ) as process: + stream_contents: list[bytes | None] = [None, None] + async with create_task_group() as tg: + if process.stdout: + tg.start_soon(drain_stream, process.stdout, 0) + + if process.stderr: + tg.start_soon(drain_stream, process.stderr, 1) + + if process.stdin and input: + await process.stdin.send(input) + await process.stdin.aclose() + + await process.wait() + + output, errors = stream_contents + if check and process.returncode != 0: + raise CalledProcessError(cast(int, process.returncode), command, output, errors) + + return CompletedProcess(command, cast(int, process.returncode), output, errors) + + +async def open_process( + command: StrOrBytesPath | Sequence[StrOrBytesPath], + *, + stdin: int | IO[Any] | None = PIPE, + stdout: int | IO[Any] | None = PIPE, + stderr: int | IO[Any] | None = PIPE, + cwd: StrOrBytesPath | None = None, + env: Mapping[str, str] | None = None, + startupinfo: Any = None, + creationflags: int = 0, + start_new_session: bool = False, + pass_fds: Sequence[int] = (), + user: str | int | None = None, + group: str | int | None = None, + extra_groups: Iterable[str | int] | None = None, + umask: int = -1, +) -> Process: + """ + Start an external command in a subprocess. + + .. seealso:: :class:`subprocess.Popen` + + :param command: either a string to pass to the shell, or an iterable of strings + containing the executable name or path and its arguments + :param stdin: one of :data:`subprocess.PIPE`, :data:`subprocess.DEVNULL`, a + file-like object, or ``None`` + :param stdout: one of :data:`subprocess.PIPE`, :data:`subprocess.DEVNULL`, + a file-like object, or ``None`` + :param stderr: one of :data:`subprocess.PIPE`, :data:`subprocess.DEVNULL`, + :data:`subprocess.STDOUT`, a file-like object, or ``None`` + :param cwd: If not ``None``, the working directory is changed before executing + :param env: If env is not ``None``, it must be a mapping that defines the + environment variables for the new process + :param creationflags: flags that can be used to control the creation of the + subprocess (see :class:`subprocess.Popen` for the specifics) + :param startupinfo: an instance of :class:`subprocess.STARTUPINFO` that can be used + to specify process startup parameters (Windows only) + :param start_new_session: if ``true`` the setsid() system call will be made in the + child process prior to the execution of the subprocess. (POSIX only) + :param pass_fds: sequence of file descriptors to keep open between the parent and + child processes. (POSIX only) + :param user: effective user to run the process as (POSIX only) + :param group: effective group to run the process as (POSIX only) + :param extra_groups: supplementary groups to set in the subprocess (POSIX only) + :param umask: if not negative, this umask is applied in the child process before + running the given command (POSIX only) + :return: an asynchronous process object + + """ + kwargs: dict[str, Any] = {} + if user is not None: + kwargs["user"] = user + + if group is not None: + kwargs["group"] = group + + if extra_groups is not None: + kwargs["extra_groups"] = group + + if umask >= 0: + kwargs["umask"] = umask + + return await get_async_backend().open_process( + command, + stdin=stdin, + stdout=stdout, + stderr=stderr, + cwd=cwd, + env=env, + startupinfo=startupinfo, + creationflags=creationflags, + start_new_session=start_new_session, + pass_fds=pass_fds, + **kwargs, + ) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/anyio/_core/_synchronization.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/anyio/_core/_synchronization.py new file mode 100644 index 0000000000000000000000000000000000000000..9c6f9a07287044dae830a48735a66ef2b0dd9b0b --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/anyio/_core/_synchronization.py @@ -0,0 +1,757 @@ +from __future__ import annotations + +import math +from collections import deque +from collections.abc import Callable +from dataclasses import dataclass +from types import TracebackType +from typing import TypeVar + +from ..lowlevel import checkpoint_if_cancelled +from ._eventloop import get_async_backend +from ._exceptions import BusyResourceError, NoEventLoopError +from ._tasks import CancelScope +from ._testing import TaskInfo, get_current_task + +T = TypeVar("T") + + +@dataclass(frozen=True) +class EventStatistics: + """ + :ivar int tasks_waiting: number of tasks waiting on :meth:`~.Event.wait` + """ + + tasks_waiting: int + + +@dataclass(frozen=True) +class CapacityLimiterStatistics: + """ + :ivar int borrowed_tokens: number of tokens currently borrowed by tasks + :ivar float total_tokens: total number of available tokens + :ivar tuple borrowers: tasks or other objects currently holding tokens borrowed from + this limiter + :ivar int tasks_waiting: number of tasks waiting on + :meth:`~.CapacityLimiter.acquire` or + :meth:`~.CapacityLimiter.acquire_on_behalf_of` + """ + + borrowed_tokens: int + total_tokens: float + borrowers: tuple[object, ...] + tasks_waiting: int + + +@dataclass(frozen=True) +class LockStatistics: + """ + :ivar bool locked: flag indicating if this lock is locked or not + :ivar ~anyio.TaskInfo owner: task currently holding the lock (or ``None`` if the + lock is not held by any task) + :ivar int tasks_waiting: number of tasks waiting on :meth:`~.Lock.acquire` + """ + + locked: bool + owner: TaskInfo | None + tasks_waiting: int + + +@dataclass(frozen=True) +class ConditionStatistics: + """ + :ivar int tasks_waiting: number of tasks blocked on :meth:`~.Condition.wait` + :ivar ~anyio.LockStatistics lock_statistics: statistics of the underlying + :class:`~.Lock` + """ + + tasks_waiting: int + lock_statistics: LockStatistics + + +@dataclass(frozen=True) +class SemaphoreStatistics: + """ + :ivar int tasks_waiting: number of tasks waiting on :meth:`~.Semaphore.acquire` + + """ + + tasks_waiting: int + + +class Event: + def __new__(cls) -> Event: + try: + return get_async_backend().create_event() + except NoEventLoopError: + return EventAdapter() + + def set(self) -> None: + """Set the flag, notifying all listeners.""" + raise NotImplementedError + + def is_set(self) -> bool: + """Return ``True`` if the flag is set, ``False`` if not.""" + raise NotImplementedError + + async def wait(self) -> None: + """ + Wait until the flag has been set. + + If the flag has already been set when this method is called, it returns + immediately. + + """ + raise NotImplementedError + + def statistics(self) -> EventStatistics: + """Return statistics about the current state of this event.""" + raise NotImplementedError + + +class EventAdapter(Event): + _internal_event: Event | None = None + _is_set: bool = False + + def __new__(cls) -> EventAdapter: + return object.__new__(cls) + + @property + def _event(self) -> Event: + if self._internal_event is None: + self._internal_event = get_async_backend().create_event() + if self._is_set: + self._internal_event.set() + + return self._internal_event + + def set(self) -> None: + if self._internal_event is None: + self._is_set = True + else: + self._event.set() + + def is_set(self) -> bool: + if self._internal_event is None: + return self._is_set + + return self._internal_event.is_set() + + async def wait(self) -> None: + await self._event.wait() + + def statistics(self) -> EventStatistics: + if self._internal_event is None: + return EventStatistics(tasks_waiting=0) + + return self._internal_event.statistics() + + +class Lock: + def __new__(cls, *, fast_acquire: bool = False) -> Lock: + try: + return get_async_backend().create_lock(fast_acquire=fast_acquire) + except NoEventLoopError: + return LockAdapter(fast_acquire=fast_acquire) + + async def __aenter__(self) -> None: + await self.acquire() + + async def __aexit__( + self, + exc_type: type[BaseException] | None, + exc_val: BaseException | None, + exc_tb: TracebackType | None, + ) -> None: + self.release() + + async def acquire(self) -> None: + """Acquire the lock.""" + raise NotImplementedError + + def acquire_nowait(self) -> None: + """ + Acquire the lock, without blocking. + + :raises ~anyio.WouldBlock: if the operation would block + + """ + raise NotImplementedError + + def release(self) -> None: + """Release the lock.""" + raise NotImplementedError + + def locked(self) -> bool: + """Return True if the lock is currently held.""" + raise NotImplementedError + + def statistics(self) -> LockStatistics: + """ + Return statistics about the current state of this lock. + + .. versionadded:: 3.0 + """ + raise NotImplementedError + + +class LockAdapter(Lock): + _internal_lock: Lock | None = None + + def __new__(cls, *, fast_acquire: bool = False) -> LockAdapter: + return object.__new__(cls) + + def __init__(self, *, fast_acquire: bool = False): + self._fast_acquire = fast_acquire + + @property + def _lock(self) -> Lock: + if self._internal_lock is None: + self._internal_lock = get_async_backend().create_lock( + fast_acquire=self._fast_acquire + ) + + return self._internal_lock + + async def __aenter__(self) -> None: + await self._lock.acquire() + + async def __aexit__( + self, + exc_type: type[BaseException] | None, + exc_val: BaseException | None, + exc_tb: TracebackType | None, + ) -> None: + if self._internal_lock is not None: + self._internal_lock.release() + + async def acquire(self) -> None: + """Acquire the lock.""" + await self._lock.acquire() + + def acquire_nowait(self) -> None: + """ + Acquire the lock, without blocking. + + :raises ~anyio.WouldBlock: if the operation would block + + """ + self._lock.acquire_nowait() + + def release(self) -> None: + """Release the lock.""" + self._lock.release() + + def locked(self) -> bool: + """Return True if the lock is currently held.""" + return self._lock.locked() + + def statistics(self) -> LockStatistics: + """ + Return statistics about the current state of this lock. + + .. versionadded:: 3.0 + + """ + if self._internal_lock is None: + return LockStatistics(False, None, 0) + + return self._internal_lock.statistics() + + +class Condition: + _owner_task: TaskInfo | None = None + + def __init__(self, lock: Lock | None = None): + self._lock = lock or Lock() + self._waiters: deque[Event] = deque() + + async def __aenter__(self) -> None: + await self.acquire() + + async def __aexit__( + self, + exc_type: type[BaseException] | None, + exc_val: BaseException | None, + exc_tb: TracebackType | None, + ) -> None: + self.release() + + def _check_acquired(self) -> None: + if self._owner_task != get_current_task(): + raise RuntimeError("The current task is not holding the underlying lock") + + async def acquire(self) -> None: + """Acquire the underlying lock.""" + await self._lock.acquire() + self._owner_task = get_current_task() + + def acquire_nowait(self) -> None: + """ + Acquire the underlying lock, without blocking. + + :raises ~anyio.WouldBlock: if the operation would block + + """ + self._lock.acquire_nowait() + self._owner_task = get_current_task() + + def release(self) -> None: + """Release the underlying lock.""" + self._lock.release() + + def locked(self) -> bool: + """Return True if the lock is set.""" + return self._lock.locked() + + def notify(self, n: int = 1) -> None: + """Notify exactly n listeners.""" + self._check_acquired() + for _ in range(n): + try: + event = self._waiters.popleft() + except IndexError: + break + + event.set() + + def notify_all(self) -> None: + """Notify all the listeners.""" + self._check_acquired() + for event in self._waiters: + event.set() + + self._waiters.clear() + + async def wait(self) -> None: + """Wait for a notification.""" + await checkpoint_if_cancelled() + self._check_acquired() + event = Event() + self._waiters.append(event) + self.release() + try: + await event.wait() + except BaseException: + if not event.is_set(): + self._waiters.remove(event) + elif self._waiters: + # This task was notified by could not act on it, so pass + # it on to the next task + self._waiters.popleft().set() + + raise + finally: + with CancelScope(shield=True): + await self.acquire() + + async def wait_for(self, predicate: Callable[[], T]) -> T: + """ + Wait until a predicate becomes true. + + :param predicate: a callable that returns a truthy value when the condition is + met + :return: the result of the predicate + + .. versionadded:: 4.11.0 + + """ + while not (result := predicate()): + await self.wait() + + return result + + def statistics(self) -> ConditionStatistics: + """ + Return statistics about the current state of this condition. + + .. versionadded:: 3.0 + """ + return ConditionStatistics(len(self._waiters), self._lock.statistics()) + + +class Semaphore: + def __new__( + cls, + initial_value: int, + *, + max_value: int | None = None, + fast_acquire: bool = False, + ) -> Semaphore: + try: + return get_async_backend().create_semaphore( + initial_value, max_value=max_value, fast_acquire=fast_acquire + ) + except NoEventLoopError: + return SemaphoreAdapter(initial_value, max_value=max_value) + + def __init__( + self, + initial_value: int, + *, + max_value: int | None = None, + fast_acquire: bool = False, + ): + if not isinstance(initial_value, int): + raise TypeError("initial_value must be an integer") + if initial_value < 0: + raise ValueError("initial_value must be >= 0") + if max_value is not None: + if not isinstance(max_value, int): + raise TypeError("max_value must be an integer or None") + if max_value < initial_value: + raise ValueError( + "max_value must be equal to or higher than initial_value" + ) + + self._fast_acquire = fast_acquire + + async def __aenter__(self) -> Semaphore: + await self.acquire() + return self + + async def __aexit__( + self, + exc_type: type[BaseException] | None, + exc_val: BaseException | None, + exc_tb: TracebackType | None, + ) -> None: + self.release() + + async def acquire(self) -> None: + """Decrement the semaphore value, blocking if necessary.""" + raise NotImplementedError + + def acquire_nowait(self) -> None: + """ + Acquire the underlying lock, without blocking. + + :raises ~anyio.WouldBlock: if the operation would block + + """ + raise NotImplementedError + + def release(self) -> None: + """Increment the semaphore value.""" + raise NotImplementedError + + @property + def value(self) -> int: + """The current value of the semaphore.""" + raise NotImplementedError + + @property + def max_value(self) -> int | None: + """The maximum value of the semaphore.""" + raise NotImplementedError + + def statistics(self) -> SemaphoreStatistics: + """ + Return statistics about the current state of this semaphore. + + .. versionadded:: 3.0 + """ + raise NotImplementedError + + +class SemaphoreAdapter(Semaphore): + _internal_semaphore: Semaphore | None = None + + def __new__( + cls, + initial_value: int, + *, + max_value: int | None = None, + fast_acquire: bool = False, + ) -> SemaphoreAdapter: + return object.__new__(cls) + + def __init__( + self, + initial_value: int, + *, + max_value: int | None = None, + fast_acquire: bool = False, + ) -> None: + super().__init__(initial_value, max_value=max_value, fast_acquire=fast_acquire) + self._initial_value = initial_value + self._max_value = max_value + + @property + def _semaphore(self) -> Semaphore: + if self._internal_semaphore is None: + self._internal_semaphore = get_async_backend().create_semaphore( + self._initial_value, max_value=self._max_value + ) + + return self._internal_semaphore + + async def acquire(self) -> None: + await self._semaphore.acquire() + + def acquire_nowait(self) -> None: + self._semaphore.acquire_nowait() + + def release(self) -> None: + self._semaphore.release() + + @property + def value(self) -> int: + if self._internal_semaphore is None: + return self._initial_value + + return self._semaphore.value + + @property + def max_value(self) -> int | None: + return self._max_value + + def statistics(self) -> SemaphoreStatistics: + if self._internal_semaphore is None: + return SemaphoreStatistics(tasks_waiting=0) + + return self._semaphore.statistics() + + +class CapacityLimiter: + def __new__(cls, total_tokens: float) -> CapacityLimiter: + try: + return get_async_backend().create_capacity_limiter(total_tokens) + except NoEventLoopError: + return CapacityLimiterAdapter(total_tokens) + + async def __aenter__(self) -> None: + raise NotImplementedError + + async def __aexit__( + self, + exc_type: type[BaseException] | None, + exc_val: BaseException | None, + exc_tb: TracebackType | None, + ) -> None: + raise NotImplementedError + + @property + def total_tokens(self) -> float: + """ + The total number of tokens available for borrowing. + + This is a read-write property. If the total number of tokens is increased, the + proportionate number of tasks waiting on this limiter will be granted their + tokens. + + .. versionchanged:: 3.0 + The property is now writable. + .. versionchanged:: 4.12 + The value can now be set to 0. + + """ + raise NotImplementedError + + @total_tokens.setter + def total_tokens(self, value: float) -> None: + raise NotImplementedError + + @property + def borrowed_tokens(self) -> int: + """The number of tokens that have currently been borrowed.""" + raise NotImplementedError + + @property + def available_tokens(self) -> float: + """The number of tokens currently available to be borrowed""" + raise NotImplementedError + + def acquire_nowait(self) -> None: + """ + Acquire a token for the current task without waiting for one to become + available. + + :raises ~anyio.WouldBlock: if there are no tokens available for borrowing + + """ + raise NotImplementedError + + def acquire_on_behalf_of_nowait(self, borrower: object) -> None: + """ + Acquire a token without waiting for one to become available. + + :param borrower: the entity borrowing a token + :raises ~anyio.WouldBlock: if there are no tokens available for borrowing + + """ + raise NotImplementedError + + async def acquire(self) -> None: + """ + Acquire a token for the current task, waiting if necessary for one to become + available. + + """ + raise NotImplementedError + + async def acquire_on_behalf_of(self, borrower: object) -> None: + """ + Acquire a token, waiting if necessary for one to become available. + + :param borrower: the entity borrowing a token + + """ + raise NotImplementedError + + def release(self) -> None: + """ + Release the token held by the current task. + + :raises RuntimeError: if the current task has not borrowed a token from this + limiter. + + """ + raise NotImplementedError + + def release_on_behalf_of(self, borrower: object) -> None: + """ + Release the token held by the given borrower. + + :raises RuntimeError: if the borrower has not borrowed a token from this + limiter. + + """ + raise NotImplementedError + + def statistics(self) -> CapacityLimiterStatistics: + """ + Return statistics about the current state of this limiter. + + .. versionadded:: 3.0 + + """ + raise NotImplementedError + + +class CapacityLimiterAdapter(CapacityLimiter): + _internal_limiter: CapacityLimiter | None = None + + def __new__(cls, total_tokens: float) -> CapacityLimiterAdapter: + return object.__new__(cls) + + def __init__(self, total_tokens: float) -> None: + self.total_tokens = total_tokens + + @property + def _limiter(self) -> CapacityLimiter: + if self._internal_limiter is None: + self._internal_limiter = get_async_backend().create_capacity_limiter( + self._total_tokens + ) + + return self._internal_limiter + + async def __aenter__(self) -> None: + await self._limiter.__aenter__() + + async def __aexit__( + self, + exc_type: type[BaseException] | None, + exc_val: BaseException | None, + exc_tb: TracebackType | None, + ) -> None: + return await self._limiter.__aexit__(exc_type, exc_val, exc_tb) + + @property + def total_tokens(self) -> float: + if self._internal_limiter is None: + return self._total_tokens + + return self._internal_limiter.total_tokens + + @total_tokens.setter + def total_tokens(self, value: float) -> None: + if not isinstance(value, int) and value is not math.inf: + raise TypeError("total_tokens must be an int or math.inf") + elif value < 1: + raise ValueError("total_tokens must be >= 1") + + if self._internal_limiter is None: + self._total_tokens = value + return + + self._limiter.total_tokens = value + + @property + def borrowed_tokens(self) -> int: + if self._internal_limiter is None: + return 0 + + return self._internal_limiter.borrowed_tokens + + @property + def available_tokens(self) -> float: + if self._internal_limiter is None: + return self._total_tokens + + return self._internal_limiter.available_tokens + + def acquire_nowait(self) -> None: + self._limiter.acquire_nowait() + + def acquire_on_behalf_of_nowait(self, borrower: object) -> None: + self._limiter.acquire_on_behalf_of_nowait(borrower) + + async def acquire(self) -> None: + await self._limiter.acquire() + + async def acquire_on_behalf_of(self, borrower: object) -> None: + await self._limiter.acquire_on_behalf_of(borrower) + + def release(self) -> None: + self._limiter.release() + + def release_on_behalf_of(self, borrower: object) -> None: + self._limiter.release_on_behalf_of(borrower) + + def statistics(self) -> CapacityLimiterStatistics: + if self._internal_limiter is None: + return CapacityLimiterStatistics( + borrowed_tokens=0, + total_tokens=self.total_tokens, + borrowers=(), + tasks_waiting=0, + ) + + return self._internal_limiter.statistics() + + +class ResourceGuard: + """ + A context manager for ensuring that a resource is only used by a single task at a + time. + + Entering this context manager while the previous has not exited it yet will trigger + :exc:`BusyResourceError`. + + :param action: the action to guard against (visible in the :exc:`BusyResourceError` + when triggered, e.g. "Another task is already {action} this resource") + + .. versionadded:: 4.1 + """ + + __slots__ = "action", "_guarded" + + def __init__(self, action: str = "using"): + self.action: str = action + self._guarded = False + + def __enter__(self) -> None: + if self._guarded: + raise BusyResourceError(self.action) + + self._guarded = True + + def __exit__( + self, + exc_type: type[BaseException] | None, + exc_val: BaseException | None, + exc_tb: TracebackType | None, + ) -> None: + self._guarded = False diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/anyio/_core/_tasks.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/anyio/_core/_tasks.py new file mode 100644 index 0000000000000000000000000000000000000000..0688bfe960cf9747373c93e482a64d1369befa11 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/anyio/_core/_tasks.py @@ -0,0 +1,173 @@ +from __future__ import annotations + +import math +from collections.abc import Generator +from contextlib import contextmanager +from types import TracebackType + +from ..abc._tasks import TaskGroup, TaskStatus +from ._eventloop import get_async_backend + + +class _IgnoredTaskStatus(TaskStatus[object]): + def started(self, value: object = None) -> None: + pass + + +TASK_STATUS_IGNORED = _IgnoredTaskStatus() + + +class CancelScope: + """ + Wraps a unit of work that can be made separately cancellable. + + :param deadline: The time (clock value) when this scope is cancelled automatically + :param shield: ``True`` to shield the cancel scope from external cancellation + :raises NoEventLoopError: if no supported asynchronous event loop is running in the + current thread + """ + + def __new__( + cls, *, deadline: float = math.inf, shield: bool = False + ) -> CancelScope: + return get_async_backend().create_cancel_scope(shield=shield, deadline=deadline) + + def cancel(self, reason: str | None = None) -> None: + """ + Cancel this scope immediately. + + :param reason: a message describing the reason for the cancellation + + """ + raise NotImplementedError + + @property + def deadline(self) -> float: + """ + The time (clock value) when this scope is cancelled automatically. + + Will be ``float('inf')`` if no timeout has been set. + + """ + raise NotImplementedError + + @deadline.setter + def deadline(self, value: float) -> None: + raise NotImplementedError + + @property + def cancel_called(self) -> bool: + """``True`` if :meth:`cancel` has been called.""" + raise NotImplementedError + + @property + def cancelled_caught(self) -> bool: + """ + ``True`` if this scope suppressed a cancellation exception it itself raised. + + This is typically used to check if any work was interrupted, or to see if the + scope was cancelled due to its deadline being reached. The value will, however, + only be ``True`` if the cancellation was triggered by the scope itself (and not + an outer scope). + + """ + raise NotImplementedError + + @property + def shield(self) -> bool: + """ + ``True`` if this scope is shielded from external cancellation. + + While a scope is shielded, it will not receive cancellations from outside. + + """ + raise NotImplementedError + + @shield.setter + def shield(self, value: bool) -> None: + raise NotImplementedError + + def __enter__(self) -> CancelScope: + raise NotImplementedError + + def __exit__( + self, + exc_type: type[BaseException] | None, + exc_val: BaseException | None, + exc_tb: TracebackType | None, + ) -> bool: + raise NotImplementedError + + +@contextmanager +def fail_after( + delay: float | None, shield: bool = False +) -> Generator[CancelScope, None, None]: + """ + Create a context manager which raises a :class:`TimeoutError` if does not finish in + time. + + :param delay: maximum allowed time (in seconds) before raising the exception, or + ``None`` to disable the timeout + :param shield: ``True`` to shield the cancel scope from external cancellation + :return: a context manager that yields a cancel scope + :rtype: :class:`~typing.ContextManager`\\[:class:`~anyio.CancelScope`\\] + :raises NoEventLoopError: if no supported asynchronous event loop is running in the + current thread + + """ + current_time = get_async_backend().current_time + deadline = (current_time() + delay) if delay is not None else math.inf + with get_async_backend().create_cancel_scope( + deadline=deadline, shield=shield + ) as cancel_scope: + yield cancel_scope + + if cancel_scope.cancelled_caught and current_time() >= cancel_scope.deadline: + raise TimeoutError + + +def move_on_after(delay: float | None, shield: bool = False) -> CancelScope: + """ + Create a cancel scope with a deadline that expires after the given delay. + + :param delay: maximum allowed time (in seconds) before exiting the context block, or + ``None`` to disable the timeout + :param shield: ``True`` to shield the cancel scope from external cancellation + :return: a cancel scope + :raises NoEventLoopError: if no supported asynchronous event loop is running in the + current thread + + """ + deadline = ( + (get_async_backend().current_time() + delay) if delay is not None else math.inf + ) + return get_async_backend().create_cancel_scope(deadline=deadline, shield=shield) + + +def current_effective_deadline() -> float: + """ + Return the nearest deadline among all the cancel scopes effective for the current + task. + + :return: a clock value from the event loop's internal clock (or ``float('inf')`` if + there is no deadline in effect, or ``float('-inf')`` if the current scope has + been cancelled) + :rtype: float + :raises NoEventLoopError: if no supported asynchronous event loop is running in the + current thread + + """ + return get_async_backend().current_effective_deadline() + + +def create_task_group() -> TaskGroup: + """ + Create a task group. + + :return: a task group + :raises NoEventLoopError: if no supported asynchronous event loop is running in the + current thread + + """ + return get_async_backend().create_task_group() diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/anyio/_core/_tempfile.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/anyio/_core/_tempfile.py new file mode 100644 index 0000000000000000000000000000000000000000..75a09f793744b8e60375ce2efab98307d077bc21 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/anyio/_core/_tempfile.py @@ -0,0 +1,613 @@ +from __future__ import annotations + +import os +import sys +import tempfile +from collections.abc import Iterable +from io import BytesIO, TextIOWrapper +from types import TracebackType +from typing import ( + TYPE_CHECKING, + Any, + AnyStr, + Generic, + overload, +) + +from .. import to_thread +from .._core._fileio import AsyncFile +from ..lowlevel import checkpoint_if_cancelled + +if TYPE_CHECKING: + from _typeshed import OpenBinaryMode, OpenTextMode, ReadableBuffer, WriteableBuffer + + +class TemporaryFile(Generic[AnyStr]): + """ + An asynchronous temporary file that is automatically created and cleaned up. + + This class provides an asynchronous context manager interface to a temporary file. + The file is created using Python's standard `tempfile.TemporaryFile` function in a + background thread, and is wrapped as an asynchronous file using `AsyncFile`. + + :param mode: The mode in which the file is opened. Defaults to "w+b". + :param buffering: The buffering policy (-1 means the default buffering). + :param encoding: The encoding used to decode or encode the file. Only applicable in + text mode. + :param newline: Controls how universal newlines mode works (only applicable in text + mode). + :param suffix: The suffix for the temporary file name. + :param prefix: The prefix for the temporary file name. + :param dir: The directory in which the temporary file is created. + :param errors: The error handling scheme used for encoding/decoding errors. + """ + + _async_file: AsyncFile[AnyStr] + + @overload + def __init__( + self: TemporaryFile[bytes], + mode: OpenBinaryMode = ..., + buffering: int = ..., + encoding: str | None = ..., + newline: str | None = ..., + suffix: str | None = ..., + prefix: str | None = ..., + dir: str | None = ..., + *, + errors: str | None = ..., + ): ... + @overload + def __init__( + self: TemporaryFile[str], + mode: OpenTextMode, + buffering: int = ..., + encoding: str | None = ..., + newline: str | None = ..., + suffix: str | None = ..., + prefix: str | None = ..., + dir: str | None = ..., + *, + errors: str | None = ..., + ): ... + + def __init__( + self, + mode: OpenTextMode | OpenBinaryMode = "w+b", + buffering: int = -1, + encoding: str | None = None, + newline: str | None = None, + suffix: str | None = None, + prefix: str | None = None, + dir: str | None = None, + *, + errors: str | None = None, + ) -> None: + self.mode = mode + self.buffering = buffering + self.encoding = encoding + self.newline = newline + self.suffix: str | None = suffix + self.prefix: str | None = prefix + self.dir: str | None = dir + self.errors = errors + + async def __aenter__(self) -> AsyncFile[AnyStr]: + fp = await to_thread.run_sync( + lambda: tempfile.TemporaryFile( + self.mode, + self.buffering, + self.encoding, + self.newline, + self.suffix, + self.prefix, + self.dir, + errors=self.errors, + ) + ) + self._async_file = AsyncFile(fp) + return self._async_file + + async def __aexit__( + self, + exc_type: type[BaseException] | None, + exc_value: BaseException | None, + traceback: TracebackType | None, + ) -> None: + await self._async_file.aclose() + + +class NamedTemporaryFile(Generic[AnyStr]): + """ + An asynchronous named temporary file that is automatically created and cleaned up. + + This class provides an asynchronous context manager for a temporary file with a + visible name in the file system. It uses Python's standard + :func:`~tempfile.NamedTemporaryFile` function and wraps the file object with + :class:`AsyncFile` for asynchronous operations. + + :param mode: The mode in which the file is opened. Defaults to "w+b". + :param buffering: The buffering policy (-1 means the default buffering). + :param encoding: The encoding used to decode or encode the file. Only applicable in + text mode. + :param newline: Controls how universal newlines mode works (only applicable in text + mode). + :param suffix: The suffix for the temporary file name. + :param prefix: The prefix for the temporary file name. + :param dir: The directory in which the temporary file is created. + :param delete: Whether to delete the file when it is closed. + :param errors: The error handling scheme used for encoding/decoding errors. + :param delete_on_close: (Python 3.12+) Whether to delete the file on close. + """ + + _async_file: AsyncFile[AnyStr] + + @overload + def __init__( + self: NamedTemporaryFile[bytes], + mode: OpenBinaryMode = ..., + buffering: int = ..., + encoding: str | None = ..., + newline: str | None = ..., + suffix: str | None = ..., + prefix: str | None = ..., + dir: str | None = ..., + delete: bool = ..., + *, + errors: str | None = ..., + delete_on_close: bool = ..., + ): ... + @overload + def __init__( + self: NamedTemporaryFile[str], + mode: OpenTextMode, + buffering: int = ..., + encoding: str | None = ..., + newline: str | None = ..., + suffix: str | None = ..., + prefix: str | None = ..., + dir: str | None = ..., + delete: bool = ..., + *, + errors: str | None = ..., + delete_on_close: bool = ..., + ): ... + + def __init__( + self, + mode: OpenBinaryMode | OpenTextMode = "w+b", + buffering: int = -1, + encoding: str | None = None, + newline: str | None = None, + suffix: str | None = None, + prefix: str | None = None, + dir: str | None = None, + delete: bool = True, + *, + errors: str | None = None, + delete_on_close: bool = True, + ) -> None: + self._params: dict[str, Any] = { + "mode": mode, + "buffering": buffering, + "encoding": encoding, + "newline": newline, + "suffix": suffix, + "prefix": prefix, + "dir": dir, + "delete": delete, + "errors": errors, + } + if sys.version_info >= (3, 12): + self._params["delete_on_close"] = delete_on_close + + async def __aenter__(self) -> AsyncFile[AnyStr]: + fp = await to_thread.run_sync( + lambda: tempfile.NamedTemporaryFile(**self._params) + ) + self._async_file = AsyncFile(fp) + return self._async_file + + async def __aexit__( + self, + exc_type: type[BaseException] | None, + exc_value: BaseException | None, + traceback: TracebackType | None, + ) -> None: + await self._async_file.aclose() + + +class SpooledTemporaryFile(AsyncFile[AnyStr]): + """ + An asynchronous spooled temporary file that starts in memory and is spooled to disk. + + This class provides an asynchronous interface to a spooled temporary file, much like + Python's standard :class:`~tempfile.SpooledTemporaryFile`. It supports asynchronous + write operations and provides a method to force a rollover to disk. + + :param max_size: Maximum size in bytes before the file is rolled over to disk. + :param mode: The mode in which the file is opened. Defaults to "w+b". + :param buffering: The buffering policy (-1 means the default buffering). + :param encoding: The encoding used to decode or encode the file (text mode only). + :param newline: Controls how universal newlines mode works (text mode only). + :param suffix: The suffix for the temporary file name. + :param prefix: The prefix for the temporary file name. + :param dir: The directory in which the temporary file is created. + :param errors: The error handling scheme used for encoding/decoding errors. + """ + + _rolled: bool = False + + @overload + def __init__( + self: SpooledTemporaryFile[bytes], + max_size: int = ..., + mode: OpenBinaryMode = ..., + buffering: int = ..., + encoding: str | None = ..., + newline: str | None = ..., + suffix: str | None = ..., + prefix: str | None = ..., + dir: str | None = ..., + *, + errors: str | None = ..., + ): ... + @overload + def __init__( + self: SpooledTemporaryFile[str], + max_size: int = ..., + mode: OpenTextMode = ..., + buffering: int = ..., + encoding: str | None = ..., + newline: str | None = ..., + suffix: str | None = ..., + prefix: str | None = ..., + dir: str | None = ..., + *, + errors: str | None = ..., + ): ... + + def __init__( + self, + max_size: int = 0, + mode: OpenBinaryMode | OpenTextMode = "w+b", + buffering: int = -1, + encoding: str | None = None, + newline: str | None = None, + suffix: str | None = None, + prefix: str | None = None, + dir: str | None = None, + *, + errors: str | None = None, + ) -> None: + self._tempfile_params: dict[str, Any] = { + "mode": mode, + "buffering": buffering, + "encoding": encoding, + "newline": newline, + "suffix": suffix, + "prefix": prefix, + "dir": dir, + "errors": errors, + } + self._max_size = max_size + if "b" in mode: + super().__init__(BytesIO()) # type: ignore[arg-type] + else: + super().__init__( + TextIOWrapper( # type: ignore[arg-type] + BytesIO(), + encoding=encoding, + errors=errors, + newline=newline, + write_through=True, + ) + ) + + async def aclose(self) -> None: + if not self._rolled: + self._fp.close() + return + + await super().aclose() + + async def _check(self) -> None: + if self._rolled or self._fp.tell() <= self._max_size: + return + + await self.rollover() + + async def rollover(self) -> None: + if self._rolled: + return + + self._rolled = True + buffer = self._fp + buffer.seek(0) + self._fp = await to_thread.run_sync( + lambda: tempfile.TemporaryFile(**self._tempfile_params) + ) + await self.write(buffer.read()) + buffer.close() + + @property + def closed(self) -> bool: + return self._fp.closed + + async def read(self, size: int = -1) -> AnyStr: + if not self._rolled: + await checkpoint_if_cancelled() + return self._fp.read(size) + + return await super().read(size) # type: ignore[return-value] + + async def read1(self: SpooledTemporaryFile[bytes], size: int = -1) -> bytes: + if not self._rolled: + await checkpoint_if_cancelled() + return self._fp.read1(size) + + return await super().read1(size) + + async def readline(self) -> AnyStr: + if not self._rolled: + await checkpoint_if_cancelled() + return self._fp.readline() + + return await super().readline() # type: ignore[return-value] + + async def readlines(self) -> list[AnyStr]: + if not self._rolled: + await checkpoint_if_cancelled() + return self._fp.readlines() + + return await super().readlines() # type: ignore[return-value] + + async def readinto(self: SpooledTemporaryFile[bytes], b: WriteableBuffer) -> int: + if not self._rolled: + await checkpoint_if_cancelled() + self._fp.readinto(b) + + return await super().readinto(b) + + async def readinto1(self: SpooledTemporaryFile[bytes], b: WriteableBuffer) -> int: + if not self._rolled: + await checkpoint_if_cancelled() + self._fp.readinto(b) + + return await super().readinto1(b) + + async def seek(self, offset: int, whence: int | None = os.SEEK_SET) -> int: + if not self._rolled: + await checkpoint_if_cancelled() + return self._fp.seek(offset, whence) + + return await super().seek(offset, whence) + + async def tell(self) -> int: + if not self._rolled: + await checkpoint_if_cancelled() + return self._fp.tell() + + return await super().tell() + + async def truncate(self, size: int | None = None) -> int: + if not self._rolled: + await checkpoint_if_cancelled() + return self._fp.truncate(size) + + return await super().truncate(size) + + @overload + async def write(self: SpooledTemporaryFile[bytes], b: ReadableBuffer) -> int: ... + @overload + async def write(self: SpooledTemporaryFile[str], b: str) -> int: ... + + async def write(self, b: ReadableBuffer | str) -> int: + """ + Asynchronously write data to the spooled temporary file. + + If the file has not yet been rolled over, the data is written synchronously, + and a rollover is triggered if the size exceeds the maximum size. + + :param s: The data to write. + :return: The number of bytes written. + :raises RuntimeError: If the underlying file is not initialized. + + """ + if not self._rolled: + await checkpoint_if_cancelled() + result = self._fp.write(b) + await self._check() + return result + + return await super().write(b) # type: ignore[misc] + + @overload + async def writelines( + self: SpooledTemporaryFile[bytes], lines: Iterable[ReadableBuffer] + ) -> None: ... + @overload + async def writelines( + self: SpooledTemporaryFile[str], lines: Iterable[str] + ) -> None: ... + + async def writelines(self, lines: Iterable[str] | Iterable[ReadableBuffer]) -> None: + """ + Asynchronously write a list of lines to the spooled temporary file. + + If the file has not yet been rolled over, the lines are written synchronously, + and a rollover is triggered if the size exceeds the maximum size. + + :param lines: An iterable of lines to write. + :raises RuntimeError: If the underlying file is not initialized. + + """ + if not self._rolled: + await checkpoint_if_cancelled() + result = self._fp.writelines(lines) + await self._check() + return result + + return await super().writelines(lines) # type: ignore[misc] + + +class TemporaryDirectory(Generic[AnyStr]): + """ + An asynchronous temporary directory that is created and cleaned up automatically. + + This class provides an asynchronous context manager for creating a temporary + directory. It wraps Python's standard :class:`~tempfile.TemporaryDirectory` to + perform directory creation and cleanup operations in a background thread. + + :param suffix: Suffix to be added to the temporary directory name. + :param prefix: Prefix to be added to the temporary directory name. + :param dir: The parent directory where the temporary directory is created. + :param ignore_cleanup_errors: Whether to ignore errors during cleanup + :param delete: Whether to delete the directory upon closing (Python 3.12+). + """ + + def __init__( + self, + suffix: AnyStr | None = None, + prefix: AnyStr | None = None, + dir: AnyStr | None = None, + *, + ignore_cleanup_errors: bool = False, + delete: bool = True, + ) -> None: + self.suffix: AnyStr | None = suffix + self.prefix: AnyStr | None = prefix + self.dir: AnyStr | None = dir + self.ignore_cleanup_errors = ignore_cleanup_errors + self.delete = delete + + self._tempdir: tempfile.TemporaryDirectory | None = None + + async def __aenter__(self) -> str: + params: dict[str, Any] = { + "suffix": self.suffix, + "prefix": self.prefix, + "dir": self.dir, + "ignore_cleanup_errors": self.ignore_cleanup_errors, + } + if sys.version_info >= (3, 12): + params["delete"] = self.delete + + self._tempdir = await to_thread.run_sync( + lambda: tempfile.TemporaryDirectory(**params) + ) + return await to_thread.run_sync(self._tempdir.__enter__) + + async def __aexit__( + self, + exc_type: type[BaseException] | None, + exc_value: BaseException | None, + traceback: TracebackType | None, + ) -> None: + if self._tempdir is not None: + await to_thread.run_sync( + self._tempdir.__exit__, exc_type, exc_value, traceback + ) + + async def cleanup(self) -> None: + if self._tempdir is not None: + await to_thread.run_sync(self._tempdir.cleanup) + + +@overload +async def mkstemp( + suffix: str | None = None, + prefix: str | None = None, + dir: str | None = None, + text: bool = False, +) -> tuple[int, str]: ... + + +@overload +async def mkstemp( + suffix: bytes | None = None, + prefix: bytes | None = None, + dir: bytes | None = None, + text: bool = False, +) -> tuple[int, bytes]: ... + + +async def mkstemp( + suffix: AnyStr | None = None, + prefix: AnyStr | None = None, + dir: AnyStr | None = None, + text: bool = False, +) -> tuple[int, str | bytes]: + """ + Asynchronously create a temporary file and return an OS-level handle and the file + name. + + This function wraps `tempfile.mkstemp` and executes it in a background thread. + + :param suffix: Suffix to be added to the file name. + :param prefix: Prefix to be added to the file name. + :param dir: Directory in which the temporary file is created. + :param text: Whether the file is opened in text mode. + :return: A tuple containing the file descriptor and the file name. + + """ + return await to_thread.run_sync(tempfile.mkstemp, suffix, prefix, dir, text) + + +@overload +async def mkdtemp( + suffix: str | None = None, + prefix: str | None = None, + dir: str | None = None, +) -> str: ... + + +@overload +async def mkdtemp( + suffix: bytes | None = None, + prefix: bytes | None = None, + dir: bytes | None = None, +) -> bytes: ... + + +async def mkdtemp( + suffix: AnyStr | None = None, + prefix: AnyStr | None = None, + dir: AnyStr | None = None, +) -> str | bytes: + """ + Asynchronously create a temporary directory and return its path. + + This function wraps `tempfile.mkdtemp` and executes it in a background thread. + + :param suffix: Suffix to be added to the directory name. + :param prefix: Prefix to be added to the directory name. + :param dir: Parent directory where the temporary directory is created. + :return: The path of the created temporary directory. + + """ + return await to_thread.run_sync(tempfile.mkdtemp, suffix, prefix, dir) + + +async def gettempdir() -> str: + """ + Asynchronously return the name of the directory used for temporary files. + + This function wraps `tempfile.gettempdir` and executes it in a background thread. + + :return: The path of the temporary directory as a string. + + """ + return await to_thread.run_sync(tempfile.gettempdir) + + +async def gettempdirb() -> bytes: + """ + Asynchronously return the name of the directory used for temporary files in bytes. + + This function wraps `tempfile.gettempdirb` and executes it in a background thread. + + :return: The path of the temporary directory as bytes. + + """ + return await to_thread.run_sync(tempfile.gettempdirb) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/anyio/_core/_testing.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/anyio/_core/_testing.py new file mode 100644 index 0000000000000000000000000000000000000000..369e65c068a426e99b7e8571209e80ce35b71f47 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/anyio/_core/_testing.py @@ -0,0 +1,82 @@ +from __future__ import annotations + +from collections.abc import Awaitable, Generator +from typing import Any, cast + +from ._eventloop import get_async_backend + + +class TaskInfo: + """ + Represents an asynchronous task. + + :ivar int id: the unique identifier of the task + :ivar parent_id: the identifier of the parent task, if any + :vartype parent_id: Optional[int] + :ivar str name: the description of the task (if any) + :ivar ~collections.abc.Coroutine coro: the coroutine object of the task + """ + + __slots__ = "_name", "id", "parent_id", "name", "coro" + + def __init__( + self, + id: int, + parent_id: int | None, + name: str | None, + coro: Generator[Any, Any, Any] | Awaitable[Any], + ): + func = get_current_task + self._name = f"{func.__module__}.{func.__qualname__}" + self.id: int = id + self.parent_id: int | None = parent_id + self.name: str | None = name + self.coro: Generator[Any, Any, Any] | Awaitable[Any] = coro + + def __eq__(self, other: object) -> bool: + if isinstance(other, TaskInfo): + return self.id == other.id + + return NotImplemented + + def __hash__(self) -> int: + return hash(self.id) + + def __repr__(self) -> str: + return f"{self.__class__.__name__}(id={self.id!r}, name={self.name!r})" + + def has_pending_cancellation(self) -> bool: + """ + Return ``True`` if the task has a cancellation pending, ``False`` otherwise. + + """ + return False + + +def get_current_task() -> TaskInfo: + """ + Return the current task. + + :return: a representation of the current task + :raises NoEventLoopError: if no supported asynchronous event loop is running in the + current thread + + """ + return get_async_backend().get_current_task() + + +def get_running_tasks() -> list[TaskInfo]: + """ + Return a list of running tasks in the current event loop. + + :return: a list of task info objects + :raises NoEventLoopError: if no supported asynchronous event loop is running in the + current thread + + """ + return cast("list[TaskInfo]", get_async_backend().get_running_tasks()) + + +async def wait_all_tasks_blocked() -> None: + """Wait until all other tasks are waiting for something.""" + await get_async_backend().wait_all_tasks_blocked() diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/anyio/_core/_typedattr.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/anyio/_core/_typedattr.py new file mode 100644 index 0000000000000000000000000000000000000000..f358a448cb12739fd4eda4f4859d3a24ddd1de63 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/anyio/_core/_typedattr.py @@ -0,0 +1,81 @@ +from __future__ import annotations + +from collections.abc import Callable, Mapping +from typing import Any, TypeVar, final, overload + +from ._exceptions import TypedAttributeLookupError + +T_Attr = TypeVar("T_Attr") +T_Default = TypeVar("T_Default") +undefined = object() + + +def typed_attribute() -> Any: + """Return a unique object, used to mark typed attributes.""" + return object() + + +class TypedAttributeSet: + """ + Superclass for typed attribute collections. + + Checks that every public attribute of every subclass has a type annotation. + """ + + def __init_subclass__(cls) -> None: + annotations: dict[str, Any] = getattr(cls, "__annotations__", {}) + for attrname in dir(cls): + if not attrname.startswith("_") and attrname not in annotations: + raise TypeError( + f"Attribute {attrname!r} is missing its type annotation" + ) + + super().__init_subclass__() + + +class TypedAttributeProvider: + """Base class for classes that wish to provide typed extra attributes.""" + + @property + def extra_attributes(self) -> Mapping[T_Attr, Callable[[], T_Attr]]: + """ + A mapping of the extra attributes to callables that return the corresponding + values. + + If the provider wraps another provider, the attributes from that wrapper should + also be included in the returned mapping (but the wrapper may override the + callables from the wrapped instance). + + """ + return {} + + @overload + def extra(self, attribute: T_Attr) -> T_Attr: ... + + @overload + def extra(self, attribute: T_Attr, default: T_Default) -> T_Attr | T_Default: ... + + @final + def extra(self, attribute: Any, default: object = undefined) -> object: + """ + extra(attribute, default=undefined) + + Return the value of the given typed extra attribute. + + :param attribute: the attribute (member of a :class:`~TypedAttributeSet`) to + look for + :param default: the value that should be returned if no value is found for the + attribute + :raises ~anyio.TypedAttributeLookupError: if the search failed and no default + value was given + + """ + try: + getter = self.extra_attributes[attribute] + except KeyError: + if default is undefined: + raise TypedAttributeLookupError("Attribute not found") from None + else: + return default + + return getter() diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/anyio/abc/__init__.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/anyio/abc/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..d560ce3f1fa45a7ee4a3bc8958aa59702caa9d0c --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/anyio/abc/__init__.py @@ -0,0 +1,58 @@ +from __future__ import annotations + +from ._eventloop import AsyncBackend as AsyncBackend +from ._resources import AsyncResource as AsyncResource +from ._sockets import ConnectedUDPSocket as ConnectedUDPSocket +from ._sockets import ConnectedUNIXDatagramSocket as ConnectedUNIXDatagramSocket +from ._sockets import IPAddressType as IPAddressType +from ._sockets import IPSockAddrType as IPSockAddrType +from ._sockets import SocketAttribute as SocketAttribute +from ._sockets import SocketListener as SocketListener +from ._sockets import SocketStream as SocketStream +from ._sockets import UDPPacketType as UDPPacketType +from ._sockets import UDPSocket as UDPSocket +from ._sockets import UNIXDatagramPacketType as UNIXDatagramPacketType +from ._sockets import UNIXDatagramSocket as UNIXDatagramSocket +from ._sockets import UNIXSocketStream as UNIXSocketStream +from ._streams import AnyByteReceiveStream as AnyByteReceiveStream +from ._streams import AnyByteSendStream as AnyByteSendStream +from ._streams import AnyByteStream as AnyByteStream +from ._streams import AnyByteStreamConnectable as AnyByteStreamConnectable +from ._streams import AnyUnreliableByteReceiveStream as AnyUnreliableByteReceiveStream +from ._streams import AnyUnreliableByteSendStream as AnyUnreliableByteSendStream +from ._streams import AnyUnreliableByteStream as AnyUnreliableByteStream +from ._streams import ByteReceiveStream as ByteReceiveStream +from ._streams import ByteSendStream as ByteSendStream +from ._streams import ByteStream as ByteStream +from ._streams import ByteStreamConnectable as ByteStreamConnectable +from ._streams import Listener as Listener +from ._streams import ObjectReceiveStream as ObjectReceiveStream +from ._streams import ObjectSendStream as ObjectSendStream +from ._streams import ObjectStream as ObjectStream +from ._streams import ObjectStreamConnectable as ObjectStreamConnectable +from ._streams import UnreliableObjectReceiveStream as UnreliableObjectReceiveStream +from ._streams import UnreliableObjectSendStream as UnreliableObjectSendStream +from ._streams import UnreliableObjectStream as UnreliableObjectStream +from ._subprocesses import Process as Process +from ._tasks import TaskGroup as TaskGroup +from ._tasks import TaskStatus as TaskStatus +from ._testing import TestRunner as TestRunner + +# Re-exported here, for backwards compatibility +# isort: off +from .._core._synchronization import ( + CapacityLimiter as CapacityLimiter, + Condition as Condition, + Event as Event, + Lock as Lock, + Semaphore as Semaphore, +) +from .._core._tasks import CancelScope as CancelScope +from ..from_thread import BlockingPortal as BlockingPortal + +# Re-export imports so they look like they live directly in this package +for __value in list(locals().values()): + if getattr(__value, "__module__", "").startswith("anyio.abc."): + __value.__module__ = __name__ + +del __value diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/anyio/abc/__pycache__/__init__.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/anyio/abc/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5fe000e609b1abe79136fe9ed1a27667cf3a109b Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/anyio/abc/__pycache__/__init__.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/anyio/abc/__pycache__/_eventloop.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/anyio/abc/__pycache__/_eventloop.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..19a1e04a479c1d45571964646ba7848309767c5b Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/anyio/abc/__pycache__/_eventloop.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/anyio/abc/__pycache__/_resources.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/anyio/abc/__pycache__/_resources.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..24fbc4506243706284ce5dc9bc5c3d8c4589cec2 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/anyio/abc/__pycache__/_resources.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/anyio/abc/__pycache__/_sockets.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/anyio/abc/__pycache__/_sockets.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a6349f7a6699d9ae93c3b9c4f5f8c2c1e8b303c3 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/anyio/abc/__pycache__/_sockets.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/anyio/abc/__pycache__/_streams.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/anyio/abc/__pycache__/_streams.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..90b4c045091041fda7c7b443cab1426a8a0cc374 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/anyio/abc/__pycache__/_streams.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/anyio/abc/__pycache__/_subprocesses.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/anyio/abc/__pycache__/_subprocesses.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e15c8c0fa7942771026e933877b32940af71a547 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/anyio/abc/__pycache__/_subprocesses.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/anyio/abc/__pycache__/_tasks.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/anyio/abc/__pycache__/_tasks.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a7fa156ddb5d8b1db051a4e12856a50bf611cadb Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/anyio/abc/__pycache__/_tasks.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/anyio/abc/__pycache__/_testing.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/anyio/abc/__pycache__/_testing.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..bf88ad3ddb3a86a27234b62ba4b788a5984519b4 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/anyio/abc/__pycache__/_testing.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/anyio/abc/_eventloop.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/anyio/abc/_eventloop.py new file mode 100644 index 0000000000000000000000000000000000000000..ae0628807c7e3f37527a9cd2c8e454601f8615f4 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/anyio/abc/_eventloop.py @@ -0,0 +1,409 @@ +from __future__ import annotations + +import math +import sys +from abc import ABCMeta, abstractmethod +from collections.abc import AsyncIterator, Awaitable, Callable, Sequence +from contextlib import AbstractContextManager +from os import PathLike +from signal import Signals +from socket import AddressFamily, SocketKind, socket +from typing import ( + IO, + TYPE_CHECKING, + Any, + TypeAlias, + TypeVar, + overload, +) + +if sys.version_info >= (3, 11): + from typing import TypeVarTuple, Unpack +else: + from typing_extensions import TypeVarTuple, Unpack + +if TYPE_CHECKING: + from _typeshed import FileDescriptorLike + + from .._core._synchronization import CapacityLimiter, Event, Lock, Semaphore + from .._core._tasks import CancelScope + from .._core._testing import TaskInfo + from ._sockets import ( + ConnectedUDPSocket, + ConnectedUNIXDatagramSocket, + IPSockAddrType, + SocketListener, + SocketStream, + UDPSocket, + UNIXDatagramSocket, + UNIXSocketStream, + ) + from ._subprocesses import Process + from ._tasks import TaskGroup + from ._testing import TestRunner + +T_Retval = TypeVar("T_Retval") +PosArgsT = TypeVarTuple("PosArgsT") +StrOrBytesPath: TypeAlias = str | bytes | PathLike[str] | PathLike[bytes] + + +class AsyncBackend(metaclass=ABCMeta): + @classmethod + @abstractmethod + def run( + cls, + func: Callable[[Unpack[PosArgsT]], Awaitable[T_Retval]], + args: tuple[Unpack[PosArgsT]], + kwargs: dict[str, Any], + options: dict[str, Any], + ) -> T_Retval: + """ + Run the given coroutine function in an asynchronous event loop. + + The current thread must not be already running an event loop. + + :param func: a coroutine function + :param args: positional arguments to ``func`` + :param kwargs: positional arguments to ``func`` + :param options: keyword arguments to call the backend ``run()`` implementation + with + :return: the return value of the coroutine function + """ + + @classmethod + @abstractmethod + def current_token(cls) -> object: + """ + Return an object that allows other threads to run code inside the event loop. + + :return: a token object, specific to the event loop running in the current + thread + """ + + @classmethod + @abstractmethod + def current_time(cls) -> float: + """ + Return the current value of the event loop's internal clock. + + :return: the clock value (seconds) + """ + + @classmethod + @abstractmethod + def cancelled_exception_class(cls) -> type[BaseException]: + """Return the exception class that is raised in a task if it's cancelled.""" + + @classmethod + @abstractmethod + async def checkpoint(cls) -> None: + """ + Check if the task has been cancelled, and allow rescheduling of other tasks. + + This is effectively the same as running :meth:`checkpoint_if_cancelled` and then + :meth:`cancel_shielded_checkpoint`. + """ + + @classmethod + async def checkpoint_if_cancelled(cls) -> None: + """ + Check if the current task group has been cancelled. + + This will check if the task has been cancelled, but will not allow other tasks + to be scheduled if not. + + """ + if cls.current_effective_deadline() == -math.inf: + await cls.checkpoint() + + @classmethod + async def cancel_shielded_checkpoint(cls) -> None: + """ + Allow the rescheduling of other tasks. + + This will give other tasks the opportunity to run, but without checking if the + current task group has been cancelled, unlike with :meth:`checkpoint`. + + """ + with cls.create_cancel_scope(shield=True): + await cls.sleep(0) + + @classmethod + @abstractmethod + async def sleep(cls, delay: float) -> None: + """ + Pause the current task for the specified duration. + + :param delay: the duration, in seconds + """ + + @classmethod + @abstractmethod + def create_cancel_scope( + cls, *, deadline: float = math.inf, shield: bool = False + ) -> CancelScope: + pass + + @classmethod + @abstractmethod + def current_effective_deadline(cls) -> float: + """ + Return the nearest deadline among all the cancel scopes effective for the + current task. + + :return: + - a clock value from the event loop's internal clock + - ``inf`` if there is no deadline in effect + - ``-inf`` if the current scope has been cancelled + :rtype: float + """ + + @classmethod + @abstractmethod + def create_task_group(cls) -> TaskGroup: + pass + + @classmethod + @abstractmethod + def create_event(cls) -> Event: + pass + + @classmethod + @abstractmethod + def create_lock(cls, *, fast_acquire: bool) -> Lock: + pass + + @classmethod + @abstractmethod + def create_semaphore( + cls, + initial_value: int, + *, + max_value: int | None = None, + fast_acquire: bool = False, + ) -> Semaphore: + pass + + @classmethod + @abstractmethod + def create_capacity_limiter(cls, total_tokens: float) -> CapacityLimiter: + pass + + @classmethod + @abstractmethod + async def run_sync_in_worker_thread( + cls, + func: Callable[[Unpack[PosArgsT]], T_Retval], + args: tuple[Unpack[PosArgsT]], + abandon_on_cancel: bool = False, + limiter: CapacityLimiter | None = None, + ) -> T_Retval: + pass + + @classmethod + @abstractmethod + def check_cancelled(cls) -> None: + pass + + @classmethod + @abstractmethod + def run_async_from_thread( + cls, + func: Callable[[Unpack[PosArgsT]], Awaitable[T_Retval]], + args: tuple[Unpack[PosArgsT]], + token: object, + ) -> T_Retval: + pass + + @classmethod + @abstractmethod + def run_sync_from_thread( + cls, + func: Callable[[Unpack[PosArgsT]], T_Retval], + args: tuple[Unpack[PosArgsT]], + token: object, + ) -> T_Retval: + pass + + @classmethod + @abstractmethod + async def open_process( + cls, + command: StrOrBytesPath | Sequence[StrOrBytesPath], + *, + stdin: int | IO[Any] | None, + stdout: int | IO[Any] | None, + stderr: int | IO[Any] | None, + **kwargs: Any, + ) -> Process: + pass + + @classmethod + @abstractmethod + def setup_process_pool_exit_at_shutdown(cls, workers: set[Process]) -> None: + pass + + @classmethod + @abstractmethod + async def connect_tcp( + cls, host: str, port: int, local_address: IPSockAddrType | None = None + ) -> SocketStream: + pass + + @classmethod + @abstractmethod + async def connect_unix(cls, path: str | bytes) -> UNIXSocketStream: + pass + + @classmethod + @abstractmethod + def create_tcp_listener(cls, sock: socket) -> SocketListener: + pass + + @classmethod + @abstractmethod + def create_unix_listener(cls, sock: socket) -> SocketListener: + pass + + @classmethod + @abstractmethod + async def create_udp_socket( + cls, + family: AddressFamily, + local_address: IPSockAddrType | None, + remote_address: IPSockAddrType | None, + reuse_port: bool, + ) -> UDPSocket | ConnectedUDPSocket: + pass + + @classmethod + @overload + async def create_unix_datagram_socket( + cls, raw_socket: socket, remote_path: None + ) -> UNIXDatagramSocket: ... + + @classmethod + @overload + async def create_unix_datagram_socket( + cls, raw_socket: socket, remote_path: str | bytes + ) -> ConnectedUNIXDatagramSocket: ... + + @classmethod + @abstractmethod + async def create_unix_datagram_socket( + cls, raw_socket: socket, remote_path: str | bytes | None + ) -> UNIXDatagramSocket | ConnectedUNIXDatagramSocket: + pass + + @classmethod + @abstractmethod + async def getaddrinfo( + cls, + host: bytes | str | None, + port: str | int | None, + *, + family: int | AddressFamily = 0, + type: int | SocketKind = 0, + proto: int = 0, + flags: int = 0, + ) -> Sequence[ + tuple[ + AddressFamily, + SocketKind, + int, + str, + tuple[str, int] | tuple[str, int, int, int] | tuple[int, bytes], + ] + ]: + pass + + @classmethod + @abstractmethod + async def getnameinfo( + cls, sockaddr: IPSockAddrType, flags: int = 0 + ) -> tuple[str, str]: + pass + + @classmethod + @abstractmethod + async def wait_readable(cls, obj: FileDescriptorLike) -> None: + pass + + @classmethod + @abstractmethod + async def wait_writable(cls, obj: FileDescriptorLike) -> None: + pass + + @classmethod + @abstractmethod + def notify_closing(cls, obj: FileDescriptorLike) -> None: + pass + + @classmethod + @abstractmethod + async def wrap_listener_socket(cls, sock: socket) -> SocketListener: + pass + + @classmethod + @abstractmethod + async def wrap_stream_socket(cls, sock: socket) -> SocketStream: + pass + + @classmethod + @abstractmethod + async def wrap_unix_stream_socket(cls, sock: socket) -> UNIXSocketStream: + pass + + @classmethod + @abstractmethod + async def wrap_udp_socket(cls, sock: socket) -> UDPSocket: + pass + + @classmethod + @abstractmethod + async def wrap_connected_udp_socket(cls, sock: socket) -> ConnectedUDPSocket: + pass + + @classmethod + @abstractmethod + async def wrap_unix_datagram_socket(cls, sock: socket) -> UNIXDatagramSocket: + pass + + @classmethod + @abstractmethod + async def wrap_connected_unix_datagram_socket( + cls, sock: socket + ) -> ConnectedUNIXDatagramSocket: + pass + + @classmethod + @abstractmethod + def current_default_thread_limiter(cls) -> CapacityLimiter: + pass + + @classmethod + @abstractmethod + def open_signal_receiver( + cls, *signals: Signals + ) -> AbstractContextManager[AsyncIterator[Signals]]: + pass + + @classmethod + @abstractmethod + def get_current_task(cls) -> TaskInfo: + pass + + @classmethod + @abstractmethod + def get_running_tasks(cls) -> Sequence[TaskInfo]: + pass + + @classmethod + @abstractmethod + async def wait_all_tasks_blocked(cls) -> None: + pass + + @classmethod + @abstractmethod + def create_test_runner(cls, options: dict[str, Any]) -> TestRunner: + pass diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/anyio/abc/_resources.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/anyio/abc/_resources.py new file mode 100644 index 0000000000000000000000000000000000000000..10df115a7b9f975493476da763cc1e26dbd822e5 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/anyio/abc/_resources.py @@ -0,0 +1,33 @@ +from __future__ import annotations + +from abc import ABCMeta, abstractmethod +from types import TracebackType +from typing import TypeVar + +T = TypeVar("T") + + +class AsyncResource(metaclass=ABCMeta): + """ + Abstract base class for all closeable asynchronous resources. + + Works as an asynchronous context manager which returns the instance itself on enter, + and calls :meth:`aclose` on exit. + """ + + __slots__ = () + + async def __aenter__(self: T) -> T: + return self + + async def __aexit__( + self, + exc_type: type[BaseException] | None, + exc_val: BaseException | None, + exc_tb: TracebackType | None, + ) -> None: + await self.aclose() + + @abstractmethod + async def aclose(self) -> None: + """Close the resource.""" diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/anyio/abc/_sockets.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/anyio/abc/_sockets.py new file mode 100644 index 0000000000000000000000000000000000000000..feb26bd44a240acb20fd0f2498dff5631b8e2fb3 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/anyio/abc/_sockets.py @@ -0,0 +1,399 @@ +from __future__ import annotations + +import errno +import socket +from abc import abstractmethod +from collections.abc import Callable, Collection, Mapping +from contextlib import AsyncExitStack +from io import IOBase +from ipaddress import IPv4Address, IPv6Address +from socket import AddressFamily +from typing import Any, TypeAlias, TypeVar + +from .._core._eventloop import get_async_backend +from .._core._typedattr import ( + TypedAttributeProvider, + TypedAttributeSet, + typed_attribute, +) +from ._streams import ByteStream, Listener, UnreliableObjectStream +from ._tasks import TaskGroup + +IPAddressType: TypeAlias = str | IPv4Address | IPv6Address +IPSockAddrType: TypeAlias = tuple[str, int] +SockAddrType: TypeAlias = IPSockAddrType | str +UDPPacketType: TypeAlias = tuple[bytes, IPSockAddrType] +UNIXDatagramPacketType: TypeAlias = tuple[bytes, str] +T_Retval = TypeVar("T_Retval") + + +def _validate_socket( + sock_or_fd: socket.socket | int, + sock_type: socket.SocketKind, + addr_family: socket.AddressFamily = socket.AF_UNSPEC, + *, + require_connected: bool = False, + require_bound: bool = False, +) -> socket.socket: + if isinstance(sock_or_fd, int): + try: + sock = socket.socket(fileno=sock_or_fd) + except OSError as exc: + if exc.errno == errno.ENOTSOCK: + raise ValueError( + "the file descriptor does not refer to a socket" + ) from exc + elif require_connected: + raise ValueError("the socket must be connected") from exc + elif require_bound: + raise ValueError("the socket must be bound to a local address") from exc + else: + raise + elif isinstance(sock_or_fd, socket.socket): + sock = sock_or_fd + else: + raise TypeError( + f"expected an int or socket, got {type(sock_or_fd).__qualname__} instead" + ) + + try: + if require_connected: + try: + sock.getpeername() + except OSError as exc: + raise ValueError("the socket must be connected") from exc + + if require_bound: + try: + if sock.family in (socket.AF_INET, socket.AF_INET6): + bound_addr = sock.getsockname()[1] + else: + bound_addr = sock.getsockname() + except OSError: + bound_addr = None + + if not bound_addr: + raise ValueError("the socket must be bound to a local address") + + if addr_family != socket.AF_UNSPEC and sock.family != addr_family: + raise ValueError( + f"address family mismatch: expected {addr_family.name}, got " + f"{sock.family.name}" + ) + + if sock.type != sock_type: + raise ValueError( + f"socket type mismatch: expected {sock_type.name}, got {sock.type.name}" + ) + except BaseException: + # Avoid ResourceWarning from the locally constructed socket object + if isinstance(sock_or_fd, int): + sock.detach() + + raise + + sock.setblocking(False) + return sock + + +class SocketAttribute(TypedAttributeSet): + """ + .. attribute:: family + :type: socket.AddressFamily + + the address family of the underlying socket + + .. attribute:: local_address + :type: tuple[str, int] | str + + the local address the underlying socket is connected to + + .. attribute:: local_port + :type: int + + for IP based sockets, the local port the underlying socket is bound to + + .. attribute:: raw_socket + :type: socket.socket + + the underlying stdlib socket object + + .. attribute:: remote_address + :type: tuple[str, int] | str + + the remote address the underlying socket is connected to + + .. attribute:: remote_port + :type: int + + for IP based sockets, the remote port the underlying socket is connected to + """ + + family: AddressFamily = typed_attribute() + local_address: SockAddrType = typed_attribute() + local_port: int = typed_attribute() + raw_socket: socket.socket = typed_attribute() + remote_address: SockAddrType = typed_attribute() + remote_port: int = typed_attribute() + + +class _SocketProvider(TypedAttributeProvider): + @property + def extra_attributes(self) -> Mapping[Any, Callable[[], Any]]: + from .._core._sockets import convert_ipv6_sockaddr as convert + + attributes: dict[Any, Callable[[], Any]] = { + SocketAttribute.family: lambda: self._raw_socket.family, + SocketAttribute.local_address: lambda: convert( + self._raw_socket.getsockname() + ), + SocketAttribute.raw_socket: lambda: self._raw_socket, + } + try: + peername: tuple[str, int] | None = convert(self._raw_socket.getpeername()) + except OSError: + peername = None + + # Provide the remote address for connected sockets + if peername is not None: + attributes[SocketAttribute.remote_address] = lambda: peername + + # Provide local and remote ports for IP based sockets + if self._raw_socket.family in (AddressFamily.AF_INET, AddressFamily.AF_INET6): + attributes[SocketAttribute.local_port] = lambda: ( + self._raw_socket.getsockname()[1] + ) + if peername is not None: + remote_port = peername[1] + attributes[SocketAttribute.remote_port] = lambda: remote_port + + return attributes + + @property + @abstractmethod + def _raw_socket(self) -> socket.socket: + pass + + +class SocketStream(ByteStream, _SocketProvider): + """ + Transports bytes over a socket. + + Supports all relevant extra attributes from :class:`~SocketAttribute`. + """ + + @classmethod + async def from_socket(cls, sock_or_fd: socket.socket | int) -> SocketStream: + """ + Wrap an existing socket object or file descriptor as a socket stream. + + The newly created socket wrapper takes ownership of the socket being passed in. + The existing socket must already be connected. + + :param sock_or_fd: a socket object or file descriptor + :return: a socket stream + + """ + sock = _validate_socket(sock_or_fd, socket.SOCK_STREAM, require_connected=True) + return await get_async_backend().wrap_stream_socket(sock) + + +class UNIXSocketStream(SocketStream): + @classmethod + async def from_socket(cls, sock_or_fd: socket.socket | int) -> UNIXSocketStream: + """ + Wrap an existing socket object or file descriptor as a UNIX socket stream. + + The newly created socket wrapper takes ownership of the socket being passed in. + The existing socket must already be connected. + + :param sock_or_fd: a socket object or file descriptor + :return: a UNIX socket stream + + """ + sock = _validate_socket( + sock_or_fd, socket.SOCK_STREAM, socket.AF_UNIX, require_connected=True + ) + return await get_async_backend().wrap_unix_stream_socket(sock) + + @abstractmethod + async def send_fds(self, message: bytes, fds: Collection[int | IOBase]) -> None: + """ + Send file descriptors along with a message to the peer. + + :param message: a non-empty bytestring + :param fds: a collection of files (either numeric file descriptors or open file + or socket objects) + """ + + @abstractmethod + async def receive_fds(self, msglen: int, maxfds: int) -> tuple[bytes, list[int]]: + """ + Receive file descriptors along with a message from the peer. + + :param msglen: length of the message to expect from the peer + :param maxfds: maximum number of file descriptors to expect from the peer + :return: a tuple of (message, file descriptors) + """ + + +class SocketListener(Listener[SocketStream], _SocketProvider): + """ + Listens to incoming socket connections. + + Supports all relevant extra attributes from :class:`~SocketAttribute`. + """ + + @classmethod + async def from_socket( + cls, + sock_or_fd: socket.socket | int, + ) -> SocketListener: + """ + Wrap an existing socket object or file descriptor as a socket listener. + + The newly created listener takes ownership of the socket being passed in. + + :param sock_or_fd: a socket object or file descriptor + :return: a socket listener + + """ + sock = _validate_socket(sock_or_fd, socket.SOCK_STREAM, require_bound=True) + return await get_async_backend().wrap_listener_socket(sock) + + @abstractmethod + async def accept(self) -> SocketStream: + """Accept an incoming connection.""" + + async def serve( + self, + handler: Callable[[SocketStream], Any], + task_group: TaskGroup | None = None, + ) -> None: + from .. import create_task_group + + async with AsyncExitStack() as stack: + if task_group is None: + task_group = await stack.enter_async_context(create_task_group()) + + while True: + stream = await self.accept() + task_group.start_soon(handler, stream) + + +class UDPSocket(UnreliableObjectStream[UDPPacketType], _SocketProvider): + """ + Represents an unconnected UDP socket. + + Supports all relevant extra attributes from :class:`~SocketAttribute`. + """ + + @classmethod + async def from_socket(cls, sock_or_fd: socket.socket | int) -> UDPSocket: + """ + Wrap an existing socket object or file descriptor as a UDP socket. + + The newly created socket wrapper takes ownership of the socket being passed in. + The existing socket must be bound to a local address. + + :param sock_or_fd: a socket object or file descriptor + :return: a UDP socket + + """ + sock = _validate_socket(sock_or_fd, socket.SOCK_DGRAM, require_bound=True) + return await get_async_backend().wrap_udp_socket(sock) + + async def sendto(self, data: bytes, host: str, port: int) -> None: + """ + Alias for :meth:`~.UnreliableObjectSendStream.send` ((data, (host, port))). + + """ + return await self.send((data, (host, port))) + + +class ConnectedUDPSocket(UnreliableObjectStream[bytes], _SocketProvider): + """ + Represents an connected UDP socket. + + Supports all relevant extra attributes from :class:`~SocketAttribute`. + """ + + @classmethod + async def from_socket(cls, sock_or_fd: socket.socket | int) -> ConnectedUDPSocket: + """ + Wrap an existing socket object or file descriptor as a connected UDP socket. + + The newly created socket wrapper takes ownership of the socket being passed in. + The existing socket must already be connected. + + :param sock_or_fd: a socket object or file descriptor + :return: a connected UDP socket + + """ + sock = _validate_socket( + sock_or_fd, + socket.SOCK_DGRAM, + require_connected=True, + ) + return await get_async_backend().wrap_connected_udp_socket(sock) + + +class UNIXDatagramSocket( + UnreliableObjectStream[UNIXDatagramPacketType], _SocketProvider +): + """ + Represents an unconnected Unix datagram socket. + + Supports all relevant extra attributes from :class:`~SocketAttribute`. + """ + + @classmethod + async def from_socket( + cls, + sock_or_fd: socket.socket | int, + ) -> UNIXDatagramSocket: + """ + Wrap an existing socket object or file descriptor as a UNIX datagram + socket. + + The newly created socket wrapper takes ownership of the socket being passed in. + + :param sock_or_fd: a socket object or file descriptor + :return: a UNIX datagram socket + + """ + sock = _validate_socket(sock_or_fd, socket.SOCK_DGRAM, socket.AF_UNIX) + return await get_async_backend().wrap_unix_datagram_socket(sock) + + async def sendto(self, data: bytes, path: str) -> None: + """Alias for :meth:`~.UnreliableObjectSendStream.send` ((data, path)).""" + return await self.send((data, path)) + + +class ConnectedUNIXDatagramSocket(UnreliableObjectStream[bytes], _SocketProvider): + """ + Represents a connected Unix datagram socket. + + Supports all relevant extra attributes from :class:`~SocketAttribute`. + """ + + @classmethod + async def from_socket( + cls, + sock_or_fd: socket.socket | int, + ) -> ConnectedUNIXDatagramSocket: + """ + Wrap an existing socket object or file descriptor as a connected UNIX datagram + socket. + + The newly created socket wrapper takes ownership of the socket being passed in. + The existing socket must already be connected. + + :param sock_or_fd: a socket object or file descriptor + :return: a connected UNIX datagram socket + + """ + sock = _validate_socket( + sock_or_fd, socket.SOCK_DGRAM, socket.AF_UNIX, require_connected=True + ) + return await get_async_backend().wrap_connected_unix_datagram_socket(sock) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/anyio/abc/_streams.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/anyio/abc/_streams.py new file mode 100644 index 0000000000000000000000000000000000000000..186e3f503a9a71ce96ac2087cf8bfdedc490c534 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/anyio/abc/_streams.py @@ -0,0 +1,233 @@ +from __future__ import annotations + +from abc import ABCMeta, abstractmethod +from collections.abc import Callable +from typing import Any, Generic, TypeAlias, TypeVar + +from .._core._exceptions import EndOfStream +from .._core._typedattr import TypedAttributeProvider +from ._resources import AsyncResource +from ._tasks import TaskGroup + +T_Item = TypeVar("T_Item") +T_co = TypeVar("T_co", covariant=True) +T_contra = TypeVar("T_contra", contravariant=True) + + +class UnreliableObjectReceiveStream( + Generic[T_co], AsyncResource, TypedAttributeProvider +): + """ + An interface for receiving objects. + + This interface makes no guarantees that the received messages arrive in the order in + which they were sent, or that no messages are missed. + + Asynchronously iterating over objects of this type will yield objects matching the + given type parameter. + """ + + def __aiter__(self) -> UnreliableObjectReceiveStream[T_co]: + return self + + async def __anext__(self) -> T_co: + try: + return await self.receive() + except EndOfStream: + raise StopAsyncIteration from None + + @abstractmethod + async def receive(self) -> T_co: + """ + Receive the next item. + + :raises ~anyio.ClosedResourceError: if the receive stream has been explicitly + closed + :raises ~anyio.EndOfStream: if this stream has been closed from the other end + :raises ~anyio.BrokenResourceError: if this stream has been rendered unusable + due to external causes + """ + + +class UnreliableObjectSendStream( + Generic[T_contra], AsyncResource, TypedAttributeProvider +): + """ + An interface for sending objects. + + This interface makes no guarantees that the messages sent will reach the + recipient(s) in the same order in which they were sent, or at all. + """ + + @abstractmethod + async def send(self, item: T_contra) -> None: + """ + Send an item to the peer(s). + + :param item: the item to send + :raises ~anyio.ClosedResourceError: if the send stream has been explicitly + closed + :raises ~anyio.BrokenResourceError: if this stream has been rendered unusable + due to external causes + """ + + +class UnreliableObjectStream( + UnreliableObjectReceiveStream[T_Item], UnreliableObjectSendStream[T_Item] +): + """ + A bidirectional message stream which does not guarantee the order or reliability of + message delivery. + """ + + +class ObjectReceiveStream(UnreliableObjectReceiveStream[T_co]): + """ + A receive message stream which guarantees that messages are received in the same + order in which they were sent, and that no messages are missed. + """ + + +class ObjectSendStream(UnreliableObjectSendStream[T_contra]): + """ + A send message stream which guarantees that messages are delivered in the same order + in which they were sent, without missing any messages in the middle. + """ + + +class ObjectStream( + ObjectReceiveStream[T_Item], + ObjectSendStream[T_Item], + UnreliableObjectStream[T_Item], +): + """ + A bidirectional message stream which guarantees the order and reliability of message + delivery. + """ + + @abstractmethod + async def send_eof(self) -> None: + """ + Send an end-of-file indication to the peer. + + You should not try to send any further data to this stream after calling this + method. This method is idempotent (does nothing on successive calls). + """ + + +class ByteReceiveStream(AsyncResource, TypedAttributeProvider): + """ + An interface for receiving bytes from a single peer. + + Iterating this byte stream will yield a byte string of arbitrary length, but no more + than 65536 bytes. + """ + + def __aiter__(self) -> ByteReceiveStream: + return self + + async def __anext__(self) -> bytes: + try: + return await self.receive() + except EndOfStream: + raise StopAsyncIteration from None + + @abstractmethod + async def receive(self, max_bytes: int = 65536) -> bytes: + """ + Receive at most ``max_bytes`` bytes from the peer. + + .. note:: Implementers of this interface should not return an empty + :class:`bytes` object, and users should ignore them. + + :param max_bytes: maximum number of bytes to receive + :return: the received bytes + :raises ~anyio.EndOfStream: if this stream has been closed from the other end + """ + + +class ByteSendStream(AsyncResource, TypedAttributeProvider): + """An interface for sending bytes to a single peer.""" + + @abstractmethod + async def send(self, item: bytes) -> None: + """ + Send the given bytes to the peer. + + :param item: the bytes to send + """ + + +class ByteStream(ByteReceiveStream, ByteSendStream): + """A bidirectional byte stream.""" + + @abstractmethod + async def send_eof(self) -> None: + """ + Send an end-of-file indication to the peer. + + You should not try to send any further data to this stream after calling this + method. This method is idempotent (does nothing on successive calls). + """ + + +#: Type alias for all unreliable bytes-oriented receive streams. +AnyUnreliableByteReceiveStream: TypeAlias = ( + UnreliableObjectReceiveStream[bytes] | ByteReceiveStream +) +#: Type alias for all unreliable bytes-oriented send streams. +AnyUnreliableByteSendStream: TypeAlias = ( + UnreliableObjectSendStream[bytes] | ByteSendStream +) +#: Type alias for all unreliable bytes-oriented streams. +AnyUnreliableByteStream: TypeAlias = UnreliableObjectStream[bytes] | ByteStream +#: Type alias for all bytes-oriented receive streams. +AnyByteReceiveStream: TypeAlias = ObjectReceiveStream[bytes] | ByteReceiveStream +#: Type alias for all bytes-oriented send streams. +AnyByteSendStream: TypeAlias = ObjectSendStream[bytes] | ByteSendStream +#: Type alias for all bytes-oriented streams. +AnyByteStream: TypeAlias = ObjectStream[bytes] | ByteStream + + +class Listener(Generic[T_co], AsyncResource, TypedAttributeProvider): + """An interface for objects that let you accept incoming connections.""" + + @abstractmethod + async def serve( + self, handler: Callable[[T_co], Any], task_group: TaskGroup | None = None + ) -> None: + """ + Accept incoming connections as they come in and start tasks to handle them. + + :param handler: a callable that will be used to handle each accepted connection + :param task_group: the task group that will be used to start tasks for handling + each accepted connection (if omitted, an ad-hoc task group will be created) + """ + + +class ObjectStreamConnectable(Generic[T_co], metaclass=ABCMeta): + @abstractmethod + async def connect(self) -> ObjectStream[T_co]: + """ + Connect to the remote endpoint. + + :return: an object stream connected to the remote end + :raises ConnectionFailed: if the connection fails + """ + + +class ByteStreamConnectable(metaclass=ABCMeta): + @abstractmethod + async def connect(self) -> ByteStream: + """ + Connect to the remote endpoint. + + :return: a bytestream connected to the remote end + :raises ConnectionFailed: if the connection fails + """ + + +#: Type alias for all connectables returning bytestreams or bytes-oriented object streams +AnyByteStreamConnectable: TypeAlias = ( + ObjectStreamConnectable[bytes] | ByteStreamConnectable +) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/anyio/abc/_subprocesses.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/anyio/abc/_subprocesses.py new file mode 100644 index 0000000000000000000000000000000000000000..ce0564ceac8aac425675b5c8f7f7205d08061fd3 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/anyio/abc/_subprocesses.py @@ -0,0 +1,79 @@ +from __future__ import annotations + +from abc import abstractmethod +from signal import Signals + +from ._resources import AsyncResource +from ._streams import ByteReceiveStream, ByteSendStream + + +class Process(AsyncResource): + """An asynchronous version of :class:`subprocess.Popen`.""" + + @abstractmethod + async def wait(self) -> int: + """ + Wait until the process exits. + + :return: the exit code of the process + """ + + @abstractmethod + def terminate(self) -> None: + """ + Terminates the process, gracefully if possible. + + On Windows, this calls ``TerminateProcess()``. + On POSIX systems, this sends ``SIGTERM`` to the process. + + .. seealso:: :meth:`subprocess.Popen.terminate` + """ + + @abstractmethod + def kill(self) -> None: + """ + Kills the process. + + On Windows, this calls ``TerminateProcess()``. + On POSIX systems, this sends ``SIGKILL`` to the process. + + .. seealso:: :meth:`subprocess.Popen.kill` + """ + + @abstractmethod + def send_signal(self, signal: Signals) -> None: + """ + Send a signal to the subprocess. + + .. seealso:: :meth:`subprocess.Popen.send_signal` + + :param signal: the signal number (e.g. :data:`signal.SIGHUP`) + """ + + @property + @abstractmethod + def pid(self) -> int: + """The process ID of the process.""" + + @property + @abstractmethod + def returncode(self) -> int | None: + """ + The return code of the process. If the process has not yet terminated, this will + be ``None``. + """ + + @property + @abstractmethod + def stdin(self) -> ByteSendStream | None: + """The stream for the standard input of the process.""" + + @property + @abstractmethod + def stdout(self) -> ByteReceiveStream | None: + """The stream for the standard output of the process.""" + + @property + @abstractmethod + def stderr(self) -> ByteReceiveStream | None: + """The stream for the standard error output of the process.""" diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/anyio/abc/_tasks.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/anyio/abc/_tasks.py new file mode 100644 index 0000000000000000000000000000000000000000..516b3ec3b38a4b140f5d607dd28da989f057b832 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/anyio/abc/_tasks.py @@ -0,0 +1,117 @@ +from __future__ import annotations + +import sys +from abc import ABCMeta, abstractmethod +from collections.abc import Awaitable, Callable +from types import TracebackType +from typing import TYPE_CHECKING, Any, Protocol, overload + +if sys.version_info >= (3, 13): + from typing import TypeVar +else: + from typing_extensions import TypeVar + +if sys.version_info >= (3, 11): + from typing import TypeVarTuple, Unpack +else: + from typing_extensions import TypeVarTuple, Unpack + +if TYPE_CHECKING: + from .._core._tasks import CancelScope + +T_Retval = TypeVar("T_Retval") +T_contra = TypeVar("T_contra", contravariant=True, default=None) +PosArgsT = TypeVarTuple("PosArgsT") + + +class TaskStatus(Protocol[T_contra]): + @overload + def started(self: TaskStatus[None]) -> None: ... + + @overload + def started(self, value: T_contra) -> None: ... + + def started(self, value: T_contra | None = None) -> None: + """ + Signal that the task has started. + + :param value: object passed back to the starter of the task + """ + + +class TaskGroup(metaclass=ABCMeta): + """ + Groups several asynchronous tasks together. + + :ivar cancel_scope: the cancel scope inherited by all child tasks + :vartype cancel_scope: CancelScope + + .. note:: On asyncio, support for eager task factories is considered to be + **experimental**. In particular, they don't follow the usual semantics of new + tasks being scheduled on the next iteration of the event loop, and may thus + cause unexpected behavior in code that wasn't written with such semantics in + mind. + """ + + cancel_scope: CancelScope + + @abstractmethod + def start_soon( + self, + func: Callable[[Unpack[PosArgsT]], Awaitable[Any]], + *args: Unpack[PosArgsT], + name: object = None, + ) -> None: + """ + Start a new task in this task group. + + :param func: a coroutine function + :param args: positional arguments to call the function with + :param name: name of the task, for the purposes of introspection and debugging + + .. versionadded:: 3.0 + """ + + @abstractmethod + async def start( + self, + func: Callable[..., Awaitable[Any]], + *args: object, + name: object = None, + ) -> Any: + """ + Start a new task and wait until it signals for readiness. + + The target callable must accept a keyword argument ``task_status`` (of type + :class:`TaskStatus`). Awaiting on this method will return whatever was passed to + ``task_status.started()`` (``None`` by default). + + .. note:: The :class:`TaskStatus` class is generic, and the type argument should + indicate the type of the value that will be passed to + ``task_status.started()``. + + :param func: a coroutine function that accepts the ``task_status`` keyword + argument + :param args: positional arguments to call the function with + :param name: an optional name for the task, for introspection and debugging + :return: the value passed to ``task_status.started()`` + :raises RuntimeError: if the task finishes without calling + ``task_status.started()`` + + .. seealso:: :ref:`start_initialize` + + .. versionadded:: 3.0 + """ + + @abstractmethod + async def __aenter__(self) -> TaskGroup: + """Enter the task group context and allow starting new tasks.""" + + @abstractmethod + async def __aexit__( + self, + exc_type: type[BaseException] | None, + exc_val: BaseException | None, + exc_tb: TracebackType | None, + ) -> bool: + """Exit the task group context waiting for all tasks to finish.""" diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/anyio/abc/_testing.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/anyio/abc/_testing.py new file mode 100644 index 0000000000000000000000000000000000000000..7c50ed76dc4d8df41262973a0122295523e2a935 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/anyio/abc/_testing.py @@ -0,0 +1,65 @@ +from __future__ import annotations + +import types +from abc import ABCMeta, abstractmethod +from collections.abc import AsyncGenerator, Callable, Coroutine, Iterable +from typing import Any, TypeVar + +_T = TypeVar("_T") + + +class TestRunner(metaclass=ABCMeta): + """ + Encapsulates a running event loop. Every call made through this object will use the + same event loop. + """ + + def __enter__(self) -> TestRunner: + return self + + @abstractmethod + def __exit__( + self, + exc_type: type[BaseException] | None, + exc_val: BaseException | None, + exc_tb: types.TracebackType | None, + ) -> bool | None: ... + + @abstractmethod + def run_asyncgen_fixture( + self, + fixture_func: Callable[..., AsyncGenerator[_T, Any]], + kwargs: dict[str, Any], + ) -> Iterable[_T]: + """ + Run an async generator fixture. + + :param fixture_func: the fixture function + :param kwargs: keyword arguments to call the fixture function with + :return: an iterator yielding the value yielded from the async generator + """ + + @abstractmethod + def run_fixture( + self, + fixture_func: Callable[..., Coroutine[Any, Any, _T]], + kwargs: dict[str, Any], + ) -> _T: + """ + Run an async fixture. + + :param fixture_func: the fixture function + :param kwargs: keyword arguments to call the fixture function with + :return: the return value of the fixture function + """ + + @abstractmethod + def run_test( + self, test_func: Callable[..., Coroutine[Any, Any, Any]], kwargs: dict[str, Any] + ) -> None: + """ + Run an async test function. + + :param test_func: the test function + :param kwargs: keyword arguments to call the test function with + """ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/anyio/streams/__init__.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/anyio/streams/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/anyio/streams/__pycache__/__init__.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/anyio/streams/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1c043b3975fd9568269eb7ebd6d0aba471d7ed1f Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/anyio/streams/__pycache__/__init__.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/anyio/streams/__pycache__/buffered.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/anyio/streams/__pycache__/buffered.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8bfb1fb09d2871d589371e0625d40c56d5490e94 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/anyio/streams/__pycache__/buffered.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/anyio/streams/__pycache__/file.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/anyio/streams/__pycache__/file.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..08e8de366d92e35fcfa87bcaa02fe4f2cd24b95b Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/anyio/streams/__pycache__/file.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/anyio/streams/__pycache__/memory.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/anyio/streams/__pycache__/memory.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..084f74cc9a472ed9860ed44d12faa4c4d0eccebf Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/anyio/streams/__pycache__/memory.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/anyio/streams/__pycache__/stapled.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/anyio/streams/__pycache__/stapled.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4bc45277bc08b93fcebf1c6d3321dfff966dc335 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/anyio/streams/__pycache__/stapled.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/anyio/streams/__pycache__/text.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/anyio/streams/__pycache__/text.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c23528ee2e675b8060f9b7cb00e15ad0a5abe19d Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/anyio/streams/__pycache__/text.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/anyio/streams/__pycache__/tls.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/anyio/streams/__pycache__/tls.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1672c2f8bea0186c4de0df1fa11be435e443cad3 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/anyio/streams/__pycache__/tls.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/anyio/streams/buffered.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/anyio/streams/buffered.py new file mode 100644 index 0000000000000000000000000000000000000000..57c7cd749bfb94bbe7a992aa9a05af268a841d3d --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/anyio/streams/buffered.py @@ -0,0 +1,188 @@ +from __future__ import annotations + +__all__ = ( + "BufferedByteReceiveStream", + "BufferedByteStream", + "BufferedConnectable", +) + +import sys +from collections.abc import Callable, Iterable, Mapping +from dataclasses import dataclass, field +from typing import Any, SupportsIndex + +from .. import ClosedResourceError, DelimiterNotFound, EndOfStream, IncompleteRead +from ..abc import ( + AnyByteReceiveStream, + AnyByteStream, + AnyByteStreamConnectable, + ByteReceiveStream, + ByteStream, + ByteStreamConnectable, +) + +if sys.version_info >= (3, 12): + from typing import override +else: + from typing_extensions import override + + +@dataclass(eq=False) +class BufferedByteReceiveStream(ByteReceiveStream): + """ + Wraps any bytes-based receive stream and uses a buffer to provide sophisticated + receiving capabilities in the form of a byte stream. + """ + + receive_stream: AnyByteReceiveStream + _buffer: bytearray = field(init=False, default_factory=bytearray) + _closed: bool = field(init=False, default=False) + + async def aclose(self) -> None: + await self.receive_stream.aclose() + self._closed = True + + @property + def buffer(self) -> bytes: + """The bytes currently in the buffer.""" + return bytes(self._buffer) + + @property + def extra_attributes(self) -> Mapping[Any, Callable[[], Any]]: + return self.receive_stream.extra_attributes + + def feed_data(self, data: Iterable[SupportsIndex], /) -> None: + """ + Append data directly into the buffer. + + Any data in the buffer will be consumed by receive operations before receiving + anything from the wrapped stream. + + :param data: the data to append to the buffer (can be bytes or anything else + that supports ``__index__()``) + + """ + self._buffer.extend(data) + + async def receive(self, max_bytes: int = 65536) -> bytes: + if self._closed: + raise ClosedResourceError + + if self._buffer: + chunk = bytes(self._buffer[:max_bytes]) + del self._buffer[:max_bytes] + return chunk + elif isinstance(self.receive_stream, ByteReceiveStream): + return await self.receive_stream.receive(max_bytes) + else: + # With a bytes-oriented object stream, we need to handle any surplus bytes + # we get from the receive() call + chunk = await self.receive_stream.receive() + if len(chunk) > max_bytes: + # Save the surplus bytes in the buffer + self._buffer.extend(chunk[max_bytes:]) + return chunk[:max_bytes] + else: + return chunk + + async def receive_exactly(self, nbytes: int) -> bytes: + """ + Read exactly the given amount of bytes from the stream. + + :param nbytes: the number of bytes to read + :return: the bytes read + :raises ~anyio.IncompleteRead: if the stream was closed before the requested + amount of bytes could be read from the stream + + """ + while True: + remaining = nbytes - len(self._buffer) + if remaining <= 0: + retval = self._buffer[:nbytes] + del self._buffer[:nbytes] + return bytes(retval) + + try: + if isinstance(self.receive_stream, ByteReceiveStream): + chunk = await self.receive_stream.receive(remaining) + else: + chunk = await self.receive_stream.receive() + except EndOfStream as exc: + raise IncompleteRead from exc + + self._buffer.extend(chunk) + + async def receive_until(self, delimiter: bytes, max_bytes: int) -> bytes: + """ + Read from the stream until the delimiter is found or max_bytes have been read. + + :param delimiter: the marker to look for in the stream + :param max_bytes: maximum number of bytes that will be read before raising + :exc:`~anyio.DelimiterNotFound` + :return: the bytes read (not including the delimiter) + :raises ~anyio.IncompleteRead: if the stream was closed before the delimiter + was found + :raises ~anyio.DelimiterNotFound: if the delimiter is not found within the + bytes read up to the maximum allowed + + """ + delimiter_size = len(delimiter) + offset = 0 + while True: + # Check if the delimiter can be found in the current buffer + index = self._buffer.find(delimiter, offset) + if index >= 0: + found = self._buffer[:index] + del self._buffer[: index + len(delimiter) :] + return bytes(found) + + # Check if the buffer is already at or over the limit + if len(self._buffer) >= max_bytes: + raise DelimiterNotFound(max_bytes) + + # Read more data into the buffer from the socket + try: + data = await self.receive_stream.receive() + except EndOfStream as exc: + raise IncompleteRead from exc + + # Move the offset forward and add the new data to the buffer + offset = max(len(self._buffer) - delimiter_size + 1, 0) + self._buffer.extend(data) + + +class BufferedByteStream(BufferedByteReceiveStream, ByteStream): + """ + A full-duplex variant of :class:`BufferedByteReceiveStream`. All writes are passed + through to the wrapped stream as-is. + """ + + def __init__(self, stream: AnyByteStream): + """ + :param stream: the stream to be wrapped + + """ + super().__init__(stream) + self._stream = stream + + @override + async def send_eof(self) -> None: + await self._stream.send_eof() + + @override + async def send(self, item: bytes) -> None: + await self._stream.send(item) + + +class BufferedConnectable(ByteStreamConnectable): + def __init__(self, connectable: AnyByteStreamConnectable): + """ + :param connectable: the connectable to wrap + + """ + self.connectable = connectable + + @override + async def connect(self) -> BufferedByteStream: + stream = await self.connectable.connect() + return BufferedByteStream(stream) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/anyio/streams/file.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/anyio/streams/file.py new file mode 100644 index 0000000000000000000000000000000000000000..79c3d500beae578832b7e960a76ead95c80be01e --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/anyio/streams/file.py @@ -0,0 +1,154 @@ +from __future__ import annotations + +__all__ = ( + "FileReadStream", + "FileStreamAttribute", + "FileWriteStream", +) + +from collections.abc import Callable, Mapping +from io import SEEK_SET, UnsupportedOperation +from os import PathLike +from pathlib import Path +from typing import IO, Any + +from .. import ( + BrokenResourceError, + ClosedResourceError, + EndOfStream, + TypedAttributeSet, + to_thread, + typed_attribute, +) +from ..abc import ByteReceiveStream, ByteSendStream + + +class FileStreamAttribute(TypedAttributeSet): + #: the open file descriptor + file: IO[bytes] = typed_attribute() + #: the path of the file on the file system, if available (file must be a real file) + path: Path = typed_attribute() + #: the file number, if available (file must be a real file or a TTY) + fileno: int = typed_attribute() + + +class _BaseFileStream: + def __init__(self, file: IO[bytes]): + self._file = file + + async def aclose(self) -> None: + await to_thread.run_sync(self._file.close) + + @property + def extra_attributes(self) -> Mapping[Any, Callable[[], Any]]: + attributes: dict[Any, Callable[[], Any]] = { + FileStreamAttribute.file: lambda: self._file, + } + + if hasattr(self._file, "name"): + attributes[FileStreamAttribute.path] = lambda: Path(self._file.name) + + try: + self._file.fileno() + except UnsupportedOperation: + pass + else: + attributes[FileStreamAttribute.fileno] = lambda: self._file.fileno() + + return attributes + + +class FileReadStream(_BaseFileStream, ByteReceiveStream): + """ + A byte stream that reads from a file in the file system. + + :param file: a file that has been opened for reading in binary mode + + .. versionadded:: 3.0 + """ + + @classmethod + async def from_path(cls, path: str | PathLike[str]) -> FileReadStream: + """ + Create a file read stream by opening the given file. + + :param path: path of the file to read from + + """ + file = await to_thread.run_sync(Path(path).open, "rb") + return cls(file) + + async def receive(self, max_bytes: int = 65536) -> bytes: + try: + data = await to_thread.run_sync(self._file.read, max_bytes) + except ValueError: + raise ClosedResourceError from None + except OSError as exc: + raise BrokenResourceError from exc + + if data: + return data + else: + raise EndOfStream + + async def seek(self, position: int, whence: int = SEEK_SET) -> int: + """ + Seek the file to the given position. + + .. seealso:: :meth:`io.IOBase.seek` + + .. note:: Not all file descriptors are seekable. + + :param position: position to seek the file to + :param whence: controls how ``position`` is interpreted + :return: the new absolute position + :raises OSError: if the file is not seekable + + """ + return await to_thread.run_sync(self._file.seek, position, whence) + + async def tell(self) -> int: + """ + Return the current stream position. + + .. note:: Not all file descriptors are seekable. + + :return: the current absolute position + :raises OSError: if the file is not seekable + + """ + return await to_thread.run_sync(self._file.tell) + + +class FileWriteStream(_BaseFileStream, ByteSendStream): + """ + A byte stream that writes to a file in the file system. + + :param file: a file that has been opened for writing in binary mode + + .. versionadded:: 3.0 + """ + + @classmethod + async def from_path( + cls, path: str | PathLike[str], append: bool = False + ) -> FileWriteStream: + """ + Create a file write stream by opening the given file for writing. + + :param path: path of the file to write to + :param append: if ``True``, open the file for appending; if ``False``, any + existing file at the given path will be truncated + + """ + mode = "ab" if append else "wb" + file = await to_thread.run_sync(Path(path).open, mode) + return cls(file) + + async def send(self, item: bytes) -> None: + try: + await to_thread.run_sync(self._file.write, item) + except ValueError: + raise ClosedResourceError from None + except OSError as exc: + raise BrokenResourceError from exc diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/anyio/streams/memory.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/anyio/streams/memory.py new file mode 100644 index 0000000000000000000000000000000000000000..a3fa0c3d9783f34fb5225938f6ce5d1d31b9b85c --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/anyio/streams/memory.py @@ -0,0 +1,325 @@ +from __future__ import annotations + +__all__ = ( + "MemoryObjectReceiveStream", + "MemoryObjectSendStream", + "MemoryObjectStreamStatistics", +) + +import warnings +from collections import OrderedDict, deque +from dataclasses import dataclass, field +from types import TracebackType +from typing import Generic, NamedTuple, TypeVar + +from .. import ( + BrokenResourceError, + ClosedResourceError, + EndOfStream, + WouldBlock, +) +from .._core._testing import TaskInfo, get_current_task +from ..abc import Event, ObjectReceiveStream, ObjectSendStream +from ..lowlevel import checkpoint + +T_Item = TypeVar("T_Item") +T_co = TypeVar("T_co", covariant=True) +T_contra = TypeVar("T_contra", contravariant=True) + + +class MemoryObjectStreamStatistics(NamedTuple): + current_buffer_used: int #: number of items stored in the buffer + #: maximum number of items that can be stored on this stream (or :data:`math.inf`) + max_buffer_size: float + open_send_streams: int #: number of unclosed clones of the send stream + open_receive_streams: int #: number of unclosed clones of the receive stream + #: number of tasks blocked on :meth:`MemoryObjectSendStream.send` + tasks_waiting_send: int + #: number of tasks blocked on :meth:`MemoryObjectReceiveStream.receive` + tasks_waiting_receive: int + + +@dataclass(eq=False) +class _MemoryObjectItemReceiver(Generic[T_Item]): + task_info: TaskInfo = field(init=False, default_factory=get_current_task) + item: T_Item = field(init=False) + + def __repr__(self) -> str: + # When item is not defined, we get following error with default __repr__: + # AttributeError: 'MemoryObjectItemReceiver' object has no attribute 'item' + item = getattr(self, "item", None) + return f"{self.__class__.__name__}(task_info={self.task_info}, item={item!r})" + + +@dataclass(eq=False) +class _MemoryObjectStreamState(Generic[T_Item]): + max_buffer_size: float = field() + buffer: deque[T_Item] = field(init=False, default_factory=deque) + open_send_channels: int = field(init=False, default=0) + open_receive_channels: int = field(init=False, default=0) + waiting_receivers: OrderedDict[Event, _MemoryObjectItemReceiver[T_Item]] = field( + init=False, default_factory=OrderedDict + ) + waiting_senders: OrderedDict[Event, T_Item] = field( + init=False, default_factory=OrderedDict + ) + + def statistics(self) -> MemoryObjectStreamStatistics: + return MemoryObjectStreamStatistics( + len(self.buffer), + self.max_buffer_size, + self.open_send_channels, + self.open_receive_channels, + len(self.waiting_senders), + len(self.waiting_receivers), + ) + + +@dataclass(eq=False) +class MemoryObjectReceiveStream(Generic[T_co], ObjectReceiveStream[T_co]): + _state: _MemoryObjectStreamState[T_co] + _closed: bool = field(init=False, default=False) + + def __post_init__(self) -> None: + self._state.open_receive_channels += 1 + + def receive_nowait(self) -> T_co: + """ + Receive the next item if it can be done without waiting. + + :return: the received item + :raises ~anyio.ClosedResourceError: if this send stream has been closed + :raises ~anyio.EndOfStream: if the buffer is empty and this stream has been + closed from the sending end + :raises ~anyio.WouldBlock: if there are no items in the buffer and no tasks + waiting to send + + """ + if self._closed: + raise ClosedResourceError + + if self._state.waiting_senders: + # Get the item from the next sender + send_event, item = self._state.waiting_senders.popitem(last=False) + self._state.buffer.append(item) + send_event.set() + + if self._state.buffer: + return self._state.buffer.popleft() + elif not self._state.open_send_channels: + raise EndOfStream + + raise WouldBlock + + async def receive(self) -> T_co: + await checkpoint() + try: + return self.receive_nowait() + except WouldBlock: + # Add ourselves in the queue + receive_event = Event() + receiver = _MemoryObjectItemReceiver[T_co]() + self._state.waiting_receivers[receive_event] = receiver + + try: + await receive_event.wait() + finally: + self._state.waiting_receivers.pop(receive_event, None) + + try: + return receiver.item + except AttributeError: + raise EndOfStream from None + + def clone(self) -> MemoryObjectReceiveStream[T_co]: + """ + Create a clone of this receive stream. + + Each clone can be closed separately. Only when all clones have been closed will + the receiving end of the memory stream be considered closed by the sending ends. + + :return: the cloned stream + + """ + if self._closed: + raise ClosedResourceError + + return MemoryObjectReceiveStream(_state=self._state) + + def close(self) -> None: + """ + Close the stream. + + This works the exact same way as :meth:`aclose`, but is provided as a special + case for the benefit of synchronous callbacks. + + """ + if not self._closed: + self._closed = True + self._state.open_receive_channels -= 1 + if self._state.open_receive_channels == 0: + send_events = list(self._state.waiting_senders.keys()) + for event in send_events: + event.set() + + async def aclose(self) -> None: + self.close() + + def statistics(self) -> MemoryObjectStreamStatistics: + """ + Return statistics about the current state of this stream. + + .. versionadded:: 3.0 + """ + return self._state.statistics() + + def __enter__(self) -> MemoryObjectReceiveStream[T_co]: + return self + + def __exit__( + self, + exc_type: type[BaseException] | None, + exc_val: BaseException | None, + exc_tb: TracebackType | None, + ) -> None: + self.close() + + def __del__(self) -> None: + if not self._closed: + warnings.warn( + f"Unclosed <{self.__class__.__name__} at {id(self):x}>", + ResourceWarning, + stacklevel=1, + source=self, + ) + + +@dataclass(eq=False) +class MemoryObjectSendStream(Generic[T_contra], ObjectSendStream[T_contra]): + _state: _MemoryObjectStreamState[T_contra] + _closed: bool = field(init=False, default=False) + + def __post_init__(self) -> None: + self._state.open_send_channels += 1 + + def send_nowait(self, item: T_contra) -> None: + """ + Send an item immediately if it can be done without waiting. + + :param item: the item to send + :raises ~anyio.ClosedResourceError: if this send stream has been closed + :raises ~anyio.BrokenResourceError: if the stream has been closed from the + receiving end + :raises ~anyio.WouldBlock: if the buffer is full and there are no tasks waiting + to receive + + """ + if self._closed: + raise ClosedResourceError + if not self._state.open_receive_channels: + raise BrokenResourceError + + while self._state.waiting_receivers: + receive_event, receiver = self._state.waiting_receivers.popitem(last=False) + if not receiver.task_info.has_pending_cancellation(): + receiver.item = item + receive_event.set() + return + + if len(self._state.buffer) < self._state.max_buffer_size: + self._state.buffer.append(item) + else: + raise WouldBlock + + async def send(self, item: T_contra) -> None: + """ + Send an item to the stream. + + If the buffer is full, this method blocks until there is again room in the + buffer or the item can be sent directly to a receiver. + + :param item: the item to send + :raises ~anyio.ClosedResourceError: if this send stream has been closed + :raises ~anyio.BrokenResourceError: if the stream has been closed from the + receiving end + + """ + await checkpoint() + try: + self.send_nowait(item) + except WouldBlock: + # Wait until there's someone on the receiving end + send_event = Event() + self._state.waiting_senders[send_event] = item + try: + await send_event.wait() + except BaseException: + self._state.waiting_senders.pop(send_event, None) + raise + + if send_event in self._state.waiting_senders: + del self._state.waiting_senders[send_event] + raise BrokenResourceError from None + + def clone(self) -> MemoryObjectSendStream[T_contra]: + """ + Create a clone of this send stream. + + Each clone can be closed separately. Only when all clones have been closed will + the sending end of the memory stream be considered closed by the receiving ends. + + :return: the cloned stream + + """ + if self._closed: + raise ClosedResourceError + + return MemoryObjectSendStream(_state=self._state) + + def close(self) -> None: + """ + Close the stream. + + This works the exact same way as :meth:`aclose`, but is provided as a special + case for the benefit of synchronous callbacks. + + """ + if not self._closed: + self._closed = True + self._state.open_send_channels -= 1 + if self._state.open_send_channels == 0: + receive_events = list(self._state.waiting_receivers.keys()) + self._state.waiting_receivers.clear() + for event in receive_events: + event.set() + + async def aclose(self) -> None: + self.close() + + def statistics(self) -> MemoryObjectStreamStatistics: + """ + Return statistics about the current state of this stream. + + .. versionadded:: 3.0 + """ + return self._state.statistics() + + def __enter__(self) -> MemoryObjectSendStream[T_contra]: + return self + + def __exit__( + self, + exc_type: type[BaseException] | None, + exc_val: BaseException | None, + exc_tb: TracebackType | None, + ) -> None: + self.close() + + def __del__(self) -> None: + if not self._closed: + warnings.warn( + f"Unclosed <{self.__class__.__name__} at {id(self):x}>", + ResourceWarning, + stacklevel=1, + source=self, + ) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/anyio/streams/stapled.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/anyio/streams/stapled.py new file mode 100644 index 0000000000000000000000000000000000000000..9248b68abfbff90ddd64646fbe9cabb9f0ebe869 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/anyio/streams/stapled.py @@ -0,0 +1,147 @@ +from __future__ import annotations + +__all__ = ( + "MultiListener", + "StapledByteStream", + "StapledObjectStream", +) + +from collections.abc import Callable, Mapping, Sequence +from dataclasses import dataclass +from typing import Any, Generic, TypeVar + +from ..abc import ( + ByteReceiveStream, + ByteSendStream, + ByteStream, + Listener, + ObjectReceiveStream, + ObjectSendStream, + ObjectStream, + TaskGroup, +) + +T_Item = TypeVar("T_Item") +T_Stream = TypeVar("T_Stream") + + +@dataclass(eq=False) +class StapledByteStream(ByteStream): + """ + Combines two byte streams into a single, bidirectional byte stream. + + Extra attributes will be provided from both streams, with the receive stream + providing the values in case of a conflict. + + :param ByteSendStream send_stream: the sending byte stream + :param ByteReceiveStream receive_stream: the receiving byte stream + """ + + send_stream: ByteSendStream + receive_stream: ByteReceiveStream + + async def receive(self, max_bytes: int = 65536) -> bytes: + return await self.receive_stream.receive(max_bytes) + + async def send(self, item: bytes) -> None: + await self.send_stream.send(item) + + async def send_eof(self) -> None: + await self.send_stream.aclose() + + async def aclose(self) -> None: + await self.send_stream.aclose() + await self.receive_stream.aclose() + + @property + def extra_attributes(self) -> Mapping[Any, Callable[[], Any]]: + return { + **self.send_stream.extra_attributes, + **self.receive_stream.extra_attributes, + } + + +@dataclass(eq=False) +class StapledObjectStream(Generic[T_Item], ObjectStream[T_Item]): + """ + Combines two object streams into a single, bidirectional object stream. + + Extra attributes will be provided from both streams, with the receive stream + providing the values in case of a conflict. + + :param ObjectSendStream send_stream: the sending object stream + :param ObjectReceiveStream receive_stream: the receiving object stream + """ + + send_stream: ObjectSendStream[T_Item] + receive_stream: ObjectReceiveStream[T_Item] + + async def receive(self) -> T_Item: + return await self.receive_stream.receive() + + async def send(self, item: T_Item) -> None: + await self.send_stream.send(item) + + async def send_eof(self) -> None: + await self.send_stream.aclose() + + async def aclose(self) -> None: + await self.send_stream.aclose() + await self.receive_stream.aclose() + + @property + def extra_attributes(self) -> Mapping[Any, Callable[[], Any]]: + return { + **self.send_stream.extra_attributes, + **self.receive_stream.extra_attributes, + } + + +@dataclass(eq=False) +class MultiListener(Generic[T_Stream], Listener[T_Stream]): + """ + Combines multiple listeners into one, serving connections from all of them at once. + + Any MultiListeners in the given collection of listeners will have their listeners + moved into this one. + + Extra attributes are provided from each listener, with each successive listener + overriding any conflicting attributes from the previous one. + + :param listeners: listeners to serve + :type listeners: Sequence[Listener[T_Stream]] + """ + + listeners: Sequence[Listener[T_Stream]] + + def __post_init__(self) -> None: + listeners: list[Listener[T_Stream]] = [] + for listener in self.listeners: + if isinstance(listener, MultiListener): + listeners.extend(listener.listeners) + del listener.listeners[:] # type: ignore[attr-defined] + else: + listeners.append(listener) + + self.listeners = listeners + + async def serve( + self, handler: Callable[[T_Stream], Any], task_group: TaskGroup | None = None + ) -> None: + from .. import create_task_group + + async with create_task_group() as tg: + for listener in self.listeners: + tg.start_soon(listener.serve, handler, task_group) + + async def aclose(self) -> None: + for listener in self.listeners: + await listener.aclose() + + @property + def extra_attributes(self) -> Mapping[Any, Callable[[], Any]]: + attributes: dict = {} + for listener in self.listeners: + attributes.update(listener.extra_attributes) + + return attributes diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/anyio/streams/text.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/anyio/streams/text.py new file mode 100644 index 0000000000000000000000000000000000000000..296cd250459f3848bb333301fff1ac32973f219a --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/anyio/streams/text.py @@ -0,0 +1,176 @@ +from __future__ import annotations + +__all__ = ( + "TextConnectable", + "TextReceiveStream", + "TextSendStream", + "TextStream", +) + +import codecs +import sys +from collections.abc import Callable, Mapping +from dataclasses import InitVar, dataclass, field +from typing import Any + +from ..abc import ( + AnyByteReceiveStream, + AnyByteSendStream, + AnyByteStream, + AnyByteStreamConnectable, + ObjectReceiveStream, + ObjectSendStream, + ObjectStream, + ObjectStreamConnectable, +) + +if sys.version_info >= (3, 12): + from typing import override +else: + from typing_extensions import override + + +@dataclass(eq=False) +class TextReceiveStream(ObjectReceiveStream[str]): + """ + Stream wrapper that decodes bytes to strings using the given encoding. + + Decoding is done using :class:`~codecs.IncrementalDecoder` which returns any + completely received unicode characters as soon as they come in. + + :param transport_stream: any bytes-based receive stream + :param encoding: character encoding to use for decoding bytes to strings (defaults + to ``utf-8``) + :param errors: handling scheme for decoding errors (defaults to ``strict``; see the + `codecs module documentation`_ for a comprehensive list of options) + + .. _codecs module documentation: + https://docs.python.org/3/library/codecs.html#codec-objects + """ + + transport_stream: AnyByteReceiveStream + encoding: InitVar[str] = "utf-8" + errors: InitVar[str] = "strict" + _decoder: codecs.IncrementalDecoder = field(init=False) + + def __post_init__(self, encoding: str, errors: str) -> None: + decoder_class = codecs.getincrementaldecoder(encoding) + self._decoder = decoder_class(errors=errors) + + async def receive(self) -> str: + while True: + chunk = await self.transport_stream.receive() + decoded = self._decoder.decode(chunk) + if decoded: + return decoded + + async def aclose(self) -> None: + await self.transport_stream.aclose() + self._decoder.reset() + + @property + def extra_attributes(self) -> Mapping[Any, Callable[[], Any]]: + return self.transport_stream.extra_attributes + + +@dataclass(eq=False) +class TextSendStream(ObjectSendStream[str]): + """ + Sends strings to the wrapped stream as bytes using the given encoding. + + :param AnyByteSendStream transport_stream: any bytes-based send stream + :param str encoding: character encoding to use for encoding strings to bytes + (defaults to ``utf-8``) + :param str errors: handling scheme for encoding errors (defaults to ``strict``; see + the `codecs module documentation`_ for a comprehensive list of options) + + .. _codecs module documentation: + https://docs.python.org/3/library/codecs.html#codec-objects + """ + + transport_stream: AnyByteSendStream + encoding: InitVar[str] = "utf-8" + errors: str = "strict" + _encoder: Callable[..., tuple[bytes, int]] = field(init=False) + + def __post_init__(self, encoding: str) -> None: + self._encoder = codecs.getencoder(encoding) + + async def send(self, item: str) -> None: + encoded = self._encoder(item, self.errors)[0] + await self.transport_stream.send(encoded) + + async def aclose(self) -> None: + await self.transport_stream.aclose() + + @property + def extra_attributes(self) -> Mapping[Any, Callable[[], Any]]: + return self.transport_stream.extra_attributes + + +@dataclass(eq=False) +class TextStream(ObjectStream[str]): + """ + A bidirectional stream that decodes bytes to strings on receive and encodes strings + to bytes on send. + + Extra attributes will be provided from both streams, with the receive stream + providing the values in case of a conflict. + + :param AnyByteStream transport_stream: any bytes-based stream + :param str encoding: character encoding to use for encoding/decoding strings to/from + bytes (defaults to ``utf-8``) + :param str errors: handling scheme for encoding errors (defaults to ``strict``; see + the `codecs module documentation`_ for a comprehensive list of options) + + .. _codecs module documentation: + https://docs.python.org/3/library/codecs.html#codec-objects + """ + + transport_stream: AnyByteStream + encoding: InitVar[str] = "utf-8" + errors: InitVar[str] = "strict" + _receive_stream: TextReceiveStream = field(init=False) + _send_stream: TextSendStream = field(init=False) + + def __post_init__(self, encoding: str, errors: str) -> None: + self._receive_stream = TextReceiveStream( + self.transport_stream, encoding=encoding, errors=errors + ) + self._send_stream = TextSendStream( + self.transport_stream, encoding=encoding, errors=errors + ) + + async def receive(self) -> str: + return await self._receive_stream.receive() + + async def send(self, item: str) -> None: + await self._send_stream.send(item) + + async def send_eof(self) -> None: + await self.transport_stream.send_eof() + + async def aclose(self) -> None: + await self._send_stream.aclose() + await self._receive_stream.aclose() + + @property + def extra_attributes(self) -> Mapping[Any, Callable[[], Any]]: + return { + **self._send_stream.extra_attributes, + **self._receive_stream.extra_attributes, + } + + +class TextConnectable(ObjectStreamConnectable[str]): + def __init__(self, connectable: AnyByteStreamConnectable): + """ + :param connectable: the bytestream endpoint to wrap + + """ + self.connectable = connectable + + @override + async def connect(self) -> TextStream: + stream = await self.connectable.connect() + return TextStream(stream) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/anyio/streams/tls.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/anyio/streams/tls.py new file mode 100644 index 0000000000000000000000000000000000000000..e2a7ca5b17b9b6c2d3f0f39e86b22342d0b4df65 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/anyio/streams/tls.py @@ -0,0 +1,421 @@ +from __future__ import annotations + +__all__ = ( + "TLSAttribute", + "TLSConnectable", + "TLSListener", + "TLSStream", +) + +import logging +import re +import ssl +import sys +from collections.abc import Callable, Mapping +from dataclasses import dataclass +from functools import wraps +from ssl import SSLContext +from typing import Any, TypeAlias, TypeVar + +from .. import ( + BrokenResourceError, + EndOfStream, + aclose_forcefully, + get_cancelled_exc_class, + to_thread, +) +from .._core._typedattr import TypedAttributeSet, typed_attribute +from ..abc import ( + AnyByteStream, + AnyByteStreamConnectable, + ByteStream, + ByteStreamConnectable, + Listener, + TaskGroup, +) + +if sys.version_info >= (3, 11): + from typing import TypeVarTuple, Unpack +else: + from typing_extensions import TypeVarTuple, Unpack + +if sys.version_info >= (3, 12): + from typing import override +else: + from typing_extensions import override + +T_Retval = TypeVar("T_Retval") +PosArgsT = TypeVarTuple("PosArgsT") +_PCTRTT: TypeAlias = tuple[tuple[str, str], ...] +_PCTRTTT: TypeAlias = tuple[_PCTRTT, ...] + + +class TLSAttribute(TypedAttributeSet): + """Contains Transport Layer Security related attributes.""" + + #: the selected ALPN protocol + alpn_protocol: str | None = typed_attribute() + #: the channel binding for type ``tls-unique`` + channel_binding_tls_unique: bytes = typed_attribute() + #: the selected cipher + cipher: tuple[str, str, int] = typed_attribute() + #: the peer certificate in dictionary form (see :meth:`ssl.SSLSocket.getpeercert` + # for more information) + peer_certificate: None | (dict[str, str | _PCTRTTT | _PCTRTT]) = typed_attribute() + #: the peer certificate in binary form + peer_certificate_binary: bytes | None = typed_attribute() + #: ``True`` if this is the server side of the connection + server_side: bool = typed_attribute() + #: ciphers shared by the client during the TLS handshake (``None`` if this is the + #: client side) + shared_ciphers: list[tuple[str, str, int]] | None = typed_attribute() + #: the :class:`~ssl.SSLObject` used for encryption + ssl_object: ssl.SSLObject = typed_attribute() + #: ``True`` if this stream does (and expects) a closing TLS handshake when the + #: stream is being closed + standard_compatible: bool = typed_attribute() + #: the TLS protocol version (e.g. ``TLSv1.2``) + tls_version: str = typed_attribute() + + +@dataclass(eq=False) +class TLSStream(ByteStream): + """ + A stream wrapper that encrypts all sent data and decrypts received data. + + This class has no public initializer; use :meth:`wrap` instead. + All extra attributes from :class:`~TLSAttribute` are supported. + + :var AnyByteStream transport_stream: the wrapped stream + + """ + + transport_stream: AnyByteStream + standard_compatible: bool + _ssl_object: ssl.SSLObject + _read_bio: ssl.MemoryBIO + _write_bio: ssl.MemoryBIO + + @classmethod + async def wrap( + cls, + transport_stream: AnyByteStream, + *, + server_side: bool | None = None, + hostname: str | None = None, + ssl_context: ssl.SSLContext | None = None, + standard_compatible: bool = True, + ) -> TLSStream: + """ + Wrap an existing stream with Transport Layer Security. + + This performs a TLS handshake with the peer. + + :param transport_stream: a bytes-transporting stream to wrap + :param server_side: ``True`` if this is the server side of the connection, + ``False`` if this is the client side (if omitted, will be set to ``False`` + if ``hostname`` has been provided, ``False`` otherwise). Used only to create + a default context when an explicit context has not been provided. + :param hostname: host name of the peer (if host name checking is desired) + :param ssl_context: the SSLContext object to use (if not provided, a secure + default will be created) + :param standard_compatible: if ``False``, skip the closing handshake when + closing the connection, and don't raise an exception if the peer does the + same + :raises ~ssl.SSLError: if the TLS handshake fails + + """ + if server_side is None: + server_side = not hostname + + if not ssl_context: + purpose = ( + ssl.Purpose.CLIENT_AUTH if server_side else ssl.Purpose.SERVER_AUTH + ) + ssl_context = ssl.create_default_context(purpose) + + # Re-enable detection of unexpected EOFs if it was disabled by Python + if hasattr(ssl, "OP_IGNORE_UNEXPECTED_EOF"): + ssl_context.options &= ~ssl.OP_IGNORE_UNEXPECTED_EOF + + bio_in = ssl.MemoryBIO() + bio_out = ssl.MemoryBIO() + + # External SSLContext implementations may do blocking I/O in wrap_bio(), + # but the standard library implementation won't + if type(ssl_context) is ssl.SSLContext: + ssl_object = ssl_context.wrap_bio( + bio_in, bio_out, server_side=server_side, server_hostname=hostname + ) + else: + ssl_object = await to_thread.run_sync( + ssl_context.wrap_bio, + bio_in, + bio_out, + server_side, + hostname, + None, + ) + + wrapper = cls( + transport_stream=transport_stream, + standard_compatible=standard_compatible, + _ssl_object=ssl_object, + _read_bio=bio_in, + _write_bio=bio_out, + ) + await wrapper._call_sslobject_method(ssl_object.do_handshake) + return wrapper + + async def _call_sslobject_method( + self, func: Callable[[Unpack[PosArgsT]], T_Retval], *args: Unpack[PosArgsT] + ) -> T_Retval: + while True: + try: + result = func(*args) + except ssl.SSLWantReadError: + try: + # Flush any pending writes first + if self._write_bio.pending: + await self.transport_stream.send(self._write_bio.read()) + + data = await self.transport_stream.receive() + except EndOfStream: + self._read_bio.write_eof() + except OSError as exc: + self._read_bio.write_eof() + self._write_bio.write_eof() + raise BrokenResourceError from exc + else: + self._read_bio.write(data) + except ssl.SSLWantWriteError: + await self.transport_stream.send(self._write_bio.read()) + except ssl.SSLSyscallError as exc: + self._read_bio.write_eof() + self._write_bio.write_eof() + raise BrokenResourceError from exc + except ssl.SSLError as exc: + self._read_bio.write_eof() + self._write_bio.write_eof() + if isinstance(exc, ssl.SSLEOFError) or ( + exc.strerror and "UNEXPECTED_EOF_WHILE_READING" in exc.strerror + ): + if self.standard_compatible: + raise BrokenResourceError from exc + else: + raise EndOfStream from None + + raise + else: + # Flush any pending writes first + if self._write_bio.pending: + await self.transport_stream.send(self._write_bio.read()) + + return result + + async def unwrap(self) -> tuple[AnyByteStream, bytes]: + """ + Does the TLS closing handshake. + + :return: a tuple of (wrapped byte stream, bytes left in the read buffer) + + """ + await self._call_sslobject_method(self._ssl_object.unwrap) + self._read_bio.write_eof() + self._write_bio.write_eof() + return self.transport_stream, self._read_bio.read() + + async def aclose(self) -> None: + if self.standard_compatible: + try: + await self.unwrap() + except BaseException: + await aclose_forcefully(self.transport_stream) + raise + + await self.transport_stream.aclose() + + async def receive(self, max_bytes: int = 65536) -> bytes: + data = await self._call_sslobject_method(self._ssl_object.read, max_bytes) + if not data: + raise EndOfStream + + return data + + async def send(self, item: bytes) -> None: + await self._call_sslobject_method(self._ssl_object.write, item) + + async def send_eof(self) -> None: + tls_version = self.extra(TLSAttribute.tls_version) + match = re.match(r"TLSv(\d+)(?:\.(\d+))?", tls_version) + if match: + major, minor = int(match.group(1)), int(match.group(2) or 0) + if (major, minor) < (1, 3): + raise NotImplementedError( + f"send_eof() requires at least TLSv1.3; current " + f"session uses {tls_version}" + ) + + raise NotImplementedError( + "send_eof() has not yet been implemented for TLS streams" + ) + + @property + def extra_attributes(self) -> Mapping[Any, Callable[[], Any]]: + return { + **self.transport_stream.extra_attributes, + TLSAttribute.alpn_protocol: self._ssl_object.selected_alpn_protocol, + TLSAttribute.channel_binding_tls_unique: ( + self._ssl_object.get_channel_binding + ), + TLSAttribute.cipher: self._ssl_object.cipher, + TLSAttribute.peer_certificate: lambda: self._ssl_object.getpeercert(False), + TLSAttribute.peer_certificate_binary: lambda: self._ssl_object.getpeercert( + True + ), + TLSAttribute.server_side: lambda: self._ssl_object.server_side, + TLSAttribute.shared_ciphers: lambda: ( + self._ssl_object.shared_ciphers() + if self._ssl_object.server_side + else None + ), + TLSAttribute.standard_compatible: lambda: self.standard_compatible, + TLSAttribute.ssl_object: lambda: self._ssl_object, + TLSAttribute.tls_version: self._ssl_object.version, + } + + +@dataclass(eq=False) +class TLSListener(Listener[TLSStream]): + """ + A convenience listener that wraps another listener and auto-negotiates a TLS session + on every accepted connection. + + If the TLS handshake times out or raises an exception, + :meth:`handle_handshake_error` is called to do whatever post-mortem processing is + deemed necessary. + + Supports only the :attr:`~TLSAttribute.standard_compatible` extra attribute. + + :param Listener listener: the listener to wrap + :param ssl_context: the SSL context object + :param standard_compatible: a flag passed through to :meth:`TLSStream.wrap` + :param handshake_timeout: time limit for the TLS handshake + (passed to :func:`~anyio.fail_after`) + """ + + listener: Listener[Any] + ssl_context: ssl.SSLContext + standard_compatible: bool = True + handshake_timeout: float = 30 + + @staticmethod + async def handle_handshake_error(exc: BaseException, stream: AnyByteStream) -> None: + """ + Handle an exception raised during the TLS handshake. + + This method does 3 things: + + #. Forcefully closes the original stream + #. Logs the exception (unless it was a cancellation exception) using the + ``anyio.streams.tls`` logger + #. Reraises the exception if it was a base exception or a cancellation exception + + :param exc: the exception + :param stream: the original stream + + """ + await aclose_forcefully(stream) + + # Log all except cancellation exceptions + if not isinstance(exc, get_cancelled_exc_class()): + # CPython (as of 3.11.5) returns incorrect `sys.exc_info()` here when using + # any asyncio implementation, so we explicitly pass the exception to log + # (https://github.com/python/cpython/issues/108668). Trio does not have this + # issue because it works around the CPython bug. + logging.getLogger(__name__).exception( + "Error during TLS handshake", exc_info=exc + ) + + # Only reraise base exceptions and cancellation exceptions + if not isinstance(exc, Exception) or isinstance(exc, get_cancelled_exc_class()): + raise + + async def serve( + self, + handler: Callable[[TLSStream], Any], + task_group: TaskGroup | None = None, + ) -> None: + @wraps(handler) + async def handler_wrapper(stream: AnyByteStream) -> None: + from .. import fail_after + + try: + with fail_after(self.handshake_timeout): + wrapped_stream = await TLSStream.wrap( + stream, + ssl_context=self.ssl_context, + standard_compatible=self.standard_compatible, + ) + except BaseException as exc: + await self.handle_handshake_error(exc, stream) + else: + await handler(wrapped_stream) + + await self.listener.serve(handler_wrapper, task_group) + + async def aclose(self) -> None: + await self.listener.aclose() + + @property + def extra_attributes(self) -> Mapping[Any, Callable[[], Any]]: + return { + TLSAttribute.standard_compatible: lambda: self.standard_compatible, + } + + +class TLSConnectable(ByteStreamConnectable): + """ + Wraps another connectable and does TLS negotiation after a successful connection. + + :param connectable: the connectable to wrap + :param hostname: host name of the server (if host name checking is desired) + :param ssl_context: the SSLContext object to use (if not provided, a secure default + will be created) + :param standard_compatible: if ``False``, skip the closing handshake when closing + the connection, and don't raise an exception if the server does the same + """ + + def __init__( + self, + connectable: AnyByteStreamConnectable, + *, + hostname: str | None = None, + ssl_context: ssl.SSLContext | None = None, + standard_compatible: bool = True, + ) -> None: + self.connectable = connectable + self.ssl_context: SSLContext = ssl_context or ssl.create_default_context( + ssl.Purpose.SERVER_AUTH + ) + if not isinstance(self.ssl_context, ssl.SSLContext): + raise TypeError( + "ssl_context must be an instance of ssl.SSLContext, not " + f"{type(self.ssl_context).__name__}" + ) + self.hostname = hostname + self.standard_compatible = standard_compatible + + @override + async def connect(self) -> TLSStream: + stream = await self.connectable.connect() + try: + return await TLSStream.wrap( + stream, + hostname=self.hostname, + ssl_context=self.ssl_context, + standard_compatible=self.standard_compatible, + ) + except BaseException: + await aclose_forcefully(stream) + raise diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/attr/__pycache__/__init__.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/attr/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4b1a23c135b48de4ad75c8e39f299113e37bb646 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/attr/__pycache__/__init__.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/attr/__pycache__/_cmp.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/attr/__pycache__/_cmp.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..301eedf79af71cc8990f632c0a08f2fe23638b94 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/attr/__pycache__/_cmp.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/attr/__pycache__/_compat.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/attr/__pycache__/_compat.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6c1eb439cbcf7927b749a406198478bf8d528d58 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/attr/__pycache__/_compat.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/attr/__pycache__/_config.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/attr/__pycache__/_config.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4cd8ba267dd65f2a3d1632b053632dd83482616c Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/attr/__pycache__/_config.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/attr/__pycache__/_funcs.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/attr/__pycache__/_funcs.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7e9636909e58b714ea51777dc5c39432f6fb02ea Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/attr/__pycache__/_funcs.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/attr/__pycache__/_next_gen.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/attr/__pycache__/_next_gen.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9b5fe1eff31f5a9edda3b1a784ed16978adef3ce Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/attr/__pycache__/_next_gen.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/attr/__pycache__/_version_info.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/attr/__pycache__/_version_info.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3474ce37ef3b229d879e24b38038ab88aee81798 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/attr/__pycache__/_version_info.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/attr/__pycache__/converters.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/attr/__pycache__/converters.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3150414aed63ebbaf50262b67ddf35c6ceb7375a Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/attr/__pycache__/converters.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/attr/__pycache__/exceptions.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/attr/__pycache__/exceptions.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c68c8833c4f8cbbb340cc718f69a88db25ed5994 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/attr/__pycache__/exceptions.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/attr/__pycache__/filters.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/attr/__pycache__/filters.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d2f975cd6744abd02a7e155671969aa6d466a8f7 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/attr/__pycache__/filters.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/attr/__pycache__/setters.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/attr/__pycache__/setters.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..843c6f838e568ba17811c7b906f1598dfca6b37c Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/attr/__pycache__/setters.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/attr/__pycache__/validators.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/attr/__pycache__/validators.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..07c2e06a2cb9d26249fca84a72abbaec64411f6d Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/attr/__pycache__/validators.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/attrs-26.1.0.dist-info/licenses/LICENSE b/micromamba_root/envs/pytorch_env/Lib/site-packages/attrs-26.1.0.dist-info/licenses/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..2bd6453d255e19b973f19b128596a8b6dd65b2c3 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/attrs-26.1.0.dist-info/licenses/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2015 Hynek Schlawack and the attrs 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/micromamba_root/envs/pytorch_env/Lib/site-packages/attrs/__pycache__/__init__.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/attrs/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..028faceaec5a1ca64b089fd14f81fc1e4e465c0a Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/attrs/__pycache__/__init__.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/attrs/__pycache__/converters.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/attrs/__pycache__/converters.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..400d73674ff023a72657a2ffcf94e32ffbf5db1b Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/attrs/__pycache__/converters.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/attrs/__pycache__/exceptions.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/attrs/__pycache__/exceptions.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f8de32dcfbb4ed51424a309776ee37f40d93d492 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/attrs/__pycache__/exceptions.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/attrs/__pycache__/filters.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/attrs/__pycache__/filters.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..735b06341c0dd63713977430bdd9fbbfd257ae9b Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/attrs/__pycache__/filters.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/attrs/__pycache__/setters.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/attrs/__pycache__/setters.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1322ab250fce15692dd35b50047383d5f4b397ad Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/attrs/__pycache__/setters.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/attrs/__pycache__/validators.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/attrs/__pycache__/validators.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a33a1ac19182d8f974cfd46e37beed7a0630a8ec Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/attrs/__pycache__/validators.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/bcrypt/__pycache__/__init__.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/bcrypt/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..061bad9864df14c41da500bfa0d68a22fff5e57a Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/bcrypt/__pycache__/__init__.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/build-1.5.0.dist-info/licenses/LICENSE b/micromamba_root/envs/pytorch_env/Lib/site-packages/build-1.5.0.dist-info/licenses/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..c3713cdcc9b5df70576fb1d5d010c7a17e02e038 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/build-1.5.0.dist-info/licenses/LICENSE @@ -0,0 +1,20 @@ +Copyright © 2019 Filipe Laíns + +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 (including the next +paragraph) 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/micromamba_root/envs/pytorch_env/Lib/site-packages/build/__pycache__/__init__.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/build/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f159867f765148c58dc03a3dd99d10968a7b2fc3 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/build/__pycache__/__init__.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/build/__pycache__/__main__.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/build/__pycache__/__main__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..daf604d4c3ce643ee7cea13550072d1fe011878f Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/build/__pycache__/__main__.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/build/__pycache__/_builder.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/build/__pycache__/_builder.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a2dbd54e8c75956b6879a7c1ec237e223ad64efa Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/build/__pycache__/_builder.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/build/__pycache__/_ctx.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/build/__pycache__/_ctx.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b8b276d210fafc60dbae8823b891d2fa6fd7426f Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/build/__pycache__/_ctx.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/build/__pycache__/_exceptions.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/build/__pycache__/_exceptions.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..254e2dca3d00ce4a6b2b193c6525ae7e4c63f014 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/build/__pycache__/_exceptions.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/build/__pycache__/_types.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/build/__pycache__/_types.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..589dac7969423eed83bc3211381ed86d9f6d94e7 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/build/__pycache__/_types.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/build/__pycache__/_util.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/build/__pycache__/_util.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5ba98caeb3f2cb9ebf1fce4522d6dd0e75ce29a1 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/build/__pycache__/_util.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/build/__pycache__/env.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/build/__pycache__/env.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c3215d55a18e49a8e0120b9968efc79f4a2e6e27 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/build/__pycache__/env.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/build/__pycache__/util.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/build/__pycache__/util.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9fec936422bcf965ac9d7d52950c68574f76d244 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/build/__pycache__/util.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/build/_compat/__init__.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/build/_compat/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/build/_compat/__pycache__/__init__.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/build/_compat/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9bff334605cd169af0c08cb180b602f91608a83e Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/build/_compat/__pycache__/__init__.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/build/_compat/__pycache__/importlib.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/build/_compat/__pycache__/importlib.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c3541f15c16a2386a120e6b96eae80722b1bc555 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/build/_compat/__pycache__/importlib.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/build/_compat/__pycache__/tarfile.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/build/_compat/__pycache__/tarfile.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..16ccd63150cf98d4f181282b8eb170d5e8c88a62 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/build/_compat/__pycache__/tarfile.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/build/_compat/__pycache__/tomllib.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/build/_compat/__pycache__/tomllib.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..de6b1499cea0a5ba148240ce9b7f5a871502833b Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/build/_compat/__pycache__/tomllib.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/build/_compat/importlib.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/build/_compat/importlib.py new file mode 100644 index 0000000000000000000000000000000000000000..e5ee2b3baac4039b28fb72b1a31aa7687a407cc0 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/build/_compat/importlib.py @@ -0,0 +1,22 @@ +from __future__ import annotations + +import sys + + +TYPE_CHECKING = False + +if TYPE_CHECKING: + import importlib_metadata as metadata +elif sys.version_info >= (3, 10, 2): + from importlib import metadata # pragma: no cover +else: # pragma: no cover + try: + import importlib_metadata as metadata + except ModuleNotFoundError: + # helps bootstrapping when dependencies aren't installed + from importlib import metadata + + +__all__ = [ + 'metadata', +] diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/build/_compat/tarfile.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/build/_compat/tarfile.py new file mode 100644 index 0000000000000000000000000000000000000000..eb81a245039f3e575d0f2d49fc46cd043f09741d --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/build/_compat/tarfile.py @@ -0,0 +1,31 @@ +from __future__ import annotations + +import sys +import tarfile + + +TYPE_CHECKING = False + +if TYPE_CHECKING: + TarFile = tarfile.TarFile + +# Per https://peps.python.org/pep-0706/, the "data" filter will become +# the default in Python 3.14. The first series of releases with the filter +# had a broken filter that could not process symlinks correctly. +elif ( + (3, 9, 18) <= sys.version_info < (3, 10) + or (3, 10, 13) <= sys.version_info < (3, 11) + or (3, 11, 5) <= sys.version_info < (3, 12) + or (3, 12) <= sys.version_info < (3, 14) +): + + class TarFile(tarfile.TarFile): # pragma: no cover + extraction_filter = staticmethod(tarfile.data_filter) + +else: + TarFile = tarfile.TarFile # pragma: no cover + + +__all__ = [ + 'TarFile', +] diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/build/_compat/tomllib.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/build/_compat/tomllib.py new file mode 100644 index 0000000000000000000000000000000000000000..aa188c02c6e7069e15bc1a1666c01aef3fb84192 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/build/_compat/tomllib.py @@ -0,0 +1,19 @@ +from __future__ import annotations + + +__lazy_modules__ = ['tomli', 'tomllib'] + +import sys + + +if sys.version_info >= (3, 11): + from tomllib import TOMLDecodeError, load, loads # pragma: no cover +else: # pragma: no cover + from tomli import TOMLDecodeError, load, loads + + +__all__ = [ + 'TOMLDecodeError', + 'load', + 'loads', +] diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/certifi-2026.4.22.dist-info/licenses/LICENSE b/micromamba_root/envs/pytorch_env/Lib/site-packages/certifi-2026.4.22.dist-info/licenses/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..62b076cdee58ec8f34034141ba0befd9015b0c7e --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/certifi-2026.4.22.dist-info/licenses/LICENSE @@ -0,0 +1,20 @@ +This package contains a modified version of ca-bundle.crt: + +ca-bundle.crt -- Bundle of CA Root Certificates + +This is a bundle of X.509 certificates of public Certificate Authorities +(CA). These were automatically extracted from Mozilla's root certificates +file (certdata.txt). This file can be found in the mozilla source tree: +https://hg.mozilla.org/mozilla-central/file/tip/security/nss/lib/ckfw/builtins/certdata.txt +It contains the certificates in PEM format and therefore +can be directly used with curl / libcurl / php_curl, or with +an Apache+mod_ssl webserver for SSL client authentication. +Just configure this file as the SSLCACertificateFile.# + +***** BEGIN LICENSE BLOCK ***** +This Source Code Form is subject to the terms of the Mozilla Public License, +v. 2.0. If a copy of the MPL was not distributed with this file, You can obtain +one at http://mozilla.org/MPL/2.0/. + +***** END LICENSE BLOCK ***** +@(#) $RCSfile: certdata.txt,v $ $Revision: 1.80 $ $Date: 2011/11/03 15:11:58 $ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/certifi/__pycache__/__init__.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/certifi/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a5b5758f40f9af5114457e240e5a8229f86867e3 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/certifi/__pycache__/__init__.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/certifi/__pycache__/__main__.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/certifi/__pycache__/__main__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..625c41a6225e076759e80b98e32e1f293f0edece Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/certifi/__pycache__/__main__.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/certifi/__pycache__/core.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/certifi/__pycache__/core.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b703e40a629217c06546e64ea559c40a29e597eb Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/certifi/__pycache__/core.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/charset_normalizer-3.4.7.dist-info/licenses/LICENSE b/micromamba_root/envs/pytorch_env/Lib/site-packages/charset_normalizer-3.4.7.dist-info/licenses/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..8885be9624d2bf3fdeca3551d3b5f475bcb536db --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/charset_normalizer-3.4.7.dist-info/licenses/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2025 TAHRI Ahmed R. + +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/micromamba_root/envs/pytorch_env/Lib/site-packages/charset_normalizer/__pycache__/__init__.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/charset_normalizer/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..dfd8d5b1d1bf6b8e5b4f0fe8380bf72f9ae1fdac Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/charset_normalizer/__pycache__/__init__.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/charset_normalizer/__pycache__/__main__.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/charset_normalizer/__pycache__/__main__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..dcc652b1125a9d14d833ff8198c7f3cf2988d95c Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/charset_normalizer/__pycache__/__main__.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/charset_normalizer/__pycache__/api.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/charset_normalizer/__pycache__/api.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1eec09606666d989f1286817f70f1df3e350a8ab Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/charset_normalizer/__pycache__/api.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/charset_normalizer/__pycache__/cd.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/charset_normalizer/__pycache__/cd.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a9025e0138fe202fa5af16c7dcb59ab2beb1e0a9 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/charset_normalizer/__pycache__/cd.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/charset_normalizer/__pycache__/constant.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/charset_normalizer/__pycache__/constant.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0eb22abbdf6d22034164700fa4e7ed126f5a3c33 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/charset_normalizer/__pycache__/constant.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/charset_normalizer/__pycache__/legacy.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/charset_normalizer/__pycache__/legacy.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6f883c3caeb70bde86cdc6bd4077da21d218da3a Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/charset_normalizer/__pycache__/legacy.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/charset_normalizer/__pycache__/md.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/charset_normalizer/__pycache__/md.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8d68f11b854ba1ec921d7373fa01c49cd4a2140e Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/charset_normalizer/__pycache__/md.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/charset_normalizer/__pycache__/models.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/charset_normalizer/__pycache__/models.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ebcb0c30d296b26293f967a4df774f17f604c5e3 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/charset_normalizer/__pycache__/models.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/charset_normalizer/__pycache__/utils.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/charset_normalizer/__pycache__/utils.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ace09b8dbe767bf0db870f32d133668cea4f5d05 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/charset_normalizer/__pycache__/utils.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/charset_normalizer/__pycache__/version.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/charset_normalizer/__pycache__/version.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..fd8dc5b9378b1b7a627a9c406417d7b70259e810 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/charset_normalizer/__pycache__/version.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/charset_normalizer/cli/__init__.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/charset_normalizer/cli/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..562b64e01cb42d989f2ddd5a8651841f700888e4 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/charset_normalizer/cli/__init__.py @@ -0,0 +1,8 @@ +from __future__ import annotations + +from .__main__ import cli_detect, query_yes_no + +__all__ = ( + "cli_detect", + "query_yes_no", +) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/charset_normalizer/cli/__main__.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/charset_normalizer/cli/__main__.py new file mode 100644 index 0000000000000000000000000000000000000000..bb4dd14eb46a13bc5e2d73163b1b6640da814912 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/charset_normalizer/cli/__main__.py @@ -0,0 +1,362 @@ +from __future__ import annotations + +import argparse +import sys +import typing +from json import dumps +from os.path import abspath, basename, dirname, join, realpath +from platform import python_version +from unicodedata import unidata_version + +import charset_normalizer.md as md_module +from charset_normalizer import from_fp +from charset_normalizer.models import CliDetectionResult +from charset_normalizer.version import __version__ + + +def query_yes_no(question: str, default: str = "yes") -> bool: # Defensive: + """Ask a yes/no question via input() and return the answer as a bool.""" + prompt = " [Y/n] " if default == "yes" else " [y/N] " + + while True: + choice = input(question + prompt).strip().lower() + if not choice: + return default == "yes" + if choice in ("y", "yes"): + return True + if choice in ("n", "no"): + return False + print("Please respond with 'y' or 'n'.") + + +class FileType: + """Factory for creating file object types + + Instances of FileType are typically passed as type= arguments to the + ArgumentParser add_argument() method. + + Keyword Arguments: + - mode -- A string indicating how the file is to be opened. Accepts the + same values as the builtin open() function. + - bufsize -- The file's desired buffer size. Accepts the same values as + the builtin open() function. + - encoding -- The file's encoding. Accepts the same values as the + builtin open() function. + - errors -- A string indicating how encoding and decoding errors are to + be handled. Accepts the same value as the builtin open() function. + + Backported from CPython 3.12 + """ + + def __init__( + self, + mode: str = "r", + bufsize: int = -1, + encoding: str | None = None, + errors: str | None = None, + ): + self._mode = mode + self._bufsize = bufsize + self._encoding = encoding + self._errors = errors + + def __call__(self, string: str) -> typing.IO: # type: ignore[type-arg] + # the special argument "-" means sys.std{in,out} + if string == "-": + if "r" in self._mode: + return sys.stdin.buffer if "b" in self._mode else sys.stdin + elif any(c in self._mode for c in "wax"): + return sys.stdout.buffer if "b" in self._mode else sys.stdout + else: + msg = f'argument "-" with mode {self._mode}' + raise ValueError(msg) + + # all other arguments are used as file names + try: + return open(string, self._mode, self._bufsize, self._encoding, self._errors) + except OSError as e: + message = f"can't open '{string}': {e}" + raise argparse.ArgumentTypeError(message) + + def __repr__(self) -> str: + args = self._mode, self._bufsize + kwargs = [("encoding", self._encoding), ("errors", self._errors)] + args_str = ", ".join( + [repr(arg) for arg in args if arg != -1] + + [f"{kw}={arg!r}" for kw, arg in kwargs if arg is not None] + ) + return f"{type(self).__name__}({args_str})" + + +def cli_detect(argv: list[str] | None = None) -> int: + """ + CLI assistant using ARGV and ArgumentParser + :param argv: + :return: 0 if everything is fine, anything else equal trouble + """ + parser = argparse.ArgumentParser( + description="The Real First Universal Charset Detector. " + "Discover originating encoding used on text file. " + "Normalize text to unicode." + ) + + parser.add_argument( + "files", type=FileType("rb"), nargs="+", help="File(s) to be analysed" + ) + parser.add_argument( + "-v", + "--verbose", + action="store_true", + default=False, + dest="verbose", + help="Display complementary information about file if any. " + "Stdout will contain logs about the detection process.", + ) + parser.add_argument( + "-a", + "--with-alternative", + action="store_true", + default=False, + dest="alternatives", + help="Output complementary possibilities if any. Top-level JSON WILL be a list.", + ) + parser.add_argument( + "-n", + "--normalize", + action="store_true", + default=False, + dest="normalize", + help="Permit to normalize input file. If not set, program does not write anything.", + ) + parser.add_argument( + "-m", + "--minimal", + action="store_true", + default=False, + dest="minimal", + help="Only output the charset detected to STDOUT. Disabling JSON output.", + ) + parser.add_argument( + "-r", + "--replace", + action="store_true", + default=False, + dest="replace", + help="Replace file when trying to normalize it instead of creating a new one.", + ) + parser.add_argument( + "-f", + "--force", + action="store_true", + default=False, + dest="force", + help="Replace file without asking if you are sure, use this flag with caution.", + ) + parser.add_argument( + "-i", + "--no-preemptive", + action="store_true", + default=False, + dest="no_preemptive", + help="Disable looking at a charset declaration to hint the detector.", + ) + parser.add_argument( + "-t", + "--threshold", + action="store", + default=0.2, + type=float, + dest="threshold", + help="Define a custom maximum amount of noise allowed in decoded content. 0. <= noise <= 1.", + ) + parser.add_argument( + "--version", + action="version", + version="Charset-Normalizer {} - Python {} - Unicode {} - SpeedUp {}".format( + __version__, + python_version(), + unidata_version, + "OFF" if md_module.__file__.lower().endswith(".py") else "ON", + ), + help="Show version information and exit.", + ) + + args = parser.parse_args(argv) + + if args.replace is True and args.normalize is False: + if args.files: + for my_file in args.files: + my_file.close() + print("Use --replace in addition of --normalize only.", file=sys.stderr) + return 1 + + if args.force is True and args.replace is False: + if args.files: + for my_file in args.files: + my_file.close() + print("Use --force in addition of --replace only.", file=sys.stderr) + return 1 + + if args.threshold < 0.0 or args.threshold > 1.0: + if args.files: + for my_file in args.files: + my_file.close() + print("--threshold VALUE should be between 0. AND 1.", file=sys.stderr) + return 1 + + x_ = [] + + for my_file in args.files: + matches = from_fp( + my_file, + threshold=args.threshold, + explain=args.verbose, + preemptive_behaviour=args.no_preemptive is False, + ) + + best_guess = matches.best() + + if best_guess is None: + print( + 'Unable to identify originating encoding for "{}". {}'.format( + my_file.name, + ( + "Maybe try increasing maximum amount of chaos." + if args.threshold < 1.0 + else "" + ), + ), + file=sys.stderr, + ) + x_.append( + CliDetectionResult( + abspath(my_file.name), + None, + [], + [], + "Unknown", + [], + False, + 1.0, + 0.0, + None, + True, + ) + ) + else: + cli_result = CliDetectionResult( + abspath(my_file.name), + best_guess.encoding, + best_guess.encoding_aliases, + [ + cp + for cp in best_guess.could_be_from_charset + if cp != best_guess.encoding + ], + best_guess.language, + best_guess.alphabets, + best_guess.bom, + best_guess.percent_chaos, + best_guess.percent_coherence, + None, + True, + ) + x_.append(cli_result) + + if len(matches) > 1 and args.alternatives: + for el in matches: + if el != best_guess: + x_.append( + CliDetectionResult( + abspath(my_file.name), + el.encoding, + el.encoding_aliases, + [ + cp + for cp in el.could_be_from_charset + if cp != el.encoding + ], + el.language, + el.alphabets, + el.bom, + el.percent_chaos, + el.percent_coherence, + None, + False, + ) + ) + + if args.normalize is True: + if best_guess.encoding.startswith("utf") is True: + print( + '"{}" file does not need to be normalized, as it already came from unicode.'.format( + my_file.name + ), + file=sys.stderr, + ) + if my_file.closed is False: + my_file.close() + continue + + dir_path = dirname(realpath(my_file.name)) + file_name = basename(realpath(my_file.name)) + + o_: list[str] = file_name.split(".") + + if args.replace is False: + o_.insert(-1, best_guess.encoding) + if my_file.closed is False: + my_file.close() + elif ( + args.force is False + and query_yes_no( + 'Are you sure to normalize "{}" by replacing it ?'.format( + my_file.name + ), + "no", + ) + is False + ): + if my_file.closed is False: + my_file.close() + continue + + try: + cli_result.unicode_path = join(dir_path, ".".join(o_)) + + with open(cli_result.unicode_path, "wb") as fp: + fp.write(best_guess.output()) + except OSError as e: # Defensive: + print(str(e), file=sys.stderr) + if my_file.closed is False: + my_file.close() + return 2 + + if my_file.closed is False: + my_file.close() + + if args.minimal is False: + print( + dumps( + [el.__dict__ for el in x_] if len(x_) > 1 else x_[0].__dict__, + ensure_ascii=True, + indent=4, + ) + ) + else: + for my_file in args.files: + print( + ", ".join( + [ + el.encoding or "undefined" + for el in x_ + if el.path == abspath(my_file.name) + ] + ) + ) + + return 0 + + +if __name__ == "__main__": # Defensive: + cli_detect() diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/charset_normalizer/cli/__pycache__/__init__.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/charset_normalizer/cli/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..664cf9ae461feb52b1061e7a16d7c70fc6f550f9 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/charset_normalizer/cli/__pycache__/__init__.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/charset_normalizer/cli/__pycache__/__main__.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/charset_normalizer/cli/__pycache__/__main__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7f66e7e998733dd44bc248509334dd5ceebd4230 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/charset_normalizer/cli/__pycache__/__main__.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb-1.5.9.dist-info/licenses/LICENSE b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb-1.5.9.dist-info/licenses/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..29f81d812f3e768fa89638d1f72920dbfd1413a8 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/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/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb-1.5.9.dist-info/sboms/chromadb_rust_bindings.cyclonedx.json b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb-1.5.9.dist-info/sboms/chromadb_rust_bindings.cyclonedx.json new file mode 100644 index 0000000000000000000000000000000000000000..c445dc33eb3e63faf054749e1908e79ff848c0ea --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/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": "TUlUIExpY2Vuc2UKCkNvcHlyaWdodCAoYykgWzIwMjFdIFtCb3JpcyBaaGd1Y2hldl0KClBlcm1pc3Npb24gaXMgaGVyZWJ5IGdyYW50ZWQsIGZyZWUgb2YgY2hhcmdlLCB0byBhbnkgcGVyc29uIG9idGFpbmluZyBhIGNvcHkKb2YgdGhpcyBzb2Z0d2FyZSBhbmQgYXNzb2NpYXRlZCBkb2N1bWVudGF0aW9uIGZpbGVzICh0aGUgIlNvZnR3YXJ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E9GIE9SIElOIENPTk5FQ1RJT04gV0lUSCBUSEUgU09GVFdBUkUgT1IgVEhFIFVTRSBPUiBPVEhFUiBERUFMSU5HUyBJTiBUSEUKU09GVFdBUkUu" + } + } + } + ], + "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/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/__pycache__/__init__.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3c2e02f2eaa9a68a306adc82c662891c0c886673 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/__pycache__/__init__.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/__pycache__/app.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/__pycache__/app.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7efde3c9306adf3df2daac9088357ab2bdc4d3ed Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/__pycache__/app.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/__pycache__/base_types.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/__pycache__/base_types.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f60cfe368ad40be3957e3f161af69a7d7b2b928e Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/__pycache__/base_types.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/__pycache__/config.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/__pycache__/config.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8901588b19110de0dd08bcd78a280e575d5b2551 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/__pycache__/config.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/__pycache__/errors.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/__pycache__/errors.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..28ed6a37cc0f201e624763783e8f0c21ed8ccee1 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/__pycache__/errors.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/__pycache__/serde.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/__pycache__/serde.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0ea892b4c72dcbcfb9918a0c9c2a019b4aefacad Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/__pycache__/serde.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/__pycache__/types.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/__pycache__/types.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4c1adb5aaad991a70bc1817f0535afb36d71ff1d Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/__pycache__/types.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/api/__init__.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/api/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..443289406663683317064a218b38917da2699ed2 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/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/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/api/__pycache__/__init__.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/api/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8066d19f12ec18290200bbab93563fc935df1fde Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/api/__pycache__/__init__.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/api/__pycache__/async_api.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/api/__pycache__/async_api.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9d8de423ace4fc142b45da714f99146140b6db4b Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/api/__pycache__/async_api.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/api/__pycache__/async_client.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/api/__pycache__/async_client.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..761e0a2799f65ce7377997ccd005a923517d65c9 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/api/__pycache__/async_client.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/api/__pycache__/async_fastapi.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/api/__pycache__/async_fastapi.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f18748151ffb9d3205856bf432f30a2c7174254d Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/api/__pycache__/async_fastapi.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/api/__pycache__/base_http_client.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/api/__pycache__/base_http_client.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..40c9983e8cf89d1eb785d3893f39cf4ea6800ca7 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/api/__pycache__/base_http_client.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/api/__pycache__/client.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/api/__pycache__/client.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..dae677ab9a5fac3f23dcf894a45676bc1a8a6700 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/api/__pycache__/client.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/api/__pycache__/collection_configuration.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/api/__pycache__/collection_configuration.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6f5aaab607012dfa045e1a23ccd944b3f2725021 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/api/__pycache__/collection_configuration.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/api/__pycache__/configuration.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/api/__pycache__/configuration.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..fc9c3035b98cacd5a194586d29ea600c693e8c4b Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/api/__pycache__/configuration.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/api/__pycache__/fastapi.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/api/__pycache__/fastapi.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..084923ded69bb6358a88eedf9d23fd913d37e6a7 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/api/__pycache__/fastapi.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/api/__pycache__/functions.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/api/__pycache__/functions.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..439526083b13340494b5d3c9dcced0d9451ead1d Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/api/__pycache__/functions.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/api/__pycache__/rust.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/api/__pycache__/rust.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f4a89e6f960e4a428d330c666c1754fcebbcf561 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/api/__pycache__/rust.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/api/__pycache__/segment.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/api/__pycache__/segment.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..27003c0403a3a24ceb13325e95406a1d70219892 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/api/__pycache__/segment.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/api/__pycache__/shared_system_client.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/api/__pycache__/shared_system_client.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..793211f5aa9b711e8e22249618a22996eb6e128d Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/api/__pycache__/shared_system_client.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/api/async_api.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/api/async_api.py new file mode 100644 index 0000000000000000000000000000000000000000..faabd1b69909cbf39f4edd3a725bda05ea358de0 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/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/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/api/async_client.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/api/async_client.py new file mode 100644 index 0000000000000000000000000000000000000000..b3742fdedebf1c4dc501b4c80062b2e0a3e6f8bf --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/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/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/api/async_fastapi.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/api/async_fastapi.py new file mode 100644 index 0000000000000000000000000000000000000000..64548b3c17d0016a59f0392fe3d886014ef9ebfd --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/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/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/api/base_http_client.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/api/base_http_client.py new file mode 100644 index 0000000000000000000000000000000000000000..6e7bb7f09f485ce68de9937dd6bd4cf0f7750b7c --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/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/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/api/client.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/api/client.py new file mode 100644 index 0000000000000000000000000000000000000000..ec7b73c81d529b7f79a9133c1b6aa166b4974c97 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/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/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/api/collection_configuration.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/api/collection_configuration.py new file mode 100644 index 0000000000000000000000000000000000000000..269c353b85fe084cad3a182fc7ad1d2503bc0e40 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/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/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/api/configuration.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/api/configuration.py new file mode 100644 index 0000000000000000000000000000000000000000..7a95510f2eb49ae3491185c55b81496dd9869736 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/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/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/api/fastapi.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/api/fastapi.py new file mode 100644 index 0000000000000000000000000000000000000000..0abf573cc524b09561797e9d34edc3ba178f845c --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/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/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/api/functions.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/api/functions.py new file mode 100644 index 0000000000000000000000000000000000000000..5cc4ee4812ad5e7a4f5af1185a293ac7e2edf27f --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/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/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/api/models/AsyncCollection.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/api/models/AsyncCollection.py new file mode 100644 index 0000000000000000000000000000000000000000..7d0c5e2540b41fe8de7e434984606a00cce216b0 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/api/models/AsyncCollection.py @@ -0,0 +1,550 @@ +from typing import TYPE_CHECKING, Optional, Union, List, cast + +from chromadb.api.types import ( + URI, + CollectionMetadata, + Embedding, + PyEmbedding, + Include, + IndexingStatus, + Metadata, + Document, + Image, + Where, + IDs, + GetResult, + QueryResult, + ID, + OneOrMany, + ReadLevel, + WhereDocument, + SearchResult, + DeleteResult, + maybe_cast_one_to_many, +) + +from chromadb.api.models.CollectionCommon import CollectionCommon +from chromadb.api.collection_configuration import UpdateCollectionConfiguration +from chromadb.execution.expression.plan import Search + +if TYPE_CHECKING: + from chromadb.api import AsyncServerAPI # noqa: F401 + + +class AsyncCollection(CollectionCommon["AsyncServerAPI"]): + async def add( + self, + ids: OneOrMany[ID], + embeddings: Optional[ + Union[ + OneOrMany[Embedding], + OneOrMany[PyEmbedding], + ] + ] = None, + metadatas: Optional[OneOrMany[Metadata]] = None, + documents: Optional[OneOrMany[Document]] = None, + images: Optional[OneOrMany[Image]] = None, + uris: Optional[OneOrMany[URI]] = None, + ) -> None: + """Add embeddings to the data store. + Args: + ids: The ids of the embeddings you wish to add + embeddings: The embeddings to add. If None, embeddings will be computed based on the documents or images using the embedding_function set for the Collection. Optional. + metadatas: The metadata to associate with the embeddings. When querying, you can filter on this metadata. Optional. + documents: The documents to associate with the embeddings. Optional. + images: The images to associate with the embeddings. Optional. + uris: The uris of the images to associate with the embeddings. Optional. + + Returns: + None + + Raises: + ValueError: If you don't provide either embeddings or documents + ValueError: If the length of ids, embeddings, metadatas, or documents don't match + ValueError: If you don't provide an embedding function and don't provide embeddings + ValueError: If you provide both embeddings and documents + ValueError: If you provide an id that already exists + + """ + add_request = self._validate_and_prepare_add_request( + ids=ids, + embeddings=embeddings, + metadatas=metadatas, + documents=documents, + images=images, + uris=uris, + ) + + await self._client._add( + collection_id=self.id, + ids=add_request["ids"], + embeddings=add_request["embeddings"], + metadatas=add_request["metadatas"], + documents=add_request["documents"], + uris=add_request["uris"], + tenant=self.tenant, + database=self.database, + ) + + async def count(self, read_level: ReadLevel = ReadLevel.INDEX_AND_WAL) -> int: + """Return the number of records in the collection. + + Args: + read_level: Controls whether to read from the write-ahead log (WAL): + - ReadLevel.INDEX_AND_WAL: Read from both the compacted index and WAL (default). + All committed writes will be visible. + - ReadLevel.INDEX_ONLY: Read only from the compacted index, skipping the WAL. + Faster, but recent writes that haven't been compacted may not be visible. + - ReadLevel.INDEX_AND_BOUNDED_WAL: Read from the index and up to a + server-configured number of WAL entries for bounded query latency. + + Returns: + int: The total number of embeddings added to the database + """ + return await self._client._count( + collection_id=self.id, + tenant=self.tenant, + database=self.database, + read_level=read_level, + ) + + async def get_indexing_status(self) -> IndexingStatus: + """Get the indexing status of this collection. + + Returns: + IndexingStatus: An object containing: + - num_indexed_ops: Number of user operations that have been indexed + - num_unindexed_ops: Number of user operations pending indexing + - total_ops: Total number of user operations in collection + - op_indexing_progress: Proportion of user operations that have been indexed as a float between 0 and 1 + """ + return await self._client._get_indexing_status( + collection_id=self.id, + tenant=self.tenant, + database=self.database, + ) + + async def get( + self, + ids: Optional[OneOrMany[ID]] = None, + where: Optional[Where] = None, + limit: Optional[int] = None, + offset: Optional[int] = None, + where_document: Optional[WhereDocument] = None, + include: Include = ["metadatas", "documents"], + ) -> GetResult: + """Get embeddings and their associate data from the data store. If no ids or where filter is provided returns + all embeddings up to limit starting at offset. + + Args: + ids: The ids of the embeddings to get. Optional. + where: A Where type dict used to filter results by. E.g. `{"$and": [{"color" : "red"}, {"price": {"$gte": 4.20}}]}`. Optional. + limit: The number of documents to return. Optional. + offset: The offset to start returning results from. Useful for paging results with limit. Optional. + where_document: A WhereDocument type dict used to filter by the documents. E.g. `{"$contains": "hello"}`. Optional. + include: A list of what to include in the results. Can contain `"embeddings"`, `"metadatas"`, `"documents"`. Ids are always included. Defaults to `["metadatas", "documents"]`. Optional. + + Returns: + GetResult: A GetResult object containing the results. + + """ + get_request = self._validate_and_prepare_get_request( + ids=ids, + where=where, + where_document=where_document, + include=include, + ) + + get_results = await self._client._get( + collection_id=self.id, + ids=get_request["ids"], + where=get_request["where"], + where_document=get_request["where_document"], + include=get_request["include"], + limit=limit, + offset=offset, + tenant=self.tenant, + database=self.database, + ) + + return self._transform_get_response( + response=get_results, include=get_request["include"] + ) + + async def peek(self, limit: int = 10) -> GetResult: + """Get the first few results in the database up to limit + + Args: + limit: The number of results to return. + + Returns: + GetResult: A GetResult object containing the results. + """ + return self._transform_peek_response( + await self._client._peek( + collection_id=self.id, + n=limit, + tenant=self.tenant, + database=self.database, + ) + ) + + async def query( + self, + query_embeddings: Optional[ + Union[ + OneOrMany[Embedding], + OneOrMany[PyEmbedding], + ] + ] = None, + query_texts: Optional[OneOrMany[Document]] = None, + query_images: Optional[OneOrMany[Image]] = None, + query_uris: Optional[OneOrMany[URI]] = None, + ids: Optional[OneOrMany[ID]] = None, + n_results: int = 10, + where: Optional[Where] = None, + where_document: Optional[WhereDocument] = None, + include: Include = [ + "metadatas", + "documents", + "distances", + ], + ) -> QueryResult: + """Get the n_results nearest neighbor embeddings for provided query_embeddings or query_texts. + + Args: + query_embeddings: The embeddings to get the closes neighbors of. Optional. + query_texts: The document texts to get the closes neighbors of. Optional. + query_images: The images to get the closes neighbors of. Optional. + ids: A subset of ids to search within. Optional. + n_results: The number of neighbors to return for each query_embedding or query_texts. Optional. + where: A Where type dict used to filter results by. E.g. `{"$and": [{"color" : "red"}, {"price": {"$gte": 4.20}}]}`. Optional. + where_document: A WhereDocument type dict used to filter by the documents. E.g. `{"$contains": "hello"}`. Optional. + include: A list of what to include in the results. Can contain `"embeddings"`, `"metadatas"`, `"documents"`, `"distances"`. Ids are always included. Defaults to `["metadatas", "documents", "distances"]`. Optional. + + Returns: + QueryResult: A QueryResult object containing the results. + + Raises: + ValueError: If you don't provide either query_embeddings, query_texts, or query_images + ValueError: If you provide both query_embeddings and query_texts + ValueError: If you provide both query_embeddings and query_images + ValueError: If you provide both query_texts and query_images + + """ + + query_request = self._validate_and_prepare_query_request( + query_embeddings=query_embeddings, + query_texts=query_texts, + query_images=query_images, + query_uris=query_uris, + ids=ids, + n_results=n_results, + where=where, + where_document=where_document, + include=include, + ) + + query_results = await self._client._query( + collection_id=self.id, + ids=query_request["ids"], + query_embeddings=query_request["embeddings"], + n_results=query_request["n_results"], + where=query_request["where"], + where_document=query_request["where_document"], + include=query_request["include"], + tenant=self.tenant, + database=self.database, + ) + + return self._transform_query_response( + response=query_results, include=query_request["include"] + ) + + async def modify( + self, + name: Optional[str] = None, + metadata: Optional[CollectionMetadata] = None, + configuration: Optional[UpdateCollectionConfiguration] = None, + ) -> None: + """Modify the collection name or metadata + + Args: + name: The updated name for the collection. Optional. + metadata: The updated metadata for the collection. Optional. + + Returns: + None + """ + + self._validate_modify_request(metadata) + + # Note there is a race condition here where the metadata can be updated + # but another thread sees the cached local metadata. + # TODO: fixme + await self._client._modify( + id=self.id, + new_name=name, + new_metadata=metadata, + new_configuration=configuration, + tenant=self.tenant, + database=self.database, + ) + + self._update_model_after_modify_success(name, metadata, configuration) + + async def fork( + self, + new_name: str, + ) -> "AsyncCollection": + """Fork the current collection under a new name. The returning collection should contain identical data to the current collection. + This only works for Hosted Chroma for now. + + Args: + new_name: The name of the new collection. + + Returns: + Collection: A new collection with the specified name and containing identical data to the current collection. + """ + model = await self._client._fork( + collection_id=self.id, + new_name=new_name, + tenant=self.tenant, + database=self.database, + ) + return AsyncCollection( + client=self._client, + model=model, + embedding_function=self._embedding_function, + data_loader=self._data_loader, + ) + + async def fork_count(self) -> int: + """Get the number of forks that exist for this collection. + This only works for Hosted Chroma for now. + + Returns: + int: The number of forks for this collection. + """ + return await self._client._fork_count( + collection_id=self.id, + tenant=self.tenant, + database=self.database, + ) + + async def search( + self, + searches: OneOrMany[Search], + read_level: ReadLevel = ReadLevel.INDEX_AND_WAL, + ) -> SearchResult: + """Perform hybrid search on the collection. + This is an experimental API that only works for Hosted Chroma for now. + + Args: + searches: A single Search object or a list of Search objects, each containing: + - where: Where expression for filtering + - rank: Ranking expression for hybrid search (defaults to Val(0.0)) + - limit: Limit configuration for pagination (defaults to no limit) + - select: Select configuration for keys to return (defaults to empty) + read_level: Controls whether to read from the write-ahead log (WAL): + - ReadLevel.INDEX_AND_WAL: Read from both the compacted index and WAL (default). + All committed writes will be visible. + - ReadLevel.INDEX_ONLY: Read only from the compacted index, skipping the WAL. + Faster, but recent writes that haven't been compacted may not be visible. + - ReadLevel.INDEX_AND_BOUNDED_WAL: Read from the index and up to a + server-configured number of WAL entries for bounded query latency. + + Returns: + SearchResult: Column-major format response with: + - ids: List of result IDs for each search payload + - documents: Optional documents for each payload + - embeddings: Optional embeddings for each payload + - metadatas: Optional metadata for each payload + - scores: Optional scores for each payload + - select: List of selected keys for each payload + + Raises: + NotImplementedError: For local/segment API implementations + + Examples: + # Using builder pattern with Key constants + from chromadb.execution.expression import ( + Search, Key, K, Knn, Val + ) + + # Note: K is an alias for Key, so K.DOCUMENT == Key.DOCUMENT + search = (Search() + .where((K("category") == "science") & (K("score") > 0.5)) + .rank(Knn(query=[0.1, 0.2, 0.3]) * 0.8 + Val(0.5) * 0.2) + .limit(10, offset=0) + .select(K.DOCUMENT, K.SCORE, "title")) + + # Direct construction + from chromadb.execution.expression import ( + Search, Eq, And, Gt, Knn, Limit, Select, Key + ) + + search = Search( + where=And([Eq("category", "science"), Gt("score", 0.5)]), + rank=Knn(query=[0.1, 0.2, 0.3]), + limit=Limit(offset=0, limit=10), + select=Select(keys={Key.DOCUMENT, Key.SCORE, "title"}) + ) + + # Single search + result = await collection.search(search) + + # Multiple searches at once + searches = [ + Search().where(K("type") == "article").rank(Knn(query=[0.1, 0.2])), + Search().where(K("type") == "paper").rank(Knn(query=[0.3, 0.4])) + ] + results = await collection.search(searches) + + # Skip WAL for faster queries (may miss recent uncommitted writes) + from chromadb.api.types import ReadLevel + result = await collection.search(search, read_level=ReadLevel.INDEX_ONLY) + """ + # Convert single search to list for consistent handling + searches_list = maybe_cast_one_to_many(searches) + if searches_list is None: + searches_list = [] + + # Embed any string queries in Knn objects + embedded_searches = [ + self._embed_search_string_queries(search) for search in searches_list + ] + + return await self._client._search( + collection_id=self.id, + searches=cast(List[Search], embedded_searches), + tenant=self.tenant, + database=self.database, + read_level=read_level, + ) + + async def update( + self, + ids: OneOrMany[ID], + embeddings: Optional[ + Union[ + OneOrMany[Embedding], + OneOrMany[PyEmbedding], + ] + ] = None, + metadatas: Optional[OneOrMany[Metadata]] = None, + documents: Optional[OneOrMany[Document]] = None, + images: Optional[OneOrMany[Image]] = None, + uris: Optional[OneOrMany[URI]] = None, + ) -> None: + """Update the embeddings, metadatas or documents for provided ids. + + Args: + ids: The ids of the embeddings to update + embeddings: The embeddings to update. If None, embeddings will be computed based on the documents or images using the embedding_function set for the Collection. Optional. + metadatas: The metadata to associate with the embeddings. When querying, you can filter on this metadata. Optional. + documents: The documents to associate with the embeddings. Optional. + images: The images to associate with the embeddings. Optional. + Returns: + None + """ + update_request = self._validate_and_prepare_update_request( + ids=ids, + embeddings=embeddings, + metadatas=metadatas, + documents=documents, + images=images, + uris=uris, + ) + + await self._client._update( + collection_id=self.id, + ids=update_request["ids"], + embeddings=update_request["embeddings"], + metadatas=update_request["metadatas"], + documents=update_request["documents"], + uris=update_request["uris"], + tenant=self.tenant, + database=self.database, + ) + + async def upsert( + self, + ids: OneOrMany[ID], + embeddings: Optional[ + Union[ + OneOrMany[Embedding], + OneOrMany[PyEmbedding], + ] + ] = None, + metadatas: Optional[OneOrMany[Metadata]] = None, + documents: Optional[OneOrMany[Document]] = None, + images: Optional[OneOrMany[Image]] = None, + uris: Optional[OneOrMany[URI]] = None, + ) -> None: + """Update the embeddings, metadatas or documents for provided ids, or create them if they don't exist. + + Args: + ids: The ids of the embeddings to update + embeddings: The embeddings to add. If None, embeddings will be computed based on the documents using the embedding_function set for the Collection. Optional. + metadatas: The metadata to associate with the embeddings. When querying, you can filter on this metadata. Optional. + documents: The documents to associate with the embeddings. Optional. + + Returns: + None + """ + upsert_request = self._validate_and_prepare_upsert_request( + ids=ids, + embeddings=embeddings, + metadatas=metadatas, + documents=documents, + images=images, + uris=uris, + ) + + await self._client._upsert( + collection_id=self.id, + ids=upsert_request["ids"], + embeddings=upsert_request["embeddings"], + metadatas=upsert_request["metadatas"], + documents=upsert_request["documents"], + uris=upsert_request["uris"], + tenant=self.tenant, + database=self.database, + ) + + async def delete( + self, + ids: Optional[IDs] = None, + where: Optional[Where] = None, + where_document: Optional[WhereDocument] = None, + limit: Optional[int] = None, + ) -> DeleteResult: + """Delete the embeddings based on ids and/or a where filter + + Args: + ids: The ids of the embeddings to delete + where: A Where type dict used to filter the delection by. E.g. `{"$and": [{"color" : "red"}, {"price": {"$gte": 4.20}}]}`. Optional. + where_document: A WhereDocument type dict used to filter the deletion by the document content. E.g. `{"$contains": "hello"}`. Optional. + limit: Maximum number of records to delete. Can only be used with where or where_document filters. + + Returns: + DeleteResult: A dict containing the number of records deleted. + + Raises: + ValueError: If you don't provide either ids, where, or where_document + ValueError: If limit is specified without a where or where_document clause. + """ + delete_request = self._validate_and_prepare_delete_request( + ids, where, where_document, limit=limit + ) + + return await self._client._delete( + collection_id=self.id, + ids=delete_request["ids"], + where=delete_request["where"], + where_document=delete_request["where_document"], + limit=delete_request["limit"], + tenant=self.tenant, + database=self.database, + ) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/api/models/AttachedFunction.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/api/models/AttachedFunction.py new file mode 100644 index 0000000000000000000000000000000000000000..954063385c4bb96b67920c5306220323e625588c --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/api/models/AttachedFunction.py @@ -0,0 +1,142 @@ +from typing import TYPE_CHECKING, Optional, Dict, Any +from uuid import UUID +import json + +if TYPE_CHECKING: + from chromadb.api import ServerAPI # noqa: F401 + + +class AttachedFunction: + """Represents a function attached to a collection.""" + + def __init__( + self, + client: "ServerAPI", + id: UUID, + name: str, + function_name: str, + input_collection_id: UUID, + output_collection: str, + params: Optional[Dict[str, Any]], + tenant: str, + database: str, + ): + """Initialize an AttachedFunction. + + Args: + client: The API client + id: Unique identifier for this attached function + name: Name of this attached function instance + function_name: The function name (e.g., "record_counter", "statistics") + input_collection_id: ID of the input collection + output_collection: Name of the output collection + params: Function-specific parameters + tenant: The tenant name + database: The database name + """ + self._client = client + self._id = id + self._name = name + self._function_name = function_name + self._input_collection_id = input_collection_id + self._output_collection = output_collection + self._params = params + self._tenant = tenant + self._database = database + + @property + def id(self) -> UUID: + """The unique identifier of this attached function.""" + return self._id + + @property + def name(self) -> str: + """The name of this attached function instance.""" + return self._name + + @property + def function_name(self) -> str: + """The function name.""" + return self._function_name + + @property + def input_collection_id(self) -> UUID: + """The ID of the input collection.""" + return self._input_collection_id + + @property + def output_collection(self) -> str: + """The name of the output collection.""" + return self._output_collection + + @property + def params(self) -> Optional[Dict[str, Any]]: + """The function parameters.""" + return self._params + + @staticmethod + def _normalize_params(params: Optional[Any]) -> Dict[str, Any]: + """Normalize params to a consistent dict format. + + Handles None, empty strings, JSON strings, and dicts. + """ + if params is None: + return {} + if isinstance(params, str): + try: + result = json.loads(params) if params else {} + return result if isinstance(result, dict) else {} + except json.JSONDecodeError: + return {} + if isinstance(params, dict): + return params + return {} + + def __repr__(self) -> str: + return ( + f"AttachedFunction(id={self._id}, name='{self._name}', " + f"function_name='{self._function_name}', " + f"input_collection_id={self._input_collection_id}, " + f"output_collection='{self._output_collection}')" + ) + + def __eq__(self, other: object) -> bool: + """Compare two AttachedFunction objects for equality.""" + if not isinstance(other, AttachedFunction): + return False + + # Normalize params: handle None, {}, and JSON strings + self_params = self._normalize_params(self._params) + other_params = self._normalize_params(other._params) + + return ( + self._id == other._id + and self._name == other._name + and self._function_name == other._function_name + and self._input_collection_id == other._input_collection_id + and self._output_collection == other._output_collection + and self_params == other_params + and self._tenant == other._tenant + and self._database == other._database + ) + + def __hash__(self) -> int: + """Return hash of the AttachedFunction.""" + # Normalize params using the same logic as __eq__ + normalized_params = self._normalize_params(self._params) + params_tuple = ( + tuple(sorted(normalized_params.items())) if normalized_params else () + ) + + return hash( + ( + self._id, + self._name, + self._function_name, + self._input_collection_id, + self._output_collection, + params_tuple, + self._tenant, + self._database, + ) + ) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/api/models/Collection.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/api/models/Collection.py new file mode 100644 index 0000000000000000000000000000000000000000..dfd1c9d7681ba6098695de3dfdc7acaabe96a721 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/api/models/Collection.py @@ -0,0 +1,663 @@ +from typing import TYPE_CHECKING, Optional, Union, List, cast, Dict, Any, Tuple + +from chromadb.api.models.CollectionCommon import CollectionCommon +from chromadb.api.types import ( + URI, + CollectionMetadata, + Embedding, + PyEmbedding, + Include, + IndexingStatus, + Metadata, + Document, + Image, + Where, + IDs, + GetResult, + QueryResult, + ID, + OneOrMany, + ReadLevel, + WhereDocument, + SearchResult, + DeleteResult, + maybe_cast_one_to_many, +) +from chromadb.api.collection_configuration import UpdateCollectionConfiguration +from chromadb.execution.expression.plan import Search + +import logging + +from chromadb.api.functions import Function + +if TYPE_CHECKING: + from chromadb.api.models.AttachedFunction import AttachedFunction + +logger = logging.getLogger(__name__) + +if TYPE_CHECKING: + from chromadb.api import ServerAPI # noqa: F401 + + +class Collection(CollectionCommon["ServerAPI"]): + def count(self, read_level: ReadLevel = ReadLevel.INDEX_AND_WAL) -> int: + """Return the number of records in the collection. + + Args: + read_level: Controls whether to read from the write-ahead log (WAL): + - ReadLevel.INDEX_AND_WAL: Read from both the compacted index and WAL (default). + All committed writes will be visible. + - ReadLevel.INDEX_ONLY: Read only from the compacted index, skipping the WAL. + Faster, but recent writes that haven't been compacted may not be visible. + - ReadLevel.INDEX_AND_BOUNDED_WAL: Read from the index and up to a + server-configured number of WAL entries for bounded query latency. + """ + return self._client._count( + collection_id=self.id, + tenant=self.tenant, + database=self.database, + read_level=read_level, + ) + + def get_indexing_status(self) -> IndexingStatus: + """Get the indexing status of this collection. + + Returns: + IndexingStatus: An object containing: + - num_indexed_ops: Number of user operations that have been indexed + - num_unindexed_ops: Number of user operations pending indexing + - total_ops: Total number of user operations in collection + - op_indexing_progress: Proportion of user operations that have been indexed as a float between 0 and 1 + """ + return self._client._get_indexing_status( + collection_id=self.id, + tenant=self.tenant, + database=self.database, + ) + + def add( + self, + ids: OneOrMany[ID], + embeddings: Optional[ + Union[ + OneOrMany[Embedding], + OneOrMany[PyEmbedding], + ] + ] = None, + metadatas: Optional[OneOrMany[Metadata]] = None, + documents: Optional[OneOrMany[Document]] = None, + images: Optional[OneOrMany[Image]] = None, + uris: Optional[OneOrMany[URI]] = None, + ) -> None: + """Add records to the collection. + + Args: + ids: Record IDs to add. + embeddings: Embeddings to add. If None, embeddings are computed. + metadatas: Optional metadata for each record. + documents: Optional documents for each record. + images: Optional images for each record. + uris: Optional URIs for loading images. + + Raises: + ValueError: If embeddings and documents are both missing. + ValueError: If embeddings and documents are both provided. + ValueError: If lengths of provided fields do not match. + ValueError: If an ID already exists. + """ + + add_request = self._validate_and_prepare_add_request( + ids=ids, + embeddings=embeddings, + metadatas=metadatas, + documents=documents, + images=images, + uris=uris, + ) + + self._client._add( + collection_id=self.id, + ids=add_request["ids"], + embeddings=add_request["embeddings"], + metadatas=add_request["metadatas"], + documents=add_request["documents"], + uris=add_request["uris"], + tenant=self.tenant, + database=self.database, + ) + + def get( + self, + ids: Optional[OneOrMany[ID]] = None, + where: Optional[Where] = None, + limit: Optional[int] = None, + offset: Optional[int] = None, + where_document: Optional[WhereDocument] = None, + include: Include = ["metadatas", "documents"], + ) -> GetResult: + """Retrieve records from the collection. + + If no filters are provided, returns records up to ``limit`` starting at + ``offset``. + + Args: + ids: If provided, only return records with these IDs. + where: A Where filter used to filter based on metadata values. + limit: Maximum number of results to return. + offset: Number of results to skip before returning. + where_document: A WhereDocument filter used to filter based on K.DOCUMENT. + include: Fields to include in results. Can contain "embeddings", "metadatas", "documents", "uris". Defaults to "metadatas" and "documents". + + Returns: + GetResult: Retrieved records and requested fields as a GetResult object. + """ + get_request = self._validate_and_prepare_get_request( + ids=ids, + where=where, + where_document=where_document, + include=include, + ) + + get_results = self._client._get( + collection_id=self.id, + ids=get_request["ids"], + where=get_request["where"], + where_document=get_request["where_document"], + include=get_request["include"], + limit=limit, + offset=offset, + tenant=self.tenant, + database=self.database, + ) + return self._transform_get_response( + response=get_results, include=get_request["include"] + ) + + def peek(self, limit: int = 10) -> GetResult: + """Return the first ``limit`` records from the collection. + + Args: + limit: Maximum number of records to return. + + Returns: + GetResult: Retrieved records and requested fields. + """ + return self._transform_peek_response( + self._client._peek( + collection_id=self.id, + n=limit, + tenant=self.tenant, + database=self.database, + ) + ) + + def query( + self, + query_embeddings: Optional[ + Union[ + OneOrMany[Embedding], + OneOrMany[PyEmbedding], + ] + ] = None, + query_texts: Optional[OneOrMany[Document]] = None, + query_images: Optional[OneOrMany[Image]] = None, + query_uris: Optional[OneOrMany[URI]] = None, + ids: Optional[OneOrMany[ID]] = None, + n_results: int = 10, + where: Optional[Where] = None, + where_document: Optional[WhereDocument] = None, + include: Include = [ + "metadatas", + "documents", + "distances", + ], + ) -> QueryResult: + """Query for the K nearest neighbor records in the collection. + + This is a batch query API. Multiple queries can be performed at once + by providing multiple embeddings, texts, or images. + + >>> query_1 = [0.1, 0.2, 0.3] + >>> query_2 = [0.4, 0.5, 0.6] + >>> results = collection.query( + >>> query_embeddings=[query_1, query_2], + >>> n_results=10, + >>> ) + + If query_texts, query_images, or query_uris are provided, the collection's + embedding function will be used to create embeddings before querying + the API. + + The `ids`, `where`, `where_document`, and `include` parameters are applied + to all queries. + + Args: + query_embeddings: Raw embeddings to query for. + query_texts: Documents to embed and query against. + query_images: Images to embed and query against. + query_uris: URIs to be loaded and embedded. + ids: Optional subset of IDs to search within. + n_results: Number of neighbors to return per query. + where: Metadata filter. + where_document: Document content filter. + include: Fields to include in results. Can contain "embeddings", "metadatas", "documents", "uris", "distances". Defaults to "metadatas", "documents", "distances". + + Returns: + QueryResult: Nearest neighbor results. + + Raises: + ValueError: If no query input is provided. + ValueError: If multiple query input types are provided. + """ + + query_request = self._validate_and_prepare_query_request( + query_embeddings=query_embeddings, + query_texts=query_texts, + query_images=query_images, + query_uris=query_uris, + ids=ids, + n_results=n_results, + where=where, + where_document=where_document, + include=include, + ) + + query_results = self._client._query( + collection_id=self.id, + ids=query_request["ids"], + query_embeddings=query_request["embeddings"], + n_results=query_request["n_results"], + where=query_request["where"], + where_document=query_request["where_document"], + include=query_request["include"], + tenant=self.tenant, + database=self.database, + ) + + return self._transform_query_response( + response=query_results, include=query_request["include"] + ) + + def modify( + self, + name: Optional[str] = None, + metadata: Optional[CollectionMetadata] = None, + configuration: Optional[UpdateCollectionConfiguration] = None, + ) -> None: + """Update collection name, metadata, or configuration. + + Args: + name: New collection name. + metadata: New metadata for the collection. + configuration: New configuration for the collection. + """ + + self._validate_modify_request(metadata) + + # Note there is a race condition here where the metadata can be updated + # but another thread sees the cached local metadata. + # TODO: fixme + self._client._modify( + id=self.id, + new_name=name, + new_metadata=metadata, + new_configuration=configuration, + tenant=self.tenant, + database=self.database, + ) + + self._update_model_after_modify_success(name, metadata, configuration) + + def fork( + self, + new_name: str, + ) -> "Collection": + """Fork the current collection under a new name. The returning collection should contain identical data to the current collection. + This only works for Hosted Chroma for now. + + Args: + new_name: The name of the new collection. + + Returns: + Collection: A new collection with the specified name and containing identical data to the current collection. + """ + model = self._client._fork( + collection_id=self.id, + new_name=new_name, + tenant=self.tenant, + database=self.database, + ) + return Collection( + client=self._client, + model=model, + embedding_function=self._embedding_function, + data_loader=self._data_loader, + ) + + def fork_count(self) -> int: + """Get the number of forks that exist for this collection. + This only works for Hosted Chroma for now. + + Returns: + int: The number of forks for this collection. + """ + return self._client._fork_count( + collection_id=self.id, + tenant=self.tenant, + database=self.database, + ) + + def search( + self, + searches: OneOrMany[Search], + read_level: ReadLevel = ReadLevel.INDEX_AND_WAL, + ) -> SearchResult: + """Perform hybrid search on the collection. + This is an experimental API that only works for distributed and hosted Chroma for now. + + Args: + searches: A single Search object or a list of Search objects, each containing: + - where: Where expression for filtering + - rank: Ranking expression for hybrid search (defaults to Val(0.0)) + - limit: Limit configuration for pagination (defaults to no limit) + - select: Select configuration for keys to return (defaults to empty) + read_level: Controls whether to read from the write-ahead log (WAL): + - ReadLevel.INDEX_AND_WAL: Read from both the compacted index and WAL (default). + All committed writes will be visible. + - ReadLevel.INDEX_ONLY: Read only from the compacted index, skipping the WAL. + Faster, but recent writes that haven't been compacted may not be visible. + - ReadLevel.INDEX_AND_BOUNDED_WAL: Read from the index and up to a + server-configured number of WAL entries for bounded query latency. + + Returns: + SearchResult: Column-major format response with: + - ids: List of result IDs for each search payload + - documents: Optional documents for each payload + - embeddings: Optional embeddings for each payload + - metadatas: Optional metadata for each payload + - scores: Optional scores for each payload + - select: List of selected keys for each payload + + Raises: + NotImplementedError: For local/segment API implementations + + Examples: + # Using builder pattern with Key constants + from chromadb.execution.expression import ( + Search, Key, K, Knn, Val + ) + + # Note: K is an alias for Key, so K.DOCUMENT == Key.DOCUMENT + search = (Search() + .where((K("category") == "science") & (K("score") > 0.5)) + .rank(Knn(query=[0.1, 0.2, 0.3]) * 0.8 + Val(0.5) * 0.2) + .limit(10, offset=0) + .select(K.DOCUMENT, K.SCORE, "title")) + + # Direct construction + from chromadb.execution.expression import ( + Search, Eq, And, Gt, Knn, Limit, Select, Key + ) + + search = Search( + where=And([Eq("category", "science"), Gt("score", 0.5)]), + rank=Knn(query=[0.1, 0.2, 0.3]), + limit=Limit(offset=0, limit=10), + select=Select(keys={Key.DOCUMENT, Key.SCORE, "title"}) + ) + + # Single search + result = collection.search(search) + + # Multiple searches at once + searches = [ + Search().where(K("type") == "article").rank(Knn(query=[0.1, 0.2])), + Search().where(K("type") == "paper").rank(Knn(query=[0.3, 0.4])) + ] + results = collection.search(searches) + + # Skip WAL for faster queries (may miss recent uncommitted writes) + from chromadb.api.types import ReadLevel + result = collection.search(search, read_level=ReadLevel.INDEX_ONLY) + """ + # Convert single search to list for consistent handling + searches_list = maybe_cast_one_to_many(searches) + if searches_list is None: + searches_list = [] + + # Embed any string queries in Knn objects + embedded_searches = [ + self._embed_search_string_queries(search) for search in searches_list + ] + + return self._client._search( + collection_id=self.id, + searches=cast(List[Search], embedded_searches), + tenant=self.tenant, + database=self.database, + read_level=read_level, + ) + + def update( + self, + ids: OneOrMany[ID], + embeddings: Optional[ + Union[ + OneOrMany[Embedding], + OneOrMany[PyEmbedding], + ] + ] = None, + metadatas: Optional[OneOrMany[Metadata]] = None, + documents: Optional[OneOrMany[Document]] = None, + images: Optional[OneOrMany[Image]] = None, + uris: Optional[OneOrMany[URI]] = None, + ) -> None: + """Update existing records by ID. + + Records are provided in columnar format. If provided, the `embeddings`, `metadatas`, `documents`, and `uris` lists must be the same length. + Entries in each list correspond to the same record. + + >>> ids = ["id1", "id2", "id3"] + >>> embeddings = [[0.1, 0.2, 0.3], [0.4, 0.5, 0.6], [0.7, 0.8, 0.9]] + >>> metadatas = [{"key": "value"}, {"key": "value"}, {"key": "value"}] + >>> documents = ["document1", "document2", "document3"] + >>> uris = ["uri1", "uri2", "uri3"] + >>> collection.update(ids, embeddings, metadatas, documents, uris) + + If `embeddings` are not provided, the embeddings will be computed based on `documents` using the collection's embedding function. + + Args: + ids: Record IDs to update. + embeddings: Updated embeddings. If None, embeddings are computed. + metadatas: Updated metadata. + documents: Updated documents. + images: Updated images. + uris: Updated URIs for loading images. + """ + update_request = self._validate_and_prepare_update_request( + ids=ids, + embeddings=embeddings, + metadatas=metadatas, + documents=documents, + images=images, + uris=uris, + ) + + self._client._update( + collection_id=self.id, + ids=update_request["ids"], + embeddings=update_request["embeddings"], + metadatas=update_request["metadatas"], + documents=update_request["documents"], + uris=update_request["uris"], + tenant=self.tenant, + database=self.database, + ) + + def upsert( + self, + ids: OneOrMany[ID], + embeddings: Optional[ + Union[ + OneOrMany[Embedding], + OneOrMany[PyEmbedding], + ] + ] = None, + metadatas: Optional[OneOrMany[Metadata]] = None, + documents: Optional[OneOrMany[Document]] = None, + images: Optional[OneOrMany[Image]] = None, + uris: Optional[OneOrMany[URI]] = None, + ) -> None: + """Create or update records by ID. + + Args: + ids: Record IDs to upsert. + embeddings: Embeddings to add or update. If None, embeddings are computed. + metadatas: Metadata to add or update. + documents: Documents to add or update. + images: Images to add or update. + uris: URIs for loading images. + """ + upsert_request = self._validate_and_prepare_upsert_request( + ids=ids, + embeddings=embeddings, + metadatas=metadatas, + documents=documents, + images=images, + uris=uris, + ) + + self._client._upsert( + collection_id=self.id, + ids=upsert_request["ids"], + embeddings=upsert_request["embeddings"], + metadatas=upsert_request["metadatas"], + documents=upsert_request["documents"], + uris=upsert_request["uris"], + tenant=self.tenant, + database=self.database, + ) + + def delete( + self, + ids: Optional[IDs] = None, + where: Optional[Where] = None, + where_document: Optional[WhereDocument] = None, + limit: Optional[int] = None, + ) -> DeleteResult: + """Delete records by ID or filters. + + All documents that match the `ids` or `where` and `where_document` filters will be deleted. + + Args: + ids: Record IDs to delete. + where: Metadata filter. + where_document: Document content filter. + limit: Maximum number of records to delete. Can only be used with where or where_document filters. + + Returns: + DeleteResult: A dict containing the number of records deleted. + + Raises: + ValueError: If no IDs or filters are provided. + ValueError: If limit is specified without a where or where_document clause. + """ + delete_request = self._validate_and_prepare_delete_request( + ids, where, where_document, limit=limit + ) + + return self._client._delete( + collection_id=self.id, + ids=delete_request["ids"], + where=delete_request["where"], + where_document=delete_request["where_document"], + limit=delete_request["limit"], + tenant=self.tenant, + database=self.database, + ) + + def attach_function( + self, + function: Function, + name: str, + output_collection: str, + params: Optional[Dict[str, Any]] = None, + ) -> Tuple["AttachedFunction", bool]: + """Attach a function to this collection. + + Args: + function: A Function enum value (e.g., STATISTICS_FUNCTION, RECORD_COUNTER_FUNCTION) + name: Unique name for this attached function + output_collection: Name of the collection where function output will be stored + params: Optional dictionary with function-specific parameters + + Returns: + Tuple of (AttachedFunction, created) where created is True if newly created, + False if already existed (idempotent request) + + Example: + >>> from chromadb.api.functions import STATISTICS_FUNCTION + >>> attached_fn = collection.attach_function( + ... function=STATISTICS_FUNCTION, + ... name="mycoll_stats_fn", + ... output_collection="mycoll_stats", + ... ) + >>> if created: + ... print("New function attached") + ... else: + ... print("Function already existed") + """ + function_id = function.value if isinstance(function, Function) else function + return self._client.attach_function( + function_id=function_id, + name=name, + input_collection_id=self.id, + output_collection=output_collection, + params=params, + tenant=self.tenant, + database=self.database, + ) + + def get_attached_function(self, name: str) -> "AttachedFunction": + """Get an attached function by name for this collection. + + Args: + name: Name of the attached function + + Returns: + AttachedFunction: The attached function object + + Raises: + NotFoundError: If the attached function doesn't exist + """ + return self._client.get_attached_function( + name=name, + input_collection_id=self.id, + tenant=self.tenant, + database=self.database, + ) + + def detach_function( + self, + name: str, + delete_output_collection: bool = False, + ) -> bool: + """Detach a function from this collection. + + Args: + name: The name of the attached function + delete_output_collection: Whether to also delete the output collection. Defaults to False. + + Returns: + bool: True if successful + + Example: + >>> success = collection.detach_function("my_function", delete_output_collection=True) + """ + return self._client.detach_function( + name=name, + input_collection_id=self.id, + delete_output=delete_output_collection, + tenant=self.tenant, + database=self.database, + ) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/api/models/CollectionCommon.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/api/models/CollectionCommon.py new file mode 100644 index 0000000000000000000000000000000000000000..438db7bbb8c040c94d6b5c1e1a2e28b142a2b423 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/api/models/CollectionCommon.py @@ -0,0 +1,1039 @@ +import functools +from typing import ( + TYPE_CHECKING, + Callable, + Dict, + Generic, + Optional, + Any, + Set, + TypeVar, + Union, + cast, + List, +) +from chromadb.types import Metadata +import numpy as np +from uuid import UUID + +from chromadb.api.types import ( + URI, + Schema, + SparseVectorIndexConfig, + URIs, + AddRequest, + BaseRecordSet, + CollectionMetadata, + DataLoader, + DeleteRequest, + Embedding, + Embeddings, + FilterSet, + GetRequest, + PyEmbedding, + Embeddable, + GetResult, + Include, + Loadable, + Document, + Image, + QueryRequest, + QueryResult, + IDs, + EmbeddingFunction, + SparseEmbeddingFunction, + ID, + OneOrMany, + UpdateRequest, + UpsertRequest, + get_default_embeddable_record_set_fields, + maybe_cast_one_to_many, + normalize_base_record_set, + normalize_insert_record_set, + validate_base_record_set, + validate_ids, + validate_include, + validate_insert_record_set, + validate_metadata, + validate_metadatas, + validate_embedding_function, + validate_sparse_embedding_function, + validate_n_results, + validate_record_set_contains_any, + validate_record_set_for_embedding, + validate_filter_set, + DefaultEmbeddingFunction, + EMBEDDING_KEY, + DOCUMENT_KEY, +) +from chromadb.api.collection_configuration import ( + UpdateCollectionConfiguration, + overwrite_collection_configuration, + load_collection_configuration_from_json, + CollectionConfiguration, +) + +# TODO: We should rename the types in chromadb.types to be Models where +# appropriate. This will help to distinguish between manipulation objects +# which are essentially API views. And the actual data models which are +# stored / retrieved / transmitted. +from chromadb.types import Collection as CollectionModel, Where, WhereDocument +import logging + +logger = logging.getLogger(__name__) + +if TYPE_CHECKING: + from chromadb.api import ServerAPI, AsyncServerAPI + +ClientT = TypeVar("ClientT", "ServerAPI", "AsyncServerAPI") + +T = TypeVar("T") + + +def validation_context(name: str) -> Callable[[Callable[..., T]], Callable[..., T]]: + """A decorator that wraps a method with a try-except block that catches + exceptions and adds the method name to the error message. This allows us to + provide more context when an error occurs, without rewriting validators. + """ + + def decorator(func: Callable[..., T]) -> Callable[..., T]: + @functools.wraps(func) + def wrapper(self: Any, *args: Any, **kwargs: Any) -> T: + try: + return func(self, *args, **kwargs) + except Exception as e: + msg = f"{str(e)} in {name}." + # add the rest of the args to the error message if they exist + e.args = (msg,) + e.args[1:] if e.args else () + # raise the same error that was caught with the modified message + raise + + return wrapper + + return decorator + + +class CollectionCommon(Generic[ClientT]): + _model: CollectionModel + _client: ClientT + _embedding_function: Optional[EmbeddingFunction[Embeddable]] + _data_loader: Optional[DataLoader[Loadable]] + + def __init__( + self, + client: ClientT, + model: CollectionModel, + embedding_function: Optional[ + EmbeddingFunction[Embeddable] + ] = DefaultEmbeddingFunction(), # type: ignore + data_loader: Optional[DataLoader[Loadable]] = None, + ): + """Initializes a new instance of the Collection class.""" + + self._client = client + self._model = model + + # Check to make sure the embedding function has the right signature, as defined by the EmbeddingFunction protocol + if embedding_function is not None: + validate_embedding_function(embedding_function) + + self._embedding_function = embedding_function + self._data_loader = data_loader + + # Expose the model properties as read-only properties on the Collection class + + @property + def id(self) -> UUID: + return self._model.id + + @property + def name(self) -> str: + return self._model.name + + @property + def configuration(self) -> CollectionConfiguration: + return load_collection_configuration_from_json(self._model.configuration_json) + + @property + def configuration_json(self) -> Dict[str, Any]: + return self._model.configuration_json + + @property + def schema(self) -> Optional[Schema]: + return Schema.deserialize_from_json( + self._model.serialized_schema if self._model.serialized_schema else {} + ) + + @property + def metadata(self) -> CollectionMetadata: + return cast(CollectionMetadata, self._model.metadata) + + @property + def tenant(self) -> str: + return self._model.tenant + + @property + def database(self) -> str: + return self._model.database + + def __eq__(self, other: object) -> bool: + if not isinstance(other, CollectionCommon): + return False + id_match = self.id == other.id + name_match = self.name == other.name + configuration_match = self.configuration_json == other.configuration_json + schema_match = self.schema == other.schema + metadata_match = self.metadata == other.metadata + tenant_match = self.tenant == other.tenant + database_match = self.database == other.database + embedding_function_match = self._embedding_function == other._embedding_function + data_loader_match = self._data_loader == other._data_loader + return ( + id_match + and name_match + and configuration_match + and schema_match + and metadata_match + and tenant_match + and database_match + and embedding_function_match + and data_loader_match + ) + + def __repr__(self) -> str: + return f"Collection(name={self.name})" + + def get_model(self) -> CollectionModel: + return self._model + + @validation_context("add") + def _validate_and_prepare_add_request( + self, + ids: OneOrMany[ID], + embeddings: Optional[ + Union[ + OneOrMany[Embedding], + OneOrMany[PyEmbedding], + ] + ], + metadatas: Optional[OneOrMany[Metadata]], + documents: Optional[OneOrMany[Document]], + images: Optional[OneOrMany[Image]], + uris: Optional[OneOrMany[URI]], + ) -> AddRequest: + # Unpack + add_records = normalize_insert_record_set( + ids=ids, + embeddings=embeddings, + metadatas=metadatas, + documents=documents, + images=images, + uris=uris, + ) + + # Validate + validate_insert_record_set(record_set=add_records) + validate_record_set_contains_any(record_set=add_records, contains_any={"ids"}) + + # Prepare + if add_records["embeddings"] is None: + validate_record_set_for_embedding(record_set=add_records) + add_embeddings = self._embed_record_set(record_set=add_records) + else: + add_embeddings = add_records["embeddings"] + + add_metadatas = self._apply_sparse_embeddings_to_metadatas( + add_records["metadatas"], add_records["documents"] + ) + + return AddRequest( + ids=add_records["ids"], + embeddings=add_embeddings, + metadatas=add_metadatas, + documents=add_records["documents"], + uris=add_records["uris"], + ) + + @validation_context("get") + def _validate_and_prepare_get_request( + self, + ids: Optional[OneOrMany[ID]], + where: Optional[Where], + where_document: Optional[WhereDocument], + include: Include, + ) -> GetRequest: + # Unpack + unpacked_ids: Optional[IDs] = maybe_cast_one_to_many(target=ids) + filters = FilterSet(where=where, where_document=where_document) + + # Validate + if unpacked_ids is not None: + validate_ids(ids=unpacked_ids) + + validate_filter_set(filter_set=filters) + validate_include(include=include, dissalowed=["distances"]) + + if "data" in include and self._data_loader is None: + raise ValueError( + "You must set a data loader on the collection if loading from URIs." + ) + + # Prepare + request_include = include + # We need to include uris in the result from the API to load datas + if "data" in include and "uris" not in include: + request_include.append("uris") + + return GetRequest( + ids=unpacked_ids, + where=filters["where"], + where_document=filters["where_document"], + include=request_include, + ) + + @validation_context("query") + def _validate_and_prepare_query_request( + self, + query_embeddings: Optional[ + Union[ + OneOrMany[Embedding], + OneOrMany[PyEmbedding], + ] + ], + query_texts: Optional[OneOrMany[Document]], + query_images: Optional[OneOrMany[Image]], + query_uris: Optional[OneOrMany[URI]], + ids: Optional[OneOrMany[ID]], + n_results: int, + where: Optional[Where], + where_document: Optional[WhereDocument], + include: Include, + ) -> QueryRequest: + # Unpack + query_records = normalize_base_record_set( + embeddings=query_embeddings, + documents=query_texts, + images=query_images, + uris=query_uris, + ) + + filter_ids = maybe_cast_one_to_many(ids) + + filters = FilterSet( + where=where, + where_document=where_document, + ) + + # Validate + validate_base_record_set(record_set=query_records) + validate_filter_set(filter_set=filters) + validate_include(include=include) + validate_n_results(n_results=n_results) + + # Prepare + if query_records["embeddings"] is None: + validate_record_set_for_embedding(record_set=query_records) + request_embeddings = self._embed_record_set( + record_set=query_records, is_query=True + ) + else: + request_embeddings = query_records["embeddings"] + + request_where = filters["where"] + request_where_document = filters["where_document"] + + # We need to manually include uris in the result from the API to load datas + request_include = include + if "data" in request_include and "uris" not in request_include: + request_include.append("uris") + + return QueryRequest( + embeddings=request_embeddings, + ids=filter_ids, + where=request_where, + where_document=request_where_document, + include=request_include, + n_results=n_results, + ) + + @validation_context("update") + def _validate_and_prepare_update_request( + self, + ids: OneOrMany[ID], + embeddings: Optional[ + Union[ + OneOrMany[Embedding], + OneOrMany[PyEmbedding], + ] + ], + metadatas: Optional[OneOrMany[Metadata]], + documents: Optional[OneOrMany[Document]], + images: Optional[OneOrMany[Image]], + uris: Optional[OneOrMany[URI]], + ) -> UpdateRequest: + # Unpack + update_records = normalize_insert_record_set( + ids=ids, + embeddings=embeddings, + metadatas=metadatas, + documents=documents, + images=images, + uris=uris, + ) + + # Validate + validate_insert_record_set(record_set=update_records) + + # Prepare + if update_records["embeddings"] is None: + # TODO: Handle URI updates. + if ( + update_records["documents"] is not None + or update_records["images"] is not None + ): + validate_record_set_for_embedding( + update_records, embeddable_fields={"documents", "images"} + ) + update_embeddings = self._embed_record_set(record_set=update_records) + else: + update_embeddings = None + else: + update_embeddings = update_records["embeddings"] + + update_metadatas = self._apply_sparse_embeddings_to_metadatas( + update_records["metadatas"], update_records["documents"] + ) + + return UpdateRequest( + ids=update_records["ids"], + embeddings=update_embeddings, + metadatas=update_metadatas, + documents=update_records["documents"], + uris=update_records["uris"], + ) + + @validation_context("upsert") + def _validate_and_prepare_upsert_request( + self, + ids: OneOrMany[ID], + embeddings: Optional[ + Union[ + OneOrMany[Embedding], + OneOrMany[PyEmbedding], + ] + ] = None, + metadatas: Optional[OneOrMany[Metadata]] = None, + documents: Optional[OneOrMany[Document]] = None, + images: Optional[OneOrMany[Image]] = None, + uris: Optional[OneOrMany[URI]] = None, + ) -> UpsertRequest: + # Unpack + upsert_records = normalize_insert_record_set( + ids=ids, + embeddings=embeddings, + metadatas=metadatas, + documents=documents, + images=images, + uris=uris, + ) + + # Validate + validate_insert_record_set(record_set=upsert_records) + + # Prepare + if upsert_records["embeddings"] is None: + validate_record_set_for_embedding( + record_set=upsert_records, embeddable_fields={"documents", "images"} + ) + upsert_embeddings = self._embed_record_set(record_set=upsert_records) + else: + upsert_embeddings = upsert_records["embeddings"] + + upsert_metadatas = self._apply_sparse_embeddings_to_metadatas( + upsert_records["metadatas"], upsert_records["documents"] + ) + + return UpsertRequest( + ids=upsert_records["ids"], + metadatas=upsert_metadatas, + embeddings=upsert_embeddings, + documents=upsert_records["documents"], + uris=upsert_records["uris"], + ) + + @validation_context("delete") + def _validate_and_prepare_delete_request( + self, + ids: Optional[IDs], + where: Optional[Where], + where_document: Optional[WhereDocument], + limit: Optional[int] = None, + ) -> DeleteRequest: + if ids is None and where is None and where_document is None: + raise ValueError( + "At least one of ids, where, or where_document must be provided" + ) + + if limit is not None: + if not isinstance(limit, int) or isinstance(limit, bool): + raise TypeError("limit must be a non-negative integer") + if limit < 0: + raise ValueError("limit must be a non-negative integer") + + if limit is not None and where is None and where_document is None: + raise ValueError( + "limit can only be specified when a where or where_document clause is provided" + ) + + # Unpack + if ids is not None: + request_ids = cast(IDs, maybe_cast_one_to_many(ids)) + else: + request_ids = None + filters = FilterSet(where=where, where_document=where_document) + + # Validate + if request_ids is not None: + validate_ids(ids=request_ids) + validate_filter_set(filter_set=filters) + + return DeleteRequest( + ids=request_ids, where=where, where_document=where_document, limit=limit + ) + + def _transform_peek_response(self, response: GetResult) -> GetResult: + if response["embeddings"] is not None: + response["embeddings"] = np.array(response["embeddings"]) + + return response + + def _transform_get_response( + self, response: GetResult, include: Include + ) -> GetResult: + if ( + "data" in include + and self._data_loader is not None + and response["uris"] is not None + ): + response["data"] = self._data_loader(response["uris"]) + + if "embeddings" in include: + response["embeddings"] = np.array(response["embeddings"]) + + # Remove URIs from the result if they weren't requested + if "uris" not in include: + response["uris"] = None + + return response + + def _transform_query_response( + self, response: QueryResult, include: Include + ) -> QueryResult: + if ( + "data" in include + and self._data_loader is not None + and response["uris"] is not None + ): + response["data"] = [self._data_loader(uris) for uris in response["uris"]] + + if "embeddings" in include and response["embeddings"] is not None: + response["embeddings"] = [ + np.array(embedding) for embedding in response["embeddings"] + ] + + # Remove URIs from the result if they weren't requested + if "uris" not in include: + response["uris"] = None + + return response + + def _validate_modify_request(self, metadata: Optional[CollectionMetadata]) -> None: + if metadata is not None: + validate_metadata(metadata) + if "hnsw:space" in metadata: + raise ValueError( + "Changing the distance function of a collection once it is created is not supported currently." + ) + + def _update_model_after_modify_success( + self, + name: Optional[str], + metadata: Optional[CollectionMetadata], + configuration: Optional[UpdateCollectionConfiguration], + ) -> None: + if name: + self._model["name"] = name + if metadata: + self._model["metadata"] = metadata + if configuration: + self._model.set_configuration( + overwrite_collection_configuration( + self._model.get_configuration(), configuration + ) + ) + + # If schema exists, also update it with the configuration changes + if self.schema: + from chromadb.api.collection_configuration import ( + update_schema_from_collection_configuration, + ) + + updated_schema = update_schema_from_collection_configuration( + self.schema, configuration + ) + self._model["serialized_schema"] = updated_schema.serialize_to_json() + + def _get_sparse_embedding_targets(self) -> Dict[str, "SparseVectorIndexConfig"]: + schema = self.schema + if schema is None: + return {} + + targets: Dict[str, "SparseVectorIndexConfig"] = {} + for key, value_types in schema.keys.items(): + if value_types.sparse_vector is None: + continue + sparse_index = value_types.sparse_vector.sparse_vector_index + if sparse_index is None or not sparse_index.enabled: + continue + config = sparse_index.config + if config.embedding_function is None or config.source_key is None: + continue + targets[key] = config + + return targets + + def _apply_sparse_embeddings_to_metadatas( + self, + metadatas: Optional[List[Metadata]], + documents: Optional[List[Document]] = None, + ) -> Optional[List[Metadata]]: + sparse_targets = self._get_sparse_embedding_targets() + if not sparse_targets: + return metadatas + + # If no metadatas provided, create empty dicts based on documents length + if metadatas is None: + if documents is None: + return None + metadatas = [{} for _ in range(len(documents))] + + # Create copies, converting None to empty dict + updated_metadatas: List[Dict[str, Any]] = [ + dict(metadata) if metadata is not None else {} for metadata in metadatas + ] + + documents_list = list(documents) if documents is not None else None + + for target_key, config in sparse_targets.items(): + source_key = config.source_key + embedding_func = config.embedding_function + if source_key is None or embedding_func is None: + continue + + if not isinstance(embedding_func, SparseEmbeddingFunction): + embedding_func = cast(SparseEmbeddingFunction[Any], embedding_func) + validate_sparse_embedding_function(embedding_func) + + # Initialize collection lists for batch processing + inputs: List[str] = [] + positions: List[int] = [] + + # Handle special case: source_key is "#document" + if source_key == DOCUMENT_KEY: + if documents_list is None: + continue + + # Collect documents that need embedding + for idx, metadata in enumerate(updated_metadatas): + # Skip if target already exists in metadata + if target_key in metadata: + continue + + # Get document at this position + if idx < len(documents_list): + doc = documents_list[idx] + if isinstance(doc, str): + inputs.append(doc) + positions.append(idx) + + # Generate embeddings for all collected documents + if len(inputs) == 0: + continue + + sparse_embeddings = self._sparse_embed( + input=inputs, + sparse_embedding_function=embedding_func, + ) + + if len(sparse_embeddings) != len(positions): + raise ValueError( + "Sparse embedding function returned unexpected number of embeddings." + ) + + for position, embedding in zip(positions, sparse_embeddings): + updated_metadatas[position][target_key] = embedding + + continue # Skip the metadata-based logic below + + # Handle normal case: source_key is a metadata field + for idx, metadata in enumerate(updated_metadatas): + if target_key in metadata: + continue + + source_value = metadata.get(source_key) + if not isinstance(source_value, str): + continue + + inputs.append(source_value) + positions.append(idx) + + if len(inputs) == 0: + continue + + sparse_embeddings = self._sparse_embed( + input=inputs, + sparse_embedding_function=embedding_func, + ) + + if len(sparse_embeddings) != len(positions): + raise ValueError( + "Sparse embedding function returned unexpected number of embeddings." + ) + + for position, embedding in zip(positions, sparse_embeddings): + updated_metadatas[position][target_key] = embedding + + # Convert empty dicts back to None, validation requires non-empty dicts or None + result_metadatas: List[Optional[Metadata]] = [ + metadata if metadata else None for metadata in updated_metadatas + ] + + validate_metadatas(cast(List[Metadata], result_metadatas)) + return cast(List[Metadata], result_metadatas) + + def _embed_record_set( + self, + record_set: BaseRecordSet, + embeddable_fields: Optional[Set[str]] = None, + is_query: bool = False, + ) -> Embeddings: + if embeddable_fields is None: + embeddable_fields = get_default_embeddable_record_set_fields() + + for field in embeddable_fields: + if record_set[field] is not None: # type: ignore[literal-required] + # uris require special handling + if field == "uris": + if self._data_loader is None: + raise ValueError( + "You must set a data loader on the collection if loading from URIs." + ) + return self._embed( + input=self._data_loader(uris=cast(URIs, record_set[field])), # type: ignore[literal-required] + is_query=is_query, + ) + else: + return self._embed( + input=record_set[field], # type: ignore[literal-required] + is_query=is_query, + ) + raise ValueError( + "Record does not contain any non-None fields that can be embedded." + f"Embeddable Fields: {embeddable_fields}" + f"Record Fields: {record_set}" + ) + + def _embed(self, input: Any, is_query: bool = False) -> Embeddings: + if self._embedding_function is not None and not isinstance( + self._embedding_function, DefaultEmbeddingFunction + ): + if is_query: + return self._embedding_function.embed_query(input=input) + else: + return self._embedding_function(input=input) + + config_ef = self.configuration.get("embedding_function") + if config_ef is not None: + if is_query: + return config_ef.embed_query(input=input) + else: + return config_ef(input=input) + schema = self.schema + schema_embedding_function: Optional[EmbeddingFunction[Embeddable]] = None + if schema is not None: + override = schema.keys.get(EMBEDDING_KEY) + if ( + override is not None + and override.float_list is not None + and override.float_list.vector_index is not None + and override.float_list.vector_index.config.embedding_function + is not None + ): + schema_embedding_function = cast( + EmbeddingFunction[Embeddable], + override.float_list.vector_index.config.embedding_function, + ) + elif ( + schema.defaults.float_list is not None + and schema.defaults.float_list.vector_index is not None + and schema.defaults.float_list.vector_index.config.embedding_function + is not None + ): + schema_embedding_function = cast( + EmbeddingFunction[Embeddable], + schema.defaults.float_list.vector_index.config.embedding_function, + ) + + if schema_embedding_function is not None: + if is_query and hasattr(schema_embedding_function, "embed_query"): + return schema_embedding_function.embed_query(input=input) + return schema_embedding_function(input=input) + if self._embedding_function is None: + raise ValueError( + "You must provide an embedding function to compute embeddings." + "https://docs.trychroma.com/guides/embeddings" + ) + if is_query: + return self._embedding_function.embed_query(input=input) + else: + return self._embedding_function(input=input) + + def _sparse_embed( + self, + input: Any, + sparse_embedding_function: SparseEmbeddingFunction[Any], + is_query: bool = False, + ) -> Any: + if is_query: + return sparse_embedding_function.embed_query(input=input) + return sparse_embedding_function(input=input) + + def _embed_knn_string_queries(self, knn: Any) -> Any: + """Embed string queries in Knn objects using the appropriate embedding function. + + Args: + knn: A Knn object that may have a string query + + Returns: + A Knn object with the string query replaced by an embedding + + Raises: + ValueError: If the query is a string but no embedding function is available + """ + from chromadb.execution.expression.operator import Knn + + if not isinstance(knn, Knn): + return knn + + # If query is not a string, nothing to do + if not isinstance(knn.query, str): + return knn + + query_text = knn.query + key = knn.key + + # Handle main embedding field + if key == EMBEDDING_KEY: + # Use the collection's main embedding function + embedding = self._embed(input=[query_text], is_query=True) + if not embedding or len(embedding) != 1: + raise ValueError( + "Embedding function returned unexpected number of embeddings" + ) + # Return a new Knn with the embedded query + return Knn( + query=embedding[0], + key=knn.key, + limit=knn.limit, + default=knn.default, + return_rank=knn.return_rank, + ) + + # Handle metadata field with potential sparse embedding + schema = self.schema + if schema is None or key not in schema.keys: + raise ValueError( + f"Cannot embed string query for key '{key}': " + f"key not found in schema. Please provide an embedded vector or " + f"configure an embedding function for this key in the schema." + ) + + value_type = schema.keys[key] + + # Check for sparse vector with embedding function + if value_type.sparse_vector is not None: + sparse_index = value_type.sparse_vector.sparse_vector_index + if sparse_index is not None and sparse_index.enabled: + sparse_config = sparse_index.config + if sparse_config.embedding_function is not None: + embedding_func = sparse_config.embedding_function + if not isinstance(embedding_func, SparseEmbeddingFunction): + embedding_func = cast( + SparseEmbeddingFunction[Any], embedding_func + ) + validate_sparse_embedding_function(embedding_func) + + # Embed the query + sparse_embedding = self._sparse_embed( + input=[query_text], + sparse_embedding_function=embedding_func, + is_query=True, + ) + + if not sparse_embedding or len(sparse_embedding) != 1: + raise ValueError( + "Sparse embedding function returned unexpected number of embeddings" + ) + + # Return a new Knn with the sparse embedding + return Knn( + query=sparse_embedding[0], + key=knn.key, + limit=knn.limit, + default=knn.default, + return_rank=knn.return_rank, + ) + + # Check for dense vector with embedding function (float_list) + if value_type.float_list is not None: + vector_index = value_type.float_list.vector_index + if vector_index is not None and vector_index.enabled: + dense_config = vector_index.config + if dense_config.embedding_function is not None: + embedding_func = dense_config.embedding_function + validate_embedding_function(embedding_func) + + # Embed the query using the schema's embedding function + try: + embeddings = embedding_func.embed_query(input=[query_text]) + except AttributeError: + # Fallback if embed_query doesn't exist + embeddings = embedding_func([query_text]) + + if not embeddings or len(embeddings) != 1: + raise ValueError( + "Embedding function returned unexpected number of embeddings" + ) + + # Return a new Knn with the dense embedding + return Knn( + query=embeddings[0], + key=knn.key, + limit=knn.limit, + default=knn.default, + return_rank=knn.return_rank, + ) + + raise ValueError( + f"Cannot embed string query for key '{key}': " + f"no embedding function configured for this key in the schema. " + f"Please provide an embedded vector or configure an embedding function." + ) + + def _embed_rank_string_queries(self, rank: Any) -> Any: + """Recursively embed string queries in Rank expressions. + + Args: + rank: A Rank expression that may contain Knn objects with string queries + + Returns: + A Rank expression with all string queries embedded + """ + # Import here to avoid circular dependency + from chromadb.execution.expression.operator import ( + Knn, + Abs, + Div, + Exp, + Log, + Max, + Min, + Mul, + Sub, + Sum, + Val, + Rrf, + ) + + if rank is None: + return None + + # Base case: Knn - embed if it has a string query + if isinstance(rank, Knn): + return self._embed_knn_string_queries(rank) + + # Base case: Val - no embedding needed + if isinstance(rank, Val): + return rank + + # Recursive cases: walk through child ranks + if isinstance(rank, Abs): + return Abs(self._embed_rank_string_queries(rank.rank)) + + if isinstance(rank, Div): + return Div( + self._embed_rank_string_queries(rank.left), + self._embed_rank_string_queries(rank.right), + ) + + if isinstance(rank, Exp): + return Exp(self._embed_rank_string_queries(rank.rank)) + + if isinstance(rank, Log): + return Log(self._embed_rank_string_queries(rank.rank)) + + if isinstance(rank, Max): + return Max([self._embed_rank_string_queries(r) for r in rank.ranks]) + + if isinstance(rank, Min): + return Min([self._embed_rank_string_queries(r) for r in rank.ranks]) + + if isinstance(rank, Mul): + return Mul([self._embed_rank_string_queries(r) for r in rank.ranks]) + + if isinstance(rank, Sub): + return Sub( + self._embed_rank_string_queries(rank.left), + self._embed_rank_string_queries(rank.right), + ) + + if isinstance(rank, Sum): + return Sum([self._embed_rank_string_queries(r) for r in rank.ranks]) + + if isinstance(rank, Rrf): + return Rrf( + ranks=[self._embed_rank_string_queries(r) for r in rank.ranks], + k=rank.k, + weights=rank.weights, + normalize=rank.normalize, + ) + + # Unknown rank type - return as is + return rank + + def _embed_search_string_queries(self, search: Any) -> Any: + """Embed string queries in a Search object. + + Args: + search: A Search object that may contain Knn objects with string queries + + Returns: + A Search object with all string queries embedded + """ + # Import here to avoid circular dependency + from chromadb.execution.expression.plan import Search + + if not isinstance(search, Search): + return search + + # Embed the rank expression if it exists + embedded_rank = self._embed_rank_string_queries(search._rank) + + # Create a new Search with the embedded rank + return Search( + where=search._where, + rank=embedded_rank, + group_by=search._group_by, + limit=search._limit, + select=search._select, + ) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/api/models/__pycache__/AsyncCollection.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/api/models/__pycache__/AsyncCollection.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c4090c789e355412b83842abc4870ce64471917e Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/api/models/__pycache__/AsyncCollection.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/api/models/__pycache__/AttachedFunction.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/api/models/__pycache__/AttachedFunction.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6a5b8d6e597c3b42cbdad33c10cac50f0fdf135b Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/api/models/__pycache__/AttachedFunction.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/api/models/__pycache__/Collection.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/api/models/__pycache__/Collection.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6f8473abe5c703ea94957bbcba490eeb0a787487 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/api/models/__pycache__/Collection.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/api/models/__pycache__/CollectionCommon.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/api/models/__pycache__/CollectionCommon.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3e64350469e460978f00e7ddac82e5cf81ddae36 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/api/models/__pycache__/CollectionCommon.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/api/rust.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/api/rust.py new file mode 100644 index 0000000000000000000000000000000000000000..1d6ff19b8cf2fbe140bfc31db6fd4d3ece5b789a --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/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/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/api/segment.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/api/segment.py new file mode 100644 index 0000000000000000000000000000000000000000..85fe694b7a932c0effc3ff3d8e45783103835207 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/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/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/api/shared_system_client.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/api/shared_system_client.py new file mode 100644 index 0000000000000000000000000000000000000000..a5ddd4bed41d1c59af498dcbb0de4f5b2fe09abc --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/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/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/api/types.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/api/types.py new file mode 100644 index 0000000000000000000000000000000000000000..9834ddd82f38497f2cddacfcb76ea7ab0cea05e3 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/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/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/auth/__init__.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/auth/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..72c71e7454ea538fe763faec2fe5bc29f33d37d6 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/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/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/auth/__pycache__/__init__.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/auth/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ef27ccde5822b96693c3b61c1020f1d974aaa008 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/auth/__pycache__/__init__.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/auth/basic_authn/__init__.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/auth/basic_authn/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..5e372915e732f9228fcf31b0f1a125489f0acdb7 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/auth/basic_authn/__init__.py @@ -0,0 +1,146 @@ +import base64 +import random +import re +import time +import traceback + +import bcrypt +import logging + +from overrides import override +from pydantic import SecretStr + +from chromadb.auth import ( + UserIdentity, + ServerAuthenticationProvider, + ClientAuthProvider, + ClientAuthHeaders, + AuthError, +) +from chromadb.config import System +from chromadb.errors import ChromaAuthError +from chromadb.telemetry.opentelemetry import ( + OpenTelemetryGranularity, + trace_method, +) + + +from typing import Dict + + +logger = logging.getLogger(__name__) + +__all__ = ["BasicAuthenticationServerProvider", "BasicAuthClientProvider"] + +AUTHORIZATION_HEADER = "Authorization" + + +class BasicAuthClientProvider(ClientAuthProvider): + """ + Client auth provider for basic auth. The credentials are passed as a + base64-encoded string in the Authorization header prepended with "Basic ". + """ + + def __init__(self, system: System) -> None: + super().__init__(system) + self._settings = system.settings + system.settings.require("chroma_client_auth_credentials") + self._creds = SecretStr(str(system.settings.chroma_client_auth_credentials)) + + @override + def authenticate(self) -> ClientAuthHeaders: + encoded = base64.b64encode( + f"{self._creds.get_secret_value()}".encode("utf-8") + ).decode("utf-8") + return { + AUTHORIZATION_HEADER: SecretStr(f"Basic {encoded}"), + } + + +class BasicAuthenticationServerProvider(ServerAuthenticationProvider): + """ + Server auth provider for basic auth. The credentials are read from + `chroma_server_authn_credentials_file` and each line must be in the format + :. + + Expects tokens to be passed as a base64-encoded string in the Authorization + header prepended with "Basic". + """ + + def __init__(self, system: System) -> None: + super().__init__(system) + self._settings = system.settings + + self._creds: Dict[str, SecretStr] = {} + creds = self.read_creds_or_creds_file() + + for line in creds: + if not line.strip(): + continue + _raw_creds = [v for v in line.strip().split(":")] + if ( + _raw_creds + and _raw_creds[0] + and len(_raw_creds) != 2 + or not all(_raw_creds) + ): + raise ValueError( + f"Invalid htpasswd credentials found: {_raw_creds}. " + "Lines must be exactly :." + ) + username = _raw_creds[0] + password = _raw_creds[1] + if username in self._creds: + raise ValueError( + "Duplicate username found in " + "[chroma_server_authn_credentials]. " + "Usernames must be unique." + ) + self._creds[username] = SecretStr(password) + + @trace_method( + "BasicAuthenticationServerProvider.authenticate", OpenTelemetryGranularity.ALL + ) + @override + def authenticate_or_raise(self, headers: Dict[str, str]) -> UserIdentity: + try: + if AUTHORIZATION_HEADER.lower() not in headers.keys(): + raise AuthError(AUTHORIZATION_HEADER + " header not found") + _auth_header = headers[AUTHORIZATION_HEADER.lower()] + _auth_header = re.sub(r"^Basic ", "", _auth_header) + _auth_header = _auth_header.strip() + + base64_decoded = base64.b64decode(_auth_header).decode("utf-8") + if ":" not in base64_decoded: + raise AuthError("Invalid Authorization header format") + username, password = base64_decoded.split(":", 1) + username = str(username) # convert to string to prevent header injection + password = str(password) # convert to string to prevent header injection + if username not in self._creds: + raise AuthError("Invalid username or password") + + _pwd_check = bcrypt.checkpw( + password.encode("utf-8"), + self._creds[username].get_secret_value().encode("utf-8"), + ) + if not _pwd_check: + raise AuthError("Invalid username or password") + return UserIdentity(user_id=username) + except AuthError as e: + logger.error( + f"BasicAuthenticationServerProvider.authenticate failed: {repr(e)}" + ) + except Exception as e: + tb = traceback.extract_tb(e.__traceback__) + # Get the last call stack + last_call_stack = tb[-1] + line_number = last_call_stack.lineno + filename = last_call_stack.filename + logger.error( + "BasicAuthenticationServerProvider.authenticate failed: " + f"Failed to authenticate {type(e).__name__} at {filename}:{line_number}" + ) + time.sleep( + random.uniform(0.001, 0.005) + ) # add some jitter to avoid timing attacks + raise ChromaAuthError() diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/auth/basic_authn/__pycache__/__init__.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/auth/basic_authn/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..dd24e37c01d87f6628f60bfc2f82a0a3b9ab924d Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/auth/basic_authn/__pycache__/__init__.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/auth/simple_rbac_authz/__init__.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/auth/simple_rbac_authz/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..bc4171b12d41faabcd5c35006e85e13d7c70da7f --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/auth/simple_rbac_authz/__init__.py @@ -0,0 +1,75 @@ +import logging +from typing import Dict, Set +from overrides import override +import yaml +from chromadb.auth import ( + AuthzAction, + AuthzResource, + UserIdentity, + ServerAuthorizationProvider, +) +from chromadb.config import System +from fastapi import HTTPException + +from chromadb.telemetry.opentelemetry import ( + OpenTelemetryGranularity, + trace_method, +) + + +logger = logging.getLogger(__name__) + + +class SimpleRBACAuthorizationProvider(ServerAuthorizationProvider): + """ + A simple Role-Based Access Control (RBAC) authorization provider. This + provider reads a configuration file that maps users to roles, and roles to + actions. The provider then checks if the user has the action they are + attempting to perform. + + For an example of an RBAC configuration file, see + examples/basic_functionality/authz/authz.yaml. + """ + + def __init__(self, system: System) -> None: + super().__init__(system) + self._settings = system.settings + self._config = yaml.safe_load("\n".join(self.read_config_or_config_file())) + + # We favor preprocessing here to avoid having to parse the config file + # on every request. This AuthorizationProvider does not support + # per-resource authorization so we just map the user ID to the + # permissions they have. We're not worried about the size of this dict + # since users are all specified in the file -- anyone with a gigantic + # number of users can roll their own AuthorizationProvider. + self._permissions: Dict[str, Set[str]] = {} + for user in self._config["users"]: + _actions = self._config["roles_mapping"][user["role"]]["actions"] + self._permissions[user["id"]] = set(_actions) + logger.info( + "Authorization Provider SimpleRBACAuthorizationProvider " "initialized" + ) + + @trace_method( + "SimpleRBACAuthorizationProvider.authorize", + OpenTelemetryGranularity.ALL, + ) + @override + def authorize_or_raise( + self, user: UserIdentity, action: AuthzAction, resource: AuthzResource + ) -> None: + policy_decision = False + if ( + user.user_id in self._permissions + and action in self._permissions[user.user_id] + ): + policy_decision = True + + logger.debug( + f"Authorization decision: Access " + f"{'granted' if policy_decision else 'denied'} for " + f"user [{user.user_id}] attempting to " + f"[{action}] [{resource}]" + ) + if not policy_decision: + raise HTTPException(status_code=403, detail="Forbidden") diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/auth/simple_rbac_authz/__pycache__/__init__.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/auth/simple_rbac_authz/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..de6a5bfb7cc9593212d5e0c2d06e5dab6eafb74d Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/auth/simple_rbac_authz/__pycache__/__init__.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/auth/token_authn/__init__.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/auth/token_authn/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..b13f2294ac5fe5f2f6d421cf4f9b59be2360af2b --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/auth/token_authn/__init__.py @@ -0,0 +1,235 @@ +import logging +import random +import re +import string +import time +import traceback +from enum import Enum +from typing import cast, Dict, List, Optional, TypedDict, TypeVar + + +from overrides import override +from pydantic import SecretStr +import yaml + +from chromadb.auth import ( + ServerAuthenticationProvider, + ClientAuthProvider, + ClientAuthHeaders, + UserIdentity, + AuthError, +) +from chromadb.config import System +from chromadb.errors import ChromaAuthError +from chromadb.telemetry.opentelemetry import ( + OpenTelemetryGranularity, + trace_method, +) + +T = TypeVar("T") + +logger = logging.getLogger(__name__) + +__all__ = [ + "TokenAuthenticationServerProvider", + "TokenAuthClientProvider", + "TokenTransportHeader", +] + + +class TokenTransportHeader(str, Enum): + """ + Accceptable token transport headers. + """ + + # I don't love having this enum here -- it's weird to have an enum + # for just two values and it's weird to have users pass X_CHROMA_TOKEN + # to configure "x-chroma-token". But I also like having a single source + # of truth, so 🤷🏻‍♂️ + AUTHORIZATION = "Authorization" + X_CHROMA_TOKEN = "X-Chroma-Token" + + +valid_token_chars = set(string.digits + string.ascii_letters + string.punctuation) + + +def _check_token(token: str) -> None: + token_str = str(token) + if not all(c in valid_token_chars for c in token_str): + raise ValueError( + "Invalid token. Must contain only ASCII letters, digits, and punctuation." + ) + + +allowed_token_headers = [ + TokenTransportHeader.AUTHORIZATION.value, + TokenTransportHeader.X_CHROMA_TOKEN.value, +] + + +def _check_allowed_token_headers(token_header: str) -> None: + if token_header not in allowed_token_headers: + raise ValueError( + f"Invalid token transport header: {token_header}. " + f"Must be one of {allowed_token_headers}" + ) + + +class TokenAuthClientProvider(ClientAuthProvider): + """ + Client auth provider for token-based auth. Header key will be either + "Authorization" or "X-Chroma-Token" depending on + `chroma_auth_token_transport_header`. If the header is "Authorization", + the token is passed as a bearer token. + """ + + def __init__(self, system: System) -> None: + super().__init__(system) + self._settings = system.settings + + system.settings.require("chroma_client_auth_credentials") + self._token = SecretStr(str(system.settings.chroma_client_auth_credentials)) + _check_token(self._token.get_secret_value()) + + if system.settings.chroma_auth_token_transport_header: + _check_allowed_token_headers( + system.settings.chroma_auth_token_transport_header + ) + self._token_transport_header = TokenTransportHeader( + system.settings.chroma_auth_token_transport_header + ) + else: + self._token_transport_header = TokenTransportHeader.AUTHORIZATION + + @override + def authenticate(self) -> ClientAuthHeaders: + val = self._token.get_secret_value() + if self._token_transport_header == TokenTransportHeader.AUTHORIZATION: + val = f"Bearer {val}" + return { + self._token_transport_header.value: SecretStr(val), + } + + +class User(TypedDict): + """ + A simple User class for use in this module only. If you need a generic + way to represent a User, please use UserIdentity as this class keeps + track of sensitive tokens. + """ + + id: str + role: str + tenant: Optional[str] + databases: Optional[List[str]] + tokens: List[str] + + +class TokenAuthenticationServerProvider(ServerAuthenticationProvider): + """ + Server authentication provider for token-based auth. The provider will + - On initialization, read the users from the file specified in + `chroma_server_authn_credentials_file`. This file must be a well-formed + YAML file with a top-level array called `users`. Each user must have + an `id` field and a `tokens` (string array) field. + - On each request, check the token in the header specified by + `chroma_auth_token_transport_header`. If the configured header is + "Authorization", the token is expected to be a bearer token. + - If the token is valid, the server will return the user identity + associated with the token. + """ + + def __init__(self, system: System) -> None: + super().__init__(system) + self._settings = system.settings + if system.settings.chroma_auth_token_transport_header: + _check_allowed_token_headers( + system.settings.chroma_auth_token_transport_header + ) + self._token_transport_header = TokenTransportHeader( + system.settings.chroma_auth_token_transport_header + ) + else: + self._token_transport_header = TokenTransportHeader.AUTHORIZATION + + self._token_user_mapping: Dict[str, User] = {} + creds = self.read_creds_or_creds_file() + + # If we only get one cred, assume it's just a valid token. + if len(creds) == 1: + self._token_user_mapping[creds[0]] = User( + id="anonymous", + tenant="*", + databases=["*"], + role="anonymous", + tokens=[creds[0]], + ) + return + + self._users = cast(List[User], yaml.safe_load("\n".join(creds))["users"]) + for user in self._users: + if "tokens" not in user: + raise ValueError("User missing tokens") + if "tenant" not in user: + user["tenant"] = "*" + if "databases" not in user: + user["databases"] = ["*"] + for token in user["tokens"]: + _check_token(token) + if ( + token in self._token_user_mapping + and self._token_user_mapping[token] != user + ): + raise ValueError( + f"Token {token} already in use: wanted to use it for " + f"user {user['id']} but it's already in use by " + f"user {self._token_user_mapping[token]}" + ) + self._token_user_mapping[token] = user + + @trace_method( + "TokenAuthenticationServerProvider.authenticate", OpenTelemetryGranularity.ALL + ) + @override + def authenticate_or_raise(self, headers: Dict[str, str]) -> UserIdentity: + try: + if self._token_transport_header.value.lower() not in headers.keys(): + raise AuthError( + f"Authorization header '{self._token_transport_header.value}' not found" + ) + token = headers[self._token_transport_header.value.lower()] + if self._token_transport_header == TokenTransportHeader.AUTHORIZATION: + if not token.startswith("Bearer "): + raise AuthError("Bearer not found in Authorization header") + token = re.sub(r"^Bearer ", "", token) + + token = token.strip() + _check_token(token) + + if token not in self._token_user_mapping: + raise AuthError("Invalid credentials: Token not found}") + + user_identity = UserIdentity( + user_id=self._token_user_mapping[token]["id"], + tenant=self._token_user_mapping[token]["tenant"], + databases=self._token_user_mapping[token]["databases"], + ) + return user_identity + except AuthError as e: + logger.debug( + f"TokenAuthenticationServerProvider.authenticate failed: {repr(e)}" + ) + except Exception as e: + tb = traceback.extract_tb(e.__traceback__) + # Get the last call stack + last_call_stack = tb[-1] + line_number = last_call_stack.lineno + filename = last_call_stack.filename + logger.debug( + "TokenAuthenticationServerProvider.authenticate failed: " + f"Failed to authenticate {type(e).__name__} at {filename}:{line_number}" + ) + time.sleep( + random.uniform(0.001, 0.005) + ) # add some jitter to avoid timing attacks + raise ChromaAuthError() diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/auth/token_authn/__pycache__/__init__.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/auth/token_authn/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..972a6b8e3a1a927c9f436602e7d3ca2355ff01a7 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/auth/token_authn/__pycache__/__init__.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/auth/utils/__init__.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/auth/utils/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..14dc2e095435fbdea3f851c63f612bafa2372f5b --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/auth/utils/__init__.py @@ -0,0 +1,86 @@ +from typing import Optional, Tuple + +from chromadb.auth import UserIdentity +from chromadb.config import DEFAULT_DATABASE, DEFAULT_TENANT +from chromadb.errors import ChromaAuthError + + +def _singleton_tenant_database_if_applicable( + user_identity: UserIdentity, + overwrite_singleton_tenant_database_access_from_auth: bool, +) -> 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 overwrite_singleton_tenant_database_access_from_auth: + return None, None + tenant = None + database = None + user_tenant = user_identity.tenant + user_databases = user_identity.databases + if user_tenant and user_tenant != "*": + tenant = user_tenant + if user_databases: + user_databases_set = set(user_databases) + if len(user_databases_set) == 1 and "*" not in user_databases_set: + database = list(user_databases_set)[0] + return tenant, database + + +def maybe_set_tenant_and_database( + user_identity: UserIdentity, + overwrite_singleton_tenant_database_access_from_auth: bool, + user_provided_tenant: Optional[str] = None, + user_provided_database: Optional[str] = None, +) -> Tuple[Optional[str], Optional[str]]: + ( + new_tenant, + new_database, + ) = _singleton_tenant_database_if_applicable( + user_identity=user_identity, + overwrite_singleton_tenant_database_access_from_auth=overwrite_singleton_tenant_database_access_from_auth, + ) + + # The only error case is if the user provides a tenant and database that + # don't match what we resolved from auth. This can incorrectly happen when + # there is no auth provider set, but overwrite_singleton_tenant_database_access_from_auth + # is set to True. In this case, we'll resolve tenant/database to the default + # values, which might not match the provided values. Thus, it's important + # to ensure that the flag is set to True only when there is an auth provider. + if ( + user_provided_tenant + and user_provided_tenant != DEFAULT_TENANT + and new_tenant + and new_tenant != user_provided_tenant + ): + raise ChromaAuthError(f"Tenant {user_provided_tenant} does not match {new_tenant} from the server. Are you sure the tenant is correct?") + if ( + user_provided_database + and user_provided_database != DEFAULT_DATABASE + and new_database + and new_database != user_provided_database + ): + raise ChromaAuthError(f"Database {user_provided_database} does not match {new_database} from the server. Are you sure the database is correct?") + + if ( + not user_provided_tenant or user_provided_tenant == DEFAULT_TENANT + ) and new_tenant: + user_provided_tenant = new_tenant + if ( + not user_provided_database or user_provided_database == DEFAULT_DATABASE + ) and new_database: + user_provided_database = new_database + + return user_provided_tenant, user_provided_database diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/auth/utils/__pycache__/__init__.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/auth/utils/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..195fa314d85b7647235b87d23aaf2c5bfe6729cb Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/auth/utils/__pycache__/__init__.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/cli/__init__.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/cli/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/cli/__pycache__/__init__.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/cli/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f8690e8bff1364a281c0317050d2a8535c69ce62 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/cli/__pycache__/__init__.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/cli/__pycache__/cli.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/cli/__pycache__/cli.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c39bda1ed6bc1c8fc98412a62136941298764d01 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/cli/__pycache__/cli.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/cli/__pycache__/utils.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/cli/__pycache__/utils.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2840381447c20015f16f106b54cca85bb66e8483 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/cli/__pycache__/utils.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/cli/cli.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/cli/cli.py new file mode 100644 index 0000000000000000000000000000000000000000..9ec33d4d330d303e39b8403a1802bb3f31240a65 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/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/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/cli/utils.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/cli/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..41acfa0af13661b878617b84600095bf540c082e --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/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/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/db/__init__.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/db/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..f6d87beb49df2fdb5272133136346f1e3eec5220 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/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/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/db/__pycache__/__init__.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/db/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..81ba3bf17318672f37b54890820390d6c6284d55 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/db/__pycache__/__init__.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/db/__pycache__/base.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/db/__pycache__/base.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..773a21f4648ba302f42c3808494aeac5e4752590 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/db/__pycache__/base.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/db/__pycache__/migrations.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/db/__pycache__/migrations.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..68f2741ca543dad13c7ca250420739bc8099c872 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/db/__pycache__/migrations.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/db/__pycache__/system.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/db/__pycache__/system.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5d78d93b7a3cfa121fd0902032b4535a8b271f30 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/db/__pycache__/system.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/db/base.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/db/base.py new file mode 100644 index 0000000000000000000000000000000000000000..89866ccc14d97ef1012386f0f9517d377669635f --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/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/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/db/impl/__init__.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/db/impl/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/db/impl/__pycache__/__init__.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/db/impl/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9375584f9499a8ade3e3b6487872dc0194c147f0 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/db/impl/__pycache__/__init__.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/db/impl/__pycache__/sqlite.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/db/impl/__pycache__/sqlite.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f1b9a00365b5687250f4c87fb2f05604c9bc735d Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/db/impl/__pycache__/sqlite.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/db/impl/__pycache__/sqlite_pool.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/db/impl/__pycache__/sqlite_pool.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..06e6e2d4d7a3a78da7aa3bb3cbe1e79b2b1880d7 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/db/impl/__pycache__/sqlite_pool.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/db/impl/grpc/__pycache__/client.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/db/impl/grpc/__pycache__/client.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1bacd683f52a2748d6e8686d9f3b0414fd2f4a4d Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/db/impl/grpc/__pycache__/client.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/db/impl/grpc/__pycache__/server.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/db/impl/grpc/__pycache__/server.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..24128c5e7562559e160b64c33116e181a2fadf13 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/db/impl/grpc/__pycache__/server.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/db/impl/grpc/client.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/db/impl/grpc/client.py new file mode 100644 index 0000000000000000000000000000000000000000..80e49060c5eb2181cc017123063f115462bac50a --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/db/impl/grpc/client.py @@ -0,0 +1,558 @@ +from typing import List, Optional, Sequence, Tuple, Union, cast +from uuid import UUID +from overrides import overrides +from chromadb.api.collection_configuration import ( + CreateCollectionConfiguration, + create_collection_configuration_to_json_str, + UpdateCollectionConfiguration, + update_collection_configuration_to_json_str, + CollectionMetadata, +) +from chromadb.api.types import Schema +from chromadb.config import DEFAULT_DATABASE, DEFAULT_TENANT, System, logger +from chromadb.db.system import SysDB +from chromadb.errors import NotFoundError, UniqueConstraintError, InternalError +from chromadb.proto.convert import ( + from_proto_collection, + from_proto_segment, + to_proto_update_metadata, + to_proto_segment, + to_proto_segment_scope, +) +from chromadb.proto.coordinator_pb2 import ( + CreateCollectionRequest, + CreateDatabaseRequest, + CreateSegmentRequest, + CreateTenantRequest, + CountCollectionsRequest, + CountCollectionsResponse, + DeleteCollectionRequest, + DeleteDatabaseRequest, + DeleteSegmentRequest, + GetCollectionsRequest, + GetCollectionsResponse, + GetCollectionSizeRequest, + GetCollectionSizeResponse, + GetCollectionWithSegmentsRequest, + GetCollectionWithSegmentsResponse, + GetDatabaseRequest, + GetSegmentsRequest, + GetTenantRequest, + ListDatabasesRequest, + UpdateCollectionRequest, + UpdateSegmentRequest, +) +from chromadb.proto.coordinator_pb2_grpc import SysDBStub +from chromadb.proto.utils import RetryOnRpcErrorClientInterceptor +from chromadb.telemetry.opentelemetry.grpc import OtelInterceptor +from chromadb.telemetry.opentelemetry import ( + OpenTelemetryGranularity, + trace_method, +) +from chromadb.types import ( + Collection, + CollectionAndSegments, + Database, + Metadata, + OptionalArgument, + Segment, + SegmentScope, + Tenant, + Unspecified, + UpdateMetadata, +) +from google.protobuf.empty_pb2 import Empty +import grpc + + +class GrpcSysDB(SysDB): + """A gRPC implementation of the SysDB. In the distributed system, the SysDB is also + called the 'Coordinator'. This implementation is used by Chroma frontend servers + to call a remote SysDB (Coordinator) service.""" + + _sys_db_stub: SysDBStub + _channel: grpc.Channel + _coordinator_url: str + _coordinator_port: int + _request_timeout_seconds: int + + def __init__(self, system: System): + self._coordinator_url = system.settings.require("chroma_coordinator_host") + # TODO: break out coordinator_port into a separate setting? + self._coordinator_port = system.settings.require("chroma_server_grpc_port") + self._request_timeout_seconds = system.settings.require( + "chroma_sysdb_request_timeout_seconds" + ) + return super().__init__(system) + + @overrides + def start(self) -> None: + self._channel = grpc.insecure_channel( + f"{self._coordinator_url}:{self._coordinator_port}", + options=[("grpc.max_concurrent_streams", 1000)], + ) + interceptors = [OtelInterceptor(), RetryOnRpcErrorClientInterceptor()] + self._channel = grpc.intercept_channel(self._channel, *interceptors) + self._sys_db_stub = SysDBStub(self._channel) # type: ignore + return super().start() + + @overrides + def stop(self) -> None: + self._channel.close() + return super().stop() + + @overrides + def reset_state(self) -> None: + self._sys_db_stub.ResetState(Empty()) + return super().reset_state() + + @overrides + def create_database( + self, id: UUID, name: str, tenant: str = DEFAULT_TENANT + ) -> None: + try: + request = CreateDatabaseRequest(id=id.hex, name=name, tenant=tenant) + response = self._sys_db_stub.CreateDatabase( + request, timeout=self._request_timeout_seconds + ) + except grpc.RpcError as e: + logger.info( + f"Failed to create database name {name} and database id {id} for tenant {tenant} due to error: {e}" + ) + if e.code() == grpc.StatusCode.ALREADY_EXISTS: + raise UniqueConstraintError() + raise InternalError() + + @overrides + def get_database(self, name: str, tenant: str = DEFAULT_TENANT) -> Database: + try: + request = GetDatabaseRequest(name=name, tenant=tenant) + response = self._sys_db_stub.GetDatabase( + request, timeout=self._request_timeout_seconds + ) + return Database( + id=UUID(hex=response.database.id), + name=response.database.name, + tenant=response.database.tenant, + ) + except grpc.RpcError as e: + logger.info( + f"Failed to get database {name} for tenant {tenant} due to error: {e}" + ) + if e.code() == grpc.StatusCode.NOT_FOUND: + raise NotFoundError() + raise InternalError() + + @overrides + def delete_database(self, name: str, tenant: str = DEFAULT_TENANT) -> None: + try: + request = DeleteDatabaseRequest(name=name, tenant=tenant) + self._sys_db_stub.DeleteDatabase( + request, timeout=self._request_timeout_seconds + ) + except grpc.RpcError as e: + logger.info( + f"Failed to delete database {name} for tenant {tenant} due to error: {e}" + ) + if e.code() == grpc.StatusCode.NOT_FOUND: + raise NotFoundError() + raise InternalError + + @overrides + def list_databases( + self, + limit: Optional[int] = None, + offset: Optional[int] = None, + tenant: str = DEFAULT_TENANT, + ) -> Sequence[Database]: + try: + request = ListDatabasesRequest(limit=limit, offset=offset, tenant=tenant) + response = self._sys_db_stub.ListDatabases( + request, timeout=self._request_timeout_seconds + ) + results: List[Database] = [] + for proto_database in response.databases: + results.append( + Database( + id=UUID(hex=proto_database.id), + name=proto_database.name, + tenant=proto_database.tenant, + ) + ) + return results + except grpc.RpcError as e: + logger.info( + f"Failed to list databases for tenant {tenant} due to error: {e}" + ) + raise InternalError() + + @overrides + def create_tenant(self, name: str) -> None: + try: + request = CreateTenantRequest(name=name) + response = self._sys_db_stub.CreateTenant( + request, timeout=self._request_timeout_seconds + ) + except grpc.RpcError as e: + logger.info(f"Failed to create tenant {name} due to error: {e}") + if e.code() == grpc.StatusCode.ALREADY_EXISTS: + raise UniqueConstraintError() + raise InternalError() + + @overrides + def get_tenant(self, name: str) -> Tenant: + try: + request = GetTenantRequest(name=name) + response = self._sys_db_stub.GetTenant( + request, timeout=self._request_timeout_seconds + ) + return Tenant( + name=response.tenant.name, + ) + except grpc.RpcError as e: + logger.info(f"Failed to get tenant {name} due to error: {e}") + if e.code() == grpc.StatusCode.NOT_FOUND: + raise NotFoundError() + raise InternalError() + + @overrides + def create_segment(self, segment: Segment) -> None: + try: + proto_segment = to_proto_segment(segment) + request = CreateSegmentRequest( + segment=proto_segment, + ) + response = self._sys_db_stub.CreateSegment( + request, timeout=self._request_timeout_seconds + ) + except grpc.RpcError as e: + logger.info(f"Failed to create segment {segment}, error: {e}") + if e.code() == grpc.StatusCode.ALREADY_EXISTS: + raise UniqueConstraintError() + raise InternalError() + + @overrides + def delete_segment(self, collection: UUID, id: UUID) -> None: + try: + request = DeleteSegmentRequest( + id=id.hex, + collection=collection.hex, + ) + response = self._sys_db_stub.DeleteSegment( + request, timeout=self._request_timeout_seconds + ) + except grpc.RpcError as e: + logger.info( + f"Failed to delete segment with id {id} for collection {collection} due to error: {e}" + ) + if e.code() == grpc.StatusCode.NOT_FOUND: + raise NotFoundError() + raise InternalError() + + @overrides + def get_segments( + self, + collection: UUID, + id: Optional[UUID] = None, + type: Optional[str] = None, + scope: Optional[SegmentScope] = None, + ) -> Sequence[Segment]: + try: + request = GetSegmentsRequest( + id=id.hex if id else None, + type=type, + scope=to_proto_segment_scope(scope) if scope else None, + collection=collection.hex, + ) + response = self._sys_db_stub.GetSegments( + request, timeout=self._request_timeout_seconds + ) + results: List[Segment] = [] + for proto_segment in response.segments: + segment = from_proto_segment(proto_segment) + results.append(segment) + return results + except grpc.RpcError as e: + logger.info( + f"Failed to get segment id {id}, type {type}, scope {scope} for collection {collection} due to error: {e}" + ) + raise InternalError() + + @overrides + def update_segment( + self, + collection: UUID, + id: UUID, + metadata: OptionalArgument[Optional[UpdateMetadata]] = Unspecified(), + ) -> None: + try: + write_metadata = None + if metadata != Unspecified(): + write_metadata = cast(Union[UpdateMetadata, None], metadata) + + request = UpdateSegmentRequest( + id=id.hex, + collection=collection.hex, + metadata=to_proto_update_metadata(write_metadata) + if write_metadata + else None, + ) + + if metadata is None: + request.ClearField("metadata") + request.reset_metadata = True + + self._sys_db_stub.UpdateSegment( + request, timeout=self._request_timeout_seconds + ) + except grpc.RpcError as e: + logger.info( + f"Failed to update segment with id {id} for collection {collection}, error: {e}" + ) + raise InternalError() + + @overrides + 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]: + try: + request = CreateCollectionRequest( + id=id.hex, + name=name, + configuration_json_str=create_collection_configuration_to_json_str( + configuration, cast(CollectionMetadata, metadata) + ), + metadata=to_proto_update_metadata(metadata) if metadata else None, + dimension=dimension, + get_or_create=get_or_create, + tenant=tenant, + database=database, + segments=[to_proto_segment(segment) for segment in segments], + ) + response = self._sys_db_stub.CreateCollection( + request, timeout=self._request_timeout_seconds + ) + collection = from_proto_collection(response.collection) + return collection, response.created + except grpc.RpcError as e: + logger.error( + f"Failed to create collection id {id}, name {name} for database {database} and tenant {tenant} due to error: {e}" + ) + if e.code() == grpc.StatusCode.ALREADY_EXISTS: + raise UniqueConstraintError() + raise InternalError() + + @overrides + def delete_collection( + self, + id: UUID, + tenant: str = DEFAULT_TENANT, + database: str = DEFAULT_DATABASE, + ) -> None: + try: + request = DeleteCollectionRequest( + id=id.hex, + tenant=tenant, + database=database, + ) + response = self._sys_db_stub.DeleteCollection( + request, timeout=self._request_timeout_seconds + ) + except grpc.RpcError as e: + logger.error( + f"Failed to delete collection id {id} for database {database} and tenant {tenant} due to error: {e}" + ) + e = cast(grpc.Call, e) + logger.error( + f"Error code: {e.code()}, NotFoundError: {grpc.StatusCode.NOT_FOUND}" + ) + if e.code() == grpc.StatusCode.NOT_FOUND: + raise NotFoundError() + raise InternalError() + + @overrides + 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]: + try: + # TODO: implement limit and offset in the gRPC service + request = None + if id is not None: + request = GetCollectionsRequest( + id=id.hex, + limit=limit, + offset=offset, + ) + if name is not None: + if tenant is None and database is None: + raise ValueError( + "If name is specified, tenant and database must also be specified in order to uniquely identify the collection" + ) + request = GetCollectionsRequest( + name=name, + tenant=tenant, + database=database, + limit=limit, + offset=offset, + ) + if id is None and name is None: + request = GetCollectionsRequest( + tenant=tenant, + database=database, + limit=limit, + offset=offset, + ) + response: GetCollectionsResponse = self._sys_db_stub.GetCollections( + request, timeout=self._request_timeout_seconds + ) + results: List[Collection] = [] + for collection in response.collections: + results.append(from_proto_collection(collection)) + return results + except grpc.RpcError as e: + logger.error( + f"Failed to get collections with id {id}, name {name}, tenant {tenant}, database {database} due to error: {e}" + ) + raise InternalError() + + @overrides + def count_collections( + self, + tenant: str = DEFAULT_TENANT, + database: Optional[str] = None, + ) -> int: + try: + if database is None or database == "": + request = CountCollectionsRequest(tenant=tenant) + response: CountCollectionsResponse = self._sys_db_stub.CountCollections( + request + ) + return response.count + else: + request = CountCollectionsRequest( + tenant=tenant, + database=database, + ) + response: CountCollectionsResponse = self._sys_db_stub.CountCollections( + request + ) + return response.count + except grpc.RpcError as e: + logger.error(f"Failed to count collections due to error: {e}") + raise InternalError() + + @overrides + def get_collection_size(self, id: UUID) -> int: + try: + request = GetCollectionSizeRequest(id=id.hex) + response: GetCollectionSizeResponse = self._sys_db_stub.GetCollectionSize( + request + ) + return response.total_records_post_compaction + except grpc.RpcError as e: + logger.error(f"Failed to get collection {id} size due to error: {e}") + raise InternalError() + + @trace_method( + "SysDB.get_collection_with_segments", OpenTelemetryGranularity.OPERATION + ) + @overrides + def get_collection_with_segments( + self, collection_id: UUID + ) -> CollectionAndSegments: + try: + request = GetCollectionWithSegmentsRequest(id=collection_id.hex) + response: GetCollectionWithSegmentsResponse = ( + self._sys_db_stub.GetCollectionWithSegments(request) + ) + return CollectionAndSegments( + collection=from_proto_collection(response.collection), + segments=[from_proto_segment(segment) for segment in response.segments], + ) + except grpc.RpcError as e: + if e.code() == grpc.StatusCode.NOT_FOUND: + raise NotFoundError() + logger.error( + f"Failed to get collection {collection_id} and its segments due to error: {e}" + ) + raise InternalError() + + @overrides + 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: + try: + write_name = None + if name != Unspecified(): + write_name = cast(str, name) + + write_dimension = None + if dimension != Unspecified(): + write_dimension = cast(Union[int, None], dimension) + + write_metadata = None + if metadata != Unspecified(): + write_metadata = cast(Union[UpdateMetadata, None], metadata) + + write_configuration = None + if configuration != Unspecified(): + write_configuration = cast( + Union[UpdateCollectionConfiguration, None], configuration + ) + + request = UpdateCollectionRequest( + id=id.hex, + name=write_name, + dimension=write_dimension, + metadata=to_proto_update_metadata(write_metadata) + if write_metadata + else None, + configuration_json_str=update_collection_configuration_to_json_str( + write_configuration + ) + if write_configuration + else None, + ) + if metadata is None: + request.ClearField("metadata") + request.reset_metadata = True + + response = self._sys_db_stub.UpdateCollection( + request, timeout=self._request_timeout_seconds + ) + except grpc.RpcError as e: + e = cast(grpc.Call, e) + logger.error( + f"Failed to update collection id {id}, name {name} due to error: {e}" + ) + if e.code() == grpc.StatusCode.NOT_FOUND: + raise NotFoundError() + if e.code() == grpc.StatusCode.ALREADY_EXISTS: + raise UniqueConstraintError() + raise InternalError() + + def reset_and_wait_for_ready(self) -> None: + self._sys_db_stub.ResetState(Empty(), wait_for_ready=True) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/db/impl/grpc/server.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/db/impl/grpc/server.py new file mode 100644 index 0000000000000000000000000000000000000000..72402ae8415d5572f2bbd24acb0b46febf2a4595 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/db/impl/grpc/server.py @@ -0,0 +1,497 @@ +from concurrent import futures +from typing import Any, Dict, List, cast +from uuid import UUID +from overrides import overrides +import json + +from chromadb.config import DEFAULT_DATABASE, DEFAULT_TENANT, Component, System +from chromadb.proto.convert import ( + from_proto_metadata, + from_proto_update_metadata, + from_proto_segment, + from_proto_segment_scope, + to_proto_collection, + to_proto_segment, +) +import chromadb.proto.chroma_pb2 as proto +from chromadb.proto.coordinator_pb2 import ( + CreateCollectionRequest, + CreateCollectionResponse, + CreateDatabaseRequest, + CreateDatabaseResponse, + CreateSegmentRequest, + CreateSegmentResponse, + CreateTenantRequest, + CreateTenantResponse, + CountCollectionsRequest, + CountCollectionsResponse, + DeleteCollectionRequest, + DeleteCollectionResponse, + DeleteSegmentRequest, + DeleteSegmentResponse, + GetCollectionsRequest, + GetCollectionsResponse, + GetCollectionSizeRequest, + GetCollectionSizeResponse, + GetCollectionWithSegmentsRequest, + GetCollectionWithSegmentsResponse, + GetDatabaseRequest, + GetDatabaseResponse, + GetSegmentsRequest, + GetSegmentsResponse, + GetTenantRequest, + GetTenantResponse, + ResetStateResponse, + UpdateCollectionRequest, + UpdateCollectionResponse, + UpdateSegmentRequest, + UpdateSegmentResponse, +) +from chromadb.proto.coordinator_pb2_grpc import ( + SysDBServicer, + add_SysDBServicer_to_server, +) +import grpc +from google.protobuf.empty_pb2 import Empty +from chromadb.types import Collection, Metadata, Segment, SegmentScope + + +class GrpcMockSysDB(SysDBServicer, Component): + """A mock sysdb implementation that can be used for testing the grpc client. It stores + state in simple python data structures instead of a database.""" + + _server: grpc.Server + _server_port: int + _segments: Dict[str, Segment] = {} + _collection_to_segments: Dict[str, List[str]] = {} + _tenants_to_databases_to_collections: Dict[ + str, Dict[str, Dict[str, Collection]] + ] = {} + _tenants_to_database_to_id: Dict[str, Dict[str, UUID]] = {} + + def __init__(self, system: System): + self._server_port = system.settings.require("chroma_server_grpc_port") + return super().__init__(system) + + @overrides + def start(self) -> None: + self._server = grpc.server(futures.ThreadPoolExecutor(max_workers=10)) + add_SysDBServicer_to_server(self, self._server) # type: ignore + self._server.add_insecure_port(f"[::]:{self._server_port}") + self._server.start() + return super().start() + + @overrides + def stop(self) -> None: + self._server.stop(None) + return super().stop() + + @overrides + def reset_state(self) -> None: + self._segments = {} + self._tenants_to_databases_to_collections = {} + # Create defaults + self._tenants_to_databases_to_collections[DEFAULT_TENANT] = {} + self._tenants_to_databases_to_collections[DEFAULT_TENANT][DEFAULT_DATABASE] = {} + self._tenants_to_database_to_id[DEFAULT_TENANT] = {} + self._tenants_to_database_to_id[DEFAULT_TENANT][DEFAULT_DATABASE] = UUID(int=0) + return super().reset_state() + + @overrides(check_signature=False) + def CreateDatabase( + self, request: CreateDatabaseRequest, context: grpc.ServicerContext + ) -> CreateDatabaseResponse: + tenant = request.tenant + database = request.name + if tenant not in self._tenants_to_databases_to_collections: + context.abort(grpc.StatusCode.NOT_FOUND, f"Tenant {tenant} not found") + if database in self._tenants_to_databases_to_collections[tenant]: + context.abort( + grpc.StatusCode.ALREADY_EXISTS, f"Database {database} already exists" + ) + self._tenants_to_databases_to_collections[tenant][database] = {} + self._tenants_to_database_to_id[tenant][database] = UUID(hex=request.id) + return CreateDatabaseResponse() + + @overrides(check_signature=False) + def GetDatabase( + self, request: GetDatabaseRequest, context: grpc.ServicerContext + ) -> GetDatabaseResponse: + tenant = request.tenant + database = request.name + if tenant not in self._tenants_to_databases_to_collections: + context.abort(grpc.StatusCode.NOT_FOUND, f"Tenant {tenant} not found") + if database not in self._tenants_to_databases_to_collections[tenant]: + context.abort(grpc.StatusCode.NOT_FOUND, f"Database {database} not found") + id = self._tenants_to_database_to_id[tenant][database] + return GetDatabaseResponse( + database=proto.Database(id=id.hex, name=database, tenant=tenant), + ) + + @overrides(check_signature=False) + def CreateTenant( + self, request: CreateTenantRequest, context: grpc.ServicerContext + ) -> CreateTenantResponse: + tenant = request.name + if tenant in self._tenants_to_databases_to_collections: + context.abort( + grpc.StatusCode.ALREADY_EXISTS, f"Tenant {tenant} already exists" + ) + self._tenants_to_databases_to_collections[tenant] = {} + self._tenants_to_database_to_id[tenant] = {} + return CreateTenantResponse() + + @overrides(check_signature=False) + def GetTenant( + self, request: GetTenantRequest, context: grpc.ServicerContext + ) -> GetTenantResponse: + tenant = request.name + if tenant not in self._tenants_to_databases_to_collections: + context.abort(grpc.StatusCode.NOT_FOUND, f"Tenant {tenant} not found") + return GetTenantResponse( + tenant=proto.Tenant(name=tenant), + ) + + # We are forced to use check_signature=False because the generated proto code + # does not have type annotations for the request and response objects. + # TODO: investigate generating types for the request and response objects + @overrides(check_signature=False) + def CreateSegment( + self, request: CreateSegmentRequest, context: grpc.ServicerContext + ) -> CreateSegmentResponse: + segment = from_proto_segment(request.segment) + return self.CreateSegmentHelper(segment, context) + + def CreateSegmentHelper( + self, segment: Segment, context: grpc.ServicerContext + ) -> CreateSegmentResponse: + if segment["id"].hex in self._segments: + context.abort( + grpc.StatusCode.ALREADY_EXISTS, + f"Segment {segment['id']} already exists", + ) + self._segments[segment["id"].hex] = segment + return CreateSegmentResponse() + + @overrides(check_signature=False) + def DeleteSegment( + self, request: DeleteSegmentRequest, context: grpc.ServicerContext + ) -> DeleteSegmentResponse: + id_to_delete = request.id + if id_to_delete in self._segments: + del self._segments[id_to_delete] + return DeleteSegmentResponse() + else: + context.abort( + grpc.StatusCode.NOT_FOUND, f"Segment {id_to_delete} not found" + ) + + @overrides(check_signature=False) + def GetSegments( + self, request: GetSegmentsRequest, context: grpc.ServicerContext + ) -> GetSegmentsResponse: + target_id = UUID(hex=request.id) if request.HasField("id") else None + target_type = request.type if request.HasField("type") else None + target_scope = ( + from_proto_segment_scope(request.scope) + if request.HasField("scope") + else None + ) + target_collection = UUID(hex=request.collection) + + found_segments = [] + for segment in self._segments.values(): + if target_id and segment["id"] != target_id: + continue + if target_type and segment["type"] != target_type: + continue + if target_scope and segment["scope"] != target_scope: + continue + if target_collection and segment["collection"] != target_collection: + continue + found_segments.append(segment) + return GetSegmentsResponse( + segments=[to_proto_segment(segment) for segment in found_segments] + ) + + @overrides(check_signature=False) + def UpdateSegment( + self, request: UpdateSegmentRequest, context: grpc.ServicerContext + ) -> UpdateSegmentResponse: + id_to_update = UUID(request.id) + if id_to_update.hex not in self._segments: + context.abort( + grpc.StatusCode.NOT_FOUND, f"Segment {id_to_update} not found" + ) + else: + segment = self._segments[id_to_update.hex] + if request.HasField("metadata"): + target = cast(Dict[str, Any], segment["metadata"]) + if segment["metadata"] is None: + segment["metadata"] = {} + self._merge_metadata(target, request.metadata) + if request.HasField("reset_metadata") and request.reset_metadata: + segment["metadata"] = {} + return UpdateSegmentResponse() + + @overrides(check_signature=False) + def CreateCollection( + self, request: CreateCollectionRequest, context: grpc.ServicerContext + ) -> CreateCollectionResponse: + collection_name = request.name + tenant = request.tenant + database = request.database + if tenant not in self._tenants_to_databases_to_collections: + context.abort(grpc.StatusCode.NOT_FOUND, f"Tenant {tenant} not found") + if database not in self._tenants_to_databases_to_collections[tenant]: + context.abort(grpc.StatusCode.NOT_FOUND, f"Database {database} not found") + + # Check if the collection already exists globally by id + for ( + search_tenant, + databases, + ) in self._tenants_to_databases_to_collections.items(): + for search_database, search_collections in databases.items(): + if request.id in search_collections: + if ( + search_tenant != request.tenant + or search_database != request.database + ): + context.abort( + grpc.StatusCode.ALREADY_EXISTS, + f"Collection {request.id} already exists in tenant {search_tenant} database {search_database}", + ) + elif not request.get_or_create: + # If the id exists for this tenant and database, and we are not doing a get_or_create, then + # we should return an already exists error + context.abort( + grpc.StatusCode.ALREADY_EXISTS, + f"Collection {request.id} already exists in tenant {search_tenant} database {search_database}", + ) + + # Check if the collection already exists in this database by name + collections = self._tenants_to_databases_to_collections[tenant][database] + matches = [c for c in collections.values() if c["name"] == collection_name] + assert len(matches) <= 1 + if len(matches) > 0: + if request.get_or_create: + existing_collection = matches[0] + return CreateCollectionResponse( + collection=to_proto_collection(existing_collection), + created=False, + ) + context.abort( + grpc.StatusCode.ALREADY_EXISTS, + f"Collection {collection_name} already exists", + ) + + configuration_json = json.loads(request.configuration_json_str) + + id = UUID(hex=request.id) + new_collection = Collection( + id=id, + name=request.name, + configuration_json=configuration_json, + serialized_schema=None, + metadata=from_proto_metadata(request.metadata), + dimension=request.dimension, + database=database, + tenant=tenant, + version=0, + ) + + # Check that segments are unique and do not already exist + # Keep a track of the segments that are being added + segments_added = [] + # Create segments for the collection + for segment_proto in request.segments: + segment = from_proto_segment(segment_proto) + if segment["id"].hex in self._segments: + # Remove the already added segment since we need to roll back + for s in segments_added: + self.DeleteSegment(DeleteSegmentRequest(id=s), context) + context.abort( + grpc.StatusCode.ALREADY_EXISTS, + f"Segment {segment['id']} already exists", + ) + self.CreateSegmentHelper(segment, context) + segments_added.append(segment["id"].hex) + + collections[request.id] = new_collection + collection_unique_key = f"{tenant}:{database}:{request.id}" + self._collection_to_segments[collection_unique_key] = segments_added + return CreateCollectionResponse( + collection=to_proto_collection(new_collection), + created=True, + ) + + @overrides(check_signature=False) + def DeleteCollection( + self, request: DeleteCollectionRequest, context: grpc.ServicerContext + ) -> DeleteCollectionResponse: + collection_id = request.id + tenant = request.tenant + database = request.database + if tenant not in self._tenants_to_databases_to_collections: + context.abort(grpc.StatusCode.NOT_FOUND, f"Tenant {tenant} not found") + if database not in self._tenants_to_databases_to_collections[tenant]: + context.abort(grpc.StatusCode.NOT_FOUND, f"Database {database} not found") + collections = self._tenants_to_databases_to_collections[tenant][database] + if collection_id in collections: + del collections[collection_id] + collection_unique_key = f"{tenant}:{database}:{collection_id}" + segment_ids = self._collection_to_segments[collection_unique_key] + if segment_ids: # Delete segments if provided. + for segment_id in segment_ids: + del self._segments[segment_id] + return DeleteCollectionResponse() + else: + context.abort( + grpc.StatusCode.NOT_FOUND, f"Collection {collection_id} not found" + ) + + @overrides(check_signature=False) + def GetCollections( + self, request: GetCollectionsRequest, context: grpc.ServicerContext + ) -> GetCollectionsResponse: + target_id = UUID(hex=request.id) if request.HasField("id") else None + target_name = request.name if request.HasField("name") else None + + allCollections = {} + for tenant, databases in self._tenants_to_databases_to_collections.items(): + for database, collections in databases.items(): + if request.tenant != "" and tenant != request.tenant: + continue + if request.database != "" and database != request.database: + continue + allCollections.update(collections) + print( + f"Tenant: {tenant}, Database: {database}, Collections: {collections}" + ) + found_collections = [] + for collection in allCollections.values(): + if target_id and collection["id"] != target_id: + continue + if target_name and collection["name"] != target_name: + continue + found_collections.append(collection) + return GetCollectionsResponse( + collections=[ + to_proto_collection(collection) for collection in found_collections + ] + ) + + @overrides(check_signature=False) + def CountCollections( + self, request: CountCollectionsRequest, context: grpc.ServicerContext + ) -> CountCollectionsResponse: + request = GetCollectionsRequest( + tenant=request.tenant, + database=request.database, + ) + collections = self.GetCollections(request, context) + return CountCollectionsResponse(count=len(collections.collections)) + + @overrides(check_signature=False) + def GetCollectionSize( + self, request: GetCollectionSizeRequest, context: grpc.ServicerContext + ) -> GetCollectionSizeResponse: + return GetCollectionSizeResponse( + total_records_post_compaction=0, + ) + + @overrides(check_signature=False) + def GetCollectionWithSegments( + self, request: GetCollectionWithSegmentsRequest, context: grpc.ServicerContext + ) -> GetCollectionWithSegmentsResponse: + allCollections = {} + for tenant, databases in self._tenants_to_databases_to_collections.items(): + for database, collections in databases.items(): + allCollections.update(collections) + print( + f"Tenant: {tenant}, Database: {database}, Collections: {collections}" + ) + collection = allCollections.get(request.id, None) + if collection is None: + context.abort( + grpc.StatusCode.NOT_FOUND, f"Collection with id {request.id} not found" + ) + collection_unique_key = ( + f"{collection.tenant}:{collection.database}:{request.id}" + ) + segments = [ + self._segments[id] + for id in self._collection_to_segments[collection_unique_key] + ] + if {segment["scope"] for segment in segments} != { + SegmentScope.METADATA, + SegmentScope.RECORD, + SegmentScope.VECTOR, + }: + context.abort( + grpc.StatusCode.INTERNAL, + f"Incomplete segments for collection {collection}: {segments}", + ) + + return GetCollectionWithSegmentsResponse( + collection=to_proto_collection(collection), + segments=[to_proto_segment(segment) for segment in segments], + ) + + @overrides(check_signature=False) + def UpdateCollection( + self, request: UpdateCollectionRequest, context: grpc.ServicerContext + ) -> UpdateCollectionResponse: + id_to_update = UUID(request.id) + # Find the collection with this id + collections = {} + for tenant, databases in self._tenants_to_databases_to_collections.items(): + for database, maybe_collections in databases.items(): + if id_to_update.hex in maybe_collections: + collections = maybe_collections + + if id_to_update.hex not in collections: + context.abort( + grpc.StatusCode.NOT_FOUND, f"Collection {id_to_update} not found" + ) + else: + collection = collections[id_to_update.hex] + if request.HasField("name"): + collection["name"] = request.name + if request.HasField("dimension"): + collection["dimension"] = request.dimension + if request.HasField("metadata"): + # TODO: IN SysDB SQlite we have technical debt where we + # replace the entire metadata dict with the new one. We should + # fix that by merging it. For now we just do the same thing here + + update_metadata = from_proto_update_metadata(request.metadata) + cleaned_metadata = None + if update_metadata is not None: + cleaned_metadata = {} + for key, value in update_metadata.items(): + if value is not None: + cleaned_metadata[key] = value + + collection["metadata"] = cleaned_metadata + elif request.HasField("reset_metadata"): + if request.reset_metadata: + collection["metadata"] = {} + + return UpdateCollectionResponse() + + @overrides(check_signature=False) + def ResetState( + self, request: Empty, context: grpc.ServicerContext + ) -> ResetStateResponse: + self.reset_state() + return ResetStateResponse() + + def _merge_metadata(self, target: Metadata, source: proto.UpdateMetadata) -> None: + target_metadata = cast(Dict[str, Any], target) + source_metadata = cast(Dict[str, Any], from_proto_update_metadata(source)) + target_metadata.update(source_metadata) + # If a key has a None value, remove it from the metadata + for key, value in source_metadata.items(): + if value is None and key in target: + del target_metadata[key] diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/db/impl/sqlite.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/db/impl/sqlite.py new file mode 100644 index 0000000000000000000000000000000000000000..32b8101c9c6e268a7c2d4a08ee80c8955ae4a2c6 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/db/impl/sqlite.py @@ -0,0 +1,273 @@ +import logging +from chromadb.db.impl.sqlite_pool import Connection, LockPool, PerThreadPool, Pool +from chromadb.db.migrations import MigratableDB, Migration +from chromadb.config import System, Settings +import chromadb.db.base as base +from chromadb.db.mixins.embeddings_queue import SqlEmbeddingsQueue +from chromadb.db.mixins.sysdb import SqlSysDB +from chromadb.telemetry.opentelemetry import ( + OpenTelemetryClient, + OpenTelemetryGranularity, + trace_method, +) +import sqlite3 +from overrides import override +import pypika +from typing import Sequence, cast, Optional, Type, Any +from typing_extensions import Literal +from types import TracebackType +import os +from uuid import UUID +from threading import local +from importlib_resources import files +from importlib_resources.abc import Traversable + +logger = logging.getLogger(__name__) + + +class TxWrapper(base.TxWrapper): + _conn: Connection + _pool: Pool + + def __init__(self, conn_pool: Pool, stack: local): + self._tx_stack = stack + self._conn = conn_pool.connect() + self._pool = conn_pool + + @override + def __enter__(self) -> base.Cursor: + if len(self._tx_stack.stack) == 0: + self._conn.execute("PRAGMA case_sensitive_like = ON") + self._conn.execute("BEGIN;") + self._tx_stack.stack.append(self) + return self._conn.cursor() # type: ignore + + @override + def __exit__( + self, + exc_type: Optional[Type[BaseException]], + exc_value: Optional[BaseException], + traceback: Optional[TracebackType], + ) -> Literal[False]: + self._tx_stack.stack.pop() + if len(self._tx_stack.stack) == 0: + if exc_type is None: + self._conn.commit() + else: + self._conn.rollback() + self._conn.cursor().close() + self._pool.return_to_pool(self._conn) + return False + + +class SqliteDB(MigratableDB, SqlEmbeddingsQueue, SqlSysDB): + _conn_pool: Pool + _settings: Settings + _migration_imports: Sequence[Traversable] + _db_file: str + _tx_stack: local + _is_persistent: bool + + def __init__(self, system: System): + self._settings = system.settings + self._migration_imports = [ + files("chromadb.migrations.embeddings_queue"), + files("chromadb.migrations.sysdb"), + files("chromadb.migrations.metadb"), + ] + self._is_persistent = self._settings.require("is_persistent") + self._opentelemetry_client = system.require(OpenTelemetryClient) + if not self._is_persistent: + # In order to allow sqlite to be shared between multiple threads, we need to use a + # URI connection string with shared cache. + # See https://www.sqlite.org/sharedcache.html + # https://stackoverflow.com/questions/3315046/sharing-a-memory-database-between-different-threads-in-python-using-sqlite3-pa + self._db_file = "file::memory:?cache=shared" + self._conn_pool = LockPool(self._db_file, is_uri=True) + else: + self._db_file = ( + self._settings.require("persist_directory") + "/chroma.sqlite3" + ) + if not os.path.exists(self._db_file): + os.makedirs(os.path.dirname(self._db_file), exist_ok=True) + self._conn_pool = PerThreadPool(self._db_file) + self._tx_stack = local() + super().__init__(system) + + @trace_method("SqliteDB.start", OpenTelemetryGranularity.ALL) + @override + def start(self) -> None: + super().start() + with self.tx() as cur: + cur.execute("PRAGMA foreign_keys = ON") + cur.execute("PRAGMA case_sensitive_like = ON") + self.initialize_migrations() + + if ( + # (don't attempt to access .config if migrations haven't been run) + self._settings.require("migrations") == "apply" + and self.config.get_parameter("automatically_purge").value is False + ): + logger.warning( + "⚠️ It looks like you upgraded from a version below 0.5.6 and could benefit from vacuuming your database. Run chromadb utils vacuum --help for more information." + ) + + @trace_method("SqliteDB.stop", OpenTelemetryGranularity.ALL) + @override + def stop(self) -> None: + super().stop() + self._conn_pool.close() + + @staticmethod + @override + def querybuilder() -> Type[pypika.Query]: + return pypika.Query # type: ignore + + @staticmethod + @override + def parameter_format() -> str: + return "?" + + @staticmethod + @override + def migration_scope() -> str: + return "sqlite" + + @override + def migration_dirs(self) -> Sequence[Traversable]: + return self._migration_imports + + @override + def tx(self) -> TxWrapper: + if not hasattr(self._tx_stack, "stack"): + self._tx_stack.stack = [] + return TxWrapper(self._conn_pool, stack=self._tx_stack) + + @trace_method("SqliteDB.reset_state", OpenTelemetryGranularity.ALL) + @override + def reset_state(self) -> None: + if not self._settings.require("allow_reset"): + raise ValueError( + "Resetting the database is not allowed. Set `allow_reset` to true in the config in tests or other non-production environments where reset should be permitted." + ) + with self.tx() as cur: + # Drop all tables + cur.execute( + """ + SELECT name FROM sqlite_master + WHERE type='table' + """ + ) + for row in cur.fetchall(): + cur.execute(f"DROP TABLE IF EXISTS {row[0]}") + self._conn_pool.close() + self.start() + super().reset_state() + + @trace_method("SqliteDB.setup_migrations", OpenTelemetryGranularity.ALL) + @override + def setup_migrations(self) -> None: + with self.tx() as cur: + cur.execute( + """ + CREATE TABLE IF NOT EXISTS migrations ( + dir TEXT NOT NULL, + version INTEGER NOT NULL, + filename TEXT NOT NULL, + sql TEXT NOT NULL, + hash TEXT NOT NULL, + PRIMARY KEY (dir, version) + ) + """ + ) + + @trace_method("SqliteDB.migrations_initialized", OpenTelemetryGranularity.ALL) + @override + def migrations_initialized(self) -> bool: + with self.tx() as cur: + cur.execute( + """SELECT count(*) FROM sqlite_master + WHERE type='table' AND name='migrations'""" + ) + + if cur.fetchone()[0] == 0: + return False + else: + return True + + @trace_method("SqliteDB.db_migrations", OpenTelemetryGranularity.ALL) + @override + def db_migrations(self, dir: Traversable) -> Sequence[Migration]: + with self.tx() as cur: + cur.execute( + """ + SELECT dir, version, filename, sql, hash + FROM migrations + WHERE dir = ? + ORDER BY version ASC + """, + (dir.name,), + ) + + migrations = [] + for row in cur.fetchall(): + found_dir = cast(str, row[0]) + found_version = cast(int, row[1]) + found_filename = cast(str, row[2]) + found_sql = cast(str, row[3]) + found_hash = cast(str, row[4]) + migrations.append( + Migration( + dir=found_dir, + version=found_version, + filename=found_filename, + sql=found_sql, + hash=found_hash, + scope=self.migration_scope(), + ) + ) + return migrations + + @override + def apply_migration(self, cur: base.Cursor, migration: Migration) -> None: + cur.executescript(migration["sql"]) + cur.execute( + """ + INSERT INTO migrations (dir, version, filename, sql, hash) + VALUES (?, ?, ?, ?, ?) + """, + ( + migration["dir"], + migration["version"], + migration["filename"], + migration["sql"], + migration["hash"], + ), + ) + + @staticmethod + @override + def uuid_from_db(value: Optional[Any]) -> Optional[UUID]: + return UUID(value) if value is not None else None + + @staticmethod + @override + def uuid_to_db(uuid: Optional[UUID]) -> Optional[Any]: + return str(uuid) if uuid is not None else None + + @staticmethod + @override + def unique_constraint_error() -> Type[BaseException]: + return sqlite3.IntegrityError + + def vacuum(self, timeout: int = 5) -> None: + """Runs VACUUM on the database. `timeout` is the maximum time to wait for an exclusive lock in seconds.""" + conn = self._conn_pool.connect() + conn.execute(f"PRAGMA busy_timeout = {int(timeout) * 1000}") + conn.execute("VACUUM") + conn.execute( + """ + INSERT INTO maintenance_log (operation, timestamp) + VALUES ('vacuum', CURRENT_TIMESTAMP) + """ + ) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/db/impl/sqlite_pool.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/db/impl/sqlite_pool.py new file mode 100644 index 0000000000000000000000000000000000000000..2d1cabf7f21db68359d20df76e388cc49a1c66cd --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/db/impl/sqlite_pool.py @@ -0,0 +1,163 @@ +import sqlite3 +import weakref +from abc import ABC, abstractmethod +from typing import Any, Set +import threading +from overrides import override +from typing_extensions import Annotated + + +class Connection: + """A threadpool connection that returns itself to the pool on close()""" + + _pool: "Pool" + _db_file: str + _conn: sqlite3.Connection + + def __init__( + self, pool: "Pool", db_file: str, is_uri: bool, *args: Any, **kwargs: Any + ): + self._pool = pool + self._db_file = db_file + self._conn = sqlite3.connect( + db_file, timeout=1000, check_same_thread=False, uri=is_uri, *args, **kwargs + ) # type: ignore + self._conn.isolation_level = None # Handle commits explicitly + + def execute(self, sql: str, parameters=...) -> sqlite3.Cursor: # type: ignore + if parameters is ...: + return self._conn.execute(sql) + return self._conn.execute(sql, parameters) + + def commit(self) -> None: + self._conn.commit() + + def rollback(self) -> None: + self._conn.rollback() + + def cursor(self) -> sqlite3.Cursor: + return self._conn.cursor() + + def close_actual(self) -> None: + """Actually closes the connection to the db""" + self._conn.close() + + +class Pool(ABC): + """Abstract base class for a pool of connections to a sqlite database.""" + + @abstractmethod + def __init__(self, db_file: str, is_uri: bool) -> None: + pass + + @abstractmethod + def connect(self, *args: Any, **kwargs: Any) -> Connection: + """Return a connection from the pool.""" + pass + + @abstractmethod + def close(self) -> None: + """Close all connections in the pool.""" + pass + + @abstractmethod + def return_to_pool(self, conn: Connection) -> None: + """Return a connection to the pool.""" + pass + + +class LockPool(Pool): + """A pool that has a single connection per thread but uses a lock to ensure that only one thread can use it at a time. + This is used because sqlite does not support multithreaded access with connection timeouts when using the + shared cache mode. We use the shared cache mode to allow multiple threads to share a database. + """ + + _connections: Set[Annotated[weakref.ReferenceType, Connection]] + _lock: threading.RLock + _connection: threading.local + _db_file: str + _is_uri: bool + + def __init__(self, db_file: str, is_uri: bool = False): + self._connections = set() + self._connection = threading.local() + self._lock = threading.RLock() + self._db_file = db_file + self._is_uri = is_uri + + @override + def connect(self, *args: Any, **kwargs: Any) -> Connection: + self._lock.acquire() + if hasattr(self._connection, "conn") and self._connection.conn is not None: + return self._connection.conn # type: ignore # cast doesn't work here for some reason + else: + new_connection = Connection( + self, self._db_file, self._is_uri, *args, **kwargs + ) + self._connection.conn = new_connection + self._connections.add(weakref.ref(new_connection)) + return new_connection + + @override + def return_to_pool(self, conn: Connection) -> None: + try: + self._lock.release() + except RuntimeError: + pass + + @override + def close(self) -> None: + for conn in self._connections: + if conn() is not None: + conn().close_actual() # type: ignore + self._connections.clear() + self._connection = threading.local() + try: + self._lock.release() + except RuntimeError: + pass + + +class PerThreadPool(Pool): + """Maintains a connection per thread. For now this does not maintain a cap on the number of connections, but it could be + extended to do so and block on connect() if the cap is reached. + """ + + _connections: Set[Annotated[weakref.ReferenceType, Connection]] + _lock: threading.Lock + _connection: threading.local + _db_file: str + _is_uri_: bool + + def __init__(self, db_file: str, is_uri: bool = False): + self._connections = set() + self._connection = threading.local() + self._lock = threading.Lock() + self._db_file = db_file + self._is_uri = is_uri + + @override + def connect(self, *args: Any, **kwargs: Any) -> Connection: + if hasattr(self._connection, "conn") and self._connection.conn is not None: + return self._connection.conn # type: ignore # cast doesn't work here for some reason + else: + new_connection = Connection( + self, self._db_file, self._is_uri, *args, **kwargs + ) + self._connection.conn = new_connection + with self._lock: + self._connections.add(weakref.ref(new_connection)) + return new_connection + + @override + def close(self) -> None: + with self._lock: + for conn in self._connections: + if conn() is not None: + conn().close_actual() # type: ignore + self._connections.clear() + self._connection = threading.local() + + @override + def return_to_pool(self, conn: Connection) -> None: + pass # Each thread gets its own connection, so we don't need to return it to the pool diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/db/migrations.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/db/migrations.py new file mode 100644 index 0000000000000000000000000000000000000000..bac9beb6a61a969e26b988d59ef4eae156ba0a2e --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/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/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/db/mixins/__pycache__/embeddings_queue.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/db/mixins/__pycache__/embeddings_queue.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c54706fff167f83fa55be425e807df28568f11d0 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/db/mixins/__pycache__/embeddings_queue.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/db/mixins/__pycache__/sysdb.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/db/mixins/__pycache__/sysdb.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4b23d3c5b04f1d4fe7b5c633f38a69f4bde3e26f Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/db/mixins/__pycache__/sysdb.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/db/mixins/embeddings_queue.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/db/mixins/embeddings_queue.py new file mode 100644 index 0000000000000000000000000000000000000000..e0b148b21da1d74b93b5420f0c8a576a5cd8a964 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/db/mixins/embeddings_queue.py @@ -0,0 +1,507 @@ +from functools import cached_property +import json +from chromadb.api.configuration import ( + ConfigurationParameter, + EmbeddingsQueueConfigurationInternal, +) +from chromadb.db.base import SqlDB, ParameterValue, get_sql +from chromadb.errors import BatchSizeExceededError +from chromadb.ingest import ( + Producer, + Consumer, + ConsumerCallbackFn, + decode_vector, + encode_vector, +) +from chromadb.types import ( + OperationRecord, + LogRecord, + ScalarEncoding, + SeqId, + Operation, +) +from chromadb.config import System +from chromadb.telemetry.opentelemetry import ( + OpenTelemetryClient, + OpenTelemetryGranularity, + trace_method, +) +from overrides import override +from collections import defaultdict +from typing import Sequence, Optional, Dict, Set, Tuple, cast +from uuid import UUID +from pypika import Table, functions +import uuid +import logging +from chromadb.ingest.impl.utils import create_topic_name + + +logger = logging.getLogger(__name__) + +_operation_codes = { + Operation.ADD: 0, + Operation.UPDATE: 1, + Operation.UPSERT: 2, + Operation.DELETE: 3, +} +_operation_codes_inv = {v: k for k, v in _operation_codes.items()} + +# Set in conftest.py to rethrow errors in the "async" path during testing +# https://doc.pytest.org/en/latest/example/simple.html#detect-if-running-from-within-a-pytest-run +_called_from_test = False + + +class SqlEmbeddingsQueue(SqlDB, Producer, Consumer): + """A SQL database that stores embeddings, allowing a traditional RDBMS to be used as + the primary ingest queue and satisfying the top level Producer/Consumer interfaces. + + Note that this class is only suitable for use cases where the producer and consumer + are in the same process. + + This is because notification of new embeddings happens solely in-process: this + implementation does not actively listen to the the database for new records added by + other processes. + """ + + class Subscription: + id: UUID + topic_name: str + start: int + end: int + callback: ConsumerCallbackFn + + def __init__( + self, + id: UUID, + topic_name: str, + start: int, + end: int, + callback: ConsumerCallbackFn, + ): + self.id = id + self.topic_name = topic_name + self.start = start + self.end = end + self.callback = callback + + _subscriptions: Dict[str, Set[Subscription]] + _max_batch_size: Optional[int] + _tenant: str + _topic_namespace: str + # How many variables are in the insert statement for a single record + VARIABLES_PER_RECORD = 6 + + def __init__(self, system: System): + self._subscriptions = defaultdict(set) + self._max_batch_size = None + self._opentelemetry_client = system.require(OpenTelemetryClient) + self._tenant = system.settings.require("tenant_id") + self._topic_namespace = system.settings.require("topic_namespace") + super().__init__(system) + + @trace_method("SqlEmbeddingsQueue.reset_state", OpenTelemetryGranularity.ALL) + @override + def reset_state(self) -> None: + super().reset_state() + self._subscriptions = defaultdict(set) + + # Invalidate the cached property + try: + del self.config + except AttributeError: + # Cached property hasn't been accessed yet + pass + + @trace_method("SqlEmbeddingsQueue.delete_topic", OpenTelemetryGranularity.ALL) + @override + def delete_log(self, collection_id: UUID) -> None: + topic_name = create_topic_name( + self._tenant, self._topic_namespace, collection_id + ) + t = Table("embeddings_queue") + q = ( + self.querybuilder() + .from_(t) + .where(t.topic == ParameterValue(topic_name)) + .delete() + ) + with self.tx() as cur: + sql, params = get_sql(q, self.parameter_format()) + cur.execute(sql, params) + + @trace_method("SqlEmbeddingsQueue.purge_log", OpenTelemetryGranularity.ALL) + @override + def purge_log(self, collection_id: UUID) -> None: + # (We need to purge on a per topic/collection basis, because the maximum sequence ID is tracked on a per topic/collection basis.) + + segments_t = Table("segments") + segment_ids_q = ( + self.querybuilder() + .from_(segments_t) + # This coalesce prevents a correctness bug when > 1 segments exist and: + # - > 1 has written to the max_seq_id table + # - > 1 has not never written to the max_seq_id table + # In that case, we should not delete any WAL entries as we can't be sure that the all segments are caught up. + .select(functions.Coalesce(Table("max_seq_id").seq_id, -1)) + .where( + segments_t.collection == ParameterValue(self.uuid_to_db(collection_id)) + ) + .left_join(Table("max_seq_id")) + .on(segments_t.id == Table("max_seq_id").segment_id) + ) + + topic_name = create_topic_name( + self._tenant, self._topic_namespace, collection_id + ) + with self.tx() as cur: + sql, params = get_sql(segment_ids_q, self.parameter_format()) + cur.execute(sql, params) + results = cur.fetchall() + if results: + min_seq_id = min(row[0] for row in results) + else: + return + + t = Table("embeddings_queue") + q = ( + self.querybuilder() + .from_(t) + .where(t.seq_id < ParameterValue(min_seq_id)) + .where(t.topic == ParameterValue(topic_name)) + .delete() + ) + + sql, params = get_sql(q, self.parameter_format()) + cur.execute(sql, params) + + @trace_method("SqlEmbeddingsQueue.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("SqlEmbeddingsQueue.submit_embeddings", OpenTelemetryGranularity.ALL) + @override + def submit_embeddings( + self, collection_id: UUID, embeddings: Sequence[OperationRecord] + ) -> Sequence[SeqId]: + if not self._running: + raise RuntimeError("Component not running") + + if len(embeddings) == 0: + return [] + + if len(embeddings) > self.max_batch_size: + raise BatchSizeExceededError( + f""" + Cannot submit more than {self.max_batch_size:,} embeddings at once. + Please submit your embeddings in batches of size + {self.max_batch_size:,} or less. + """ + ) + + # This creates the persisted configuration if it doesn't exist. + # It should be run as soon as possible (before any WAL mutations) since the default configuration depends on the WAL size. + # (We can't run this in __init__()/start() because the migrations have not been run at that point and the table may not be available.) + _ = self.config + + topic_name = create_topic_name( + self._tenant, self._topic_namespace, collection_id + ) + + t = Table("embeddings_queue") + insert = ( + self.querybuilder() + .into(t) + .columns(t.operation, t.topic, t.id, t.vector, t.encoding, t.metadata) + ) + id_to_idx: Dict[str, int] = {} + for embedding in embeddings: + ( + embedding_bytes, + encoding, + metadata, + ) = self._prepare_vector_encoding_metadata(embedding) + insert = insert.insert( + ParameterValue(_operation_codes[embedding["operation"]]), + ParameterValue(topic_name), + ParameterValue(embedding["id"]), + ParameterValue(embedding_bytes), + ParameterValue(encoding), + ParameterValue(metadata), + ) + id_to_idx[embedding["id"]] = len(id_to_idx) + with self.tx() as cur: + sql, params = get_sql(insert, self.parameter_format()) + # The returning clause does not guarantee order, so we need to do reorder + # the results. https://www.sqlite.org/lang_returning.html + sql = f"{sql} RETURNING seq_id, id" # Pypika doesn't support RETURNING + results = cur.execute(sql, params).fetchall() + # Reorder the results + seq_ids = [cast(SeqId, None)] * len( + results + ) # Lie to mypy: https://stackoverflow.com/questions/76694215/python-type-casting-when-preallocating-list + embedding_records = [] + for seq_id, id in results: + seq_ids[id_to_idx[id]] = seq_id + submit_embedding_record = embeddings[id_to_idx[id]] + # We allow notifying consumers out of order relative to one call to + # submit_embeddings so we do not reorder the records before submitting them + embedding_record = LogRecord( + log_offset=seq_id, + record=OperationRecord( + id=id, + embedding=submit_embedding_record["embedding"], + encoding=submit_embedding_record["encoding"], + metadata=submit_embedding_record["metadata"], + operation=submit_embedding_record["operation"], + ), + ) + embedding_records.append(embedding_record) + self._notify_all(topic_name, embedding_records) + + if self.config.get_parameter("automatically_purge").value: + self.purge_log(collection_id) + + return seq_ids + + @trace_method("SqlEmbeddingsQueue.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: + if not self._running: + raise RuntimeError("Component not running") + + topic_name = create_topic_name( + self._tenant, self._topic_namespace, collection_id + ) + + subscription_id = id or uuid.uuid4() + start, end = self._validate_range(start, end) + + subscription = self.Subscription( + subscription_id, topic_name, start, end, consume_fn + ) + + # Backfill first, so if it errors we do not add the subscription + self._backfill(subscription) + self._subscriptions[topic_name].add(subscription) + + return subscription_id + + @trace_method("SqlEmbeddingsQueue.unsubscribe", OpenTelemetryGranularity.ALL) + @override + def unsubscribe(self, subscription_id: UUID) -> None: + for topic_name, subscriptions in self._subscriptions.items(): + for subscription in subscriptions: + if subscription.id == subscription_id: + subscriptions.remove(subscription) + if len(subscriptions) == 0: + del self._subscriptions[topic_name] + return + + @override + def min_seqid(self) -> SeqId: + return -1 + + @override + def max_seqid(self) -> SeqId: + return 2**63 - 1 + + @property + @trace_method("SqlEmbeddingsQueue.max_batch_size", OpenTelemetryGranularity.ALL) + @override + def max_batch_size(self) -> int: + if self._max_batch_size is None: + with self.tx() as cur: + cur.execute("PRAGMA compile_options;") + compile_options = cur.fetchall() + + for option in compile_options: + if "MAX_VARIABLE_NUMBER" in option[0]: + # The pragma returns a string like 'MAX_VARIABLE_NUMBER=999' + self._max_batch_size = int(option[0].split("=")[1]) // ( + self.VARIABLES_PER_RECORD + ) + + if self._max_batch_size is None: + # This value is the default for sqlite3 versions < 3.32.0 + # It is the safest value to use if we can't find the pragma for some + # reason + self._max_batch_size = 999 // self.VARIABLES_PER_RECORD + return self._max_batch_size + + @trace_method( + "SqlEmbeddingsQueue._prepare_vector_encoding_metadata", + OpenTelemetryGranularity.ALL, + ) + def _prepare_vector_encoding_metadata( + self, embedding: OperationRecord + ) -> Tuple[Optional[bytes], Optional[str], Optional[str]]: + if embedding["embedding"] is not None: + encoding_type = cast(ScalarEncoding, embedding["encoding"]) + encoding = encoding_type.value + embedding_bytes = encode_vector(embedding["embedding"], encoding_type) + else: + embedding_bytes = None + encoding = None + metadata = json.dumps(embedding["metadata"]) if embedding["metadata"] else None + return embedding_bytes, encoding, metadata + + @trace_method("SqlEmbeddingsQueue._backfill", OpenTelemetryGranularity.ALL) + def _backfill(self, subscription: Subscription) -> None: + """Backfill the given subscription with any currently matching records in the + DB""" + t = Table("embeddings_queue") + q = ( + self.querybuilder() + .from_(t) + .where(t.topic == ParameterValue(subscription.topic_name)) + .where(t.seq_id > ParameterValue(subscription.start)) + .where(t.seq_id <= ParameterValue(subscription.end)) + .select(t.seq_id, t.operation, t.id, t.vector, t.encoding, t.metadata) + .orderby(t.seq_id) + ) + with self.tx() as cur: + sql, params = get_sql(q, self.parameter_format()) + cur.execute(sql, params) + rows = cur.fetchall() + for row in rows: + if row[3]: + encoding = ScalarEncoding(row[4]) + vector = decode_vector(row[3], encoding) + else: + encoding = None + vector = None + self._notify_one( + subscription, + [ + LogRecord( + log_offset=row[0], + record=OperationRecord( + operation=_operation_codes_inv[row[1]], + id=row[2], + embedding=vector, + encoding=encoding, + metadata=json.loads(row[5]) if row[5] else None, + ), + ) + ], + ) + + @trace_method("SqlEmbeddingsQueue._validate_range", OpenTelemetryGranularity.ALL) + def _validate_range( + self, start: Optional[SeqId], end: Optional[SeqId] + ) -> Tuple[int, int]: + """Validate and normalize the start and end SeqIDs for a subscription using this + impl.""" + start = start or self._next_seq_id() + end = end or self.max_seqid() + if not isinstance(start, int) or not isinstance(end, int): + raise TypeError("SeqIDs must be integers for sql-based EmbeddingsDB") + if start >= end: + raise ValueError(f"Invalid SeqID range: {start} to {end}") + return start, end + + @trace_method("SqlEmbeddingsQueue._next_seq_id", OpenTelemetryGranularity.ALL) + def _next_seq_id(self) -> int: + """Get the next SeqID for this database.""" + t = Table("embeddings_queue") + q = self.querybuilder().from_(t).select(functions.Max(t.seq_id)) + with self.tx() as cur: + cur.execute(q.get_sql()) + return int(cur.fetchone()[0]) + 1 + + @trace_method("SqlEmbeddingsQueue._notify_all", OpenTelemetryGranularity.ALL) + def _notify_all(self, topic: str, embeddings: Sequence[LogRecord]) -> None: + """Send a notification to each subscriber of the given topic.""" + if self._running: + for sub in self._subscriptions[topic]: + self._notify_one(sub, embeddings) + + @trace_method("SqlEmbeddingsQueue._notify_one", OpenTelemetryGranularity.ALL) + def _notify_one(self, sub: Subscription, embeddings: Sequence[LogRecord]) -> None: + """Send a notification to a single subscriber.""" + # Filter out any embeddings that are not in the subscription range + should_unsubscribe = False + filtered_embeddings = [] + for embedding in embeddings: + if embedding["log_offset"] <= sub.start: + continue + if embedding["log_offset"] > sub.end: + should_unsubscribe = True + break + filtered_embeddings.append(embedding) + + # Log errors instead of throwing them to preserve async semantics + # for consistency between local and distributed configurations + try: + if len(filtered_embeddings) > 0: + sub.callback(filtered_embeddings) + if should_unsubscribe: + self.unsubscribe(sub.id) + except BaseException as e: + logger.error( + f"Exception occurred invoking consumer for subscription {sub.id.hex}" + + f"to topic {sub.topic_name} %s", + str(e), + ) + if _called_from_test: + raise e + + @cached_property + def config(self) -> EmbeddingsQueueConfigurationInternal: + t = Table("embeddings_queue_config") + q = self.querybuilder().from_(t).select(t.config_json_str).limit(1) + + with self.tx() as cur: + cur.execute(q.get_sql()) + result = cur.fetchone() + + if result is None: + is_fresh_system = self._get_wal_size() == 0 + config = EmbeddingsQueueConfigurationInternal( + [ConfigurationParameter("automatically_purge", is_fresh_system)] + ) + self.set_config(config) + return config + + return EmbeddingsQueueConfigurationInternal.from_json_str(result[0]) + + def set_config(self, config: EmbeddingsQueueConfigurationInternal) -> None: + with self.tx() as cur: + cur.execute( + """ + INSERT OR REPLACE INTO embeddings_queue_config (id, config_json_str) + VALUES (?, ?) + """, + ( + 1, + config.to_json_str(), + ), + ) + + # Invalidate the cached property + try: + del self.config + except AttributeError: + # Cached property hasn't been accessed yet + pass + + def _get_wal_size(self) -> int: + t = Table("embeddings_queue") + q = self.querybuilder().from_(t).select(functions.Count("*")) + + with self.tx() as cur: + cur.execute(q.get_sql()) + return int(cur.fetchone()[0]) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/db/mixins/sysdb.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/db/mixins/sysdb.py new file mode 100644 index 0000000000000000000000000000000000000000..10b661504dfb655c9eca2810dd3b34dc38b876e1 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/db/mixins/sysdb.py @@ -0,0 +1,986 @@ +import logging +import sys +from typing import Optional, Sequence, Any, Tuple, cast, Dict, Union, Set +from uuid import UUID +from overrides import override +from pypika import Table, Column +from itertools import groupby + +from chromadb.api.types import Schema +from chromadb.config import DEFAULT_DATABASE, DEFAULT_TENANT, System +from chromadb.db.base import Cursor, SqlDB, ParameterValue, get_sql +from chromadb.db.system import SysDB +from chromadb.errors import ( + NotFoundError, + UniqueConstraintError, +) +from chromadb.telemetry.opentelemetry import ( + add_attributes_to_current_span, + OpenTelemetryClient, + OpenTelemetryGranularity, + trace_method, +) +from chromadb.ingest import Producer +from chromadb.types import ( + CollectionAndSegments, + Database, + OptionalArgument, + Segment, + Metadata, + Collection, + SegmentScope, + Tenant, + Unspecified, + UpdateMetadata, +) +from chromadb.api.collection_configuration import ( + CreateCollectionConfiguration, + UpdateCollectionConfiguration, + create_collection_configuration_to_json_str, + load_collection_configuration_from_json_str, + CollectionConfiguration, + create_collection_configuration_to_json, + collection_configuration_to_json, + collection_configuration_to_json_str, + overwrite_collection_configuration, + update_collection_configuration_from_legacy_update_metadata, + CollectionMetadata, +) + +logger = logging.getLogger(__name__) + + +class SqlSysDB(SqlDB, SysDB): + # Used only to delete log streams on collection deletion. + # TODO: refactor to remove this dependency into a separate interface + _producer: Producer + + def __init__(self, system: System): + super().__init__(system) + self._opentelemetry_client = system.require(OpenTelemetryClient) + + @trace_method("SqlSysDB.create_segment", OpenTelemetryGranularity.ALL) + @override + def start(self) -> None: + super().start() + self._producer = self._system.instance(Producer) + + @override + def create_database( + self, id: UUID, name: str, tenant: str = DEFAULT_TENANT + ) -> None: + with self.tx() as cur: + # Get the tenant id for the tenant name and then insert the database with the id, name and tenant id + databases = Table("databases") + tenants = Table("tenants") + insert_database = ( + self.querybuilder() + .into(databases) + .columns(databases.id, databases.name, databases.tenant_id) + .insert( + ParameterValue(self.uuid_to_db(id)), + ParameterValue(name), + self.querybuilder() + .select(tenants.id) + .from_(tenants) + .where(tenants.id == ParameterValue(tenant)), + ) + ) + sql, params = get_sql(insert_database, self.parameter_format()) + try: + cur.execute(sql, params) + except self.unique_constraint_error() as e: + raise UniqueConstraintError( + f"Database {name} already exists for tenant {tenant}" + ) from e + + @override + def get_database(self, name: str, tenant: str = DEFAULT_TENANT) -> Database: + with self.tx() as cur: + databases = Table("databases") + q = ( + self.querybuilder() + .from_(databases) + .select(databases.id, databases.name) + .where(databases.name == ParameterValue(name)) + .where(databases.tenant_id == ParameterValue(tenant)) + ) + sql, params = get_sql(q, self.parameter_format()) + row = cur.execute(sql, params).fetchone() + if not row: + raise NotFoundError( + f"Database {name} not found for tenant {tenant}. Are you sure it exists?" + ) + if row[0] is None: + raise NotFoundError( + f"Database {name} not found for tenant {tenant}. Are you sure it exists?" + ) + id: UUID = cast(UUID, self.uuid_from_db(row[0])) + return Database( + id=id, + name=row[1], + tenant=tenant, + ) + + @override + def delete_database(self, name: str, tenant: str = DEFAULT_TENANT) -> None: + with self.tx() as cur: + databases = Table("databases") + q = ( + self.querybuilder() + .from_(databases) + .where(databases.name == ParameterValue(name)) + .where(databases.tenant_id == ParameterValue(tenant)) + .delete() + ) + sql, params = get_sql(q, self.parameter_format()) + sql = sql + " RETURNING id" + result = cur.execute(sql, params).fetchone() + if not result: + raise NotFoundError(f"Database {name} not found for tenant {tenant}") + + # As of 01/09/2025, cascading deletes don't work because foreign keys are not enabled. + # See https://github.com/chroma-core/chroma/issues/3456. + collections = Table("collections") + q = ( + self.querybuilder() + .from_(collections) + .where(collections.database_id == ParameterValue(result[0])) + .delete() + ) + sql, params = get_sql(q, self.parameter_format()) + cur.execute(sql, params) + + @override + def list_databases( + self, + limit: Optional[int] = None, + offset: Optional[int] = None, + tenant: str = DEFAULT_TENANT, + ) -> Sequence[Database]: + with self.tx() as cur: + databases = Table("databases") + q = ( + self.querybuilder() + .from_(databases) + .select(databases.id, databases.name) + .where(databases.tenant_id == ParameterValue(tenant)) + .offset(offset) + .limit( + sys.maxsize if limit is None else limit + ) # SQLite requires that a limit is provided to use offset + .orderby(databases.created_at) + ) + sql, params = get_sql(q, self.parameter_format()) + rows = cur.execute(sql, params).fetchall() + return [ + Database( + id=cast(UUID, self.uuid_from_db(row[0])), + name=row[1], + tenant=tenant, + ) + for row in rows + ] + + @override + def create_tenant(self, name: str) -> None: + with self.tx() as cur: + tenants = Table("tenants") + insert_tenant = ( + self.querybuilder() + .into(tenants) + .columns(tenants.id) + .insert(ParameterValue(name)) + ) + sql, params = get_sql(insert_tenant, self.parameter_format()) + try: + cur.execute(sql, params) + except self.unique_constraint_error() as e: + raise UniqueConstraintError(f"Tenant {name} already exists") from e + + @override + def get_tenant(self, name: str) -> Tenant: + with self.tx() as cur: + tenants = Table("tenants") + q = ( + self.querybuilder() + .from_(tenants) + .select(tenants.id) + .where(tenants.id == ParameterValue(name)) + ) + sql, params = get_sql(q, self.parameter_format()) + row = cur.execute(sql, params).fetchone() + if not row: + raise NotFoundError(f"Tenant {name} not found") + return Tenant(name=name) + + # Create a segment using the passed cursor, so that the other changes + # can be in the same transaction. + def create_segment_with_tx(self, cur: Cursor, segment: Segment) -> None: + add_attributes_to_current_span( + { + "segment_id": str(segment["id"]), + "segment_type": segment["type"], + "segment_scope": segment["scope"].value, + "collection": str(segment["collection"]), + } + ) + + segments = Table("segments") + insert_segment = ( + self.querybuilder() + .into(segments) + .columns( + segments.id, + segments.type, + segments.scope, + segments.collection, + ) + .insert( + ParameterValue(self.uuid_to_db(segment["id"])), + ParameterValue(segment["type"]), + ParameterValue(segment["scope"].value), + ParameterValue(self.uuid_to_db(segment["collection"])), + ) + ) + sql, params = get_sql(insert_segment, self.parameter_format()) + try: + cur.execute(sql, params) + except self.unique_constraint_error() as e: + raise UniqueConstraintError( + f"Segment {segment['id']} already exists" + ) from e + + # Insert segment metadata if it exists + metadata_t = Table("segment_metadata") + if segment["metadata"]: + try: + self._insert_metadata( + cur, + metadata_t, + metadata_t.segment_id, + segment["id"], + segment["metadata"], + ) + except Exception as e: + logger.error(f"Error inserting segment metadata: {e}") + raise + + # TODO(rohit): Investigate and remove this method completely. + @trace_method("SqlSysDB.create_segment", OpenTelemetryGranularity.ALL) + @override + def create_segment(self, segment: Segment) -> None: + with self.tx() as cur: + self.create_segment_with_tx(cur, segment) + + @trace_method("SqlSysDB.create_collection", OpenTelemetryGranularity.ALL) + @override + 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]: + if id is None and not get_or_create: + raise ValueError("id must be specified if get_or_create is False") + + add_attributes_to_current_span( + { + "collection_id": str(id), + "collection_name": name, + } + ) + + existing = self.get_collections(name=name, tenant=tenant, database=database) + if existing: + if get_or_create: + collection = existing[0] + return ( + self.get_collections( + id=collection.id, tenant=tenant, database=database + )[0], + False, + ) + else: + raise UniqueConstraintError(f"Collection {name} already exists") + + collection = Collection( + id=id, + name=name, + configuration_json=create_collection_configuration_to_json( + configuration, cast(CollectionMetadata, metadata) + ), + serialized_schema=None, + metadata=metadata, + dimension=dimension, + tenant=tenant, + database=database, + version=0, + ) + + with self.tx() as cur: + collections = Table("collections") + databases = Table("databases") + + insert_collection = ( + self.querybuilder() + .into(collections) + .columns( + collections.id, + collections.name, + collections.config_json_str, + collections.dimension, + collections.database_id, + ) + .insert( + ParameterValue(self.uuid_to_db(collection["id"])), + ParameterValue(collection["name"]), + ParameterValue( + create_collection_configuration_to_json_str( + configuration, cast(CollectionMetadata, metadata) + ) + ), + ParameterValue(collection["dimension"]), + # Get the database id for the database with the given name and tenant + self.querybuilder() + .select(databases.id) + .from_(databases) + .where(databases.name == ParameterValue(database)) + .where(databases.tenant_id == ParameterValue(tenant)), + ) + ) + sql, params = get_sql(insert_collection, self.parameter_format()) + try: + cur.execute(sql, params) + except self.unique_constraint_error() as e: + raise UniqueConstraintError( + f"Collection {collection['id']} already exists" + ) from e + metadata_t = Table("collection_metadata") + if collection["metadata"]: + self._insert_metadata( + cur, + metadata_t, + metadata_t.collection_id, + collection.id, + collection["metadata"], + ) + + for segment in segments: + self.create_segment_with_tx(cur, segment) + + return collection, True + + @trace_method("SqlSysDB.get_segments", OpenTelemetryGranularity.ALL) + @override + def get_segments( + self, + collection: UUID, + id: Optional[UUID] = None, + type: Optional[str] = None, + scope: Optional[SegmentScope] = None, + ) -> Sequence[Segment]: + add_attributes_to_current_span( + { + "segment_id": str(id), + "segment_type": type if type else "", + "segment_scope": scope.value if scope else "", + "collection": str(collection), + } + ) + segments_t = Table("segments") + metadata_t = Table("segment_metadata") + q = ( + self.querybuilder() + .from_(segments_t) + .select( + segments_t.id, + segments_t.type, + segments_t.scope, + segments_t.collection, + metadata_t.key, + metadata_t.str_value, + metadata_t.int_value, + metadata_t.float_value, + metadata_t.bool_value, + ) + .left_join(metadata_t) + .on(segments_t.id == metadata_t.segment_id) + .orderby(segments_t.id) + ) + if id: + q = q.where(segments_t.id == ParameterValue(self.uuid_to_db(id))) + if type: + q = q.where(segments_t.type == ParameterValue(type)) + if scope: + q = q.where(segments_t.scope == ParameterValue(scope.value)) + if collection: + q = q.where( + segments_t.collection == ParameterValue(self.uuid_to_db(collection)) + ) + + with self.tx() as cur: + sql, params = get_sql(q, self.parameter_format()) + rows = cur.execute(sql, params).fetchall() + by_segment = groupby(rows, lambda r: cast(object, r[0])) + segments = [] + for segment_id, segment_rows in by_segment: + id = self.uuid_from_db(str(segment_id)) + rows = list(segment_rows) + type = str(rows[0][1]) + scope = SegmentScope(str(rows[0][2])) + collection = self.uuid_from_db(rows[0][3]) # type: ignore[assignment] + metadata = self._metadata_from_rows(rows) + segments.append( + Segment( + id=cast(UUID, id), + type=type, + scope=scope, + collection=collection, + metadata=metadata, + file_paths={}, + ) + ) + + return segments + + @trace_method("SqlSysDB.get_collections", OpenTelemetryGranularity.ALL) + @override + 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]: + """Get collections by name, embedding function and/or metadata""" + + if name is not None and (tenant is None or database is None): + raise ValueError( + "If name is specified, tenant and database must also be specified in order to uniquely identify the collection" + ) + + add_attributes_to_current_span( + { + "collection_id": str(id), + "collection_name": name if name else "", + } + ) + + collections_t = Table("collections") + metadata_t = Table("collection_metadata") + databases_t = Table("databases") + q = ( + self.querybuilder() + .from_(collections_t) + .select( + collections_t.id, + collections_t.name, + collections_t.config_json_str, + collections_t.dimension, + databases_t.name, + databases_t.tenant_id, + metadata_t.key, + metadata_t.str_value, + metadata_t.int_value, + metadata_t.float_value, + metadata_t.bool_value, + ) + .left_join(metadata_t) + .on(collections_t.id == metadata_t.collection_id) + .left_join(databases_t) + .on(collections_t.database_id == databases_t.id) + .orderby(collections_t.id) + ) + if id: + q = q.where(collections_t.id == ParameterValue(self.uuid_to_db(id))) + if name: + q = q.where(collections_t.name == ParameterValue(name)) + + # Only if we have a name, tenant and database do we need to filter databases + # Given an id, we can uniquely identify the collection so we don't need to filter databases + if id is None and tenant and database: + databases_t = Table("databases") + q = q.where( + collections_t.database_id + == self.querybuilder() + .select(databases_t.id) + .from_(databases_t) + .where(databases_t.name == ParameterValue(database)) + .where(databases_t.tenant_id == ParameterValue(tenant)) + ) + # cant set limit and offset here because this is metadata and we havent reduced yet + + with self.tx() as cur: + sql, params = get_sql(q, self.parameter_format()) + rows = cur.execute(sql, params).fetchall() + by_collection = groupby(rows, lambda r: cast(object, r[0])) + collections = [] + for collection_id, collection_rows in by_collection: + id = self.uuid_from_db(str(collection_id)) + rows = list(collection_rows) + name = str(rows[0][1]) + metadata = self._metadata_from_rows(rows) + dimension = int(rows[0][3]) if rows[0][3] else None + if rows[0][2] is not None: + configuration = load_collection_configuration_from_json_str( + rows[0][2] + ) + else: + # 07/2024: This is a legacy case where we don't have a collection + # configuration stored in the database. This non-destructively migrates + # the collection to have a configuration, and takes into account any + # HNSW params that might be in the existing metadata. + configuration = self._insert_config_from_legacy_params( + collection_id, metadata + ) + + collections.append( + Collection( + id=cast(UUID, id), + name=name, + configuration_json=collection_configuration_to_json( + configuration + ), + serialized_schema=None, + metadata=metadata, + dimension=dimension, + tenant=str(rows[0][5]), + database=str(rows[0][4]), + version=0, + ) + ) + + # apply limit and offset + if limit is not None: + if offset is None: + offset = 0 + collections = collections[offset : offset + limit] + else: + collections = collections[offset:] + + return collections + + @override + def get_collection_with_segments( + self, collection_id: UUID + ) -> CollectionAndSegments: + collections = self.get_collections(id=collection_id) + if len(collections) == 0: + raise NotFoundError(f"Collection {collection_id} does not exist.") + return CollectionAndSegments( + collection=collections[0], + segments=self.get_segments(collection=collection_id), + ) + + @trace_method("SqlSysDB.delete_segment", OpenTelemetryGranularity.ALL) + @override + def delete_segment(self, collection: UUID, id: UUID) -> None: + """Delete a segment from the SysDB""" + add_attributes_to_current_span( + { + "segment_id": str(id), + } + ) + t = Table("segments") + q = ( + self.querybuilder() + .from_(t) + .where(t.id == ParameterValue(self.uuid_to_db(id))) + .delete() + ) + with self.tx() as cur: + # no need for explicit del from metadata table because of ON DELETE CASCADE + sql, params = get_sql(q, self.parameter_format()) + sql = sql + " RETURNING id" + result = cur.execute(sql, params).fetchone() + if not result: + raise NotFoundError(f"Segment {id} not found") + + # Used by delete_collection to delete all segments for a collection along with + # the collection itself in a single transaction. + def delete_segments_for_collection(self, cur: Cursor, collection: UUID) -> None: + segments_t = Table("segments") + q = ( + self.querybuilder() + .from_(segments_t) + .where(segments_t.collection == ParameterValue(self.uuid_to_db(collection))) + .delete() + ) + sql, params = get_sql(q, self.parameter_format()) + cur.execute(sql, params) + + @trace_method("SqlSysDB.delete_collection", OpenTelemetryGranularity.ALL) + @override + def delete_collection( + self, + id: UUID, + tenant: str = DEFAULT_TENANT, + database: str = DEFAULT_DATABASE, + ) -> None: + """Delete a collection and all associated segments from the SysDB. Deletes + the log stream for this collection as well.""" + add_attributes_to_current_span( + { + "collection_id": str(id), + } + ) + t = Table("collections") + databases_t = Table("databases") + q = ( + self.querybuilder() + .from_(t) + .where(t.id == ParameterValue(self.uuid_to_db(id))) + .where( + t.database_id + == self.querybuilder() + .select(databases_t.id) + .from_(databases_t) + .where(databases_t.name == ParameterValue(database)) + .where(databases_t.tenant_id == ParameterValue(tenant)) + ) + .delete() + ) + with self.tx() as cur: + # no need for explicit del from metadata table because of ON DELETE CASCADE + sql, params = get_sql(q, self.parameter_format()) + sql = sql + " RETURNING id" + result = cur.execute(sql, params).fetchone() + if not result: + raise NotFoundError(f"Collection {id} not found") + # Delete segments. + self.delete_segments_for_collection(cur, id) + + self._producer.delete_log(result[0]) + + @trace_method("SqlSysDB.update_segment", OpenTelemetryGranularity.ALL) + @override + def update_segment( + self, + collection: UUID, + id: UUID, + metadata: OptionalArgument[Optional[UpdateMetadata]] = Unspecified(), + ) -> None: + add_attributes_to_current_span( + { + "segment_id": str(id), + "collection": str(collection), + } + ) + segments_t = Table("segments") + metadata_t = Table("segment_metadata") + + q = ( + self.querybuilder() + .update(segments_t) + .where(segments_t.id == ParameterValue(self.uuid_to_db(id))) + .set(segments_t.collection, ParameterValue(self.uuid_to_db(collection))) + ) + + with self.tx() as cur: + sql, params = get_sql(q, self.parameter_format()) + if sql: # pypika emits a blank string if nothing to do + cur.execute(sql, params) + + if metadata is None: + q = ( + self.querybuilder() + .from_(metadata_t) + .where(metadata_t.segment_id == ParameterValue(self.uuid_to_db(id))) + .delete() + ) + sql, params = get_sql(q, self.parameter_format()) + cur.execute(sql, params) + elif metadata != Unspecified(): + metadata = cast(UpdateMetadata, metadata) + metadata = cast(UpdateMetadata, metadata) + self._insert_metadata( + cur, + metadata_t, + metadata_t.segment_id, + id, + metadata, + set(metadata.keys()), + ) + + @trace_method("SqlSysDB.update_collection", OpenTelemetryGranularity.ALL) + @override + 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: + add_attributes_to_current_span( + { + "collection_id": str(id), + } + ) + collections_t = Table("collections") + metadata_t = Table("collection_metadata") + + q = ( + self.querybuilder() + .update(collections_t) + .where(collections_t.id == ParameterValue(self.uuid_to_db(id))) + ) + + if not name == Unspecified(): + q = q.set(collections_t.name, ParameterValue(name)) + + if not dimension == Unspecified(): + q = q.set(collections_t.dimension, ParameterValue(dimension)) + + with self.tx() as cur: + sql, params = get_sql(q, self.parameter_format()) + if sql: # pypika emits a blank string if nothing to do + sql = sql + " RETURNING id" + result = cur.execute(sql, params) + if not result.fetchone(): + raise NotFoundError(f"Collection {id} not found") + + # TODO: Update to use better semantics where it's possible to update + # individual keys without wiping all the existing metadata. + + # For now, follow current legancy semantics where metadata is fully reset + if metadata != Unspecified(): + q = ( + self.querybuilder() + .from_(metadata_t) + .where( + metadata_t.collection_id == ParameterValue(self.uuid_to_db(id)) + ) + .delete() + ) + sql, params = get_sql(q, self.parameter_format()) + cur.execute(sql, params) + if metadata is not None: + metadata = cast(UpdateMetadata, metadata) + self._insert_metadata( + cur, + metadata_t, + metadata_t.collection_id, + id, + metadata, + set(metadata.keys()), + ) + + if configuration != Unspecified(): + update_configuration = cast( + UpdateCollectionConfiguration, configuration + ) + self._update_config_json_str(cur, update_configuration, id) + else: + if metadata != Unspecified(): + metadata = cast(UpdateMetadata, metadata) + if metadata is not None: + update_configuration = ( + update_collection_configuration_from_legacy_update_metadata( + metadata + ) + ) + self._update_config_json_str(cur, update_configuration, id) + + def _update_config_json_str( + self, cur: Cursor, update_configuration: UpdateCollectionConfiguration, id: UUID + ) -> None: + collections_t = Table("collections") + q = ( + self.querybuilder() + .from_(collections_t) + .select(collections_t.config_json_str) + .where(collections_t.id == ParameterValue(self.uuid_to_db(id))) + ) + sql, params = get_sql(q, self.parameter_format()) + row = cur.execute(sql, params).fetchone() + if not row: + raise NotFoundError(f"Collection {id} not found") + config_json_str = row[0] + existing_config = load_collection_configuration_from_json_str(config_json_str) + new_config = overwrite_collection_configuration( + existing_config, update_configuration + ) + q = ( + self.querybuilder() + .update(collections_t) + .set( + collections_t.config_json_str, + ParameterValue(collection_configuration_to_json_str(new_config)), + ) + .where(collections_t.id == ParameterValue(self.uuid_to_db(id))) + ) + sql, params = get_sql(q, self.parameter_format()) + cur.execute(sql, params) + + @trace_method("SqlSysDB._metadata_from_rows", OpenTelemetryGranularity.ALL) + def _metadata_from_rows( + self, rows: Sequence[Tuple[Any, ...]] + ) -> Optional[Metadata]: + """Given SQL rows, return a metadata map (assuming that the last four columns + are the key, str_value, int_value & float_value)""" + add_attributes_to_current_span( + { + "num_rows": len(rows), + } + ) + metadata: Dict[str, Union[str, int, float, bool]] = {} + for row in rows: + key = str(row[-5]) + if row[-4] is not None: + metadata[key] = str(row[-4]) + elif row[-3] is not None: + metadata[key] = int(row[-3]) + elif row[-2] is not None: + metadata[key] = float(row[-2]) + elif row[-1] is not None: + metadata[key] = bool(row[-1]) + return metadata or None + + @trace_method("SqlSysDB._insert_metadata", OpenTelemetryGranularity.ALL) + def _insert_metadata( + self, + cur: Cursor, + table: Table, + id_col: Column, + id: UUID, + metadata: UpdateMetadata, + clear_keys: Optional[Set[str]] = None, + ) -> None: + # It would be cleaner to use something like ON CONFLICT UPDATE here But that is + # very difficult to do in a portable way (e.g sqlite and postgres have + # completely different sytnax) + add_attributes_to_current_span( + { + "num_keys": len(metadata), + } + ) + if clear_keys: + q = ( + self.querybuilder() + .from_(table) + .where(id_col == ParameterValue(self.uuid_to_db(id))) + .where(table.key.isin([ParameterValue(k) for k in clear_keys])) + .delete() + ) + sql, params = get_sql(q, self.parameter_format()) + cur.execute(sql, params) + + q = ( + self.querybuilder() + .into(table) + .columns( + id_col, + table.key, + table.str_value, + table.int_value, + table.float_value, + table.bool_value, + ) + ) + sql_id = self.uuid_to_db(id) + for k, v in metadata.items(): + # Note: The order is important here because isinstance(v, bool) + # and isinstance(v, int) both are true for v of bool type. + if isinstance(v, bool): + q = q.insert( + ParameterValue(sql_id), + ParameterValue(k), + None, + None, + None, + ParameterValue(int(v)), + ) + elif isinstance(v, str): + q = q.insert( + ParameterValue(sql_id), + ParameterValue(k), + ParameterValue(v), + None, + None, + None, + ) + elif isinstance(v, int): + q = q.insert( + ParameterValue(sql_id), + ParameterValue(k), + None, + ParameterValue(v), + None, + None, + ) + elif isinstance(v, float): + q = q.insert( + ParameterValue(sql_id), + ParameterValue(k), + None, + None, + ParameterValue(v), + None, + ) + elif v is None: + continue + + sql, params = get_sql(q, self.parameter_format()) + if sql: + cur.execute(sql, params) + + def _insert_config_from_legacy_params( + self, collection_id: Any, metadata: Optional[Metadata] + ) -> CollectionConfiguration: + """Insert the configuration from legacy metadata params into the collections table, and return the configuration object.""" + + # This is a legacy case where we don't have configuration stored in the database + # This is non-destructive, we don't delete or overwrite any keys in the metadata + + collections_t = Table("collections") + + create_collection_config = CreateCollectionConfiguration() + # Write the configuration into the database + configuration_json_str = create_collection_configuration_to_json_str( + create_collection_config, cast(CollectionMetadata, metadata) + ) + q = ( + self.querybuilder() + .update(collections_t) + .set( + collections_t.config_json_str, + ParameterValue(configuration_json_str), + ) + .where(collections_t.id == ParameterValue(collection_id)) + ) + sql, params = get_sql(q, self.parameter_format()) + with self.tx() as cur: + cur.execute(sql, params) + return load_collection_configuration_from_json_str(configuration_json_str) + + @override + def get_collection_size(self, id: UUID) -> int: + raise NotImplementedError + + @override + def count_collections( + self, + tenant: str = DEFAULT_TENANT, + database: Optional[str] = None, + ) -> int: + """Gets the number of collections for the (tenant, database) combination.""" + # TODO(Sanket): Implement this efficiently using a count query. + # Note, the underlying get_collections api always requires a database + # to be specified. In the sysdb implementation in go code, it does not + # filter on database if it is set to "". This is a bad API and + # should be fixed. For now, we will replicate the behavior. + request_database: str = "" if database is None or database == "" else database + return len(self.get_collections(tenant=tenant, database=request_database)) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/db/system.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/db/system.py new file mode 100644 index 0000000000000000000000000000000000000000..638c1aecddb965f155f119cf19fe0a6f0bb67ac9 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/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/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/execution/__init__.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/execution/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/execution/__pycache__/__init__.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/execution/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..cf30f02e886eea6deec15303f4c9942dec216a62 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/execution/__pycache__/__init__.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/execution/executor/__pycache__/abstract.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/execution/executor/__pycache__/abstract.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4b33cf3c9eead2aa938c14eca19e89dd3b51cf31 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/execution/executor/__pycache__/abstract.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/execution/executor/__pycache__/distributed.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/execution/executor/__pycache__/distributed.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a07e92446dae0e8b00f54f7c299eea0ae28b816d Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/execution/executor/__pycache__/distributed.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/execution/executor/__pycache__/local.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/execution/executor/__pycache__/local.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b4612c504a1efffac6b9c2a17518cd15468a6e6a Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/execution/executor/__pycache__/local.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/execution/executor/abstract.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/execution/executor/abstract.py new file mode 100644 index 0000000000000000000000000000000000000000..05ad9f4897f20c9a44f0fe081bc34aba0681cd25 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/execution/executor/abstract.py @@ -0,0 +1,19 @@ +from abc import abstractmethod + +from chromadb.api.types import GetResult, QueryResult +from chromadb.config import Component +from chromadb.execution.expression.plan import CountPlan, GetPlan, KNNPlan + + +class Executor(Component): + @abstractmethod + def count(self, plan: CountPlan) -> int: + pass + + @abstractmethod + def get(self, plan: GetPlan) -> GetResult: + pass + + @abstractmethod + def knn(self, plan: KNNPlan) -> QueryResult: + pass diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/execution/executor/distributed.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/execution/executor/distributed.py new file mode 100644 index 0000000000000000000000000000000000000000..15d3fa07dc3be62f55a5a98f87fb703250961dd6 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/execution/executor/distributed.py @@ -0,0 +1,242 @@ +import threading +import random +from typing import Callable, Dict, List, Optional, TypeVar +import grpc +from overrides import overrides +from chromadb.api.types import GetResult, Metadata, QueryResult +from chromadb.config import System +from chromadb.execution.executor.abstract import Executor +from chromadb.execution.expression.operator import Scan +from chromadb.execution.expression.plan import CountPlan, GetPlan, KNNPlan +from chromadb.proto import convert +from chromadb.proto.query_executor_pb2_grpc import QueryExecutorStub +from chromadb.segment.impl.manager.distributed import DistributedSegmentManager +from chromadb.telemetry.opentelemetry.grpc import OtelInterceptor +from tenacity import ( + RetryCallState, + Retrying, + stop_after_attempt, + wait_exponential_jitter, + retry_if_exception, +) +from opentelemetry.trace import Span + + +def _clean_metadata(metadata: Optional[Metadata]) -> Optional[Metadata]: + """Remove any chroma-specific metadata keys that the client shouldn't see from a metadata map.""" + if not metadata: + return None + result = {} + for k, v in metadata.items(): + if not k.startswith("chroma:"): + result[k] = v + if len(result) == 0: + return None + return result + + +def _uri(metadata: Optional[Metadata]) -> Optional[str]: + """Retrieve the uri (if any) from a Metadata map""" + + if metadata and "chroma:uri" in metadata: + return str(metadata["chroma:uri"]) + return None + + +# Type variables for input and output types of the round-robin retry function +I = TypeVar("I") # noqa: E741 +O = TypeVar("O") # noqa: E741 + + +class DistributedExecutor(Executor): + _mtx: threading.Lock + _grpc_stub_pool: Dict[str, QueryExecutorStub] + _manager: DistributedSegmentManager + _request_timeout_seconds: int + _query_replication_factor: int + + def __init__(self, system: System): + super().__init__(system) + self._mtx = threading.Lock() + self._grpc_stub_pool = {} + self._manager = self.require(DistributedSegmentManager) + self._request_timeout_seconds = system.settings.require( + "chroma_query_request_timeout_seconds" + ) + self._query_replication_factor = system.settings.require( + "chroma_query_replication_factor" + ) + + def _round_robin_retry(self, funcs: List[Callable[[I], O]], args: I) -> O: + """ + Retry a list of functions in a round-robin fashion until one of them succeeds. + + funcs: List of functions to retry + args: Arguments to pass to each function + + """ + attempt_count = 0 + sleep_span: Optional[Span] = None + + def before_sleep(_: RetryCallState) -> None: + # HACK(hammadb) 1/14/2024 - this is a hack to avoid the fact that tracer is not yet available and there are boot order issues + # This should really use our component system to get the tracer. Since our grpc utils use this pattern + # we are copying it here. This should be removed once we have a better way to get the tracer + from chromadb.telemetry.opentelemetry import tracer + + nonlocal sleep_span + if tracer is not None: + sleep_span = tracer.start_span("Waiting to retry RPC") + + for attempt in Retrying( + stop=stop_after_attempt(5), + wait=wait_exponential_jitter(0.1, jitter=0.1), + reraise=True, + retry=retry_if_exception( + lambda x: isinstance(x, grpc.RpcError) + and x.code() in [grpc.StatusCode.UNAVAILABLE, grpc.StatusCode.UNKNOWN] + ), + before_sleep=before_sleep, + ): + if sleep_span is not None: + sleep_span.end() + sleep_span = None + + with attempt: + return funcs[attempt_count % len(funcs)](args) + attempt_count += 1 + + # NOTE(hammadb) because Retrying() will always either return or raise an exception, this line should never be reached + raise Exception("Unreachable code error - should never reach here") + + @overrides + def count(self, plan: CountPlan) -> int: + endpoints = self._get_grpc_endpoints(plan.scan) + count_funcs = [self._get_stub(endpoint).Count for endpoint in endpoints] + count_result = self._round_robin_retry( + count_funcs, convert.to_proto_count_plan(plan) + ) + return convert.from_proto_count_result(count_result) + + @overrides + def get(self, plan: GetPlan) -> GetResult: + endpoints = self._get_grpc_endpoints(plan.scan) + get_funcs = [self._get_stub(endpoint).Get for endpoint in endpoints] + get_result = self._round_robin_retry(get_funcs, convert.to_proto_get_plan(plan)) + records = convert.from_proto_get_result(get_result) + + ids = [record["id"] for record in records] + embeddings = ( + [record["embedding"] for record in records] + if plan.projection.embedding + else None + ) + documents = ( + [record["document"] for record in records] + if plan.projection.document + else None + ) + uris = ( + [_uri(record["metadata"]) for record in records] + if plan.projection.uri + else None + ) + metadatas = ( + [_clean_metadata(record["metadata"]) for record in records] + if plan.projection.metadata + else None + ) + + # TODO: Fix typing + return GetResult( + ids=ids, + embeddings=embeddings, # type: ignore[typeddict-item] + documents=documents, # type: ignore[typeddict-item] + uris=uris, # type: ignore[typeddict-item] + data=None, + metadatas=metadatas, # type: ignore[typeddict-item] + included=plan.projection.included, + ) + + @overrides + def knn(self, plan: KNNPlan) -> QueryResult: + endpoints = self._get_grpc_endpoints(plan.scan) + knn_funcs = [self._get_stub(endpoint).KNN for endpoint in endpoints] + knn_result = self._round_robin_retry(knn_funcs, convert.to_proto_knn_plan(plan)) + results = convert.from_proto_knn_batch_result(knn_result) + + ids = [[record["record"]["id"] for record in records] for records in results] + embeddings = ( + [ + [record["record"]["embedding"] for record in records] + for records in results + ] + if plan.projection.embedding + else None + ) + documents = ( + [ + [record["record"]["document"] for record in records] + for records in results + ] + if plan.projection.document + else None + ) + uris = ( + [ + [_uri(record["record"]["metadata"]) for record in records] + for records in results + ] + if plan.projection.uri + else None + ) + metadatas = ( + [ + [_clean_metadata(record["record"]["metadata"]) for record in records] + for records in results + ] + if plan.projection.metadata + else None + ) + distances = ( + [[record["distance"] for record in records] for records in results] + if plan.projection.rank + else None + ) + + # TODO: Fix typing + return QueryResult( + ids=ids, + embeddings=embeddings, # type: ignore[typeddict-item] + documents=documents, # type: ignore[typeddict-item] + uris=uris, # type: ignore[typeddict-item] + data=None, + metadatas=metadatas, # type: ignore[typeddict-item] + distances=distances, # type: ignore[typeddict-item] + included=plan.projection.included, + ) + + def _get_grpc_endpoints(self, scan: Scan) -> List[str]: + # Since grpc endpoint is endpoint is determined by collection uuid, + # the endpoint should be the same for all segments of the same collection + grpc_urls = self._manager.get_endpoints( + scan.record, self._query_replication_factor + ) + # Shuffle the grpc urls to distribute the load evenly + random.shuffle(grpc_urls) + return grpc_urls + + def _get_stub(self, grpc_url: str) -> QueryExecutorStub: + with self._mtx: + if grpc_url not in self._grpc_stub_pool: + channel = grpc.insecure_channel( + grpc_url, + options=[ + ("grpc.max_concurrent_streams", 1000), + ("grpc.max_receive_message_length", 32000000), # 32 MB + ], + ) + interceptors = [OtelInterceptor()] + channel = grpc.intercept_channel(channel, *interceptors) + self._grpc_stub_pool[grpc_url] = QueryExecutorStub(channel) + return self._grpc_stub_pool[grpc_url] diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/execution/executor/local.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/execution/executor/local.py new file mode 100644 index 0000000000000000000000000000000000000000..79d6a8d31d642d3e1df3a1b3c732b7655159b85a --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/execution/executor/local.py @@ -0,0 +1,205 @@ +from typing import Optional, Sequence + +from overrides import overrides + +from chromadb.api.types import GetResult, Metadata, QueryResult +from chromadb.config import System +from chromadb.execution.executor.abstract import Executor +from chromadb.execution.expression.plan import CountPlan, GetPlan, KNNPlan +from chromadb.segment import MetadataReader, VectorReader +from chromadb.segment.impl.manager.local import LocalSegmentManager +from chromadb.types import Collection, VectorQuery, VectorQueryResult + + +def _clean_metadata(metadata: Optional[Metadata]) -> Optional[Metadata]: + """Remove any chroma-specific metadata keys that the client shouldn't see from a metadata map.""" + if not metadata: + return None + result = {} + for k, v in metadata.items(): + if not k.startswith("chroma:"): + result[k] = v + if len(result) == 0: + return None + return result + + +def _doc(metadata: Optional[Metadata]) -> Optional[str]: + """Retrieve the document (if any) from a Metadata map""" + + if metadata and "chroma:document" in metadata: + return str(metadata["chroma:document"]) + return None + + +def _uri(metadata: Optional[Metadata]) -> Optional[str]: + """Retrieve the uri (if any) from a Metadata map""" + + if metadata and "chroma:uri" in metadata: + return str(metadata["chroma:uri"]) + return None + + +class LocalExecutor(Executor): + _manager: LocalSegmentManager + + def __init__(self, system: System): + super().__init__(system) + self._manager = self.require(LocalSegmentManager) + + @overrides + def count(self, plan: CountPlan) -> int: + return self._metadata_segment(plan.scan.collection).count(plan.scan.version) + + @overrides + def get(self, plan: GetPlan) -> GetResult: + records = self._metadata_segment(plan.scan.collection).get_metadata( + request_version_context=plan.scan.version, + where=plan.filter.where, + where_document=plan.filter.where_document, + ids=plan.filter.user_ids, + limit=plan.limit.limit, + offset=plan.limit.offset, + include_metadata=True, + ) + + ids = [r["id"] for r in records] + embeddings = None + documents = None + uris = None + metadatas = None + included = list() + + if plan.projection.embedding: + if len(records) > 0: + vectors = self._vector_segment(plan.scan.collection).get_vectors( + ids=ids, request_version_context=plan.scan.version + ) + embeddings = [v["embedding"] for v in vectors] + else: + embeddings = list() + included.append("embeddings") + + if plan.projection.document: + documents = [_doc(r["metadata"]) for r in records] + included.append("documents") + + if plan.projection.uri: + uris = [_uri(r["metadata"]) for r in records] + included.append("uris") + + if plan.projection.metadata: + metadatas = [_clean_metadata(r["metadata"]) for r in records] + included.append("metadatas") + + # TODO: Fix typing + return GetResult( + ids=ids, + embeddings=embeddings, + documents=documents, # type: ignore[typeddict-item] + uris=uris, # type: ignore[typeddict-item] + data=None, + metadatas=metadatas, # type: ignore[typeddict-item] + included=included, + ) + + @overrides + def knn(self, plan: KNNPlan) -> QueryResult: + prefiltered_ids = None + if plan.filter.user_ids or plan.filter.where or plan.filter.where_document: + records = self._metadata_segment(plan.scan.collection).get_metadata( + request_version_context=plan.scan.version, + where=plan.filter.where, + where_document=plan.filter.where_document, + ids=plan.filter.user_ids, + limit=None, + offset=0, + include_metadata=False, + ) + prefiltered_ids = [r["id"] for r in records] + + knns: Sequence[Sequence[VectorQueryResult]] = [[]] * len(plan.knn.embeddings) + + # Query vectors only when the user did not specify a filter or when the filter + # yields non-empty ids. Otherwise, the user specified a filter but it yields + # no matching ids, in which case we can return an empty result. + if prefiltered_ids is None or len(prefiltered_ids) > 0: + query = VectorQuery( + vectors=plan.knn.embeddings, + k=plan.knn.fetch, + allowed_ids=prefiltered_ids, + include_embeddings=plan.projection.embedding, + options=None, + request_version_context=plan.scan.version, + ) + knns = self._vector_segment(plan.scan.collection).query_vectors(query) + + ids = [[r["id"] for r in result] for result in knns] + embeddings = None + documents = None + uris = None + metadatas = None + distances = None + included = list() + + if plan.projection.embedding: + embeddings = [[r["embedding"] for r in result] for result in knns] + included.append("embeddings") + + if plan.projection.rank: + distances = [[r["distance"] for r in result] for result in knns] + included.append("distances") + + if plan.projection.document or plan.projection.metadata or plan.projection.uri: + merged_ids = list(set([id for result in ids for id in result])) + hydrated_records = self._metadata_segment( + plan.scan.collection + ).get_metadata( + request_version_context=plan.scan.version, + where=None, + where_document=None, + ids=merged_ids, + limit=None, + offset=0, + include_metadata=True, + ) + metadata_by_id = {r["id"]: r["metadata"] for r in hydrated_records} + + if plan.projection.document: + documents = [ + [_doc(metadata_by_id.get(id, None)) for id in result] + for result in ids + ] + included.append("documents") + + if plan.projection.uri: + uris = [ + [_uri(metadata_by_id.get(id, None)) for id in result] + for result in ids + ] + included.append("uris") + + if plan.projection.metadata: + metadatas = [ + [_clean_metadata(metadata_by_id.get(id, None)) for id in result] + for result in ids + ] + included.append("metadatas") + + # TODO: Fix typing + return QueryResult( + ids=ids, + embeddings=embeddings, # type: ignore[typeddict-item] + documents=documents, # type: ignore[typeddict-item] + uris=uris, # type: ignore[typeddict-item] + data=None, + metadatas=metadatas, # type: ignore[typeddict-item] + distances=distances, + included=included, + ) + + def _metadata_segment(self, collection: Collection) -> MetadataReader: + return self._manager.get_segment(collection.id, MetadataReader) + + def _vector_segment(self, collection: Collection) -> VectorReader: + return self._manager.get_segment(collection.id, VectorReader) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/execution/expression/__init__.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/execution/expression/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..89a2b378014171fa97c1b83a5ab7b529f17aded1 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/execution/expression/__init__.py @@ -0,0 +1,100 @@ +""" +Chromadb execution expression module for search operations. +""" + +from chromadb.execution.expression.operator import ( + # Field proxy for building Where conditions + Key, + K, + # Where expressions + Where, + And, + Or, + Eq, + Ne, + Gt, + Gte, + Lt, + Lte, + In, + Nin, + Regex, + NotRegex, + Contains, + NotContains, + # Search configuration + Limit, + Select, + # Rank expressions + Rank, + Abs, + Div, + Exp, + Log, + Max, + Min, + Mul, + Knn, + Rrf, + Sub, + Sum, + Val, + # GroupBy and Aggregate expressions + Aggregate, + MinK, + MaxK, + GroupBy, +) + +from chromadb.execution.expression.plan import ( + Search, +) + +SearchWhere = Where + +__all__ = [ + # Main search class + "Search", + # Field proxy + "Key", + "K", + # Where expressions + "SearchWhere", + "Where", + "And", + "Or", + "Eq", + "Ne", + "Gt", + "Gte", + "Lt", + "Lte", + "In", + "Nin", + "Regex", + "NotRegex", + "Contains", + "NotContains", + # Search configuration + "Limit", + "Select", + # Rank expressions + "Rank", + "Abs", + "Div", + "Exp", + "Log", + "Max", + "Min", + "Mul", + "Knn", + "Rrf", + "Sub", + "Sum", + "Val", + # GroupBy and Aggregate expressions + "Aggregate", + "MinK", + "MaxK", + "GroupBy", +] diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/execution/expression/__pycache__/__init__.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/execution/expression/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..87da069528f7d3ab8114cb85c0a7fa82aa531d6c Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/execution/expression/__pycache__/__init__.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/execution/expression/__pycache__/operator.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/execution/expression/__pycache__/operator.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1ca1101d7f8d8d958d6b88f6e81f7b718a46c541 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/execution/expression/__pycache__/operator.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/execution/expression/__pycache__/plan.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/execution/expression/__pycache__/plan.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..bfb3b3cce2477c75b00262d2250eb82ba03f080d Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/execution/expression/__pycache__/plan.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/execution/expression/operator.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/execution/expression/operator.py new file mode 100644 index 0000000000000000000000000000000000000000..c2de0e6a88139413fe522503795ea0eedd80137a --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/execution/expression/operator.py @@ -0,0 +1,1535 @@ +from dataclasses import dataclass, field +from typing import Optional, List, Dict, Set, Any, Union, cast + +from chromadb.base_types import LiteralValue + +import numpy as np +from numpy.typing import NDArray +from chromadb.api.types import ( + Embeddings, + IDs, + Include, + OneOrMany, + SparseVector, + TYPE_KEY, + SPARSE_VECTOR_TYPE_VALUE, + maybe_cast_one_to_many, + normalize_embeddings, + validate_embeddings, +) +from chromadb.types import ( + Collection, + RequestVersionContext, + Segment, +) + + +@dataclass +class Scan: + collection: Collection + knn: Segment + metadata: Segment + record: Segment + + @property + def version(self) -> RequestVersionContext: + return RequestVersionContext( + collection_version=self.collection.version, + log_position=self.collection.log_position, + ) + + +# Where expression types for filtering +@dataclass +class Where: + """Base class for Where expressions (algebraic data type). + + Supports logical operators for combining conditions: + - AND: where1 & where2 + - OR: where1 | where2 + + Examples: + # Simple conditions + where1 = Key("status") == "active" + where2 = Key("score") > 0.5 + + # Combining with AND + combined_and = where1 & where2 + + # Combining with OR + combined_or = where1 | where2 + + # Complex expressions + complex_where = (Key("status") == "active") & ((Key("score") > 0.5) | (Key("priority") == "high")) + """ + + def to_dict(self) -> Dict[str, Any]: + """Convert the Where expression to a dictionary for JSON serialization""" + raise NotImplementedError("Subclasses must implement to_dict()") + + @staticmethod + def from_dict(data: Dict[str, Any]) -> "Where": + """Create Where expression from dictionary. + + Supports MongoDB-style query operators: + - {"field": "value"} -> Key("field") == "value" (shorthand for equality) + - {"field": {"$eq": value}} -> Key("field") == value + - {"field": {"$ne": value}} -> Key("field") != value + - {"field": {"$gt": value}} -> Key("field") > value + - {"field": {"$gte": value}} -> Key("field") >= value + - {"field": {"$lt": value}} -> Key("field") < value + - {"field": {"$lte": value}} -> Key("field") <= value + - {"field": {"$in": [values]}} -> Key("field").is_in([values]) + - {"field": {"$nin": [values]}} -> Key("field").not_in([values]) + - {"field": {"$contains": "text"}} -> Key("field").contains("text") + - {"field": {"$not_contains": "text"}} -> Key("field").not_contains("text") + - {"field": {"$regex": "pattern"}} -> Key("field").regex("pattern") + - {"field": {"$not_regex": "pattern"}} -> Key("field").not_regex("pattern") + - {"$and": [conditions]} -> condition1 & condition2 & ... + - {"$or": [conditions]} -> condition1 | condition2 | ... + """ + if not isinstance(data, dict): + raise TypeError(f"Expected dict for Where, got {type(data).__name__}") + + if not data: + raise ValueError("Where dict cannot be empty") + + # Handle logical operators + if "$and" in data: + if not isinstance(data["$and"], list): + raise TypeError( + f"$and must be a list, got {type(data['$and']).__name__}" + ) + if len(data["$and"]) == 0: + raise ValueError("$and requires at least one condition") + if len(data) > 1: + raise ValueError( + "$and cannot be combined with other fields in the same dict" + ) + + conditions = [Where.from_dict(c) for c in data["$and"]] + if len(conditions) == 1: + return conditions[0] + result = conditions[0] + for c in conditions[1:]: + result = result & c + return result + + elif "$or" in data: + if not isinstance(data["$or"], list): + raise TypeError(f"$or must be a list, got {type(data['$or']).__name__}") + if len(data["$or"]) == 0: + raise ValueError("$or requires at least one condition") + if len(data) > 1: + raise ValueError( + "$or cannot be combined with other fields in the same dict" + ) + + conditions = [Where.from_dict(c) for c in data["$or"]] + if len(conditions) == 1: + return conditions[0] + result = conditions[0] + for c in conditions[1:]: + result = result | c + return result + + else: + # Single field condition + if len(data) != 1: + raise ValueError( + f"Where dict must contain exactly one field, got {len(data)}" + ) + + field, condition = next(iter(data.items())) + + if not isinstance(field, str): + raise TypeError( + f"Field name must be a string, got {type(field).__name__}" + ) + + if isinstance(condition, dict): + # Operator-based condition + if not condition: + raise ValueError( + f"Operator dict for field '{field}' cannot be empty" + ) + if len(condition) != 1: + raise ValueError( + f"Operator dict for field '{field}' must contain exactly one operator" + ) + + op, value = next(iter(condition.items())) + + if op == "$eq": + return Key(field) == value + elif op == "$ne": + return Key(field) != value + elif op == "$gt": + return Key(field) > value + elif op == "$gte": + return Key(field) >= value + elif op == "$lt": + return Key(field) < value + elif op == "$lte": + return Key(field) <= value + elif op == "$in": + if not isinstance(value, list): + raise TypeError( + f"$in requires a list, got {type(value).__name__}" + ) + return Key(field).is_in(value) + elif op == "$nin": + if not isinstance(value, list): + raise TypeError( + f"$nin requires a list, got {type(value).__name__}" + ) + return Key(field).not_in(value) + elif op == "$contains": + if not isinstance(value, (str, int, float, bool)): + raise TypeError( + f"$contains requires a str, int, float, or bool, got {type(value).__name__}" + ) + return Key(field).contains(value) + elif op == "$not_contains": + if not isinstance(value, (str, int, float, bool)): + raise TypeError( + f"$not_contains requires a str, int, float, or bool, got {type(value).__name__}" + ) + return Key(field).not_contains(value) + elif op == "$regex": + if not isinstance(value, str): + raise TypeError( + f"$regex requires a string pattern, got {type(value).__name__}" + ) + return Key(field).regex(value) + elif op == "$not_regex": + if not isinstance(value, str): + raise TypeError( + f"$not_regex requires a string pattern, got {type(value).__name__}" + ) + return Key(field).not_regex(value) + else: + raise ValueError(f"Unknown operator: {op}") + else: + # Direct value is shorthand for equality + return Key(field) == condition + + def __and__(self, other: "Where") -> "And": + """Overload & operator for AND""" + # If self is already an And, extend it + if isinstance(self, And): + # If other is also And, combine all conditions + if isinstance(other, And): + return And(self.conditions + other.conditions) + return And(self.conditions + [other]) + # If other is And, prepend self to it + elif isinstance(other, And): + return And([self] + other.conditions) + # Create new And with both conditions + return And([self, other]) + + def __or__(self, other: "Where") -> "Or": + """Overload | operator for OR""" + # If self is already an Or, extend it + if isinstance(self, Or): + # If other is also Or, combine all conditions + if isinstance(other, Or): + return Or(self.conditions + other.conditions) + return Or(self.conditions + [other]) + # If other is Or, prepend self to it + elif isinstance(other, Or): + return Or([self] + other.conditions) + # Create new Or with both conditions + return Or([self, other]) + + +@dataclass +class And(Where): + """Logical AND of multiple where conditions""" + + conditions: List[Where] + + def to_dict(self) -> Dict[str, Any]: + return {"$and": [c.to_dict() for c in self.conditions]} + + +@dataclass +class Or(Where): + """Logical OR of multiple where conditions""" + + conditions: List[Where] + + def to_dict(self) -> Dict[str, Any]: + return {"$or": [c.to_dict() for c in self.conditions]} + + +@dataclass +class Eq(Where): + """Equality comparison""" + + key: str + value: Any + + def to_dict(self) -> Dict[str, Any]: + return {self.key: {"$eq": self.value}} + + +@dataclass +class Ne(Where): + """Not equal comparison""" + + key: str + value: Any + + def to_dict(self) -> Dict[str, Any]: + return {self.key: {"$ne": self.value}} + + +@dataclass +class Gt(Where): + """Greater than comparison""" + + key: str + value: Any + + def to_dict(self) -> Dict[str, Any]: + return {self.key: {"$gt": self.value}} + + +@dataclass +class Gte(Where): + """Greater than or equal comparison""" + + key: str + value: Any + + def to_dict(self) -> Dict[str, Any]: + return {self.key: {"$gte": self.value}} + + +@dataclass +class Lt(Where): + """Less than comparison""" + + key: str + value: Any + + def to_dict(self) -> Dict[str, Any]: + return {self.key: {"$lt": self.value}} + + +@dataclass +class Lte(Where): + """Less than or equal comparison""" + + key: str + value: Any + + def to_dict(self) -> Dict[str, Any]: + return {self.key: {"$lte": self.value}} + + +@dataclass +class In(Where): + """In comparison - value is in a list""" + + key: str + values: List[Any] + + def to_dict(self) -> Dict[str, Any]: + return {self.key: {"$in": self.values}} + + +@dataclass +class Nin(Where): + """Not in comparison - value is not in a list""" + + key: str + values: List[Any] + + def to_dict(self) -> Dict[str, Any]: + return {self.key: {"$nin": self.values}} + + +@dataclass +class Contains(Where): + """Contains comparison for document content or metadata array membership""" + + key: str + value: LiteralValue + + def to_dict(self) -> Dict[str, Any]: + return {self.key: {"$contains": self.value}} + + +@dataclass +class NotContains(Where): + """Not-contains comparison for document content or metadata array membership""" + + key: str + value: LiteralValue + + def to_dict(self) -> Dict[str, Any]: + return {self.key: {"$not_contains": self.value}} + + +@dataclass +class Regex(Where): + """Regular expression matching""" + + key: str + pattern: str + + def to_dict(self) -> Dict[str, Any]: + return {self.key: {"$regex": self.pattern}} + + +@dataclass +class NotRegex(Where): + """Negative regular expression matching""" + + key: str + pattern: str + + def to_dict(self) -> Dict[str, Any]: + return {self.key: {"$not_regex": self.pattern}} + + +# Field proxy for building Where conditions +class Key: + """Field proxy for building Where filter expressions. + + The Key class allows for readable field references using either: + 1. Predefined constants for special fields: K.EMBEDDING, K.DOCUMENT, K.SCORE, etc. + 2. String literals with # prefix for special fields: Key("#embedding") + 3. Metadata field names without # prefix: Key("my_metadata_field") + + Predefined field constants (special fields with # prefix): + Key.ID - ID field (equivalent to Key("#id")) + Key.DOCUMENT - Document field (equivalent to Key("#document")) + Key.EMBEDDING - Embedding field (equivalent to Key("#embedding")) + Key.METADATA - Metadata field (equivalent to Key("#metadata")) + Key.SCORE - Score field (equivalent to Key("#score")) + + Note: K is an alias for Key, so you can use K.DOCUMENT or Key.DOCUMENT interchangeably. + + Examples: + # Using predefined keys with K alias for special fields + from chromadb.execution.expression import K + K.DOCUMENT.contains("search text") # Searches document field + + # Custom metadata field names (without # prefix) + K("status") == "active" # Metadata field named "status" + K("category").is_in(["science", "tech"]) # Metadata field named "category" + K("sparse_embedding") # Example: metadata field (could store anything) + + # Using with Knn for different fields + Knn(query=[0.1, 0.2]) # Default: searches "#embedding" + Knn(query=[0.1, 0.2], key=K.EMBEDDING) # Explicit: searches "#embedding" + Knn(query=sparse, key="sparse_embedding") # Example: searches a metadata field + + # Combining conditions + (K("status") == "active") & (K.SCORE > 0.5) + """ + + # Predefined key constants (initialized after class definition) + ID: "Key" + DOCUMENT: "Key" + EMBEDDING: "Key" + METADATA: "Key" + SCORE: "Key" + + def __init__(self, name: str): + self.name = name + + def __hash__(self) -> int: + """Make Key hashable for use in sets""" + return hash(self.name) + + # Comparison operators + def __eq__(self, value: Any) -> Eq: # type: ignore[override] + """Equality: Key('field') == value""" + return Eq(self.name, value) + + def __ne__(self, value: Any) -> Ne: # type: ignore[override] + """Not equal: Key('field') != value""" + return Ne(self.name, value) + + def __gt__(self, value: Any) -> Gt: + """Greater than: Key('field') > value""" + return Gt(self.name, value) + + def __ge__(self, value: Any) -> Gte: + """Greater than or equal: Key('field') >= value""" + return Gte(self.name, value) + + def __lt__(self, value: Any) -> Lt: + """Less than: Key('field') < value""" + return Lt(self.name, value) + + def __le__(self, value: Any) -> Lte: + """Less than or equal: Key('field') <= value""" + return Lte(self.name, value) + + # Builder methods for operations without operators + def is_in(self, values: List[Any]) -> In: + """Check if field value is in list: Key('field').is_in(['a', 'b'])""" + return In(self.name, values) + + def not_in(self, values: List[Any]) -> Nin: + """Check if field value is not in list: Key('field').not_in(['a', 'b'])""" + return Nin(self.name, values) + + def regex(self, pattern: str) -> Regex: + """Match field against regex: Key('field').regex('^pattern')""" + return Regex(self.name, pattern) + + def not_regex(self, pattern: str) -> NotRegex: + """Field should not match regex: Key('field').not_regex('^pattern')""" + return NotRegex(self.name, pattern) + + def contains(self, value: LiteralValue) -> Contains: + """Check if field contains a value. + + On Key.DOCUMENT: substring search (value must be a string). + On metadata fields: checks if the array field contains the scalar value. + + Examples: + Key.DOCUMENT.contains("machine learning") # document substring + Key("tags").contains("action") # metadata array contains + Key("scores").contains(42) # metadata array contains + """ + if self.name == "#document" and not isinstance(value, str): + raise TypeError("$contains on #document requires a string pattern") + return Contains(self.name, value) + + def not_contains(self, value: LiteralValue) -> NotContains: + """Check if field does not contain a value. + + On Key.DOCUMENT: excludes documents containing the substring. + On metadata fields: checks that the array field does not contain the scalar value. + + Examples: + Key.DOCUMENT.not_contains("deprecated") # document substring exclusion + Key("tags").not_contains("draft") # metadata array not-contains + """ + if self.name == "#document" and not isinstance(value, str): + raise TypeError("$not_contains on #document requires a string pattern") + return NotContains(self.name, value) + + +# Initialize predefined key constants +Key.ID = Key("#id") +Key.DOCUMENT = Key("#document") +Key.EMBEDDING = Key("#embedding") +Key.METADATA = Key("#metadata") +Key.SCORE = Key("#score") + +# Alias for Key +K = Key + + +@dataclass +class Filter: + user_ids: Optional[IDs] = None + where: Optional[Any] = None # Old Where type from chromadb.types + where_document: Optional[Any] = None # Old WhereDocument type + + +@dataclass +class KNN: + embeddings: Embeddings + fetch: int + + +@dataclass +class Limit: + offset: int = 0 + limit: Optional[int] = None + + def to_dict(self) -> Dict[str, Any]: + """Convert the Limit to a dictionary for JSON serialization""" + result = {"offset": self.offset} + if self.limit is not None: + result["limit"] = self.limit + return result + + @staticmethod + def from_dict(data: Dict[str, Any]) -> "Limit": + """Create Limit from dictionary. + + Examples: + - {"offset": 10} -> Limit(offset=10) + - {"offset": 10, "limit": 20} -> Limit(offset=10, limit=20) + - {"limit": 20} -> Limit(offset=0, limit=20) + """ + if not isinstance(data, dict): + raise TypeError(f"Expected dict for Limit, got {type(data).__name__}") + + offset = data.get("offset", 0) + if not isinstance(offset, int): + raise TypeError( + f"Limit offset must be an integer, got {type(offset).__name__}" + ) + if offset < 0: + raise ValueError(f"Limit offset must be non-negative, got {offset}") + + limit = data.get("limit") + if limit is not None: + if not isinstance(limit, int): + raise TypeError( + f"Limit limit must be an integer, got {type(limit).__name__}" + ) + if limit <= 0: + raise ValueError(f"Limit limit must be positive, got {limit}") + + # Check for unexpected keys + allowed_keys = {"offset", "limit"} + unexpected_keys = set(data.keys()) - allowed_keys + if unexpected_keys: + raise ValueError(f"Unexpected keys in Limit dict: {unexpected_keys}") + + return Limit(offset=offset, limit=limit) + + +@dataclass +class Projection: + document: bool = False + embedding: bool = False + metadata: bool = False + rank: bool = False + uri: bool = False + + @property + def included(self) -> Include: + includes = list() + if self.document: + includes.append("documents") + if self.embedding: + includes.append("embeddings") + if self.metadata: + includes.append("metadatas") + if self.rank: + includes.append("distances") + if self.uri: + includes.append("uris") + return includes # type: ignore[return-value] + + +# Rank expression types for hybrid search +@dataclass +class Rank: + """Base class for rank expressions. + + Supports arithmetic operations for combining rank expressions: + - Addition: rank1 + rank2, rank + 0.5 + - Subtraction: rank1 - rank2, rank - 0.5 + - Multiplication: rank1 * rank2, rank * 0.8 + - Division: rank1 / rank2, rank / 2.0 + - Negation: -rank + - Absolute value: abs(rank) + + Supports mathematical functions: + - Exponential: rank.exp() + - Logarithm: rank.log() + - Maximum: rank.max(other) + - Minimum: rank.min(other) + + Examples: + # Weighted combination + Knn(query=[0.1, 0.2]) * 0.8 + Val(0.5) * 0.2 + + # Normalization + Knn(query=[0.1, 0.2]) / Val(10.0) + + # Clamping + Knn(query=[0.1, 0.2]).min(1.0).max(0.0) + """ + + def to_dict(self) -> Dict[str, Any]: + """Convert the Score expression to a dictionary for JSON serialization""" + raise NotImplementedError("Subclasses must implement to_dict()") + + @staticmethod + def from_dict(data: Dict[str, Any]) -> "Rank": + """Create Rank expression from dictionary. + + Supports operators: + - {"$val": number} -> Val(number) + - {"$knn": {...}} -> Knn(...) + - {"$sum": [ranks]} -> rank1 + rank2 + ... + - {"$sub": {"left": ..., "right": ...}} -> left - right + - {"$mul": [ranks]} -> rank1 * rank2 * ... + - {"$div": {"left": ..., "right": ...}} -> left / right + - {"$abs": rank} -> abs(rank) + - {"$exp": rank} -> rank.exp() + - {"$log": rank} -> rank.log() + - {"$max": [ranks]} -> rank1.max(rank2).max(rank3)... + - {"$min": [ranks]} -> rank1.min(rank2).min(rank3)... + """ + if not isinstance(data, dict): + raise TypeError(f"Expected dict for Rank, got {type(data).__name__}") + + if not data: + raise ValueError("Rank dict cannot be empty") + + if len(data) != 1: + raise ValueError( + f"Rank dict must contain exactly one operator, got {len(data)}" + ) + + op = next(iter(data.keys())) + + if op == "$val": + value = data["$val"] + if not isinstance(value, (int, float)): + raise TypeError(f"$val requires a number, got {type(value).__name__}") + return Val(value) + + elif op == "$knn": + knn_data = data["$knn"] + if not isinstance(knn_data, dict): + raise TypeError(f"$knn requires a dict, got {type(knn_data).__name__}") + + if "query" not in knn_data: + raise ValueError("$knn requires 'query' field") + + query = knn_data["query"] + + if isinstance(query, dict): + # SparseVector case - deserialize from transport format + if query.get(TYPE_KEY) == SPARSE_VECTOR_TYPE_VALUE: + query = SparseVector.from_dict(query) + else: + # Old format or invalid - try to construct directly + raise ValueError( + f"Expected dict with {TYPE_KEY}='{SPARSE_VECTOR_TYPE_VALUE}', got {query}" + ) + + elif isinstance(query, (list, tuple, np.ndarray)): + # Dense vector case - normalize then validate + normalized = normalize_embeddings(query) + if not normalized or len(normalized) > 1: + raise ValueError("$knn requires exactly one query embedding") + + # Validate the normalized version + validate_embeddings(normalized) + + query = normalized[0] + + else: + raise TypeError( + f"$knn query must be a list, numpy array, or SparseVector dict, got {type(query).__name__}" + ) + + key = knn_data.get("key", "#embedding") + if not isinstance(key, str): + raise TypeError(f"$knn key must be a string, got {type(key).__name__}") + + limit = knn_data.get("limit", 16) + if not isinstance(limit, int): + raise TypeError( + f"$knn limit must be an integer, got {type(limit).__name__}" + ) + if limit <= 0: + raise ValueError(f"$knn limit must be positive, got {limit}") + + return_rank = knn_data.get("return_rank", False) + if not isinstance(return_rank, bool): + raise TypeError( + f"$knn return_rank must be a boolean, got {type(return_rank).__name__}" + ) + + return Knn( + query=query, + key=key, + limit=limit, + default=knn_data.get("default"), + return_rank=return_rank, + ) + + elif op == "$sum": + ranks_data = data["$sum"] + if not isinstance(ranks_data, (list, tuple)): + raise TypeError( + f"$sum requires a list, got {type(ranks_data).__name__}" + ) + if len(ranks_data) < 2: + raise ValueError( + f"$sum requires at least 2 ranks, got {len(ranks_data)}" + ) + + ranks = [Rank.from_dict(r) for r in ranks_data] + result = ranks[0] + for r in ranks[1:]: + result = result + r + return result + + elif op == "$sub": + sub_data = data["$sub"] + if not isinstance(sub_data, dict): + raise TypeError( + f"$sub requires a dict with 'left' and 'right', got {type(sub_data).__name__}" + ) + if "left" not in sub_data or "right" not in sub_data: + raise ValueError("$sub requires 'left' and 'right' fields") + + left = Rank.from_dict(sub_data["left"]) + right = Rank.from_dict(sub_data["right"]) + return left - right + + elif op == "$mul": + ranks_data = data["$mul"] + if not isinstance(ranks_data, (list, tuple)): + raise TypeError( + f"$mul requires a list, got {type(ranks_data).__name__}" + ) + if len(ranks_data) < 2: + raise ValueError( + f"$mul requires at least 2 ranks, got {len(ranks_data)}" + ) + + ranks = [Rank.from_dict(r) for r in ranks_data] + result = ranks[0] + for r in ranks[1:]: + result = result * r + return result + + elif op == "$div": + div_data = data["$div"] + if not isinstance(div_data, dict): + raise TypeError( + f"$div requires a dict with 'left' and 'right', got {type(div_data).__name__}" + ) + if "left" not in div_data or "right" not in div_data: + raise ValueError("$div requires 'left' and 'right' fields") + + left = Rank.from_dict(div_data["left"]) + right = Rank.from_dict(div_data["right"]) + return left / right + + elif op == "$abs": + child_data = data["$abs"] + if not isinstance(child_data, dict): + raise TypeError( + f"$abs requires a rank dict, got {type(child_data).__name__}" + ) + return abs(Rank.from_dict(child_data)) + + elif op == "$exp": + child_data = data["$exp"] + if not isinstance(child_data, dict): + raise TypeError( + f"$exp requires a rank dict, got {type(child_data).__name__}" + ) + return Rank.from_dict(child_data).exp() + + elif op == "$log": + child_data = data["$log"] + if not isinstance(child_data, dict): + raise TypeError( + f"$log requires a rank dict, got {type(child_data).__name__}" + ) + return Rank.from_dict(child_data).log() + + elif op == "$max": + ranks_data = data["$max"] + if not isinstance(ranks_data, (list, tuple)): + raise TypeError( + f"$max requires a list, got {type(ranks_data).__name__}" + ) + if len(ranks_data) < 2: + raise ValueError( + f"$max requires at least 2 ranks, got {len(ranks_data)}" + ) + + ranks = [Rank.from_dict(r) for r in ranks_data] + result = ranks[0] + for r in ranks[1:]: + result = result.max(r) + return result + + elif op == "$min": + ranks_data = data["$min"] + if not isinstance(ranks_data, (list, tuple)): + raise TypeError( + f"$min requires a list, got {type(ranks_data).__name__}" + ) + if len(ranks_data) < 2: + raise ValueError( + f"$min requires at least 2 ranks, got {len(ranks_data)}" + ) + + ranks = [Rank.from_dict(r) for r in ranks_data] + result = ranks[0] + for r in ranks[1:]: + result = result.min(r) + return result + + else: + raise ValueError(f"Unknown rank operator: {op}") + + # Arithmetic operators + def __add__(self, other: Union["Rank", float, int]) -> "Sum": + """Addition: rank1 + rank2 or rank + value""" + other_rank = Val(other) if isinstance(other, (int, float)) else other + # Flatten if already Sum + if isinstance(self, Sum): + if isinstance(other_rank, Sum): + return Sum(self.ranks + other_rank.ranks) + return Sum(self.ranks + [other_rank]) + elif isinstance(other_rank, Sum): + return Sum([self] + other_rank.ranks) + return Sum([self, other_rank]) + + def __radd__(self, other: Union[float, int]) -> "Sum": + """Right addition: value + rank""" + return Val(other) + self + + def __sub__(self, other: Union["Rank", float, int]) -> "Sub": + """Subtraction: rank1 - rank2 or rank - value""" + other_rank = Val(other) if isinstance(other, (int, float)) else other + return Sub(self, other_rank) + + def __rsub__(self, other: Union[float, int]) -> "Sub": + """Right subtraction: value - rank""" + return Sub(Val(other), self) + + def __mul__(self, other: Union["Rank", float, int]) -> "Mul": + """Multiplication: rank1 * rank2 or rank * value""" + other_rank = Val(other) if isinstance(other, (int, float)) else other + # Flatten if already Mul + if isinstance(self, Mul): + if isinstance(other_rank, Mul): + return Mul(self.ranks + other_rank.ranks) + return Mul(self.ranks + [other_rank]) + elif isinstance(other_rank, Mul): + return Mul([self] + other_rank.ranks) + return Mul([self, other_rank]) + + def __rmul__(self, other: Union[float, int]) -> "Mul": + """Right multiplication: value * rank""" + return Val(other) * self + + def __truediv__(self, other: Union["Rank", float, int]) -> "Div": + """Division: rank1 / rank2 or rank / value""" + other_rank = Val(other) if isinstance(other, (int, float)) else other + return Div(self, other_rank) + + def __rtruediv__(self, other: Union[float, int]) -> "Div": + """Right division: value / rank""" + return Div(Val(other), self) + + def __neg__(self) -> "Mul": + """Negation: -rank (equivalent to -1 * rank)""" + return Mul([Val(-1), self]) + + def __abs__(self) -> "Abs": + """Absolute value: abs(rank)""" + return Abs(self) + + def abs(self) -> "Abs": + """Absolute value builder: rank.abs()""" + return Abs(self) + + # Builder methods for functions + def exp(self) -> "Exp": + """Exponential: e^rank""" + return Exp(self) + + def log(self) -> "Log": + """Natural logarithm: ln(rank)""" + return Log(self) + + def max(self, other: Union["Rank", float, int]) -> "Max": + """Maximum of this rank and another: rank.max(rank2)""" + other_rank = Val(other) if isinstance(other, (int, float)) else other + + # Flatten if already Max + if isinstance(self, Max): + if isinstance(other_rank, Max): + return Max(self.ranks + other_rank.ranks) + return Max(self.ranks + [other_rank]) + elif isinstance(other_rank, Max): + return Max([self] + other_rank.ranks) + return Max([self, other_rank]) + + def min(self, other: Union["Rank", float, int]) -> "Min": + """Minimum of this rank and another: rank.min(rank2)""" + other_rank = Val(other) if isinstance(other, (int, float)) else other + + # Flatten if already Min + if isinstance(self, Min): + if isinstance(other_rank, Min): + return Min(self.ranks + other_rank.ranks) + return Min(self.ranks + [other_rank]) + elif isinstance(other_rank, Min): + return Min([self] + other_rank.ranks) + return Min([self, other_rank]) + + +@dataclass +class Abs(Rank): + """Absolute value of a rank""" + + rank: Rank + + def to_dict(self) -> Dict[str, Any]: + return {"$abs": self.rank.to_dict()} + + +@dataclass +class Div(Rank): + """Division of two ranks""" + + left: Rank + right: Rank + + def to_dict(self) -> Dict[str, Any]: + return {"$div": {"left": self.left.to_dict(), "right": self.right.to_dict()}} + + +@dataclass +class Exp(Rank): + """Exponentiation of a rank""" + + rank: Rank + + def to_dict(self) -> Dict[str, Any]: + return {"$exp": self.rank.to_dict()} + + +@dataclass +class Log(Rank): + """Logarithm of a rank""" + + rank: Rank + + def to_dict(self) -> Dict[str, Any]: + return {"$log": self.rank.to_dict()} + + +@dataclass +class Max(Rank): + """Maximum of multiple ranks""" + + ranks: List[Rank] + + def to_dict(self) -> Dict[str, Any]: + return {"$max": [r.to_dict() for r in self.ranks]} + + +@dataclass +class Min(Rank): + """Minimum of multiple ranks""" + + ranks: List[Rank] + + def to_dict(self) -> Dict[str, Any]: + return {"$min": [r.to_dict() for r in self.ranks]} + + +@dataclass +class Mul(Rank): + """Multiplication of multiple ranks""" + + ranks: List[Rank] + + def to_dict(self) -> Dict[str, Any]: + return {"$mul": [r.to_dict() for r in self.ranks]} + + +@dataclass +class Knn(Rank): + """KNN-based ranking expression. + + Args: + query: The query for KNN search. Can be: + - A string (will be automatically embedded using the collection's embedding function) + - A dense vector (list or numpy array) + - A sparse vector (SparseVector dict) + key: The embedding key to search against. Can be: + - Key.EMBEDDING (default) - searches the main embedding field + - A metadata field name (e.g., "my_custom_field") - searches that metadata field + limit: Maximum number of results to consider (default: 16) + default: Default score for records not in KNN results (default: None) + return_rank: If True, return the rank position (0, 1, 2, ...) instead of distance (default: False) + + Examples: + # Search with string query (automatically embedded) + Knn(query="hello world") # Will use collection's embedding function + + # Search main embeddings with vectors (equivalent forms) + Knn(query=[0.1, 0.2]) # Uses default key="#embedding" + Knn(query=[0.1, 0.2], key=K.EMBEDDING) + Knn(query=[0.1, 0.2], key="#embedding") + + # Search sparse embeddings stored in metadata with string + Knn(query="hello world", key="custom_embedding") # Will use schema's embedding function + + # Search sparse embeddings stored in metadata with vector + Knn(query=my_vector, key="custom_embedding") # Example: searches a metadata field + """ + + query: Union[ + str, + List[float], + SparseVector, + "NDArray[np.float32]", + "NDArray[np.float64]", + "NDArray[np.int32]", + ] + key: Union[Key, str] = K.EMBEDDING + limit: int = 16 + default: Optional[float] = None + return_rank: bool = False + + def to_dict(self) -> Dict[str, Any]: + # Convert to transport format + query_value = self.query + if isinstance(query_value, SparseVector): + # Convert SparseVector dataclass to transport dict + query_value = query_value.to_dict() + elif isinstance(query_value, np.ndarray): + # Convert numpy array to list + query_value = query_value.tolist() + + key_value = self.key + if isinstance(key_value, Key): + key_value = key_value.name + + # Build result dict - only include non-default values to keep JSON clean + result = {"query": query_value, "key": key_value, "limit": self.limit} + + # Only include optional fields if they're set to non-default values + if self.default is not None: + result["default"] = self.default # type: ignore[assignment] + if self.return_rank: # Only include if True (non-default) + result["return_rank"] = self.return_rank + + return {"$knn": result} + + +@dataclass +class Sub(Rank): + """Subtraction of two ranks""" + + left: Rank + right: Rank + + def to_dict(self) -> Dict[str, Any]: + return {"$sub": {"left": self.left.to_dict(), "right": self.right.to_dict()}} + + +@dataclass +class Sum(Rank): + """Summation of multiple ranks""" + + ranks: List[Rank] + + def to_dict(self) -> Dict[str, Any]: + return {"$sum": [r.to_dict() for r in self.ranks]} + + +@dataclass +class Val(Rank): + """Constant rank value""" + + value: float + + def to_dict(self) -> Dict[str, Any]: + return {"$val": self.value} + + +@dataclass +class Rrf(Rank): + """Reciprocal Rank Fusion for combining ranking strategies. + + RRF formula: score = -sum(weight_i / (k + rank_i)) for each ranking strategy + The negative is used because RRF produces higher scores for better results, + but Chroma uses ascending order (lower scores = better results). + + Args: + ranks: List of Rank expressions to fuse (must have at least one) + k: Smoothing constant (default: 60, standard in literature) + weights: Optional weights for each ranking strategy. If not provided, + all ranks are weighted equally (weight=1.0 each). + normalize: If True, normalize weights to sum to 1.0 (default: False). + When False, weights are used as-is for relative importance. + When True, weights are scaled so they sum to 1.0. + + Examples: + # Note: metadata fields (like "sparse_embedding" below) are user-defined and can store any data. + # The field name is just an example - use whatever name matches your metadata structure. + # Basic RRF combining KNN rankings (equal weight) + Rrf([ + Knn(query=[0.1, 0.2], return_rank=True), + Knn(query=another_vector, key="custom_embedding", return_rank=True) # Example metadata field + ]) + + # Weighted RRF with relative weights (not normalized) + Rrf( + ranks=[ + Knn(query=[0.1, 0.2], return_rank=True), + Knn(query=another_vector, key="custom_embedding", return_rank=True) # Example metadata field + weights=[2.0, 1.0], # First ranking is 2x more important + k=100 + ) + + # Weighted RRF with normalized weights + Rrf( + ranks=[ + Knn(query=[0.1, 0.2], return_rank=True), + Knn(query=another_vector, key="custom_embedding", return_rank=True) # Example metadata field + ], + weights=[3.0, 1.0], # Will be normalized to [0.75, 0.25] + normalize=True, + k=100 + ) + """ + + ranks: List[Rank] + k: int = 60 + weights: Optional[List[float]] = None + normalize: bool = False + + def to_dict(self) -> Dict[str, Any]: + """Convert RRF to a composition of existing expression operators. + + Builds: -sum(weight_i / (k + rank_i)) for each rank + Using Python's overloaded operators for cleaner code. + """ + # Validate RRF parameters + if not self.ranks: + raise ValueError("RRF requires at least one rank") + if self.k <= 0: + raise ValueError(f"k must be positive, got {self.k}") + + # Validate weights if provided + if self.weights is not None: + if len(self.weights) != len(self.ranks): + raise ValueError( + f"Number of weights ({len(self.weights)}) must match number of ranks ({len(self.ranks)})" + ) + if any(w < 0.0 for w in self.weights): + raise ValueError("All weights must be non-negative") + + # Populate weights with 1.0 if not provided + weights = self.weights if self.weights else [1.0] * len(self.ranks) + + # Normalize weights if requested + if self.normalize: + weight_sum = sum(weights) + if weight_sum == 0: + raise ValueError("Sum of weights must be positive when normalize=True") + weights = [w / weight_sum for w in weights] + + # Zip weights with ranks and build terms: weight / (k + rank) + terms = [w / (self.k + rank) for w, rank in zip(weights, self.ranks)] + + # Sum all terms - guaranteed to have at least one + rrf_sum: Rank = terms[0] + for term in terms[1:]: + rrf_sum = rrf_sum + term + + # Negate (RRF gives higher scores for better, Chroma needs lower for better) + return (-rrf_sum).to_dict() + + +@dataclass +class Select: + """Selection configuration for search results. + + Fields can be: + - Key.DOCUMENT - Select document key (equivalent to Key("#document")) + - Key.EMBEDDING - Select embedding key (equivalent to Key("#embedding")) + - Key.SCORE - Select score key (equivalent to Key("#score")) + - Any other string - Select specific metadata property + + Note: You can use K as an alias for Key for more concise code. + + Examples: + # Select predefined keys using K alias (K is shorthand for Key) + from chromadb.execution.expression import K + Select(keys={K.DOCUMENT, K.SCORE}) + + # Select specific metadata properties + Select(keys={"title", "author", "date"}) + + # Mixed selection + Select(keys={K.DOCUMENT, "title", "author"}) + """ + + keys: Set[Union[Key, str]] = field(default_factory=set) + + def to_dict(self) -> Dict[str, Any]: + """Convert the Select to a dictionary for JSON serialization""" + # Convert Key objects to their string values + key_strings = [] + for k in self.keys: + if isinstance(k, Key): + key_strings.append(k.name) + else: + key_strings.append(k) + # Remove duplicates while preserving order + return {"keys": list(dict.fromkeys(key_strings))} + + @staticmethod + def from_dict(data: Dict[str, Any]) -> "Select": + """Create Select from dictionary. + + Examples: + - {"keys": ["#document", "#score"]} -> Select(keys={Key.DOCUMENT, Key.SCORE}) + - {"keys": ["title", "author"]} -> Select(keys={"title", "author"}) + """ + if not isinstance(data, dict): + raise TypeError(f"Expected dict for Select, got {type(data).__name__}") + + keys = data.get("keys", []) + if not isinstance(keys, (list, tuple, set)): + raise TypeError( + f"Select keys must be a list/tuple/set, got {type(keys).__name__}" + ) + + # Validate and convert each key + key_list = [] + for k in keys: + if not isinstance(k, str): + raise TypeError(f"Select key must be a string, got {type(k).__name__}") + + # Map special keys to Key instances + if k == "#id": + key_list.append(Key.ID) + elif k == "#document": + key_list.append(Key.DOCUMENT) + elif k == "#embedding": + key_list.append(Key.EMBEDDING) + elif k == "#metadata": + key_list.append(Key.METADATA) + elif k == "#score": + key_list.append(Key.SCORE) + else: + # Regular metadata field + key_list.append(Key(k)) + + # Check for unexpected keys in dict + allowed_keys = {"keys"} + unexpected_keys = set(data.keys()) - allowed_keys + if unexpected_keys: + raise ValueError(f"Unexpected keys in Select dict: {unexpected_keys}") + + # Convert to set while preserving the Key instances + return Select(keys=set(key_list)) + + +# GroupBy and Aggregate types for grouping search results + + +def _keys_to_strings(keys: OneOrMany[Union[Key, str]]) -> List[str]: + """Convert OneOrMany[Key|str] to List[str] for serialization.""" + keys_list = cast(List[Union[Key, str]], maybe_cast_one_to_many(keys)) + return [k.name if isinstance(k, Key) else k for k in keys_list] + + +def _strings_to_keys(keys: Union[List[Any], tuple[Any, ...]]) -> List[Union[Key, str]]: + """Convert List[str] to List[Key] for deserialization.""" + return [Key(k) if isinstance(k, str) else k for k in keys] + + +def _parse_k_aggregate( + op: str, data: Dict[str, Any] +) -> tuple[List[Union[Key, str]], int]: + """Parse common fields for MinK/MaxK from dict. + + Args: + op: The operator name (e.g., "$min_k" or "$max_k") + data: The dict containing the operator + + Returns: + Tuple of (keys, k) where keys is List[Union[Key, str]] and k is int + + Raises: + TypeError: If data types are invalid + ValueError: If required fields are missing or invalid + """ + agg_data = data[op] + if not isinstance(agg_data, dict): + raise TypeError(f"{op} requires a dict, got {type(agg_data).__name__}") + if "keys" not in agg_data: + raise ValueError(f"{op} requires 'keys' field") + if "k" not in agg_data: + raise ValueError(f"{op} requires 'k' field") + + keys = agg_data["keys"] + if not isinstance(keys, (list, tuple)): + raise TypeError(f"{op} keys must be a list, got {type(keys).__name__}") + if not keys: + raise ValueError(f"{op} keys cannot be empty") + + k = agg_data["k"] + if not isinstance(k, int): + raise TypeError(f"{op} k must be an integer, got {type(k).__name__}") + if k <= 0: + raise ValueError(f"{op} k must be positive, got {k}") + + return _strings_to_keys(keys), k + + +@dataclass +class Aggregate: + """Base class for aggregation expressions within groups. + + Aggregations determine which records to keep from each group: + - MinK: Keep k records with minimum values (ascending order) + - MaxK: Keep k records with maximum values (descending order) + + Examples: + # Keep top 3 by score per group (single key) + MinK(keys=Key.SCORE, k=3) + + # Keep top 5 by priority, then score as tiebreaker (multiple keys) + MinK(keys=[Key("priority"), Key.SCORE], k=5) + + # Keep bottom 2 by score per group + MaxK(keys=Key.SCORE, k=2) + """ + + def to_dict(self) -> Dict[str, Any]: + """Convert the Aggregate expression to a dictionary for JSON serialization""" + raise NotImplementedError("Subclasses must implement to_dict()") + + @staticmethod + def from_dict(data: Dict[str, Any]) -> "Aggregate": + """Create Aggregate expression from dictionary. + + Supports: + - {"$min_k": {"keys": [...], "k": n}} -> MinK(keys=[...], k=n) + - {"$max_k": {"keys": [...], "k": n}} -> MaxK(keys=[...], k=n) + """ + if not isinstance(data, dict): + raise TypeError(f"Expected dict for Aggregate, got {type(data).__name__}") + + if not data: + raise ValueError("Aggregate dict cannot be empty") + + if len(data) != 1: + raise ValueError( + f"Aggregate dict must contain exactly one operator, got {len(data)}" + ) + + op = next(iter(data.keys())) + + if op == "$min_k": + keys, k = _parse_k_aggregate(op, data) + return MinK(keys=keys, k=k) + elif op == "$max_k": + keys, k = _parse_k_aggregate(op, data) + return MaxK(keys=keys, k=k) + else: + raise ValueError(f"Unknown aggregate operator: {op}") + + +@dataclass +class MinK(Aggregate): + """Keep k records with minimum aggregate key values per group""" + + keys: OneOrMany[Union[Key, str]] + k: int + + def to_dict(self) -> Dict[str, Any]: + return {"$min_k": {"keys": _keys_to_strings(self.keys), "k": self.k}} + + +@dataclass +class MaxK(Aggregate): + """Keep k records with maximum aggregate key values per group""" + + keys: OneOrMany[Union[Key, str]] + k: int + + def to_dict(self) -> Dict[str, Any]: + return {"$max_k": {"keys": _keys_to_strings(self.keys), "k": self.k}} + + +@dataclass +class GroupBy: + """Group results by metadata keys and aggregate within each group. + + Groups search results by one or more metadata fields, then applies an + aggregation (MinK or MaxK) to select records within each group. + The final output is flattened and sorted by score. + + Args: + keys: Metadata key(s) to group by. Can be a single key or a list of keys. + E.g., Key("category") or [Key("category"), Key("author")] + aggregate: Aggregation to apply within each group (MinK or MaxK) + + Note: Both keys and aggregate must be specified together. + + Examples: + # Top 3 documents per category (single key) + GroupBy( + keys=Key("category"), + aggregate=MinK(keys=Key.SCORE, k=3) + ) + + # Top 2 per (year, category) combination (multiple keys) + GroupBy( + keys=[Key("year"), Key("category")], + aggregate=MinK(keys=Key.SCORE, k=2) + ) + + # Top 1 per category by priority, score as tiebreaker + GroupBy( + keys=Key("category"), + aggregate=MinK(keys=[Key("priority"), Key.SCORE], k=1) + ) + """ + + keys: OneOrMany[Union[Key, str]] = field(default_factory=list) + aggregate: Optional[Aggregate] = None + + def to_dict(self) -> Dict[str, Any]: + """Convert the GroupBy to a dictionary for JSON serialization""" + # Default GroupBy (no keys, no aggregate) serializes to {} + if not self.keys or self.aggregate is None: + return {} + result: Dict[str, Any] = {"keys": _keys_to_strings(self.keys)} + result["aggregate"] = self.aggregate.to_dict() + return result + + @staticmethod + def from_dict(data: Dict[str, Any]) -> "GroupBy": + """Create GroupBy from dictionary. + + Examples: + - {} -> GroupBy() (default, no grouping) + - {"keys": ["category"], "aggregate": {"$min_k": {"keys": ["#score"], "k": 3}}} + """ + if not isinstance(data, dict): + raise TypeError(f"Expected dict for GroupBy, got {type(data).__name__}") + + # Empty dict returns default GroupBy (no grouping) + if not data: + return GroupBy() + + # Non-empty dict requires keys and aggregate + if "keys" not in data: + raise ValueError("GroupBy requires 'keys' field") + if "aggregate" not in data: + raise ValueError("GroupBy requires 'aggregate' field") + + keys = data["keys"] + if not isinstance(keys, (list, tuple)): + raise TypeError(f"GroupBy keys must be a list, got {type(keys).__name__}") + if not keys: + raise ValueError("GroupBy keys cannot be empty") + + aggregate_data = data["aggregate"] + if not isinstance(aggregate_data, dict): + raise TypeError( + f"GroupBy aggregate must be a dict, got {type(aggregate_data).__name__}" + ) + aggregate = Aggregate.from_dict(aggregate_data) + + return GroupBy(keys=_strings_to_keys(keys), aggregate=aggregate) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/execution/expression/plan.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/execution/expression/plan.py new file mode 100644 index 0000000000000000000000000000000000000000..83bceba72a2a41a00f1ea5a0f04305a517858454 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/execution/expression/plan.py @@ -0,0 +1,281 @@ +from dataclasses import dataclass, field +from typing import List, Dict, Any, Union, Set, Optional + +from chromadb.execution.expression.operator import ( + KNN, + Filter, + GroupBy, + Limit, + Projection, + Scan, + Rank, + Select, + Where, + Key, +) + + +@dataclass +class CountPlan: + scan: Scan + + +@dataclass +class GetPlan: + scan: Scan + filter: Filter = field(default_factory=Filter) + limit: Limit = field(default_factory=Limit) + projection: Projection = field(default_factory=Projection) + + +@dataclass +class KNNPlan: + scan: Scan + knn: KNN + filter: Filter = field(default_factory=Filter) + projection: Projection = field(default_factory=Projection) + + +class Search: + """Payload for hybrid search operations. + + Can be constructed by directly providing the parameters, or by using the builder pattern. + + Examples: + Direct construction with expressions: + Search( + where=Key("status") == "active", + rank=Knn(query=[0.1, 0.2]), + limit=Limit(limit=10), + select=Select(keys={Key.DOCUMENT}), + ) + + Direct construction with dicts: + Search( + where={"status": "active"}, + rank={"$knn": {"query": [0.1, 0.2]}}, + limit=10, + select=["#document", "#score"], + ) + + Builder pattern: + (Search() + .where(Key("status") == "active") + .rank(Knn(query=[0.1, 0.2])) + .limit(10) + .select(Key.DOCUMENT)) + """ + + def __init__( + self, + where: Optional[Union[Where, Dict[str, Any]]] = None, + rank: Optional[Union[Rank, Dict[str, Any]]] = None, + group_by: Optional[Union[GroupBy, Dict[str, Any]]] = None, + limit: Optional[Union[Limit, Dict[str, Any], int]] = None, + select: Optional[Union[Select, Dict[str, Any], List[str], Set[str]]] = None, + ): + """Initialize a Search payload. + + Args: + where: Where expression or dict for filtering results (defaults to None - no filtering) + Dict will be converted using Where.from_dict() + rank: Rank expression or dict for scoring (defaults to None - no ranking) + Dict will be converted using Rank.from_dict() + Note: Primitive numbers are not accepted - use {"$val": number} for constant ranks + group_by: GroupBy configuration for grouping and aggregating results (defaults to None) + Dict will be converted using GroupBy.from_dict() + limit: Limit configuration for pagination (defaults to no limit) + Can be a Limit object, a dict for Limit.from_dict(), or an int + When passing an int, it creates Limit(limit=value, offset=0) + select: Select configuration for keys (defaults to empty selection) + Can be a Select object, a dict for Select.from_dict(), + or a list/set of strings (e.g., ["#document", "#score"]) + """ + # Handle where parameter + if where is None: + self._where = None + elif isinstance(where, Where): + self._where = where + elif isinstance(where, dict): + self._where = Where.from_dict(where) + else: + raise TypeError( + f"where must be a Where object, dict, or None, got {type(where).__name__}" + ) + + # Handle rank parameter + if rank is None: + self._rank = None + elif isinstance(rank, Rank): + self._rank = rank + elif isinstance(rank, dict): + self._rank = Rank.from_dict(rank) + else: + raise TypeError( + f"rank must be a Rank object, dict, or None, got {type(rank).__name__}" + ) + + # Handle group_by parameter + if group_by is None: + self._group_by = GroupBy() + elif isinstance(group_by, GroupBy): + self._group_by = group_by + elif isinstance(group_by, dict): + self._group_by = GroupBy.from_dict(group_by) + else: + raise TypeError( + f"group_by must be a GroupBy object, dict, or None, got {type(group_by).__name__}" + ) + + # Handle limit parameter + if limit is None: + self._limit = Limit() + elif isinstance(limit, Limit): + self._limit = limit + elif isinstance(limit, int): + self._limit = Limit.from_dict({"limit": limit, "offset": 0}) + elif isinstance(limit, dict): + self._limit = Limit.from_dict(limit) + else: + raise TypeError( + f"limit must be a Limit object, dict, int, or None, got {type(limit).__name__}" + ) + + # Handle select parameter + if select is None: + self._select = Select() + elif isinstance(select, Select): + self._select = select + elif isinstance(select, dict): + self._select = Select.from_dict(select) + elif isinstance(select, (list, set)): + # Convert list/set of strings to Select object + self._select = Select.from_dict({"keys": list(select)}) + else: + raise TypeError( + f"select must be a Select object, dict, list, set, or None, got {type(select).__name__}" + ) + + def to_dict(self) -> Dict[str, Any]: + """Return a JSON-serializable dictionary representation.""" + return { + "filter": self._where.to_dict() if self._where is not None else None, + "rank": self._rank.to_dict() if self._rank is not None else None, + "group_by": self._group_by.to_dict(), + "limit": self._limit.to_dict(), + "select": self._select.to_dict(), + } + + # Builder methods for chaining + def select_all(self) -> "Search": + """Select all predefined keys (document, embedding, metadata, score).""" + new_select = Select(keys={Key.DOCUMENT, Key.EMBEDDING, Key.METADATA, Key.SCORE}) + return Search( + where=self._where, + rank=self._rank, + group_by=self._group_by, + limit=self._limit, + select=new_select, + ) + + def select(self, *keys: Union[Key, str]) -> "Search": + """Select specific keys to return. + + Args: + *keys: Key objects or string key names. + + Returns: + Search: A new Search with updated selection. + """ + new_select = Select(keys=set(keys)) + return Search( + where=self._where, + rank=self._rank, + group_by=self._group_by, + limit=self._limit, + select=new_select, + ) + + def where(self, where: Optional[Union[Where, Dict[str, Any]]]) -> "Search": + """Set the where clause for filtering. + + Args: + where: Where expression, dict, or None. + + Example: + search.where((Key("status") == "active") & (Key("score") > 0.5)) + search.where({"status": "active"}) + search.where({"$and": [{"status": "active"}, {"score": {"$gt": 0.5}}]}) + """ + return Search( + where=where, + rank=self._rank, + group_by=self._group_by, + limit=self._limit, + select=self._select, + ) + + def rank(self, rank_expr: Optional[Union[Rank, Dict[str, Any]]]) -> "Search": + """Set the ranking expression. + + Args: + rank_expr: A Rank expression, dict, or None for scoring + Dicts will be converted using Rank.from_dict() + Note: Primitive numbers are not accepted - use {"$val": number} for constant ranks + + Example: + search.rank(Knn(query=[0.1, 0.2]) * 0.8 + Val(0.5) * 0.2) + search.rank({"$knn": {"query": [0.1, 0.2]}}) + search.rank({"$sum": [{"$knn": {"query": [0.1, 0.2]}}, {"$val": 0.5}]}) + """ + return Search( + where=self._where, + rank=rank_expr, + group_by=self._group_by, + limit=self._limit, + select=self._select, + ) + + def group_by(self, group_by: Optional[Union[GroupBy, Dict[str, Any]]]) -> "Search": + """Set the group_by configuration for grouping and aggregating results + + Args: + group_by: A GroupBy object, dict, or None for grouping + Dicts will be converted using GroupBy.from_dict() + + Example: + search.group_by(GroupBy( + keys=[Key("category")], + aggregate=MinK(keys=[Key.SCORE], k=3) + )) + search.group_by({ + "keys": ["category"], + "aggregate": {"$min_k": {"keys": ["#score"], "k": 3}} + }) + """ + return Search( + where=self._where, + rank=self._rank, + group_by=group_by, + limit=self._limit, + select=self._select, + ) + + def limit(self, limit: int, offset: int = 0) -> "Search": + """Set the limit and offset for pagination + + Args: + limit: Maximum number of results to return + offset: Number of results to skip (default: 0) + + Example: + search.limit(20, offset=10) + """ + new_limit = Limit(offset=offset, limit=limit) + return Search( + where=self._where, + rank=self._rank, + group_by=self._group_by, + limit=new_limit, + select=self._select, + ) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/experimental/density_relevance.ipynb b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/experimental/density_relevance.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..ff32598dead5d97bf43d353e3b3923906e87200c --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/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/gOQfCwcFBWlpazvV0RVEURVEUZZr09fXR3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E7UtLeVubWwhdLhf0ej1CQkIgSVKbgiMiIiKi+0cIAaPRiG7dujX7ZJc2J4RERERE9HDgwtREREREfo4JIREREZGfY0JIRERE5OeYEBIRERH5OSaERERERH6OCSERERGRn2NCSEREROTnmBASERER+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+cNkNw55znPazIMw0BERETETczuHoCIiIg0bwojIiIi4lYKIyIiIuJWCiMiIiLiVgojIiIi4lYKIyIiIuJWCiMiIiLiVh7uHkBV2Gw2jh07RmB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GRxqmgoIDjx4/z5JNPcuWVVyqINFLNe5nGYj999RkREWmcPv30U2JjY0lPT+fFF19093Ckhpp3GNFuGhGRRm3atGlYrVY2btxI69at3T0cqaFmHUZcW3ut6jMiIiLiLs06jHiqHbyIiIjbNeswYtHWXhEREbdr1mHEQ8s0IiIibte8w4hFBawiIiLu1rzDiFk1IyIijZHJZOLbb79tMK/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+zYTLqolqplmVmZhIcHExGRgZBQUG19rrLd6dw45wN9GoTzHd3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0nrVq1iqlTp3L33Xezc+dO3nvvPebMmcNzzz1XV18mEakJd182WEQaluuvv9649NJLK3xs8uTJRrdu3QzDMAzA+OabbwzDMIw777zTGDNmjGGz2Sp8Xuljz6R79+7Gm2++6bodGxtr/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/fuLbX9tm3bdMcdd2jChAnatWuXYmJiFBMToz179lRI8QAAoPqzWZZlXU0HjRo10oIFCz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FRGjNmjCIiIjRgwAC99dZbatq0qV588cUy94mPj1deXp7jdfToUU+XCQAADHFpzUiTJk3k5eWl3Nxcp+25ublXvCakXr166tGjhw4ePFhmG7vdLrvd7kppAACgmnIpjHh7eysyMlJpaWmKiYmRJJWUlCgtLU2TJ0++oj6Ki4u1e/duDR061OViATjrm7XcdAkAcNVcvpomLi5OY8eOVa9evdS7d28tXrxYBQUFjqtrxowZo+bNmysxMVGSNGfOHPXt21dt27bVqVOntGDBAh05ckQTJ06s2G8CAACqJZfDyKhRo3T8+HHNnDlTOTk5ioiI0ObNmx2LWrOyslSnzn+Xopw8eVKTJk1STk6OGjZsqMjISG3btk2dOnWquG8BAACqLZtlWZbpIi4nPz9fAQEBysvLk7+/v+lyjOOpvbioupym2X7tPRXeZ3X57kB1EDXhaY/0e6W/3zybBgAAGEUYAQAARrm8ZgRXjtMpAABcHjMjAADAKMIIAAAwijACAACMIowAAACjCCMAAMAowggAADCKMAIAAIwijAAAAKO46RlQCk8898QTz2cBgJqAMALA43ioHYDycJoGAAAYRRgBAABGEUYAAIBRhBEAAGAUC1hRabhCBQBQGmZGAACAUcyMoFrjklEAqP6YGQEAAEYRRgAAgFGEEQAAYBRrRoBKwvoWACgdMyMAAMAowggAADCKMAIAAIwijAAAAKMIIwAAwCjCCAAAMIowAgAAjCKMAAAAowgjAADAKMIIAAAwijACAACM4tk0KBXPUQEAVBZmRgAAgFGEEQAAYBRhBAAAGEUYAQAARhFGAACAUbX+appFqQdMlwAAQK3GzAgAADCq1s+M1ATcEwQAUJ0xMwIAAIwijAAAAKMIIwAAwCjCCAAAMIowAgAAjHLrapolS5ZowYIFysnJUffu3fXcc8+pd+/eZbZfu3atZsyYoW+++Ubt2rXT/PnzNXToULeLrs648gUAAGcuz4y89tpriouLU0JCgj777DN1795d0dHROnbsWKntt23bpjvuuEMTJkzQrl27FBMTo5iYGO3Zs+eqiwcAANWfy2HkmWee0aRJkzR+/Hh16tRJy5YtU/369bVy5cpS2z/77LP69a9/rWnTpqljx46aO3euevbsqeeff/6qiwcAANWfS6dpioqKtHPnTsXHxzu21alTR4MHD1ZGRkap+2RkZCguLs5pW3R0tFJSUso8TmFhoQoLCx3v8/LyJEn5+fmulHtFzhX8UOF9lqfgbOHlGwEAUIk88fv6034tyyq3nUth5MSJEyouLlZwcLDT9uDgYH355Zel7pOTk1Nq+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/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/ingest/__init__.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/ingest/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..71ae6a1439847390098efa516b01940ace5c49d9 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/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/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/ingest/__pycache__/__init__.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/ingest/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c547c57db8992369595d6cb062e89f498790cfdc Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/ingest/__pycache__/__init__.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/ingest/impl/__pycache__/utils.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/ingest/impl/__pycache__/utils.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..94798e50e34f3ce018c01a2cbbaad0505de1b7df Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/ingest/impl/__pycache__/utils.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/ingest/impl/utils.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/ingest/impl/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..ca0c57d548310ab11bfee65245b8c3eda161dcea --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/ingest/impl/utils.py @@ -0,0 +1,49 @@ +import re +from typing import Tuple +from uuid import UUID + +from chromadb.db.base import SqlDB +from chromadb.segment import SegmentManager, VectorReader + +topic_regex = r"persistent:\/\/(?P.+)\/(?P.+)\/(?P.+)" + + +def parse_topic_name(topic_name: str) -> Tuple[str, str, str]: + """Parse the topic name into the tenant, namespace and topic name""" + match = re.match(topic_regex, topic_name) + if not match: + raise ValueError(f"Invalid topic name: {topic_name}") + return match.group("tenant"), match.group("namespace"), match.group("topic") + + +def create_topic_name(tenant: str, namespace: str, collection_id: UUID) -> str: + return f"persistent://{tenant}/{namespace}/{str(collection_id)}" + + +def trigger_vector_segments_max_seq_id_migration( + db: SqlDB, segment_manager: SegmentManager +) -> None: + """ + Trigger the migration of vector segments' max_seq_id from the pickled metadata file to SQLite. + + Vector segments migrate this field automatically on init—so this should be used when we know segments are likely unmigrated and unloaded. + + This is a no-op if all vector segments have already migrated their max_seq_id. + """ + with db.tx() as cur: + cur.execute( + """ + SELECT collection + FROM "segments" + WHERE "id" NOT IN (SELECT "segment_id" FROM "max_seq_id") AND + "type" = 'urn:chroma:segment/vector/hnsw-local-persisted' + """ + ) + collection_ids_with_unmigrated_segments = [row[0] for row in cur.fetchall()] + + if len(collection_ids_with_unmigrated_segments) == 0: + return + + for collection_id in collection_ids_with_unmigrated_segments: + # Loading the segment triggers the migration on init + segment_manager.get_segment(UUID(collection_id), VectorReader) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/logservice/__pycache__/logservice.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/logservice/__pycache__/logservice.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..bf05dfdd3fdfd67354aa6af96d89476e689940fc Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/logservice/__pycache__/logservice.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/logservice/logservice.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/logservice/logservice.py new file mode 100644 index 0000000000000000000000000000000000000000..b228e249c6d62ea3c8a7078ccbc4883ed5f92ac2 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/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/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/migrations/__init__.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/migrations/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/migrations/__pycache__/__init__.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/migrations/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e690f3ae67dede97df1d01b3d5e8c2940e3fb568 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/migrations/__pycache__/__init__.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/migrations/embeddings_queue/00001-embeddings.sqlite.sql b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/migrations/embeddings_queue/00001-embeddings.sqlite.sql new file mode 100644 index 0000000000000000000000000000000000000000..24fb14f8e5eef35623d858778d226c39cf655b3b --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/migrations/embeddings_queue/00001-embeddings.sqlite.sql @@ -0,0 +1,10 @@ +CREATE TABLE embeddings_queue ( + seq_id INTEGER PRIMARY KEY, + created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, + operation INTEGER NOT NULL, + topic TEXT NOT NULL, + id TEXT NOT NULL, + vector BLOB, + encoding TEXT, + metadata TEXT +); diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/migrations/embeddings_queue/00002-embeddings-queue-config.sqlite.sql b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/migrations/embeddings_queue/00002-embeddings-queue-config.sqlite.sql new file mode 100644 index 0000000000000000000000000000000000000000..5b5393069400a08ac5d1ef02f1d4a482136c92c2 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/migrations/embeddings_queue/00002-embeddings-queue-config.sqlite.sql @@ -0,0 +1,4 @@ +CREATE TABLE embeddings_queue_config ( + id INTEGER PRIMARY KEY, + config_json_str TEXT +); diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/migrations/metadb/00001-embedding-metadata.sqlite.sql b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/migrations/metadb/00001-embedding-metadata.sqlite.sql new file mode 100644 index 0000000000000000000000000000000000000000..655c7656810e8c8270b51ac9c4dd12bb91237f74 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/migrations/metadb/00001-embedding-metadata.sqlite.sql @@ -0,0 +1,24 @@ +CREATE TABLE embeddings ( + id INTEGER PRIMARY KEY, + segment_id TEXT NOT NULL, + embedding_id TEXT NOT NULL, + seq_id BLOB NOT NULL, + created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, + UNIQUE (segment_id, embedding_id) +); + +CREATE TABLE embedding_metadata ( + id INTEGER REFERENCES embeddings(id), + key TEXT NOT NULL, + string_value TEXT, + int_value INTEGER, + float_value REAL, + PRIMARY KEY (id, key) +); + +CREATE TABLE max_seq_id ( + segment_id TEXT PRIMARY KEY, + seq_id BLOB NOT NULL +); + +CREATE VIRTUAL TABLE embedding_fulltext USING fts5(id, string_value); diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/migrations/metadb/00002-embedding-metadata.sqlite.sql b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/migrations/metadb/00002-embedding-metadata.sqlite.sql new file mode 100644 index 0000000000000000000000000000000000000000..43de804ccde77a75345e4cf76523510c59a584db --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/migrations/metadb/00002-embedding-metadata.sqlite.sql @@ -0,0 +1,5 @@ +-- SQLite does not support adding check with alter table, as a result, adding a check +-- involve creating a new table and copying the data over. It is over kill with adding +-- a boolean type column. The application write to the table needs to ensure the data +-- integrity. +ALTER TABLE embedding_metadata ADD COLUMN bool_value INTEGER diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/migrations/metadb/00003-full-text-tokenize.sqlite.sql b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/migrations/metadb/00003-full-text-tokenize.sqlite.sql new file mode 100644 index 0000000000000000000000000000000000000000..42afe2e1cf2a2443aaf5cf2b3d234670f9f002e3 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/migrations/metadb/00003-full-text-tokenize.sqlite.sql @@ -0,0 +1,3 @@ +CREATE VIRTUAL TABLE embedding_fulltext_search USING fts5(string_value, tokenize='trigram'); +INSERT INTO embedding_fulltext_search (rowid, string_value) SELECT rowid, string_value FROM embedding_metadata; +DROP TABLE embedding_fulltext; diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/migrations/metadb/00004-metadata-indices.sqlite.sql b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/migrations/metadb/00004-metadata-indices.sqlite.sql new file mode 100644 index 0000000000000000000000000000000000000000..0a58e77e875bdf4744877f859e3ec097cdb1e961 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/migrations/metadb/00004-metadata-indices.sqlite.sql @@ -0,0 +1,3 @@ +CREATE INDEX IF NOT EXISTS embedding_metadata_int_value ON embedding_metadata (key, int_value) WHERE int_value IS NOT NULL; +CREATE INDEX IF NOT EXISTS embedding_metadata_float_value ON embedding_metadata (key, float_value) WHERE float_value IS NOT NULL; +CREATE INDEX IF NOT EXISTS embedding_metadata_string_value ON embedding_metadata (key, string_value) WHERE string_value IS NOT NULL; diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/migrations/metadb/00005-max-seq-id-int.sqlite.sql b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/migrations/metadb/00005-max-seq-id-int.sqlite.sql new file mode 100644 index 0000000000000000000000000000000000000000..5b465a11209ab1ae0e03a13cc05ac83930b06bb0 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/migrations/metadb/00005-max-seq-id-int.sqlite.sql @@ -0,0 +1,27 @@ +ALTER TABLE max_seq_id ADD COLUMN int_seq_id INTEGER; + +-- Convert 8 byte wide big-endian integer as blob to native 64 bit integer. +-- Adapted from https://stackoverflow.com/a/70296198. +UPDATE max_seq_id SET int_seq_id = ( + SELECT ( + (instr('123456789ABCDEF', substr(hex(seq_id), -1 , 1)) << 0) + | (instr('123456789ABCDEF', substr(hex(seq_id), -2 , 1)) << 4) + | (instr('123456789ABCDEF', substr(hex(seq_id), -3 , 1)) << 8) + | (instr('123456789ABCDEF', substr(hex(seq_id), -4 , 1)) << 12) + | (instr('123456789ABCDEF', substr(hex(seq_id), -5 , 1)) << 16) + | (instr('123456789ABCDEF', substr(hex(seq_id), -6 , 1)) << 20) + | (instr('123456789ABCDEF', substr(hex(seq_id), -7 , 1)) << 24) + | (instr('123456789ABCDEF', substr(hex(seq_id), -8 , 1)) << 28) + | (instr('123456789ABCDEF', substr(hex(seq_id), -9 , 1)) << 32) + | (instr('123456789ABCDEF', substr(hex(seq_id), -10, 1)) << 36) + | (instr('123456789ABCDEF', substr(hex(seq_id), -11, 1)) << 40) + | (instr('123456789ABCDEF', substr(hex(seq_id), -12, 1)) << 44) + | (instr('123456789ABCDEF', substr(hex(seq_id), -13, 1)) << 48) + | (instr('123456789ABCDEF', substr(hex(seq_id), -14, 1)) << 52) + | (instr('123456789ABCDEF', substr(hex(seq_id), -15, 1)) << 56) + | (instr('123456789ABCDEF', substr(hex(seq_id), -16, 1)) << 60) + ) +); + +ALTER TABLE max_seq_id DROP COLUMN seq_id; +ALTER TABLE max_seq_id RENAME COLUMN int_seq_id TO seq_id; diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/migrations/sysdb/00001-collections.sqlite.sql b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/migrations/sysdb/00001-collections.sqlite.sql new file mode 100644 index 0000000000000000000000000000000000000000..7ba0eb0a02caf9374e0e0fa0d5d21cdc96e94ec8 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/migrations/sysdb/00001-collections.sqlite.sql @@ -0,0 +1,15 @@ +CREATE TABLE collections ( + id TEXT PRIMARY KEY, + name TEXT NOT NULL, + topic TEXT NOT NULL, + UNIQUE (name) +); + +CREATE TABLE collection_metadata ( + collection_id TEXT REFERENCES collections(id) ON DELETE CASCADE, + key TEXT NOT NULL, + str_value TEXT, + int_value INTEGER, + float_value REAL, + PRIMARY KEY (collection_id, key) +); diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/migrations/sysdb/00002-segments.sqlite.sql b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/migrations/sysdb/00002-segments.sqlite.sql new file mode 100644 index 0000000000000000000000000000000000000000..5ad08f70ab785e52e3815813223c28e41d6c5fbb --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/migrations/sysdb/00002-segments.sqlite.sql @@ -0,0 +1,16 @@ +CREATE TABLE segments ( + id TEXT PRIMARY KEY, + type TEXT NOT NULL, + scope TEXT NOT NULL, + topic TEXT, + collection TEXT REFERENCES collection(id) +); + +CREATE TABLE segment_metadata ( + segment_id TEXT REFERENCES segments(id) ON DELETE CASCADE, + key TEXT NOT NULL, + str_value TEXT, + int_value INTEGER, + float_value REAL, + PRIMARY KEY (segment_id, key) +); diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/migrations/sysdb/00003-collection-dimension.sqlite.sql b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/migrations/sysdb/00003-collection-dimension.sqlite.sql new file mode 100644 index 0000000000000000000000000000000000000000..c4b49b1faf7f1bbd2ee2fe86ce4456f1e947b449 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/migrations/sysdb/00003-collection-dimension.sqlite.sql @@ -0,0 +1 @@ +ALTER TABLE collections ADD COLUMN dimension INTEGER; diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/migrations/sysdb/00004-tenants-databases.sqlite.sql b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/migrations/sysdb/00004-tenants-databases.sqlite.sql new file mode 100644 index 0000000000000000000000000000000000000000..be4bd0e867f47fabf227f1b7b1b365de3ffc8afa --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/migrations/sysdb/00004-tenants-databases.sqlite.sql @@ -0,0 +1,29 @@ +CREATE TABLE IF NOT EXISTS tenants ( + id TEXT PRIMARY KEY, + UNIQUE (id) +); + +CREATE TABLE IF NOT EXISTS databases ( + id TEXT PRIMARY KEY, -- unique globally + name TEXT NOT NULL, -- unique per tenant + tenant_id TEXT NOT NULL REFERENCES tenants(id) ON DELETE CASCADE, + UNIQUE (tenant_id, name) -- Ensure that a tenant has only one database with a given name +); + +CREATE TABLE IF NOT EXISTS collections_tmp ( + id TEXT PRIMARY KEY, -- unique globally + name TEXT NOT NULL, -- unique per database + topic TEXT NOT NULL, + dimension INTEGER, + database_id TEXT NOT NULL REFERENCES databases(id) ON DELETE CASCADE, + UNIQUE (name, database_id) +); + +-- Create default tenant and database +INSERT OR REPLACE INTO tenants (id) VALUES ('default_tenant'); -- The default tenant id is 'default_tenant' others are UUIDs +INSERT OR REPLACE INTO databases (id, name, tenant_id) VALUES ('00000000-0000-0000-0000-000000000000', 'default_database', 'default_tenant'); + +INSERT OR REPLACE INTO collections_tmp (id, name, topic, dimension, database_id) + SELECT id, name, topic, dimension, '00000000-0000-0000-0000-000000000000' FROM collections; +DROP TABLE collections; +ALTER TABLE collections_tmp RENAME TO collections; diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/migrations/sysdb/00005-remove-topic.sqlite.sql b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/migrations/sysdb/00005-remove-topic.sqlite.sql new file mode 100644 index 0000000000000000000000000000000000000000..6fa19ff8deb076d6d1aabc53588c577848b7ef3c --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/migrations/sysdb/00005-remove-topic.sqlite.sql @@ -0,0 +1,4 @@ +-- Remove the topic column from the Collections and Segments tables + +ALTER TABLE collections DROP COLUMN topic; +ALTER TABLE segments DROP COLUMN topic; diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/migrations/sysdb/00006-collection-segment-metadata.sqlite.sql b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/migrations/sysdb/00006-collection-segment-metadata.sqlite.sql new file mode 100644 index 0000000000000000000000000000000000000000..68507177a2de9f7d6c85861b0ac9828610148bab --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/migrations/sysdb/00006-collection-segment-metadata.sqlite.sql @@ -0,0 +1,6 @@ +-- SQLite does not support adding check with alter table, as a result, adding a check +-- involve creating a new table and copying the data over. It is over kill with adding +-- a boolean type column. The application write to the table needs to ensure the data +-- integrity. +ALTER TABLE collection_metadata ADD COLUMN bool_value INTEGER; +ALTER TABLE segment_metadata ADD COLUMN bool_value INTEGER; diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/migrations/sysdb/00007-collection-config.sqlite.sql b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/migrations/sysdb/00007-collection-config.sqlite.sql new file mode 100644 index 0000000000000000000000000000000000000000..f9796e80dea7f6c3f7ab2990c7da4f47d80ba246 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/migrations/sysdb/00007-collection-config.sqlite.sql @@ -0,0 +1,2 @@ +-- Stores collection configuration dictionaries. +ALTER TABLE collections ADD COLUMN config_json_str TEXT; diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/migrations/sysdb/00008-maintenance-log.sqlite.sql b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/migrations/sysdb/00008-maintenance-log.sqlite.sql new file mode 100644 index 0000000000000000000000000000000000000000..b9a7ae9c17a0a70ed318da1364f9857bf41c680e --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/migrations/sysdb/00008-maintenance-log.sqlite.sql @@ -0,0 +1,7 @@ +-- Records when database maintenance operations are performed. +-- At time of creation, this table is only used to record vacuum operations. +CREATE TABLE maintenance_log ( + id INT PRIMARY KEY, + timestamp INT NOT NULL, + operation TEXT NOT NULL +); diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/migrations/sysdb/00009-segment-collection-not-null.sqlite.sql b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/migrations/sysdb/00009-segment-collection-not-null.sqlite.sql new file mode 100644 index 0000000000000000000000000000000000000000..8c4e6a59a56d05cb67197b85b6151264ebba65a6 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/migrations/sysdb/00009-segment-collection-not-null.sqlite.sql @@ -0,0 +1,11 @@ +-- This makes segments.collection non-nullable. +CREATE TABLE segments_temp ( + id TEXT PRIMARY KEY, + type TEXT NOT NULL, + scope TEXT NOT NULL, + collection TEXT REFERENCES collection(id) NOT NULL +); + +INSERT INTO segments_temp SELECT * FROM segments; +DROP TABLE segments; +ALTER TABLE segments_temp RENAME TO segments; diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/proto/.gitignore b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/proto/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..6d2a6dd14a7310806630d0977e9fc0b0256c8fb2 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/proto/.gitignore @@ -0,0 +1,2 @@ +*_pb2.py* +*_pb2_grpc.py diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/proto/__init__.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/proto/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/proto/__pycache__/__init__.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/proto/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..131304b2ae1f81d91c2ef620375aaffeb4d612f2 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/proto/__pycache__/__init__.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/proto/__pycache__/convert.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/proto/__pycache__/convert.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ac81e55b7dd69e7451721fe444991f10a2271e8f Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/proto/__pycache__/convert.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/proto/__pycache__/utils.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/proto/__pycache__/utils.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4b03c259a33cf14b9696bb629dc3204f37cf5823 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/proto/__pycache__/utils.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/proto/convert.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/proto/convert.py new file mode 100644 index 0000000000000000000000000000000000000000..0e5f5b7e0daaa53d43aecdc572cc3d7afae24e6f --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/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/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/proto/utils.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/proto/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..040f733d2610edf1be977a757b1190c4030a1d3e --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/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/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/quota/__init__.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/quota/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..a684ec33838d6b5e83c65b94be52a4c13f8e1a35 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/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/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/quota/__pycache__/__init__.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/quota/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7cae2168759688037a42241d0d91355338424011 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/quota/__pycache__/__init__.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/quota/simple_quota_enforcer/__init__.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/quota/simple_quota_enforcer/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..952ee7b9351dc2c76848a22bbe7536b877350667 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/quota/simple_quota_enforcer/__init__.py @@ -0,0 +1,54 @@ +from overrides import override +from typing import Any, Callable, TypeVar, Dict, Optional +from uuid import UUID + +from chromadb.api.types import ( + Embeddings, + Metadatas, + Documents, + URIs, + IDs, + CollectionMetadata, + Where, + WhereDocument, +) +from chromadb.quota import QuotaEnforcer, Action +from chromadb.config import System + +T = TypeVar("T", bound=Callable[..., Any]) + + +class SimpleQuotaEnforcer(QuotaEnforcer): + """ + A naive implementation of a quota enforcer that allows all requests. + """ + + def __init__(self, system: System) -> None: + super().__init__(system) + + @override + def set_context(self, context: Dict[str, Any]) -> None: + pass + + @override + 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: + pass diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/quota/simple_quota_enforcer/__pycache__/__init__.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/quota/simple_quota_enforcer/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..72789db861ec26afe2b7032a03ab048900e1286e Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/quota/simple_quota_enforcer/__pycache__/__init__.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/rate_limit/__init__.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/rate_limit/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..6937ebfcc9ed6a0039d8468b71cc3fe3e872453e --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/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/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/rate_limit/__pycache__/__init__.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/rate_limit/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a33984931ae0d41a33f33bb679191872a58c561a Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/rate_limit/__pycache__/__init__.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/rate_limit/simple_rate_limit/__init__.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/rate_limit/simple_rate_limit/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..350d64b067135a3326d9435f1364ca64528ba0b9 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/rate_limit/simple_rate_limit/__init__.py @@ -0,0 +1,42 @@ +from overrides import override +from typing import Any, Awaitable, Callable, TypeVar +from functools import wraps + +from chromadb.rate_limit import RateLimitEnforcer +from chromadb.config import System + +T = TypeVar("T", bound=Callable[..., Any]) +A = TypeVar("A", bound=Awaitable[Any]) + + +class SimpleRateLimitEnforcer(RateLimitEnforcer): + """ + A naive implementation of a rate limit enforcer that allows all requests. + """ + + def __init__(self, system: System) -> None: + super().__init__(system) + + @override + def rate_limit(self, func: T) -> T: + @wraps(func) + def wrapper(*args: Any, **kwargs: Any) -> Any: + return func(*args, **kwargs) + + return wrapper # type: ignore + + +class SimpleAsyncRateLimitEnforcer(RateLimitEnforcer): + """ + A naive implementation of a rate limit enforcer that allows all requests. + """ + + def __init__(self, system: System) -> None: + super().__init__(system) + + @override + def rate_limit(self, func: A) -> A: + @wraps(func) + async def wrapper(*args: Any, **kwargs: Any) -> Any: + return await func(*args, **kwargs) + return wrapper # type: ignore diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/rate_limit/simple_rate_limit/__pycache__/__init__.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/rate_limit/simple_rate_limit/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..df5d0fcc81081b9d879eefb9ddb28ec87134b3e0 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/rate_limit/simple_rate_limit/__pycache__/__init__.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/segment/__init__.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/segment/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..7a2b8c9e5dd27d25bbbc3166db6375e2f9f33c92 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/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/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/segment/__pycache__/__init__.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/segment/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2489e6008c9df804360e9c564a82a6bea1c5cbcd Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/segment/__pycache__/__init__.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/segment/distributed/__init__.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/segment/distributed/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..69c59c13a3f7678717ceb0f1e5847b01372ff86d --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/segment/distributed/__init__.py @@ -0,0 +1,80 @@ +from abc import abstractmethod +from dataclasses import dataclass +from typing import Any, Callable, List + +from overrides import EnforceOverrides, overrides +from chromadb.config import Component, System +from chromadb.types import Segment + + +class SegmentDirectory(Component): + """A segment directory is a data interface that manages the location of segments. Concretely, this + means that for distributed chroma, it provides the grpc endpoint for a segment.""" + + @abstractmethod + def get_segment_endpoints(self, segment: Segment, n: int) -> List[str]: + """Return the segment residences for a given segment ID. Will return at most n residences. + Should only return less than n residences if there are less than n residences available. + """ + + @abstractmethod + def register_updated_segment_callback( + self, callback: Callable[[Segment], None] + ) -> None: + """Register a callback that will be called when a segment is updated""" + pass + + +@dataclass +class Member: + id: str + ip: str + node: str + + +Memberlist = List[Member] + + +class MemberlistProvider(Component, EnforceOverrides): + """Returns the latest memberlist and provdes a callback for when it changes. This + callback may be called from a different thread than the one that called. Callers should ensure + that they are thread-safe.""" + + callbacks: List[Callable[[Memberlist], Any]] + + def __init__(self, system: System): + self.callbacks = [] + super().__init__(system) + + @abstractmethod + def get_memberlist(self) -> Memberlist: + """Returns the latest memberlist""" + pass + + @abstractmethod + def set_memberlist_name(self, memberlist: str) -> None: + """Sets the memberlist that this provider will watch""" + pass + + @overrides + def stop(self) -> None: + """Stops watching the memberlist""" + self.callbacks = [] + + def register_updated_memberlist_callback( + self, callback: Callable[[Memberlist], Any] + ) -> None: + """Registers a callback that will be called when the memberlist changes. May be called many times + with the same memberlist, so callers should be idempotent. May be called from a different thread. + """ + self.callbacks.append(callback) + + def unregister_updated_memberlist_callback( + self, callback: Callable[[Memberlist], Any] + ) -> bool: + """Unregisters a callback that was previously registered. Returns True if the callback was + successfully unregistered, False if it was not ever registered.""" + if callback in self.callbacks: + self.callbacks.remove(callback) + return True + return False diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/segment/distributed/__pycache__/__init__.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/segment/distributed/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..34ba502ac0c27b688f63ad2dfd400714a5625f0e Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/segment/distributed/__pycache__/__init__.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/segment/impl/__init__.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/segment/impl/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/segment/impl/__pycache__/__init__.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/segment/impl/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..89e7bb318203c95909f0ef822c599f323dd69662 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/segment/impl/__pycache__/__init__.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/segment/impl/distributed/__pycache__/segment_directory.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/segment/impl/distributed/__pycache__/segment_directory.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6ebb570224173be9213a6fca06353da51cee71b2 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/segment/impl/distributed/__pycache__/segment_directory.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/segment/impl/distributed/segment_directory.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/segment/impl/distributed/segment_directory.py new file mode 100644 index 0000000000000000000000000000000000000000..a2310870246ef55060a7fa60a6b479d702a6aec8 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/segment/impl/distributed/segment_directory.py @@ -0,0 +1,337 @@ +import threading +import time +from typing import Any, Callable, Dict, List, Optional, cast +from kubernetes import client, config, watch +from kubernetes.client.rest import ApiException +from overrides import EnforceOverrides, override +from chromadb.config import RoutingMode, System +from chromadb.segment.distributed import ( + Member, + Memberlist, + MemberlistProvider, + SegmentDirectory, +) +from chromadb.telemetry.opentelemetry import ( + OpenTelemetryGranularity, + add_attributes_to_current_span, + trace_method, +) +from chromadb.types import Segment +from chromadb.utils.rendezvous_hash import assign, murmur3hasher + +# These could go in config but given that they will rarely change, they are here for now to avoid +# polluting the config file further. +WATCH_TIMEOUT_SECONDS = 60 +KUBERNETES_NAMESPACE = "chroma" +KUBERNETES_GROUP = "chroma.cluster" +HEADLESS_SERVICE = "svc.cluster.local" + + +class MockMemberlistProvider(MemberlistProvider, EnforceOverrides): + """A mock memberlist provider for testing""" + + _memberlist: Memberlist + + def __init__(self, system: System): + super().__init__(system) + self._memberlist = [ + Member(id="a", ip="10.0.0.1", node="node1"), + Member(id="b", ip="10.0.0.2", node="node2"), + Member(id="c", ip="10.0.0.3", node="node3"), + ] + + @override + def get_memberlist(self) -> Memberlist: + return self._memberlist + + @override + def set_memberlist_name(self, memberlist: str) -> None: + pass # The mock provider does not need to set the memberlist name + + def update_memberlist(self, memberlist: Memberlist) -> None: + """Updates the memberlist and calls all registered callbacks. This mocks an update from a k8s CR""" + self._memberlist = memberlist + for callback in self.callbacks: + callback(memberlist) + + +class CustomResourceMemberlistProvider(MemberlistProvider, EnforceOverrides): + """A memberlist provider that uses a k8s custom resource to store the memberlist""" + + _kubernetes_api: client.CustomObjectsApi + _memberlist_name: Optional[str] + _curr_memberlist: Optional[Memberlist] + _curr_memberlist_mutex: threading.Lock + _watch_thread: Optional[threading.Thread] + _kill_watch_thread: threading.Event + _done_waiting_for_reset: threading.Event + + def __init__(self, system: System): + super().__init__(system) + config.load_config() + self._kubernetes_api = client.CustomObjectsApi() + self._watch_thread = None + self._memberlist_name = None + self._curr_memberlist = None + self._curr_memberlist_mutex = threading.Lock() + self._kill_watch_thread = threading.Event() + self._done_waiting_for_reset = threading.Event() + + @override + def start(self) -> None: + if self._memberlist_name is None: + raise ValueError("Memberlist name must be set before starting") + self.get_memberlist() + self._done_waiting_for_reset.clear() + self._watch_worker_memberlist() + return super().start() + + @override + def stop(self) -> None: + self._curr_memberlist = None + self._memberlist_name = None + + # Stop the watch thread + self._kill_watch_thread.set() + if self._watch_thread is not None: + self._watch_thread.join() + self._watch_thread = None + self._kill_watch_thread.clear() + self._done_waiting_for_reset.clear() + return super().stop() + + @override + def reset_state(self) -> None: + # Reset the memberlist in kubernetes, and wait for it to + # get propagated back again + # Note that the component must be running in order to reset the state + if not self._system.settings.require("allow_reset"): + raise ValueError( + "Resetting the database is not allowed. Set `allow_reset` to true in the config in tests or other non-production environments where reset should be permitted." + ) + if self._memberlist_name: + self._done_waiting_for_reset.clear() + self._kubernetes_api.patch_namespaced_custom_object( + group=KUBERNETES_GROUP, + version="v1", + namespace=KUBERNETES_NAMESPACE, + plural="memberlists", + name=self._memberlist_name, + body={ + "kind": "MemberList", + "spec": {"members": []}, + }, + ) + self._done_waiting_for_reset.wait(5.0) + # TODO: For some reason the above can flake and the memberlist won't be populated + # Given that this is a test harness, just sleep for an additional 500ms for now + # We should understand why this flaps + time.sleep(0.5) + + @override + def get_memberlist(self) -> Memberlist: + if self._curr_memberlist is None: + self._curr_memberlist = self._fetch_memberlist() + return self._curr_memberlist + + @override + def set_memberlist_name(self, memberlist: str) -> None: + self._memberlist_name = memberlist + + def _fetch_memberlist(self) -> Memberlist: + api_response = self._kubernetes_api.get_namespaced_custom_object( + group=KUBERNETES_GROUP, + version="v1", + namespace=KUBERNETES_NAMESPACE, + plural="memberlists", + name=f"{self._memberlist_name}", + ) + api_response = cast(Dict[str, Any], api_response) + if "spec" not in api_response: + return [] + response_spec = cast(Dict[str, Any], api_response["spec"]) + return self._parse_response_memberlist(response_spec) + + def _watch_worker_memberlist(self) -> None: + # TODO: We may want to make this watch function a library function that can be used by other + # components that need to watch k8s custom resources. + def run_watch() -> None: + w = watch.Watch() + + def do_watch() -> None: + for event in w.stream( + self._kubernetes_api.list_namespaced_custom_object, + group=KUBERNETES_GROUP, + version="v1", + namespace=KUBERNETES_NAMESPACE, + plural="memberlists", + field_selector=f"metadata.name={self._memberlist_name}", + timeout_seconds=WATCH_TIMEOUT_SECONDS, + ): + event = cast(Dict[str, Any], event) + response_spec = event["object"]["spec"] + response_spec = cast(Dict[str, Any], response_spec) + with self._curr_memberlist_mutex: + self._curr_memberlist = self._parse_response_memberlist( + response_spec + ) + self._notify(self._curr_memberlist) + if ( + self._system.settings.require("allow_reset") + and not self._done_waiting_for_reset.is_set() + and len(self._curr_memberlist) > 0 + ): + self._done_waiting_for_reset.set() + + # Watch the custom resource for changes + # Watch with a timeout and retry so we can gracefully stop this if needed + while not self._kill_watch_thread.is_set(): + try: + do_watch() + except ApiException as e: + # If status code is 410, the watch has expired and we need to start a new one. + if e.status == 410: + pass + return + + if self._watch_thread is None: + thread = threading.Thread(target=run_watch, daemon=True) + thread.start() + self._watch_thread = thread + else: + raise Exception("A watch thread is already running.") + + def _parse_response_memberlist( + self, api_response_spec: Dict[str, Any] + ) -> Memberlist: + if "members" not in api_response_spec: + return [] + parsed = [] + for m in api_response_spec["members"]: + id = m["member_id"] + ip = m["member_ip"] if "member_ip" in m else "" + node = m["member_node_name"] if "member_node_name" in m else "" + parsed.append(Member(id=id, ip=ip, node=node)) + return parsed + + def _notify(self, memberlist: Memberlist) -> None: + for callback in self.callbacks: + callback(memberlist) + + +class RendezvousHashSegmentDirectory(SegmentDirectory, EnforceOverrides): + _memberlist_provider: MemberlistProvider + _curr_memberlist_mutex: threading.Lock + _curr_memberlist: Optional[Memberlist] + _routing_mode: RoutingMode + + def __init__(self, system: System): + super().__init__(system) + self._memberlist_provider = self.require(MemberlistProvider) + memberlist_name = system.settings.require("worker_memberlist_name") + self._memberlist_provider.set_memberlist_name(memberlist_name) + self._routing_mode = system.settings.require( + "chroma_segment_directory_routing_mode" + ) + + self._curr_memberlist = None + self._curr_memberlist_mutex = threading.Lock() + + @override + def start(self) -> None: + self._curr_memberlist = self._memberlist_provider.get_memberlist() + self._memberlist_provider.register_updated_memberlist_callback( + self._update_memberlist + ) + return super().start() + + @override + def stop(self) -> None: + self._memberlist_provider.unregister_updated_memberlist_callback( + self._update_memberlist + ) + return super().stop() + + @override + def get_segment_endpoints(self, segment: Segment, n: int) -> List[str]: + if self._curr_memberlist is None or len(self._curr_memberlist) == 0: + raise ValueError("Memberlist is not initialized") + + # assign() will throw an error if n is greater than the number of members + # clamp n to the number of members to align with the contract of this method + # which is to return at most n endpoints + n = min(n, len(self._curr_memberlist)) + + # Check if all members in the memberlist have a node set, + # if so, route using the node + + # NOTE(@hammadb) 1/8/2024: This is to handle the migration between routing + # using the member id and routing using the node name + # We want to route using the node name over the member id + # because the node may have a disk cache that we want a + # stable identifier for over deploys. + can_use_node_routing = ( + all([m.node != "" and len(m.node) != 0 for m in self._curr_memberlist]) + and self._routing_mode == RoutingMode.NODE + ) + if can_use_node_routing: + # If we are using node routing and the segments + assignments = assign( + segment["collection"].hex, + [m.node for m in self._curr_memberlist], + murmur3hasher, + n, + ) + else: + # Query to the same collection should end up on the same endpoint + assignments = assign( + segment["collection"].hex, + [m.id for m in self._curr_memberlist], + murmur3hasher, + n, + ) + assignments_set = set(assignments) + out_endpoints = [] + for member in self._curr_memberlist: + is_chosen_with_node_routing = ( + can_use_node_routing and member.node in assignments_set + ) + is_chosen_with_id_routing = ( + not can_use_node_routing and member.id in assignments_set + ) + if is_chosen_with_node_routing or is_chosen_with_id_routing: + # If the memberlist has an ip, use it, otherwise use the member id with the headless service + # this is for backwards compatibility with the old memberlist which only had ids + if member.ip is not None and member.ip != "": + endpoint = f"{member.ip}:50051" + out_endpoints.append(endpoint) + else: + service_name = self.extract_service_name(member.id) + endpoint = f"{member.id}.{service_name}.{KUBERNETES_NAMESPACE}.{HEADLESS_SERVICE}:50051" + out_endpoints.append(endpoint) + return out_endpoints + + @override + def register_updated_segment_callback( + self, callback: Callable[[Segment], None] + ) -> None: + raise NotImplementedError() + + @trace_method( + "RendezvousHashSegmentDirectory._update_memberlist", + OpenTelemetryGranularity.ALL, + ) + def _update_memberlist(self, memberlist: Memberlist) -> None: + with self._curr_memberlist_mutex: + add_attributes_to_current_span( + {"new_memberlist": [m.id for m in memberlist]} + ) + self._curr_memberlist = memberlist + + def extract_service_name(self, pod_name: str) -> Optional[str]: + # Split the pod name by the hyphen + parts = pod_name.split("-") + # The service name is expected to be the prefix before the last hyphen + if len(parts) > 1: + return "-".join(parts[:-1]) + return None diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/segment/impl/manager/__init__.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/segment/impl/manager/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/segment/impl/manager/__pycache__/__init__.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/segment/impl/manager/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f88902334113ba2c371f2473fe7823fdb9f82451 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/segment/impl/manager/__pycache__/__init__.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/segment/impl/manager/__pycache__/distributed.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/segment/impl/manager/__pycache__/distributed.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f6389678cf2e4c659384bd1ea6e1dc0f68b7bca6 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/segment/impl/manager/__pycache__/distributed.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/segment/impl/manager/__pycache__/local.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/segment/impl/manager/__pycache__/local.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0d41f8e05cb02b03770a2e3cd90599d44b17b7a5 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/segment/impl/manager/__pycache__/local.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/segment/impl/manager/cache/__init__.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/segment/impl/manager/cache/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/segment/impl/manager/cache/__pycache__/__init__.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/segment/impl/manager/cache/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..bedb8542c7d1116c607ba775251dd7bc641d5c57 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/segment/impl/manager/cache/__pycache__/__init__.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/segment/impl/manager/cache/__pycache__/cache.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/segment/impl/manager/cache/__pycache__/cache.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..94ff154615e5b0ae039413e1a0a9213420038412 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/segment/impl/manager/cache/__pycache__/cache.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/segment/impl/manager/cache/cache.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/segment/impl/manager/cache/cache.py new file mode 100644 index 0000000000000000000000000000000000000000..ae98102b615285ab93f38e2e2fb702a97ab9e009 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/segment/impl/manager/cache/cache.py @@ -0,0 +1,119 @@ +import threading +import uuid +from typing import Any, Callable +from chromadb.types import Segment +from overrides import override +from typing import Dict, Optional +from abc import ABC, abstractmethod + + +class SegmentCache(ABC): + @abstractmethod + def get(self, key: uuid.UUID) -> Optional[Segment]: + pass + + @abstractmethod + def pop(self, key: uuid.UUID) -> Optional[Segment]: + pass + + @abstractmethod + def set(self, key: uuid.UUID, value: Segment) -> None: + pass + + @abstractmethod + def reset(self) -> None: + pass + + +class BasicCache(SegmentCache): + def __init__(self): + self.cache: Dict[uuid.UUID, Segment] = {} + self.lock = threading.RLock() + + @override + def get(self, key: uuid.UUID) -> Optional[Segment]: + with self.lock: + return self.cache.get(key) + + @override + def pop(self, key: uuid.UUID) -> Optional[Segment]: + with self.lock: + return self.cache.pop(key, None) + + @override + def set(self, key: uuid.UUID, value: Segment) -> None: + with self.lock: + self.cache[key] = value + + @override + def reset(self) -> None: + with self.lock: + self.cache = {} + + +class SegmentLRUCache(BasicCache): + """A simple LRU cache implementation that handles objects with dynamic sizes. + The size of each object is determined by a user-provided size function.""" + + def __init__( + self, + capacity: int, + size_func: Callable[[uuid.UUID], int], + callback: Optional[Callable[[uuid.UUID, Segment], Any]] = None, + ): + self.capacity = capacity + self.size_func = size_func + self.cache: Dict[uuid.UUID, Segment] = {} + self.history = [] + self.callback = callback + self.lock = threading.RLock() + + def _upsert_key(self, key: uuid.UUID): + if key in self.history: + self.history.remove(key) + self.history.append(key) + else: + self.history.append(key) + + @override + def get(self, key: uuid.UUID) -> Optional[Segment]: + with self.lock: + self._upsert_key(key) + if key in self.cache: + return self.cache[key] + else: + return None + + @override + def pop(self, key: uuid.UUID) -> Optional[Segment]: + with self.lock: + if key in self.history: + self.history.remove(key) + return self.cache.pop(key, None) + + @override + def set(self, key: uuid.UUID, value: Segment) -> None: + with self.lock: + if key in self.cache: + return + item_size = self.size_func(key) + key_sizes = {key: self.size_func(key) for key in self.cache} + total_size = sum(key_sizes.values()) + index = 0 + # Evict items if capacity is exceeded + while total_size + item_size > self.capacity and len(self.history) > index: + key_delete = self.history[index] + if key_delete in self.cache: + self.callback(key_delete, self.cache[key_delete]) + del self.cache[key_delete] + total_size -= key_sizes[key_delete] + index += 1 + + self.cache[key] = value + self._upsert_key(key) + + @override + def reset(self): + with self.lock: + self.cache = {} + self.history = [] diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/segment/impl/manager/distributed.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/segment/impl/manager/distributed.py new file mode 100644 index 0000000000000000000000000000000000000000..ff3b02eb30ac2cdb3b86422e7a8f90410addad0a --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/segment/impl/manager/distributed.py @@ -0,0 +1,97 @@ +from threading import Lock +from typing import Dict, List, Sequence +from uuid import UUID, uuid4 + +from overrides import override + +from chromadb.config import System +from chromadb.db.system import SysDB +from chromadb.segment import ( + SegmentImplementation, + SegmentManager, + SegmentType, +) +from chromadb.segment.distributed import SegmentDirectory +from chromadb.segment.impl.vector.hnsw_params import PersistentHnswParams +from chromadb.telemetry.opentelemetry import ( + OpenTelemetryGranularity, + trace_method, +) +from chromadb.types import ( + Collection, + Operation, + Segment, + SegmentScope, +) + + +class DistributedSegmentManager(SegmentManager): + _sysdb: SysDB + _system: System + _instances: Dict[UUID, SegmentImplementation] + _segment_directory: SegmentDirectory + _lock: Lock + + def __init__(self, system: System): + super().__init__(system) + self._sysdb = self.require(SysDB) + self._segment_directory = self.require(SegmentDirectory) + self._system = system + self._instances = {} + self._lock = Lock() + + @trace_method( + "DistributedSegmentManager.prepare_segments_for_new_collection", + OpenTelemetryGranularity.OPERATION_AND_SEGMENT, + ) + @override + def prepare_segments_for_new_collection( + self, collection: Collection + ) -> Sequence[Segment]: + vector_segment = Segment( + id=uuid4(), + type=SegmentType.HNSW_DISTRIBUTED.value, + scope=SegmentScope.VECTOR, + collection=collection.id, + metadata=PersistentHnswParams.extract(collection.metadata) + if collection.metadata + else None, + file_paths={}, + ) + metadata_segment = Segment( + id=uuid4(), + type=SegmentType.BLOCKFILE_METADATA.value, + scope=SegmentScope.METADATA, + collection=collection.id, + metadata=None, + file_paths={}, + ) + record_segment = Segment( + id=uuid4(), + type=SegmentType.BLOCKFILE_RECORD.value, + scope=SegmentScope.RECORD, + collection=collection.id, + metadata=None, + file_paths={}, + ) + return [vector_segment, record_segment, metadata_segment] + + @override + def delete_segments(self, collection_id: UUID) -> Sequence[UUID]: + # delete_collection deletes segments in distributed mode + return [] + + @trace_method( + "DistributedSegmentManager.get_endpoint", + OpenTelemetryGranularity.OPERATION_AND_SEGMENT, + ) + def get_endpoints(self, segment: Segment, n: int) -> List[str]: + return self._segment_directory.get_segment_endpoints(segment, n) + + @trace_method( + "DistributedSegmentManager.hint_use_collection", + OpenTelemetryGranularity.OPERATION_AND_SEGMENT, + ) + @override + def hint_use_collection(self, collection_id: UUID, hint_type: Operation) -> None: + pass diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/segment/impl/manager/local.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/segment/impl/manager/local.py new file mode 100644 index 0000000000000000000000000000000000000000..b01cd9255cc1af26748484ce6703e036ade76998 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/segment/impl/manager/local.py @@ -0,0 +1,269 @@ +from threading import Lock +from chromadb.segment import ( + SegmentImplementation, + SegmentManager, + MetadataReader, + SegmentType, + VectorReader, + S, +) +import logging +from chromadb.segment.impl.manager.cache.cache import ( + SegmentLRUCache, + BasicCache, + SegmentCache, +) +import os + +from chromadb.config import System, get_class +from chromadb.db.system import SysDB +from overrides import override +from chromadb.segment.impl.vector.local_persistent_hnsw import ( + PersistentLocalHnswSegment, +) +from chromadb.telemetry.opentelemetry import ( + OpenTelemetryClient, + OpenTelemetryGranularity, + trace_method, +) +from chromadb.types import Collection, Operation, Segment, SegmentScope, Metadata +from typing import Dict, Type, Sequence, Optional, cast +from uuid import UUID, uuid4 +import platform + +from chromadb.utils.lru_cache import LRUCache +from chromadb.utils.directory import get_directory_size + + +if platform.system() != "Windows": + import resource +elif platform.system() == "Windows": + import ctypes + +SEGMENT_TYPE_IMPLS = { + SegmentType.SQLITE: "chromadb.segment.impl.metadata.sqlite.SqliteMetadataSegment", + SegmentType.HNSW_LOCAL_MEMORY: "chromadb.segment.impl.vector.local_hnsw.LocalHnswSegment", + SegmentType.HNSW_LOCAL_PERSISTED: "chromadb.segment.impl.vector.local_persistent_hnsw.PersistentLocalHnswSegment", +} + + +class LocalSegmentManager(SegmentManager): + _sysdb: SysDB + _system: System + _opentelemetry_client: OpenTelemetryClient + _instances: Dict[UUID, SegmentImplementation] + _vector_instances_file_handle_cache: LRUCache[ + UUID, PersistentLocalHnswSegment + ] # LRU cache to manage file handles across vector segment instances + _vector_segment_type: SegmentType = SegmentType.HNSW_LOCAL_MEMORY + _lock: Lock + _max_file_handles: int + + def __init__(self, system: System): + super().__init__(system) + self._sysdb = self.require(SysDB) + self._system = system + self._opentelemetry_client = system.require(OpenTelemetryClient) + self.logger = logging.getLogger(__name__) + self._instances = {} + self.segment_cache: Dict[SegmentScope, SegmentCache] = { + SegmentScope.METADATA: BasicCache() # type: ignore[no-untyped-call] + } + if ( + system.settings.chroma_segment_cache_policy == "LRU" + and system.settings.chroma_memory_limit_bytes > 0 + ): + self.segment_cache[SegmentScope.VECTOR] = SegmentLRUCache( + capacity=system.settings.chroma_memory_limit_bytes, + callback=lambda k, v: self.callback_cache_evict(v), + size_func=lambda k: self._get_segment_disk_size(k), + ) + else: + self.segment_cache[SegmentScope.VECTOR] = BasicCache() # type: ignore[no-untyped-call] + + self._lock = Lock() + + # TODO: prototyping with distributed segment for now, but this should be a configurable option + # we need to think about how to handle this configuration + if self._system.settings.require("is_persistent"): + self._vector_segment_type = SegmentType.HNSW_LOCAL_PERSISTED + if platform.system() != "Windows": + self._max_file_handles = resource.getrlimit(resource.RLIMIT_NOFILE)[0] + else: + self._max_file_handles = ctypes.windll.msvcrt._getmaxstdio() # type: ignore + segment_limit = ( + self._max_file_handles + # This is integer division in Python 3, and not a comment. + // PersistentLocalHnswSegment.get_file_handle_count() + ) + self._vector_instances_file_handle_cache = LRUCache( + segment_limit, callback=lambda _, v: v.close_persistent_index() + ) + + @trace_method( + "LocalSegmentManager.callback_cache_evict", + OpenTelemetryGranularity.OPERATION_AND_SEGMENT, + ) + def callback_cache_evict(self, segment: Segment) -> None: + collection_id = segment["collection"] + self.logger.info(f"LRU cache evict collection {collection_id}") + instance = self._instance(segment) + instance.stop() + del self._instances[segment["id"]] + + @override + def start(self) -> None: + for instance in self._instances.values(): + instance.start() + super().start() + + @override + def stop(self) -> None: + for instance in self._instances.values(): + instance.stop() + super().stop() + + @override + def reset_state(self) -> None: + for instance in self._instances.values(): + instance.stop() + instance.reset_state() + self._instances = {} + self.segment_cache[SegmentScope.VECTOR].reset() + super().reset_state() + + @trace_method( + "LocalSegmentManager.prepare_segments_for_new_collection", + OpenTelemetryGranularity.OPERATION_AND_SEGMENT, + ) + @override + def prepare_segments_for_new_collection( + self, collection: Collection + ) -> Sequence[Segment]: + vector_segment = _segment( + self._vector_segment_type, SegmentScope.VECTOR, collection + ) + metadata_segment = _segment( + SegmentType.SQLITE, SegmentScope.METADATA, collection + ) + return [vector_segment, metadata_segment] + + @trace_method( + "LocalSegmentManager.delete_segments", + OpenTelemetryGranularity.OPERATION_AND_SEGMENT, + ) + @override + def delete_segments(self, collection_id: UUID) -> Sequence[UUID]: + segments = self._sysdb.get_segments(collection=collection_id) + for segment in segments: + if segment["id"] in self._instances: + if segment["type"] == SegmentType.HNSW_LOCAL_PERSISTED.value: + instance = self.get_segment(collection_id, VectorReader) + instance.delete() + elif segment["type"] == SegmentType.SQLITE.value: + instance = self.get_segment(collection_id, MetadataReader) # type: ignore[assignment] + instance.delete() + del self._instances[segment["id"]] + if segment["scope"] is SegmentScope.VECTOR: + self.segment_cache[SegmentScope.VECTOR].pop(collection_id) + if segment["scope"] is SegmentScope.METADATA: + self.segment_cache[SegmentScope.METADATA].pop(collection_id) + return [s["id"] for s in segments] + + def _get_segment_disk_size(self, collection_id: UUID) -> int: + segments = self._sysdb.get_segments( + collection=collection_id, scope=SegmentScope.VECTOR + ) + if len(segments) == 0: + return 0 + # With local segment manager (single server chroma), a collection always have one segment. + size = get_directory_size( + os.path.join( + self._system.settings.require("persist_directory"), + str(segments[0]["id"]), + ) + ) + return size + + @trace_method( + "LocalSegmentManager._get_segment_sysdb", + OpenTelemetryGranularity.OPERATION_AND_SEGMENT, + ) + def _get_segment_sysdb(self, collection_id: UUID, scope: SegmentScope) -> Segment: + segments = self._sysdb.get_segments(collection=collection_id, scope=scope) + known_types = set([k.value for k in SEGMENT_TYPE_IMPLS.keys()]) + # Get the first segment of a known type + segment = next(filter(lambda s: s["type"] in known_types, segments)) + return segment + + @trace_method( + "LocalSegmentManager.get_segment", + OpenTelemetryGranularity.OPERATION_AND_SEGMENT, + ) + def get_segment(self, collection_id: UUID, type: Type[S]) -> S: + if type == MetadataReader: + scope = SegmentScope.METADATA + elif type == VectorReader: + scope = SegmentScope.VECTOR + else: + raise ValueError(f"Invalid segment type: {type}") + + segment = self.segment_cache[scope].get(collection_id) + if segment is None: + segment = self._get_segment_sysdb(collection_id, scope) + self.segment_cache[scope].set(collection_id, segment) + + # Instances must be atomically created, so we use a lock to ensure that only one thread + # creates the instance. + with self._lock: + instance = self._instance(segment) + return cast(S, instance) + + @trace_method( + "LocalSegmentManager.hint_use_collection", + OpenTelemetryGranularity.OPERATION_AND_SEGMENT, + ) + @override + def hint_use_collection(self, collection_id: UUID, hint_type: Operation) -> None: + # The local segment manager responds to hints by pre-loading both the metadata and vector + # segments for the given collection. + for type in [MetadataReader, VectorReader]: + # Just use get_segment to load the segment into the cache + instance = self.get_segment(collection_id, type) + # If the segment is a vector segment, we need to keep segments in an LRU cache + # to avoid hitting the OS file handle limit. + if type == VectorReader and self._system.settings.require("is_persistent"): + instance = cast(PersistentLocalHnswSegment, instance) + instance.open_persistent_index() + self._vector_instances_file_handle_cache.set(collection_id, instance) + + def _cls(self, segment: Segment) -> Type[SegmentImplementation]: + classname = SEGMENT_TYPE_IMPLS[SegmentType(segment["type"])] + cls = get_class(classname, SegmentImplementation) + return cls + + def _instance(self, segment: Segment) -> SegmentImplementation: + if segment["id"] not in self._instances: + cls = self._cls(segment) + instance = cls(self._system, segment) + instance.start() + self._instances[segment["id"]] = instance + return self._instances[segment["id"]] + + +def _segment(type: SegmentType, scope: SegmentScope, collection: Collection) -> Segment: + """Create a metadata dict, propagating metadata correctly for the given segment type.""" + cls = get_class(SEGMENT_TYPE_IMPLS[type], SegmentImplementation) + collection_metadata = collection.metadata + metadata: Optional[Metadata] = None + if collection_metadata: + metadata = cls.propagate_collection_metadata(collection_metadata) + + return Segment( + id=uuid4(), + type=type.value, + scope=scope, + collection=collection.id, + metadata=metadata, + file_paths={}, + ) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/segment/impl/metadata/__pycache__/sqlite.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/segment/impl/metadata/__pycache__/sqlite.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d31bd1dadecbf9c4dcb15926680540c6735421bc Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/segment/impl/metadata/__pycache__/sqlite.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/segment/impl/metadata/sqlite.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/segment/impl/metadata/sqlite.py new file mode 100644 index 0000000000000000000000000000000000000000..e5b4e2cc6ae443fd9fb6f426fcd37a73be5d288f --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/segment/impl/metadata/sqlite.py @@ -0,0 +1,723 @@ +from typing import Optional, Sequence, Any, Tuple, cast, Generator, Union, Dict, List +from chromadb.segment import MetadataReader +from chromadb.ingest import Consumer +from chromadb.config import System +from chromadb.types import RequestVersionContext, Segment, InclusionExclusionOperator +from chromadb.db.impl.sqlite import SqliteDB +from overrides import override +from chromadb.db.base import ( + Cursor, + ParameterValue, + get_sql, +) +from chromadb.telemetry.opentelemetry import ( + OpenTelemetryClient, + OpenTelemetryGranularity, + trace_method, +) +from chromadb.types import ( + Where, + WhereDocument, + MetadataEmbeddingRecord, + LogRecord, + SeqId, + Operation, + UpdateMetadata, + LiteralValue, + WhereOperator, +) +from uuid import UUID +from pypika import Table, Tables +from pypika.queries import QueryBuilder +import pypika.functions as fn +from pypika.terms import Criterion +from itertools import groupby +from functools import reduce +import sqlite3 + +import logging + +logger = logging.getLogger(__name__) + + +class SqliteMetadataSegment(MetadataReader): + _consumer: Consumer + _db: SqliteDB + _id: UUID + _opentelemetry_client: OpenTelemetryClient + _collection_id: Optional[UUID] + _subscription: Optional[UUID] = None + + def __init__(self, system: System, segment: Segment): + self._db = system.instance(SqliteDB) + self._consumer = system.instance(Consumer) + self._id = segment["id"] + self._opentelemetry_client = system.require(OpenTelemetryClient) + self._collection_id = segment["collection"] + + @trace_method("SqliteMetadataSegment.start", OpenTelemetryGranularity.ALL) + @override + def start(self) -> None: + if self._collection_id: + seq_id = self.max_seqid() + self._subscription = self._consumer.subscribe( + collection_id=self._collection_id, + consume_fn=self._write_metadata, + start=seq_id, + ) + + @trace_method("SqliteMetadataSegment.stop", OpenTelemetryGranularity.ALL) + @override + def stop(self) -> None: + if self._subscription: + self._consumer.unsubscribe(self._subscription) + + @trace_method("SqliteMetadataSegment.max_seqid", OpenTelemetryGranularity.ALL) + @override + def max_seqid(self) -> SeqId: + t = Table("max_seq_id") + q = ( + self._db.querybuilder() + .from_(t) + .select(t.seq_id) + .where(t.segment_id == ParameterValue(self._db.uuid_to_db(self._id))) + ) + sql, params = get_sql(q) + with self._db.tx() as cur: + result = cur.execute(sql, params).fetchone() + + if result is None: + return self._consumer.min_seqid() + else: + return cast(int, result[0]) + + @trace_method("SqliteMetadataSegment.count", OpenTelemetryGranularity.ALL) + @override + def count(self, request_version_context: RequestVersionContext) -> int: + embeddings_t = Table("embeddings") + q = ( + self._db.querybuilder() + .from_(embeddings_t) + .where( + embeddings_t.segment_id == ParameterValue(self._db.uuid_to_db(self._id)) + ) + .select(fn.Count(embeddings_t.id)) + ) + sql, params = get_sql(q) + with self._db.tx() as cur: + result = cur.execute(sql, params).fetchone()[0] + return cast(int, result) + + @trace_method("SqliteMetadataSegment.get_metadata", OpenTelemetryGranularity.ALL) + @override + 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.""" + embeddings_t, metadata_t, fulltext_t = Tables( + "embeddings", "embedding_metadata", "embedding_fulltext_search" + ) + + limit = limit or 2**63 - 1 + offset = offset or 0 + + if limit < 0: + raise ValueError("Limit cannot be negative") + + select_clause = [ + embeddings_t.id, + embeddings_t.embedding_id, + embeddings_t.seq_id, + ] + if include_metadata: + select_clause.extend( + [ + metadata_t.key, + metadata_t.string_value, + metadata_t.int_value, + metadata_t.float_value, + metadata_t.bool_value, + ] + ) + + q = ( + ( + self._db.querybuilder() + .from_(embeddings_t) + .left_join(metadata_t) + .on(embeddings_t.id == metadata_t.id) + ) + .select(*select_clause) + .orderby(embeddings_t.id) + ) + + # If there is a query that touches the metadata table, it uses + # where and where_document filters, we treat this case seperately + if where is not None or where_document is not None: + metadata_q = ( + self._db.querybuilder() + .from_(embeddings_t) + .select(embeddings_t.id) + .left_join(metadata_t) + .on(embeddings_t.id == metadata_t.id) + .orderby(embeddings_t.id) + .where( + embeddings_t.segment_id + == ParameterValue(self._db.uuid_to_db(self._id)) + ) + .distinct() # These are embedding ids + ) + + if where: + metadata_q = metadata_q.where( + self._where_map_criterion( + metadata_q, where, metadata_t, embeddings_t + ) + ) + if where_document: + metadata_q = metadata_q.where( + self._where_doc_criterion( + metadata_q, where_document, metadata_t, fulltext_t, embeddings_t + ) + ) + if ids is not None: + metadata_q = metadata_q.where( + embeddings_t.embedding_id.isin(ParameterValue(ids)) + ) + + metadata_q = metadata_q.limit(limit) + metadata_q = metadata_q.offset(offset) + + q = q.where(embeddings_t.id.isin(metadata_q)) + else: + # In the case where we don't use the metadata table + # We have to apply limit/offset to embeddings and then join + # with metadata + embeddings_q = ( + self._db.querybuilder() + .from_(embeddings_t) + .select(embeddings_t.id) + .where( + embeddings_t.segment_id + == ParameterValue(self._db.uuid_to_db(self._id)) + ) + .orderby(embeddings_t.id) + .limit(limit) + .offset(offset) + ) + + if ids is not None: + embeddings_q = embeddings_q.where( + embeddings_t.embedding_id.isin(ParameterValue(ids)) + ) + + q = q.where(embeddings_t.id.isin(embeddings_q)) + + with self._db.tx() as cur: + # Execute the query with the limit and offset already applied + return list(self._records(cur, q, include_metadata)) + + def _records( + self, cur: Cursor, q: QueryBuilder, include_metadata: bool + ) -> Generator[MetadataEmbeddingRecord, None, None]: + """Given a cursor and a QueryBuilder, yield a generator of records. Assumes + cursor returns rows in ID order.""" + + sql, params = get_sql(q) + cur.execute(sql, params) + + cur_iterator = iter(cur.fetchone, None) + group_iterator = groupby(cur_iterator, lambda r: int(r[0])) + + for _, group in group_iterator: + yield self._record(list(group), include_metadata) + + @trace_method("SqliteMetadataSegment._record", OpenTelemetryGranularity.ALL) + def _record( + self, rows: Sequence[Tuple[Any, ...]], include_metadata: bool + ) -> MetadataEmbeddingRecord: + """Given a list of DB rows with the same ID, construct a + MetadataEmbeddingRecord""" + _, embedding_id, seq_id = rows[0][:3] + if not include_metadata: + return MetadataEmbeddingRecord(id=embedding_id, metadata=None) + + metadata = {} + for row in rows: + key, string_value, int_value, float_value, bool_value = row[3:] + if string_value is not None: + metadata[key] = string_value + elif int_value is not None: + metadata[key] = int_value + elif float_value is not None: + metadata[key] = float_value + elif bool_value is not None: + if bool_value == 1: + metadata[key] = True + else: + metadata[key] = False + + return MetadataEmbeddingRecord( + id=embedding_id, + metadata=metadata or None, + ) + + @trace_method("SqliteMetadataSegment._insert_record", OpenTelemetryGranularity.ALL) + def _insert_record(self, cur: Cursor, record: LogRecord, upsert: bool) -> None: + """Add or update a single EmbeddingRecord into the DB""" + + t = Table("embeddings") + q = ( + self._db.querybuilder() + .into(t) + .columns(t.segment_id, t.embedding_id, t.seq_id) + .where(t.segment_id == ParameterValue(self._db.uuid_to_db(self._id))) + .where(t.embedding_id == ParameterValue(record["record"]["id"])) + ).insert( + ParameterValue(self._db.uuid_to_db(self._id)), + ParameterValue(record["record"]["id"]), + ParameterValue(record["log_offset"]), + ) + sql, params = get_sql(q) + sql = sql + "RETURNING id" + try: + id = cur.execute(sql, params).fetchone()[0] + except sqlite3.IntegrityError: + # Can't use INSERT OR REPLACE here because it changes the primary key. + if upsert: + return self._update_record(cur, record) + else: + logger.warning( + f"Insert of existing embedding ID: {record['record']['id']}" + ) + # We are trying to add for a record that already exists. Fail the call. + # We don't throw an exception since this is in principal an async path + return + + if record["record"]["metadata"]: + self._update_metadata(cur, id, record["record"]["metadata"]) + + @trace_method( + "SqliteMetadataSegment._update_metadata", OpenTelemetryGranularity.ALL + ) + def _update_metadata(self, cur: Cursor, id: int, metadata: UpdateMetadata) -> None: + """Update the metadata for a single EmbeddingRecord""" + t = Table("embedding_metadata") + to_delete = [k for k, v in metadata.items() if v is None] + if to_delete: + q = ( + self._db.querybuilder() + .from_(t) + .where(t.id == ParameterValue(id)) + .where(t.key.isin(ParameterValue(to_delete))) + .delete() + ) + sql, params = get_sql(q) + cur.execute(sql, params) + + self._insert_metadata(cur, id, metadata) + + @trace_method( + "SqliteMetadataSegment._insert_metadata", OpenTelemetryGranularity.ALL + ) + def _insert_metadata(self, cur: Cursor, id: int, metadata: UpdateMetadata) -> None: + """Insert or update each metadata row for a single embedding record""" + t = Table("embedding_metadata") + q = ( + self._db.querybuilder() + .into(t) + .columns( + t.id, + t.key, + t.string_value, + t.int_value, + t.float_value, + t.bool_value, + ) + ) + for key, value in metadata.items(): + if isinstance(value, str): + q = q.insert( + ParameterValue(id), + ParameterValue(key), + ParameterValue(value), + None, + None, + None, + ) + # isinstance(True, int) evaluates to True, so we need to check for bools separately + elif isinstance(value, bool): + q = q.insert( + ParameterValue(id), + ParameterValue(key), + None, + None, + None, + ParameterValue(value), + ) + elif isinstance(value, int): + q = q.insert( + ParameterValue(id), + ParameterValue(key), + None, + ParameterValue(value), + None, + None, + ) + elif isinstance(value, float): + q = q.insert( + ParameterValue(id), + ParameterValue(key), + None, + None, + ParameterValue(value), + None, + ) + + sql, params = get_sql(q) + sql = sql.replace("INSERT", "INSERT OR REPLACE") + if sql: + cur.execute(sql, params) + + if "chroma:document" in metadata: + t = Table("embedding_fulltext_search") + + def insert_into_fulltext_search() -> None: + q = ( + self._db.querybuilder() + .into(t) + .columns(t.rowid, t.string_value) + .insert( + ParameterValue(id), + ParameterValue(metadata["chroma:document"]), + ) + ) + sql, params = get_sql(q) + cur.execute(sql, params) + + try: + insert_into_fulltext_search() + except sqlite3.IntegrityError: + q = ( + self._db.querybuilder() + .from_(t) + .where(t.rowid == ParameterValue(id)) + .delete() + ) + sql, params = get_sql(q) + cur.execute(sql, params) + insert_into_fulltext_search() + + @trace_method("SqliteMetadataSegment._delete_record", OpenTelemetryGranularity.ALL) + def _delete_record(self, cur: Cursor, record: LogRecord) -> None: + """Delete a single EmbeddingRecord from the DB""" + t = Table("embeddings") + fts_t = Table("embedding_fulltext_search") + q = ( + self._db.querybuilder() + .from_(t) + .where(t.segment_id == ParameterValue(self._db.uuid_to_db(self._id))) + .where(t.embedding_id == ParameterValue(record["record"]["id"])) + .delete() + ) + q_fts = ( + self._db.querybuilder() + .from_(fts_t) + .delete() + .where( + fts_t.rowid.isin( + self._db.querybuilder() + .from_(t) + .select(t.id) + .where( + t.segment_id == ParameterValue(self._db.uuid_to_db(self._id)) + ) + .where(t.embedding_id == ParameterValue(record["record"]["id"])) + ) + ) + ) + cur.execute(*get_sql(q_fts)) + sql, params = get_sql(q) + sql = sql + " RETURNING id" + result = cur.execute(sql, params).fetchone() + if result is None: + logger.warning( + f"Delete of nonexisting embedding ID: {record['record']['id']}" + ) + else: + id = result[0] + + # Manually delete metadata; cannot use cascade because + # that triggers on replace + metadata_t = Table("embedding_metadata") + + q = ( + self._db.querybuilder() + .from_(metadata_t) + .where(metadata_t.id == ParameterValue(id)) + .delete() + ) + sql, params = get_sql(q) + cur.execute(sql, params) + + @trace_method("SqliteMetadataSegment._update_record", OpenTelemetryGranularity.ALL) + def _update_record(self, cur: Cursor, record: LogRecord) -> None: + """Update a single EmbeddingRecord in the DB""" + t = Table("embeddings") + q = ( + self._db.querybuilder() + .update(t) + .set(t.seq_id, ParameterValue(record["log_offset"])) + .where(t.segment_id == ParameterValue(self._db.uuid_to_db(self._id))) + .where(t.embedding_id == ParameterValue(record["record"]["id"])) + ) + sql, params = get_sql(q) + sql = sql + " RETURNING id" + result = cur.execute(sql, params).fetchone() + if result is None: + logger.warning( + f"Update of nonexisting embedding ID: {record['record']['id']}" + ) + else: + id = result[0] + if record["record"]["metadata"]: + self._update_metadata(cur, id, record["record"]["metadata"]) + + @trace_method("SqliteMetadataSegment._write_metadata", OpenTelemetryGranularity.ALL) + def _write_metadata(self, records: Sequence[LogRecord]) -> None: + """Write embedding metadata to the database. Care should be taken to ensure + records are append-only (that is, that seq-ids should increase monotonically)""" + with self._db.tx() as cur: + for record in records: + if record["record"]["operation"] == Operation.ADD: + self._insert_record(cur, record, False) + elif record["record"]["operation"] == Operation.UPSERT: + self._insert_record(cur, record, True) + elif record["record"]["operation"] == Operation.DELETE: + self._delete_record(cur, record) + elif record["record"]["operation"] == Operation.UPDATE: + self._update_record(cur, record) + + q = ( + self._db.querybuilder() + .into(Table("max_seq_id")) + .columns("segment_id", "seq_id") + .insert( + ParameterValue(self._db.uuid_to_db(self._id)), + ParameterValue(record["log_offset"]), + ) + ) + sql, params = get_sql(q) + sql = sql.replace("INSERT", "INSERT OR REPLACE") + cur.execute(sql, params) + + @trace_method( + "SqliteMetadataSegment._where_map_criterion", OpenTelemetryGranularity.ALL + ) + def _where_map_criterion( + self, q: QueryBuilder, where: Where, metadata_t: Table, embeddings_t: Table + ) -> Criterion: + clause: List[Criterion] = [] + for k, v in where.items(): + if k == "$and": + criteria = [ + self._where_map_criterion(q, w, metadata_t, embeddings_t) + for w in cast(Sequence[Where], v) + ] + clause.append(reduce(lambda x, y: x & y, criteria)) + elif k == "$or": + criteria = [ + self._where_map_criterion(q, w, metadata_t, embeddings_t) + for w in cast(Sequence[Where], v) + ] + clause.append(reduce(lambda x, y: x | y, criteria)) + else: + expr = cast(Union[LiteralValue, Dict[WhereOperator, LiteralValue]], v) + clause.append(_where_clause(k, expr, q, metadata_t, embeddings_t)) + return reduce(lambda x, y: x & y, clause) + + @trace_method( + "SqliteMetadataSegment._where_doc_criterion", OpenTelemetryGranularity.ALL + ) + def _where_doc_criterion( + self, + q: QueryBuilder, + where: WhereDocument, + metadata_t: Table, + fulltext_t: Table, + embeddings_t: Table, + ) -> Criterion: + for k, v in where.items(): + if k == "$and": + criteria = [ + self._where_doc_criterion( + q, w, metadata_t, fulltext_t, embeddings_t + ) + for w in cast(Sequence[WhereDocument], v) + ] + return reduce(lambda x, y: x & y, criteria) + elif k == "$or": + criteria = [ + self._where_doc_criterion( + q, w, metadata_t, fulltext_t, embeddings_t + ) + for w in cast(Sequence[WhereDocument], v) + ] + return reduce(lambda x, y: x | y, criteria) + elif k in ("$contains", "$not_contains"): + v = cast(str, v) + search_term = f"%{v}%" + + sq = ( + self._db.querybuilder() + .from_(fulltext_t) + .select(fulltext_t.rowid) + .where(fulltext_t.string_value.like(ParameterValue(search_term))) + ) + return ( + embeddings_t.id.isin(sq) + if k == "$contains" + else embeddings_t.id.notin(sq) + ) + else: + raise ValueError(f"Unknown where_doc operator {k}") + raise ValueError("Empty where_doc") + + @trace_method("SqliteMetadataSegment.delete", OpenTelemetryGranularity.ALL) + @override + def delete(self) -> None: + t = Table("embeddings") + t1 = Table("embedding_metadata") + t2 = Table("embedding_fulltext_search") + q0 = ( + self._db.querybuilder() + .from_(t1) + .delete() + .where( + t1.id.isin( + self._db.querybuilder() + .from_(t) + .select(t.id) + .where( + t.segment_id == ParameterValue(self._db.uuid_to_db(self._id)) + ) + ) + ) + ) + q = ( + self._db.querybuilder() + .from_(t) + .delete() + .where( + t.id.isin( + self._db.querybuilder() + .from_(t) + .select(t.id) + .where( + t.segment_id == ParameterValue(self._db.uuid_to_db(self._id)) + ) + ) + ) + ) + q_fts = ( + self._db.querybuilder() + .from_(t2) + .delete() + .where( + t2.rowid.isin( + self._db.querybuilder() + .from_(t) + .select(t.id) + .where( + t.segment_id == ParameterValue(self._db.uuid_to_db(self._id)) + ) + ) + ) + ) + with self._db.tx() as cur: + cur.execute(*get_sql(q_fts)) + cur.execute(*get_sql(q0)) + cur.execute(*get_sql(q)) + + +def _where_clause( + key: str, + expr: Union[ + LiteralValue, + Dict[WhereOperator, LiteralValue], + Dict[InclusionExclusionOperator, List[LiteralValue]], + ], + metadata_q: QueryBuilder, + metadata_t: Table, + embeddings_t: Table, +) -> Criterion: + """Given a field name, an expression, and a table, construct a Pypika Criterion""" + + # Literal value case + if isinstance(expr, (str, int, float, bool)): + return _where_clause( + key, + {cast(WhereOperator, "$eq"): expr}, + metadata_q, + metadata_t, + embeddings_t, + ) + + # Operator dict case + operator, value = next(iter(expr.items())) + return _value_criterion(key, value, operator, metadata_q, metadata_t, embeddings_t) + + +def _value_criterion( + key: str, + value: Union[LiteralValue, List[LiteralValue]], + op: Union[WhereOperator, InclusionExclusionOperator], + metadata_q: QueryBuilder, + metadata_t: Table, + embeddings_t: Table, +) -> Criterion: + """Creates the filter for a single operator""" + + def is_numeric(obj: object) -> bool: + return (not isinstance(obj, bool)) and isinstance(obj, (int, float)) + + sub_q = metadata_q.where(metadata_t.key == ParameterValue(key)) + p_val = ParameterValue(value) + + if is_numeric(value) or (isinstance(value, list) and is_numeric(value[0])): + int_col, float_col = metadata_t.int_value, metadata_t.float_value + if op in ("$eq", "$ne"): + expr = (int_col == p_val) | (float_col == p_val) + elif op == "$gt": + expr = (int_col > p_val) | (float_col > p_val) + elif op == "$gte": + expr = (int_col >= p_val) | (float_col >= p_val) + elif op == "$lt": + expr = (int_col < p_val) | (float_col < p_val) + elif op == "$lte": + expr = (int_col <= p_val) | (float_col <= p_val) + else: + expr = int_col.isin(p_val) | float_col.isin(p_val) + else: + if isinstance(value, bool) or ( + isinstance(value, list) and isinstance(value[0], bool) + ): + col = metadata_t.bool_value + else: + col = metadata_t.string_value + if op in ("$eq", "$ne"): + expr = col == p_val + else: + expr = col.isin(p_val) + + if op in ("$ne", "$nin"): + return embeddings_t.id.notin(sub_q.where(expr)) + else: + return embeddings_t.id.isin(sub_q.where(expr)) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/segment/impl/vector/__pycache__/batch.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/segment/impl/vector/__pycache__/batch.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..74c90a728afc1b471d26708316fbd5530ff7cbbf Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/segment/impl/vector/__pycache__/batch.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/segment/impl/vector/__pycache__/brute_force_index.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/segment/impl/vector/__pycache__/brute_force_index.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..771d369e15dd1307a8d734ad3a428ba4fc49648b Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/segment/impl/vector/__pycache__/brute_force_index.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/segment/impl/vector/__pycache__/hnsw_params.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/segment/impl/vector/__pycache__/hnsw_params.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f1f6853f9a32011b8ddb0325f12b4c5aba92858c Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/segment/impl/vector/__pycache__/hnsw_params.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/segment/impl/vector/__pycache__/local_hnsw.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/segment/impl/vector/__pycache__/local_hnsw.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..22999fd75f91a90139b64c2d6df5f4701b63bbb8 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/segment/impl/vector/__pycache__/local_hnsw.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/segment/impl/vector/__pycache__/local_persistent_hnsw.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/segment/impl/vector/__pycache__/local_persistent_hnsw.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..cb8a1c09d5d9186979b2be3c2f17fc995165394c Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/segment/impl/vector/__pycache__/local_persistent_hnsw.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/segment/impl/vector/batch.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/segment/impl/vector/batch.py new file mode 100644 index 0000000000000000000000000000000000000000..cd99e18a4d41cbe4da148451e3d13d58087c8468 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/segment/impl/vector/batch.py @@ -0,0 +1,106 @@ +from typing import Dict, List, Set, cast +from chromadb.types import LogRecord, Operation, Vector + + +class Batch: + """Used to model the set of changes as an atomic operation""" + + _ids_to_records: Dict[str, LogRecord] + _deleted_ids: Set[str] + _written_ids: Set[str] + _upsert_add_ids: Set[str] # IDs that are being added in an upsert + add_count: int + update_count: int + + def __init__(self) -> None: + self._ids_to_records = {} + self._deleted_ids = set() + self._written_ids = set() + self._upsert_add_ids = set() + self.add_count = 0 + self.update_count = 0 + + def __len__(self) -> int: + """Get the number of changes in this batch""" + return len(self._written_ids) + len(self._deleted_ids) + + def get_deleted_ids(self) -> List[str]: + """Get the list of deleted embeddings in this batch""" + return list(self._deleted_ids) + + def get_written_ids(self) -> List[str]: + """Get the list of written embeddings in this batch""" + return list(self._written_ids) + + def get_written_vectors(self, ids: List[str]) -> List[Vector]: + """Get the list of vectors to write in this batch""" + return [ + cast(Vector, self._ids_to_records[id]["record"]["embedding"]) for id in ids + ] + + def get_record(self, id: str) -> LogRecord: + """Get the record for a given ID""" + return self._ids_to_records[id] + + def is_deleted(self, id: str) -> bool: + """Check if a given ID is deleted""" + return id in self._deleted_ids + + @property + def delete_count(self) -> int: + return len(self._deleted_ids) + + def apply(self, record: LogRecord, exists_already: bool = False) -> None: + """Apply an embedding record to this batch. Records passed to this method are assumed to be validated for correctness. + For example, a delete or update presumes the ID exists in the index. An add presumes the ID does not exist in the index. + The exists_already flag should be set to True if the ID does exist in the index, and False otherwise. + """ + id = record["record"]["id"] + if record["record"]["operation"] == Operation.DELETE: + # If the ID was previously written, remove it from the written set + # And update the add/update/delete counts + if id in self._written_ids: + self._written_ids.remove(id) + if self._ids_to_records[id]["record"]["operation"] == Operation.ADD: + self.add_count -= 1 + elif ( + self._ids_to_records[id]["record"]["operation"] == Operation.UPDATE + ): + self.update_count -= 1 + self._deleted_ids.add(id) + elif ( + self._ids_to_records[id]["record"]["operation"] == Operation.UPSERT + ): + if id in self._upsert_add_ids: + self.add_count -= 1 + self._upsert_add_ids.remove(id) + else: + self.update_count -= 1 + self._deleted_ids.add(id) + elif id not in self._deleted_ids: + self._deleted_ids.add(id) + + # Remove the record from the batch + if id in self._ids_to_records: + del self._ids_to_records[id] + + else: + self._ids_to_records[id] = record + self._written_ids.add(id) + + # If the ID was previously deleted, remove it from the deleted set + # And update the delete count + if id in self._deleted_ids: + self._deleted_ids.remove(id) + + # Update the add/update counts + if record["record"]["operation"] == Operation.UPSERT: + if not exists_already: + self.add_count += 1 + self._upsert_add_ids.add(id) + else: + self.update_count += 1 + elif record["record"]["operation"] == Operation.ADD: + self.add_count += 1 + elif record["record"]["operation"] == Operation.UPDATE: + self.update_count += 1 diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/segment/impl/vector/brute_force_index.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/segment/impl/vector/brute_force_index.py new file mode 100644 index 0000000000000000000000000000000000000000..c640c77644c8d12f72a686937aad1ed9bff1a0fc --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/segment/impl/vector/brute_force_index.py @@ -0,0 +1,151 @@ +from typing import Any, Callable, Dict, List, Optional, Sequence, Set +import numpy as np +import numpy.typing as npt +from chromadb.types import ( + LogRecord, + VectorEmbeddingRecord, + VectorQuery, + VectorQueryResult, +) + +from chromadb.utils import distance_functions +import logging + +logger = logging.getLogger(__name__) + + +class BruteForceIndex: + """A lightweight, numpy based brute force index that is used for batches that have not been indexed into hnsw yet. It is not + thread safe and callers should ensure that only one thread is accessing it at a time. + """ + + id_to_index: Dict[str, int] + index_to_id: Dict[int, str] + id_to_seq_id: Dict[str, int] + deleted_ids: Set[str] + free_indices: List[int] + size: int + dimensionality: int + distance_fn: Callable[[npt.NDArray[Any], npt.NDArray[Any]], float] + vectors: npt.NDArray[Any] + + def __init__(self, size: int, dimensionality: int, space: str = "l2"): + if space == "l2": + self.distance_fn = distance_functions.l2 + elif space == "ip": + self.distance_fn = distance_functions.ip + elif space == "cosine": + self.distance_fn = distance_functions.cosine + else: + raise Exception(f"Unknown distance function: {space}") + + self.id_to_index = {} + self.index_to_id = {} + self.id_to_seq_id = {} + self.deleted_ids = set() + self.free_indices = list(range(size)) + self.size = size + self.dimensionality = dimensionality + self.vectors = np.zeros((size, dimensionality)) + + def __len__(self) -> int: + return len(self.id_to_index) + + def clear(self) -> None: + self.id_to_index = {} + self.index_to_id = {} + self.id_to_seq_id = {} + self.deleted_ids.clear() + self.free_indices = list(range(self.size)) + self.vectors.fill(0) + + def upsert(self, records: List[LogRecord]) -> None: + if len(records) + len(self) > self.size: + raise Exception( + "Index with capacity {} and {} current entries cannot add {} records".format( + self.size, len(self), len(records) + ) + ) + + for i, record in enumerate(records): + id = record["record"]["id"] + vector = record["record"]["embedding"] + self.id_to_seq_id[id] = record["log_offset"] + if id in self.deleted_ids: + self.deleted_ids.remove(id) + + # TODO: It may be faster to use multi-index selection on the vectors array + if id in self.id_to_index: + # Update + index = self.id_to_index[id] + self.vectors[index] = vector + else: + # Add + next_index = self.free_indices.pop() + self.id_to_index[id] = next_index + self.index_to_id[next_index] = id + self.vectors[next_index] = vector + + def delete(self, records: List[LogRecord]) -> None: + for record in records: + id = record["record"]["id"] + if id in self.id_to_index: + index = self.id_to_index[id] + self.deleted_ids.add(id) + del self.id_to_index[id] + del self.index_to_id[index] + del self.id_to_seq_id[id] + self.vectors[index].fill(np.nan) + self.free_indices.append(index) + else: + logger.warning(f"Delete of nonexisting embedding ID: {id}") + + def has_id(self, id: str) -> bool: + """Returns whether the index contains the given ID""" + return id in self.id_to_index and id not in self.deleted_ids + + def get_vectors( + self, ids: Optional[Sequence[str]] = None + ) -> Sequence[VectorEmbeddingRecord]: + target_ids = ids or self.id_to_index.keys() + + return [ + VectorEmbeddingRecord( + id=id, + embedding=self.vectors[self.id_to_index[id]], + ) + for id in target_ids + ] + + def query(self, query: VectorQuery) -> Sequence[Sequence[VectorQueryResult]]: + np_query = np.array(query["vectors"], dtype=np.float32) + allowed_ids = ( + None if query["allowed_ids"] is None else set(query["allowed_ids"]) + ) + distances = np.apply_along_axis( + lambda query: np.apply_along_axis(self.distance_fn, 1, self.vectors, query), + 1, + np_query, + ) + + indices = np.argsort(distances) + # Filter out deleted labels + filtered_results = [] + for i, index_list in enumerate(indices): + curr_results = [] + for j in index_list: + # If the index is in the index_to_id map, then it has been added + if j in self.index_to_id: + id = self.index_to_id[j] + if id not in self.deleted_ids and ( + allowed_ids is None or id in allowed_ids + ): + curr_results.append( + VectorQueryResult( + id=id, + distance=distances[i][j].item(), + embedding=self.vectors[j], + ) + ) + filtered_results.append(curr_results) + return filtered_results diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/segment/impl/vector/hnsw_params.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/segment/impl/vector/hnsw_params.py new file mode 100644 index 0000000000000000000000000000000000000000..285b2527ba6a7c3c2239c59b3e7c402270a0cba2 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/segment/impl/vector/hnsw_params.py @@ -0,0 +1,88 @@ +import multiprocessing +import re +from typing import Any, Callable, Dict, Union + +from chromadb.types import Metadata + + +Validator = Callable[[Union[str, int, float]], bool] + +param_validators: Dict[str, Validator] = { + "hnsw:space": lambda p: bool(re.match(r"^(l2|cosine|ip)$", str(p))), + "hnsw:construction_ef": lambda p: isinstance(p, int), + "hnsw:search_ef": lambda p: isinstance(p, int), + "hnsw:M": lambda p: isinstance(p, int), + "hnsw:num_threads": lambda p: isinstance(p, int), + "hnsw:resize_factor": lambda p: isinstance(p, (int, float)), +} + +# Extra params used for persistent hnsw +persistent_param_validators: Dict[str, Validator] = { + "hnsw:batch_size": lambda p: isinstance(p, int) and p > 2, + "hnsw:sync_threshold": lambda p: isinstance(p, int) and p > 2, +} + + +class Params: + @staticmethod + def _select(metadata: Metadata) -> Dict[str, Any]: + segment_metadata = {} + for param, value in metadata.items(): + if param.startswith("hnsw:"): + segment_metadata[param] = value + return segment_metadata + + @staticmethod + def _validate(metadata: Dict[str, Any], validators: Dict[str, Validator]) -> None: + """Validates the metadata""" + # Validate it + for param, value in metadata.items(): + if param not in validators: + raise ValueError(f"Unknown HNSW parameter: {param}") + if not validators[param](value): + raise ValueError(f"Invalid value for HNSW parameter: {param} = {value}") + + +class HnswParams(Params): + space: str + construction_ef: int + search_ef: int + M: int + num_threads: int + resize_factor: float + + def __init__(self, metadata: Metadata): + metadata = metadata or {} + self.space = str(metadata.get("hnsw:space", "l2")) + self.construction_ef = int(metadata.get("hnsw:construction_ef", 100)) + self.search_ef = int(metadata.get("hnsw:search_ef", 100)) + self.M = int(metadata.get("hnsw:M", 16)) + self.num_threads = int( + metadata.get("hnsw:num_threads", multiprocessing.cpu_count()) + ) + self.resize_factor = float(metadata.get("hnsw:resize_factor", 1.2)) + + @staticmethod + def extract(metadata: Metadata) -> Metadata: + """Validate and return only the relevant hnsw params""" + segment_metadata = HnswParams._select(metadata) + HnswParams._validate(segment_metadata, param_validators) + return segment_metadata + + +class PersistentHnswParams(HnswParams): + batch_size: int + sync_threshold: int + + def __init__(self, metadata: Metadata): + super().__init__(metadata) + self.batch_size = int(metadata.get("hnsw:batch_size", 100)) + self.sync_threshold = int(metadata.get("hnsw:sync_threshold", 1000)) + + @staticmethod + def extract(metadata: Metadata) -> Metadata: + """Returns only the relevant hnsw params""" + all_validators = {**param_validators, **persistent_param_validators} + segment_metadata = PersistentHnswParams._select(metadata) + PersistentHnswParams._validate(segment_metadata, all_validators) + return segment_metadata diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/segment/impl/vector/local_hnsw.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/segment/impl/vector/local_hnsw.py new file mode 100644 index 0000000000000000000000000000000000000000..a05c030dbc74c42fb044f0939034b8236486e3d2 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/segment/impl/vector/local_hnsw.py @@ -0,0 +1,332 @@ +from overrides import override +from typing import Optional, Sequence, Dict, Set, List, cast +from uuid import UUID +from chromadb.segment import VectorReader +from chromadb.ingest import Consumer +from chromadb.config import System, Settings +from chromadb.segment.impl.vector.batch import Batch +from chromadb.segment.impl.vector.hnsw_params import HnswParams +from chromadb.telemetry.opentelemetry import ( + OpenTelemetryClient, + OpenTelemetryGranularity, + trace_method, +) +from chromadb.types import ( + LogRecord, + RequestVersionContext, + VectorEmbeddingRecord, + VectorQuery, + VectorQueryResult, + SeqId, + Segment, + Metadata, + Operation, + Vector, +) +from chromadb.errors import InvalidDimensionException +import hnswlib +from chromadb.utils.read_write_lock import ReadWriteLock, ReadRWLock, WriteRWLock +import logging +import numpy as np + +logger = logging.getLogger(__name__) + +DEFAULT_CAPACITY = 1000 + + +class LocalHnswSegment(VectorReader): + _id: UUID + _consumer: Consumer + _collection: Optional[UUID] + _subscription: Optional[UUID] + _settings: Settings + _params: HnswParams + + _index: Optional[hnswlib.Index] + _dimensionality: Optional[int] + _total_elements_added: int + _max_seq_id: SeqId + + _lock: ReadWriteLock + + _id_to_label: Dict[str, int] + _label_to_id: Dict[int, str] + # Note: As of the time of writing, this mapping is no longer needed. + # We merely keep it around for easy compatibility with the old code and + # debugging purposes. + _id_to_seq_id: Dict[str, SeqId] + + _opentelemtry_client: OpenTelemetryClient + + def __init__(self, system: System, segment: Segment): + self._consumer = system.instance(Consumer) + self._id = segment["id"] + self._collection = segment["collection"] + self._subscription = None + self._settings = system.settings + self._params = HnswParams(segment["metadata"] or {}) + + self._index = None + self._dimensionality = None + self._total_elements_added = 0 + self._max_seq_id = self._consumer.min_seqid() + + self._id_to_seq_id = {} + self._id_to_label = {} + self._label_to_id = {} + + self._lock = ReadWriteLock() + self._opentelemtry_client = system.require(OpenTelemetryClient) + + @staticmethod + @override + def propagate_collection_metadata(metadata: Metadata) -> Optional[Metadata]: + # Extract relevant metadata + segment_metadata = HnswParams.extract(metadata) + return segment_metadata + + @trace_method("LocalHnswSegment.start", OpenTelemetryGranularity.ALL) + @override + def start(self) -> None: + super().start() + if self._collection: + seq_id = self.max_seqid() + self._subscription = self._consumer.subscribe( + self._collection, self._write_records, start=seq_id + ) + + @trace_method("LocalHnswSegment.stop", OpenTelemetryGranularity.ALL) + @override + def stop(self) -> None: + super().stop() + if self._subscription: + self._consumer.unsubscribe(self._subscription) + + @trace_method("LocalHnswSegment.get_vectors", OpenTelemetryGranularity.ALL) + @override + def get_vectors( + self, + request_version_context: RequestVersionContext, + ids: Optional[Sequence[str]] = None, + ) -> Sequence[VectorEmbeddingRecord]: + if ids is None: + labels = list(self._label_to_id.keys()) + else: + labels = [] + for id in ids: + if id in self._id_to_label: + labels.append(self._id_to_label[id]) + + results = [] + if self._index is not None: + vectors = cast( + Sequence[Vector], np.array(self._index.get_items(labels)) + ) # version 0.8 of hnswlib allows return_type="numpy" + + for label, vector in zip(labels, vectors): + id = self._label_to_id[label] + results.append(VectorEmbeddingRecord(id=id, embedding=vector)) + + return results + + @trace_method("LocalHnswSegment.query_vectors", OpenTelemetryGranularity.ALL) + @override + def query_vectors( + self, query: VectorQuery + ) -> Sequence[Sequence[VectorQueryResult]]: + if self._index is None: + return [[] for _ in range(len(query["vectors"]))] + + k = query["k"] + size = len(self._id_to_label) + + if k > size: + logger.warning( + f"Number of requested results {k} is greater than number of elements in index {size}, updating n_results = {size}" + ) + k = size + + labels: Set[int] = set() + ids = query["allowed_ids"] + if ids is not None: + labels = {self._id_to_label[id] for id in ids if id in self._id_to_label} + if len(labels) < k: + k = len(labels) + + def filter_function(label: int) -> bool: + return label in labels + + query_vectors = query["vectors"] + + with ReadRWLock(self._lock): + result_labels, distances = self._index.knn_query( + np.array(query_vectors, dtype=np.float32), + k=k, + filter=filter_function if ids else None, + ) + + # TODO: these casts are not correct, hnswlib returns np + # distances = cast(List[List[float]], distances) + # result_labels = cast(List[List[int]], result_labels) + + all_results: List[List[VectorQueryResult]] = [] + for result_i in range(len(result_labels)): + results: List[VectorQueryResult] = [] + for label, distance in zip( + result_labels[result_i], distances[result_i] + ): + id = self._label_to_id[label] + if query["include_embeddings"]: + embedding = np.array( + self._index.get_items([label])[0] + ) # version 0.8 of hnswlib allows return_type="numpy" + else: + embedding = None + results.append( + VectorQueryResult( + id=id, + distance=distance.item(), + embedding=embedding, + ) + ) + all_results.append(results) + + return all_results + + @override + def max_seqid(self) -> SeqId: + return self._max_seq_id + + @override + def count(self, request_version_context: RequestVersionContext) -> int: + return len(self._id_to_label) + + @trace_method("LocalHnswSegment._init_index", OpenTelemetryGranularity.ALL) + def _init_index(self, dimensionality: int) -> None: + # more comments available at the source: https://github.com/nmslib/hnswlib + + index = hnswlib.Index( + space=self._params.space, dim=dimensionality + ) # possible options are l2, cosine or ip + index.init_index( + max_elements=DEFAULT_CAPACITY, + ef_construction=self._params.construction_ef, + M=self._params.M, + ) + index.set_ef(self._params.search_ef) + index.set_num_threads(self._params.num_threads) + + self._index = index + self._dimensionality = dimensionality + + @trace_method("LocalHnswSegment._ensure_index", OpenTelemetryGranularity.ALL) + def _ensure_index(self, n: int, dim: int) -> None: + """Create or resize the index as necessary to accomodate N new records""" + if not self._index: + self._dimensionality = dim + self._init_index(dim) + else: + if dim != self._dimensionality: + raise InvalidDimensionException( + f"Dimensionality of ({dim}) does not match index" + + f"dimensionality ({self._dimensionality})" + ) + + index = cast(hnswlib.Index, self._index) + + if (self._total_elements_added + n) > index.get_max_elements(): + new_size = int( + (self._total_elements_added + n) * self._params.resize_factor + ) + index.resize_index(max(new_size, DEFAULT_CAPACITY)) + + @trace_method("LocalHnswSegment._apply_batch", OpenTelemetryGranularity.ALL) + def _apply_batch(self, batch: Batch) -> None: + """Apply a batch of changes, as atomically as possible.""" + deleted_ids = batch.get_deleted_ids() + written_ids = batch.get_written_ids() + vectors_to_write = batch.get_written_vectors(written_ids) + labels_to_write = [0] * len(vectors_to_write) + + if len(deleted_ids) > 0: + index = cast(hnswlib.Index, self._index) + for i in range(len(deleted_ids)): + id = deleted_ids[i] + # Never added this id to hnsw, so we can safely ignore it for deletions + if id not in self._id_to_label: + continue + label = self._id_to_label[id] + + index.mark_deleted(label) + del self._id_to_label[id] + del self._label_to_id[label] + del self._id_to_seq_id[id] + + if len(written_ids) > 0: + self._ensure_index(batch.add_count, len(vectors_to_write[0])) + + next_label = self._total_elements_added + 1 + for i in range(len(written_ids)): + if written_ids[i] not in self._id_to_label: + labels_to_write[i] = next_label + next_label += 1 + else: + labels_to_write[i] = self._id_to_label[written_ids[i]] + + index = cast(hnswlib.Index, self._index) + + # First, update the index + index.add_items(vectors_to_write, labels_to_write) + + # If that succeeds, update the mappings + for i, id in enumerate(written_ids): + self._id_to_seq_id[id] = batch.get_record(id)["log_offset"] + self._id_to_label[id] = labels_to_write[i] + self._label_to_id[labels_to_write[i]] = id + + # If that succeeds, update the total count + self._total_elements_added += batch.add_count + + @trace_method("LocalHnswSegment._write_records", OpenTelemetryGranularity.ALL) + def _write_records(self, records: Sequence[LogRecord]) -> None: + """Add a batch of embeddings to the index""" + if not self._running: + raise RuntimeError("Cannot add embeddings to stopped component") + + # Avoid all sorts of potential problems by ensuring single-threaded access + with WriteRWLock(self._lock): + batch = Batch() + + for record in records: + self._max_seq_id = max(self._max_seq_id, record["log_offset"]) + id = record["record"]["id"] + op = record["record"]["operation"] + label = self._id_to_label.get(id, None) + + if op == Operation.DELETE: + if label: + batch.apply(record) + else: + logger.warning(f"Delete of nonexisting embedding ID: {id}") + + elif op == Operation.UPDATE: + if record["record"]["embedding"] is not None: + if label is not None: + batch.apply(record) + else: + logger.warning( + f"Update of nonexisting embedding ID: {record['record']['id']}" + ) + elif op == Operation.ADD: + if not label: + batch.apply(record, False) + else: + logger.warning(f"Add of existing embedding ID: {id}") + elif op == Operation.UPSERT: + batch.apply(record, label is not None) + + self._apply_batch(batch) + + @override + def delete(self) -> None: + raise NotImplementedError() diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/segment/impl/vector/local_persistent_hnsw.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/segment/impl/vector/local_persistent_hnsw.py new file mode 100644 index 0000000000000000000000000000000000000000..b69e9c394a524849298db9f11ac0a706a1d00c8c --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/segment/impl/vector/local_persistent_hnsw.py @@ -0,0 +1,543 @@ +import os +import shutil +from overrides import override +import pickle +from typing import Dict, List, Optional, Sequence, Set, cast +from chromadb.config import System +from chromadb.db.base import ParameterValue, get_sql +from chromadb.db.impl.sqlite import SqliteDB +from chromadb.segment.impl.vector.batch import Batch +from chromadb.segment.impl.vector.hnsw_params import PersistentHnswParams +from chromadb.segment.impl.vector.local_hnsw import ( + DEFAULT_CAPACITY, + LocalHnswSegment, +) +from chromadb.segment.impl.vector.brute_force_index import BruteForceIndex +from chromadb.telemetry.opentelemetry import ( + OpenTelemetryClient, + OpenTelemetryGranularity, + trace_method, +) +from chromadb.types import ( + LogRecord, + Metadata, + Operation, + RequestVersionContext, + Segment, + SeqId, + Vector, + VectorEmbeddingRecord, + VectorQuery, + VectorQueryResult, +) +import hnswlib +import logging +from pypika import Table +import numpy as np + +from chromadb.utils.read_write_lock import ReadRWLock, WriteRWLock + + +logger = logging.getLogger(__name__) + + +class PersistentData: + """Stores the data and metadata needed for a PersistentLocalHnswSegment""" + + dimensionality: Optional[int] + total_elements_added: int + + max_seq_id: SeqId + "This is a legacy field. It is no longer mutated, but kept to allow automatic migration of the `max_seq_id` from the pickled file to the `max_seq_id` table in SQLite." + + id_to_label: Dict[str, int] + label_to_id: Dict[int, str] + id_to_seq_id: Dict[str, SeqId] + + def __init__( + self, + dimensionality: Optional[int], + total_elements_added: int, + id_to_label: Dict[str, int], + label_to_id: Dict[int, str], + id_to_seq_id: Dict[str, SeqId], + ): + self.dimensionality = dimensionality + self.total_elements_added = total_elements_added + self.id_to_label = id_to_label + self.label_to_id = label_to_id + self.id_to_seq_id = id_to_seq_id + + @staticmethod + def load_from_file(filename: str) -> "PersistentData": + """Load persistent data from a file""" + with open(filename, "rb") as f: + ret = cast(PersistentData, pickle.load(f)) + return ret + + +class PersistentLocalHnswSegment(LocalHnswSegment): + METADATA_FILE: str = "index_metadata.pickle" + # How many records to add to index at once, we do this because crossing the python/c++ boundary is expensive (for add()) + # When records are not added to the c++ index, they are buffered in memory and served + # via brute force search. + _batch_size: int + _brute_force_index: Optional[BruteForceIndex] + _index_initialized: bool = False + _curr_batch: Batch + # How many records to add to index before syncing to disk + _sync_threshold: int + _persist_data: PersistentData + _persist_directory: str + _allow_reset: bool + + _db: SqliteDB + _opentelemtry_client: OpenTelemetryClient + + _num_log_records_since_last_batch: int = 0 + _num_log_records_since_last_persist: int = 0 + + def __init__(self, system: System, segment: Segment): + super().__init__(system, segment) + + self._db = system.instance(SqliteDB) + self._opentelemtry_client = system.require(OpenTelemetryClient) + + self._params = PersistentHnswParams(segment["metadata"] or {}) + self._batch_size = self._params.batch_size + self._sync_threshold = self._params.sync_threshold + self._allow_reset = system.settings.allow_reset + self._persist_directory = system.settings.require("persist_directory") + self._curr_batch = Batch() + self._brute_force_index = None + if not os.path.exists(self._get_storage_folder()): + os.makedirs(self._get_storage_folder(), exist_ok=True) + # Load persist data if it exists already, otherwise create it + if self._index_exists(): + self._persist_data = PersistentData.load_from_file( + self._get_metadata_file() + ) + self._dimensionality = self._persist_data.dimensionality + self._total_elements_added = self._persist_data.total_elements_added + self._id_to_label = self._persist_data.id_to_label + self._label_to_id = self._persist_data.label_to_id + self._id_to_seq_id = self._persist_data.id_to_seq_id + # If the index was written to, we need to re-initialize it + if len(self._id_to_label) > 0: + self._dimensionality = cast(int, self._dimensionality) + self._init_index(self._dimensionality) + else: + self._persist_data = PersistentData( + self._dimensionality, + self._total_elements_added, + self._id_to_label, + self._label_to_id, + self._id_to_seq_id, + ) + + # Hydrate the max_seq_id + with self._db.tx() as cur: + t = Table("max_seq_id") + q = ( + self._db.querybuilder() + .from_(t) + .select(t.seq_id) + .where(t.segment_id == ParameterValue(self._db.uuid_to_db(self._id))) + .limit(1) + ) + sql, params = get_sql(q) + cur.execute(sql, params) + result = cur.fetchone() + + if result: + self._max_seq_id = result[0] + elif self._index_exists(): + # Migrate the max_seq_id from the legacy field in the pickled file to the SQLite database + q = ( + self._db.querybuilder() + .into(Table("max_seq_id")) + .columns("segment_id", "seq_id") + .insert( + ParameterValue(self._db.uuid_to_db(self._id)), + ParameterValue(self._persist_data.max_seq_id), + ) + ) + sql, params = get_sql(q) + cur.execute(sql, params) + + self._max_seq_id = self._persist_data.max_seq_id + else: + self._max_seq_id = self._consumer.min_seqid() + + @staticmethod + @override + def propagate_collection_metadata(metadata: Metadata) -> Optional[Metadata]: + # Extract relevant metadata + segment_metadata = PersistentHnswParams.extract(metadata) + return segment_metadata + + def _index_exists(self) -> bool: + """Check if the index exists via the metadata file""" + return os.path.exists(self._get_metadata_file()) + + def _get_metadata_file(self) -> str: + """Get the metadata file path""" + return os.path.join(self._get_storage_folder(), self.METADATA_FILE) + + def _get_storage_folder(self) -> str: + """Get the storage folder path""" + folder = os.path.join(self._persist_directory, str(self._id)) + return folder + + @trace_method( + "PersistentLocalHnswSegment._init_index", OpenTelemetryGranularity.ALL + ) + @override + def _init_index(self, dimensionality: int) -> None: + index = hnswlib.Index(space=self._params.space, dim=dimensionality) + self._brute_force_index = BruteForceIndex( + size=self._batch_size, + dimensionality=dimensionality, + space=self._params.space, + ) + + # Check if index exists and load it if it does + if self._index_exists(): + index.load_index( + self._get_storage_folder(), + is_persistent_index=True, + max_elements=int( + max( + self.count( + request_version_context=RequestVersionContext( + collection_version=0, log_position=0 + ) + ) + * self._params.resize_factor, + DEFAULT_CAPACITY, + ) + ), + ) + else: + index.init_index( + max_elements=DEFAULT_CAPACITY, + ef_construction=self._params.construction_ef, + M=self._params.M, + is_persistent_index=True, + persistence_location=self._get_storage_folder(), + ) + + index.set_ef(self._params.search_ef) + index.set_num_threads(self._params.num_threads) + + self._index = index + self._dimensionality = dimensionality + self._index_initialized = True + + @trace_method("PersistentLocalHnswSegment._persist", OpenTelemetryGranularity.ALL) + def _persist(self) -> None: + """Persist the index and data to disk""" + index = cast(hnswlib.Index, self._index) + + # Persist the index + index.persist_dirty() + + # Persist the metadata + self._persist_data.dimensionality = self._dimensionality + self._persist_data.total_elements_added = self._total_elements_added + + # TODO: This should really be stored in sqlite, the index itself, or a better + # storage format + self._persist_data.id_to_label = self._id_to_label + self._persist_data.label_to_id = self._label_to_id + self._persist_data.id_to_seq_id = self._id_to_seq_id + + with open(self._get_metadata_file(), "wb") as metadata_file: + pickle.dump(self._persist_data, metadata_file, pickle.HIGHEST_PROTOCOL) + + with self._db.tx() as cur: + q = ( + self._db.querybuilder() + .into(Table("max_seq_id")) + .columns("segment_id", "seq_id") + .insert( + ParameterValue(self._db.uuid_to_db(self._id)), + ParameterValue(self._max_seq_id), + ) + ) + sql, params = get_sql(q) + sql = sql.replace("INSERT", "INSERT OR REPLACE") + cur.execute(sql, params) + + self._num_log_records_since_last_persist = 0 + + @trace_method( + "PersistentLocalHnswSegment._apply_batch", OpenTelemetryGranularity.ALL + ) + @override + def _apply_batch(self, batch: Batch) -> None: + super()._apply_batch(batch) + if self._num_log_records_since_last_persist >= self._sync_threshold: + self._persist() + + self._num_log_records_since_last_batch = 0 + + @trace_method( + "PersistentLocalHnswSegment._write_records", OpenTelemetryGranularity.ALL + ) + @override + def _write_records(self, records: Sequence[LogRecord]) -> None: + """Add a batch of embeddings to the index""" + if not self._running: + raise RuntimeError("Cannot add embeddings to stopped component") + with WriteRWLock(self._lock): + for record in records: + self._num_log_records_since_last_batch += 1 + self._num_log_records_since_last_persist += 1 + + if record["record"]["embedding"] is not None: + self._ensure_index(len(records), len(record["record"]["embedding"])) + if not self._index_initialized: + # If the index is not initialized here, it means that we have + # not yet added any records to the index. So we can just + # ignore the record since it was a delete. + continue + self._brute_force_index = cast(BruteForceIndex, self._brute_force_index) + + self._max_seq_id = max(self._max_seq_id, record["log_offset"]) + id = record["record"]["id"] + op = record["record"]["operation"] + + exists_in_bf_index = self._brute_force_index.has_id(id) + exists_in_persisted_index = self._id_to_label.get(id, None) is not None + exists_in_index = exists_in_bf_index or exists_in_persisted_index + + id_is_pending_delete = self._curr_batch.is_deleted(id) + + if op == Operation.DELETE: + if exists_in_index: + self._curr_batch.apply(record) + if exists_in_bf_index: + self._brute_force_index.delete([record]) + else: + logger.warning(f"Delete of nonexisting embedding ID: {id}") + + elif op == Operation.UPDATE: + if record["record"]["embedding"] is not None: + if exists_in_index: + self._curr_batch.apply(record) + self._brute_force_index.upsert([record]) + else: + logger.warning( + f"Update of nonexisting embedding ID: {record['record']['id']}" + ) + elif op == Operation.ADD: + if record["record"]["embedding"] is not None: + if exists_in_index and not id_is_pending_delete: + logger.warning(f"Add of existing embedding ID: {id}") + else: + self._curr_batch.apply(record, not exists_in_index) + self._brute_force_index.upsert([record]) + elif op == Operation.UPSERT: + if record["record"]["embedding"] is not None: + self._curr_batch.apply(record, exists_in_index) + self._brute_force_index.upsert([record]) + + if self._num_log_records_since_last_batch >= self._batch_size: + self._apply_batch(self._curr_batch) + self._curr_batch = Batch() + self._brute_force_index.clear() + + @override + def count(self, request_version_context: RequestVersionContext) -> int: + return ( + len(self._id_to_label) + + self._curr_batch.add_count + - self._curr_batch.delete_count + ) + + @trace_method( + "PersistentLocalHnswSegment.get_vectors", OpenTelemetryGranularity.ALL + ) + @override + def get_vectors( + self, + request_version_context: RequestVersionContext, + ids: Optional[Sequence[str]] = None, + ) -> Sequence[VectorEmbeddingRecord]: + """Get the embeddings from the HNSW index and layered brute force + batch index.""" + + ids_hnsw: Set[str] = set() + ids_bf: Set[str] = set() + + if self._index is not None: + ids_hnsw = set(self._id_to_label.keys()) + if self._brute_force_index is not None: + ids_bf = set(self._curr_batch.get_written_ids()) + + target_ids = ids or list(ids_hnsw.union(ids_bf)) + self._brute_force_index = cast(BruteForceIndex, self._brute_force_index) + hnsw_labels = [] + + results: List[Optional[VectorEmbeddingRecord]] = [] + id_to_index: Dict[str, int] = {} + for i, id in enumerate(target_ids): + if id in ids_bf: + results.append(self._brute_force_index.get_vectors([id])[0]) + elif id in ids_hnsw and id not in self._curr_batch._deleted_ids: + hnsw_labels.append(self._id_to_label[id]) + # Placeholder for hnsw results to be filled in down below so we + # can batch the hnsw get() call + results.append(None) + id_to_index[id] = i + + if len(hnsw_labels) > 0 and self._index is not None: + vectors = cast( + Sequence[Vector], np.array(self._index.get_items(hnsw_labels)) + ) # version 0.8 of hnswlib allows return_type="numpy" + + for label, vector in zip(hnsw_labels, vectors): + id = self._label_to_id[label] + results[id_to_index[id]] = VectorEmbeddingRecord( + id=id, embedding=vector + ) + + return results # type: ignore ## Python can't cast List with Optional to List with VectorEmbeddingRecord + + @trace_method( + "PersistentLocalHnswSegment.query_vectors", OpenTelemetryGranularity.ALL + ) + @override + def query_vectors( + self, query: VectorQuery + ) -> Sequence[Sequence[VectorQueryResult]]: + if self._index is None and self._brute_force_index is None: + return [[] for _ in range(len(query["vectors"]))] + + k = query["k"] + if k > self.count(query["request_version_context"]): + count = self.count(query["request_version_context"]) + logger.warning( + f"Number of requested results {k} is greater than number of elements in index {count}, updating n_results = {count}" + ) + k = count + + # Overquery by updated and deleted elements layered on the index because they may + # hide the real nearest neighbors in the hnsw index + hnsw_k = k + self._curr_batch.update_count + self._curr_batch.delete_count + # self._id_to_label contains the ids of the elements in the hnsw index + # so its length is the number of elements in the hnsw index + if hnsw_k > len(self._id_to_label): + hnsw_k = len(self._id_to_label) + hnsw_query = VectorQuery( + vectors=query["vectors"], + k=hnsw_k, + allowed_ids=query["allowed_ids"], + include_embeddings=query["include_embeddings"], + options=query["options"], + request_version_context=query["request_version_context"], + ) + + # For each query vector, we want to take the top k results from the + # combined results of the brute force and hnsw index + results: List[List[VectorQueryResult]] = [] + self._brute_force_index = cast(BruteForceIndex, self._brute_force_index) + with ReadRWLock(self._lock): + bf_results = self._brute_force_index.query(query) + hnsw_results = super().query_vectors(hnsw_query) + for i in range(len(query["vectors"])): + # Merge results into a single list of size k + bf_pointer: int = 0 + hnsw_pointer: int = 0 + curr_bf_result: Sequence[VectorQueryResult] = bf_results[i] + curr_hnsw_result: Sequence[VectorQueryResult] = hnsw_results[i] + + # Filter deleted results that haven't yet been removed from the persisted index + curr_hnsw_result = [ + x + for x in curr_hnsw_result + if not self._curr_batch.is_deleted(x["id"]) + ] + + curr_results: List[VectorQueryResult] = [] + # In the case where filters cause the number of results to be less than k, + # we set k to be the number of results + total_results = len(curr_bf_result) + len(curr_hnsw_result) + if total_results == 0: + results.append([]) + else: + while len(curr_results) < min(k, total_results): + if bf_pointer < len(curr_bf_result) and hnsw_pointer < len( + curr_hnsw_result + ): + bf_dist = curr_bf_result[bf_pointer]["distance"] + hnsw_dist = curr_hnsw_result[hnsw_pointer]["distance"] + if bf_dist <= hnsw_dist: + curr_results.append(curr_bf_result[bf_pointer]) + bf_pointer += 1 + else: + id = curr_hnsw_result[hnsw_pointer]["id"] + # Only add the hnsw result if it is not in the brute force index + if not self._brute_force_index.has_id(id): + curr_results.append(curr_hnsw_result[hnsw_pointer]) + hnsw_pointer += 1 + else: + break + remaining = min(k, total_results) - len(curr_results) + if remaining > 0 and hnsw_pointer < len(curr_hnsw_result): + for i in range( + hnsw_pointer, + min(len(curr_hnsw_result), hnsw_pointer + remaining), + ): + id = curr_hnsw_result[i]["id"] + if not self._brute_force_index.has_id(id): + curr_results.append(curr_hnsw_result[i]) + elif remaining > 0 and bf_pointer < len(curr_bf_result): + curr_results.extend( + curr_bf_result[bf_pointer : bf_pointer + remaining] + ) + results.append(curr_results) + return results + + @trace_method( + "PersistentLocalHnswSegment.reset_state", OpenTelemetryGranularity.ALL + ) + @override + def reset_state(self) -> None: + if self._allow_reset: + data_path = self._get_storage_folder() + if os.path.exists(data_path): + self.close_persistent_index() + shutil.rmtree(data_path, ignore_errors=True) + + @trace_method("PersistentLocalHnswSegment.delete", OpenTelemetryGranularity.ALL) + @override + def delete(self) -> None: + data_path = self._get_storage_folder() + if os.path.exists(data_path): + self.close_persistent_index() + shutil.rmtree(data_path, ignore_errors=False) + + @staticmethod + def get_file_handle_count() -> int: + """Return how many file handles are used by the index""" + hnswlib_count = hnswlib.Index.file_handle_count + hnswlib_count = cast(int, hnswlib_count) + # One extra for the metadata file + return hnswlib_count + 1 # type: ignore + + def open_persistent_index(self) -> None: + """Open the persistent index""" + if self._index is not None: + self._index.open_file_handles() + + @override + def stop(self) -> None: + super().stop() + self.close_persistent_index() + + def close_persistent_index(self) -> None: + """Close the persistent index""" + if self._index is not None: + self._index.close_file_handles() diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/server/__init__.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/server/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..52b1cf16e3b1d13a88198161676a5b4632b06235 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/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/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/server/__pycache__/__init__.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/server/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..75db98dd5be315f80deff8b12166150d863383ea Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/server/__pycache__/__init__.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/server/fastapi/__init__.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/server/fastapi/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..a8cdc971289173ae77815ab9da4b3cf1278f483c --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/server/fastapi/__init__.py @@ -0,0 +1,2334 @@ +from typing import ( + Any, + Callable, + cast, + Dict, + Sequence, + Optional, + Type, + TypeVar, + Tuple, +) +import fastapi +import orjson +from anyio import ( + to_thread, + CapacityLimiter, +) +from fastapi import FastAPI as _FastAPI, Response, Request +from fastapi.openapi.utils import get_openapi +from fastapi.middleware.cors import CORSMiddleware +from fastapi.responses import ORJSONResponse +from fastapi.routing import APIRoute +from fastapi import HTTPException, status +from functools import wraps + +from chromadb.api.collection_configuration import ( + load_update_collection_configuration_from_json, + load_create_collection_configuration_from_json, + create_collection_configuration_from_legacy_collection_metadata, + CreateCollectionConfiguration, +) +from pydantic import BaseModel +from chromadb import __version__ as chromadb_version +from chromadb.api.types import ( + DeleteResult, + Embedding, + GetResult, + QueryResult, + Embeddings, + convert_list_embeddings_to_np, +) +from chromadb.auth import UserIdentity +from chromadb.auth import ( + AuthzAction, + AuthzResource, + ServerAuthenticationProvider, + ServerAuthorizationProvider, +) +from chromadb.config import DEFAULT_DATABASE, DEFAULT_TENANT, Settings, System +from chromadb.api import ServerAPI +from chromadb.errors import ( + ChromaError, + InvalidDimensionException, + InvalidHTTPVersion, + RateLimitError, + QuotaError, +) +from chromadb.quota import QuotaEnforcer +from chromadb.rate_limit import AsyncRateLimitEnforcer +from chromadb.server import Server +from chromadb.server.fastapi.types import ( + AddEmbedding, + CreateDatabase, + CreateTenant, + DeleteEmbedding, + GetEmbedding, + QueryEmbedding, + CreateCollection, + UpdateCollection, + UpdateEmbedding, +) +from starlette.datastructures import Headers +import logging + +from chromadb.telemetry.product.events import ServerStartEvent +from chromadb.utils.fastapi import fastapi_json_response, string_to_uuid as _uuid +from opentelemetry import trace + +from chromadb.telemetry.opentelemetry.fastapi import instrument_fastapi +from chromadb.types import Database, Tenant +from chromadb.telemetry.product import ServerContext, ProductTelemetryClient +from chromadb.telemetry.opentelemetry import ( + OpenTelemetryClient, + OpenTelemetryGranularity, + add_attributes_to_current_span, + trace_method, +) +from chromadb.types import Collection as CollectionModel + +logger = logging.getLogger(__name__) + + +def rate_limit(func): + @wraps(func) + async def wrapper(*args: Any, **kwargs: Any) -> Any: + self = args[0] + return await self._async_rate_limit_enforcer.rate_limit(func)(*args, **kwargs) + + return wrapper + + +def use_route_names_as_operation_ids(app: _FastAPI) -> None: + """ + Simplify operation IDs so that generated API clients have simpler function + names. + Should be called only after all routes have been added. + """ + for route in app.routes: + if isinstance(route, APIRoute): + route.operation_id = route.name + ("-v2" if "v2" in route.path else "-v1") + + +async def add_trace_id_to_response_middleware( + request: Request, call_next: Callable[[Request], Any] +) -> Response: + trace_id = trace.get_current_span().get_span_context().trace_id + response = await call_next(request) + response.headers["Chroma-Trace-Id"] = format(trace_id, "x") + return response + + +async def catch_exceptions_middleware( + request: Request, call_next: Callable[[Request], Any] +) -> Response: + try: + return await call_next(request) + except ChromaError as e: + return fastapi_json_response(e) + except ValueError as e: + return ORJSONResponse( + content={"error": "InvalidArgumentError", "message": str(e)}, + status_code=400, + ) + except TypeError as e: + return ORJSONResponse( + content={"error": "InvalidArgumentError", "message": str(e)}, + status_code=400, + ) + except Exception as e: + logger.exception(e) + return ORJSONResponse(content={"error": repr(e)}, status_code=500) + + +async def check_http_version_middleware( + request: Request, call_next: Callable[[Request], Any] +) -> Response: + http_version = request.scope.get("http_version") + if http_version not in ["1.1", "2"]: + raise InvalidHTTPVersion(f"HTTP version {http_version} is not supported") + return await call_next(request) + + +D = TypeVar("D", bound=BaseModel, contravariant=True) + + +def validate_model(model: Type[D], data: Any) -> D: # type: ignore + """Used for backward compatibility with Pydantic 1.x""" + try: + return model.model_validate(data) # pydantic 2.x + except AttributeError: + return model.parse_obj(data) # pydantic 1.x + + +class ChromaAPIRouter(fastapi.APIRouter): # type: ignore + # A simple subclass of fastapi's APIRouter which treats URLs with a + # trailing "/" the same as URLs without. Docs will only contain URLs + # without trailing "/"s. + def add_api_route(self, path: str, *args: Any, **kwargs: Any) -> None: + # If kwargs["include_in_schema"] isn't passed OR is True, we should + # only include the non-"/" path. If kwargs["include_in_schema"] is + # False, include neither. + exclude_from_schema = ( + "include_in_schema" in kwargs and not kwargs["include_in_schema"] + ) + + def include_in_schema(path: str) -> bool: + nonlocal exclude_from_schema + return not exclude_from_schema and not path.endswith("/") + + kwargs["include_in_schema"] = include_in_schema(path) + super().add_api_route(path, *args, **kwargs) + + if path.endswith("/"): + path = path[:-1] + else: + path = path + "/" + + kwargs["include_in_schema"] = include_in_schema(path) + super().add_api_route(path, *args, **kwargs) + + +class FastAPI(Server): + def __init__(self, settings: Settings): + ProductTelemetryClient.SERVER_CONTEXT = ServerContext.FASTAPI + # https://fastapi.tiangolo.com/advanced/custom-response/#use-orjsonresponse + self._app = fastapi.FastAPI(debug=True, default_response_class=ORJSONResponse) + self._system = System(settings) + self._api: ServerAPI = self._system.instance(ServerAPI) + + self._extra_openapi_schemas: Dict[str, Any] = {} + self._app.openapi = self.generate_openapi + + self._opentelemetry_client = self._api.require(OpenTelemetryClient) + self._capacity_limiter = CapacityLimiter( + settings.chroma_server_thread_pool_size + ) + self._quota_enforcer = self._system.require(QuotaEnforcer) + self._system.start() + + self._app.middleware("http")(check_http_version_middleware) + self._app.middleware("http")(catch_exceptions_middleware) + self._app.middleware("http")(add_trace_id_to_response_middleware) + self._app.add_middleware( + CORSMiddleware, + allow_headers=["*"], + allow_origins=settings.chroma_server_cors_allow_origins, + allow_methods=["*"], + ) + self._app.add_exception_handler(QuotaError, self.quota_exception_handler) + self._app.add_exception_handler( + RateLimitError, self.rate_limit_exception_handler + ) + self._async_rate_limit_enforcer = self._system.require(AsyncRateLimitEnforcer) + + self._app.on_event("shutdown")(self.shutdown) + + self.authn_provider = None + if settings.chroma_server_authn_provider: + self.authn_provider = self._system.require(ServerAuthenticationProvider) + + self.authz_provider = None + if settings.chroma_server_authz_provider: + self.authz_provider = self._system.require(ServerAuthorizationProvider) + + self.router = ChromaAPIRouter() + + self.setup_v1_routes() + self.setup_v2_routes() + + self._app.include_router(self.router) + + use_route_names_as_operation_ids(self._app) + instrument_fastapi(self._app) + telemetry_client = self._system.instance(ProductTelemetryClient) + telemetry_client.capture(ServerStartEvent()) + + def generate_openapi(self) -> Dict[str, Any]: + """Used instead of the default openapi() generation handler to include manually-populated schemas.""" + schema: Dict[str, Any] = get_openapi( + title="Chroma", + routes=self._app.routes, + version=chromadb_version, + ) + + for key, value in self._extra_openapi_schemas.items(): + schema["components"]["schemas"][key] = value + + return schema + + def get_openapi_extras_for_body_model( + self, request_model: Type[D] + ) -> Dict[str, Any]: + schema = request_model.model_json_schema( + ref_template="#/components/schemas/{model}" + ) + if "$defs" in schema: + for key, value in schema["$defs"].items(): + self._extra_openapi_schemas[key] = value + + openapi_extra = { + "requestBody": { + "content": {"application/json": {"schema": schema}}, + "required": True, + } + } + return openapi_extra + + def setup_v2_routes(self) -> None: + self.router.add_api_route("/api/v2", self.root, methods=["GET"]) + self.router.add_api_route("/api/v2/reset", self.reset, methods=["POST"]) + self.router.add_api_route("/api/v2/version", self.version, methods=["GET"]) + self.router.add_api_route("/api/v2/heartbeat", self.heartbeat, methods=["GET"]) + self.router.add_api_route( + "/api/v2/pre-flight-checks", self.pre_flight_checks, methods=["GET"] + ) + + self.router.add_api_route( + "/api/v2/auth/identity", + self.get_user_identity, + methods=["GET"], + response_model=None, + ) + + self.router.add_api_route( + "/api/v2/tenants/{tenant}/databases", + self.create_database, + methods=["POST"], + response_model=None, + openapi_extra=self.get_openapi_extras_for_body_model(CreateDatabase), + ) + + self.router.add_api_route( + "/api/v2/tenants/{tenant}/databases/{database_name}", + self.get_database, + methods=["GET"], + response_model=None, + ) + + self.router.add_api_route( + "/api/v2/tenants/{tenant}/databases/{database_name}", + self.delete_database, + methods=["DELETE"], + response_model=None, + ) + + self.router.add_api_route( + "/api/v2/tenants", + self.create_tenant, + methods=["POST"], + response_model=None, + openapi_extra=self.get_openapi_extras_for_body_model(CreateTenant), + ) + + self.router.add_api_route( + "/api/v2/tenants/{tenant}", + self.get_tenant, + methods=["GET"], + response_model=None, + ) + + self.router.add_api_route( + "/api/v2/tenants/{tenant}/databases", + self.list_databases, + methods=["GET"], + response_model=None, + ) + + self.router.add_api_route( + "/api/v2/tenants/{tenant}/databases/{database_name}/collections", + self.list_collections, + methods=["GET"], + response_model=None, + ) + self.router.add_api_route( + "/api/v2/tenants/{tenant}/databases/{database_name}/collections_count", + self.count_collections, + methods=["GET"], + response_model=None, + ) + self.router.add_api_route( + "/api/v2/tenants/{tenant}/databases/{database_name}/collections", + self.create_collection, + methods=["POST"], + response_model=None, + openapi_extra=self.get_openapi_extras_for_body_model(CreateCollection), + ) + + self.router.add_api_route( + "/api/v2/tenants/{tenant}/databases/{database_name}/collections/{collection_id}/add", + self.add, + methods=["POST"], + status_code=status.HTTP_201_CREATED, + response_model=None, + openapi_extra=self.get_openapi_extras_for_body_model(AddEmbedding), + ) + self.router.add_api_route( + "/api/v2/tenants/{tenant}/databases/{database_name}/collections/{collection_id}/update", + self.update, + methods=["POST"], + response_model=None, + openapi_extra=self.get_openapi_extras_for_body_model(UpdateEmbedding), + ) + self.router.add_api_route( + "/api/v2/tenants/{tenant}/databases/{database_name}/collections/{collection_id}/upsert", + self.upsert, + methods=["POST"], + response_model=None, + openapi_extra=self.get_openapi_extras_for_body_model(AddEmbedding), + ) + self.router.add_api_route( + "/api/v2/tenants/{tenant}/databases/{database_name}/collections/{collection_id}/get", + self.get, + methods=["POST"], + response_model=None, + openapi_extra=self.get_openapi_extras_for_body_model(GetEmbedding), + ) + self.router.add_api_route( + "/api/v2/tenants/{tenant}/databases/{database_name}/collections/{collection_id}/delete", + self.delete, + methods=["POST"], + response_model=DeleteResult, + openapi_extra=self.get_openapi_extras_for_body_model(DeleteEmbedding), + ) + self.router.add_api_route( + "/api/v2/tenants/{tenant}/databases/{database_name}/collections/{collection_id}/count", + self.count, + methods=["GET"], + response_model=None, + ) + self.router.add_api_route( + "/api/v2/tenants/{tenant}/databases/{database_name}/collections/{collection_id}/query", + self.get_nearest_neighbors, + methods=["POST"], + response_model=None, + openapi_extra=self.get_openapi_extras_for_body_model( + request_model=QueryEmbedding + ), + ) + self.router.add_api_route( + "/api/v2/tenants/{tenant}/databases/{database_name}/collections/{collection_name}", + self.get_collection, + methods=["GET"], + response_model=None, + ) + self.router.add_api_route( + "/api/v2/tenants/{tenant}/databases/{database_name}/collections/{collection_id}", + self.update_collection, + methods=["PUT"], + response_model=None, + openapi_extra=self.get_openapi_extras_for_body_model(UpdateCollection), + ) + self.router.add_api_route( + "/api/v2/tenants/{tenant}/databases/{database_name}/collections/{collection_name}", + self.delete_collection, + methods=["DELETE"], + response_model=None, + ) + + self.router.add_api_route( + "/api/v2/tenants/{tenant}/databases/{database_name}/collections/{collection_id}/functions/attach", + self.attach_function, + methods=["POST"], + response_model=None, + ) + + self.router.add_api_route( + "/api/v2/tenants/{tenant}/databases/{database_name}/collections/{collection_id}/functions/{function_name}", + self.get_attached_function, + methods=["GET"], + response_model=None, + ) + + self.router.add_api_route( + "/api/v2/tenants/{tenant}/databases/{database_name}/collections/by-id/{collection_id}", + self.get_collection_by_id, + methods=["GET"], + response_model=None, + ) + + def shutdown(self) -> None: + self._system.stop() + + def app(self) -> fastapi.FastAPI: + return self._app + + async def rate_limit_exception_handler( + self, request: Request, exc: RateLimitError + ) -> ORJSONResponse: + return ORJSONResponse( + status_code=429, + content={"message": "Rate limit exceeded."}, + ) + + def root(self) -> Dict[str, int]: + return {"nanosecond heartbeat": self._api.heartbeat()} + + async def quota_exception_handler( + self, request: Request, exc: QuotaError + ) -> ORJSONResponse: + return ORJSONResponse( + status_code=400, + content={"message": exc.message()}, + ) + + async def heartbeat(self) -> Dict[str, int]: + return self.root() + + async def version(self) -> str: + return self._api.get_version() + + def _set_request_context(self, request: Request) -> None: + """ + Set context about the request on any components that might need it. + """ + self._quota_enforcer.set_context(context={"request": request}) + + @trace_method( + "auth_request", + OpenTelemetryGranularity.OPERATION, + ) + @rate_limit + async def auth_request( + self, + headers: Headers, + action: AuthzAction, + tenant: Optional[str], + database: Optional[str], + collection: Optional[str], + ) -> None: + return await to_thread.run_sync( + # NOTE(rescrv, iron will auth): No need to migrate because this is the utility call. + self.sync_auth_request, + *(headers, action, tenant, database, collection), + ) + + @trace_method( + "FastAPI.sync_auth_request", + OpenTelemetryGranularity.OPERATION, + ) + def sync_auth_request( + self, + headers: Headers, + action: AuthzAction, + tenant: Optional[str], + database: Optional[str], + collection: Optional[str], + ) -> None: + """ + Authenticates and authorizes the request based on the given headers + and other parameters. If the request cannot be authenticated or cannot + be authorized (with the configured providers), raises an HTTP 401. + """ + if not self.authn_provider: + add_attributes_to_current_span( + { + "tenant": tenant, + "database": database, + "collection": collection, + } + ) + return + + user_identity = self.authn_provider.authenticate_or_raise(dict(headers)) + + if not self.authz_provider: + return + + authz_resource = AuthzResource( + tenant=tenant, + database=database, + collection=collection, + ) + + self.authz_provider.authorize_or_raise(user_identity, action, authz_resource) + add_attributes_to_current_span( + { + "tenant": tenant, + "database": database, + "collection": collection, + } + ) + return + + @trace_method("FastAPI.get_user_identity", OpenTelemetryGranularity.OPERATION) + async def get_user_identity( + self, + request: Request, + ) -> UserIdentity: + if not self.authn_provider: + return UserIdentity( + user_id="", tenant=DEFAULT_TENANT, databases=[DEFAULT_DATABASE] + ) + + return cast( + UserIdentity, + await to_thread.run_sync( + lambda: cast( + ServerAuthenticationProvider, self.authn_provider + ).authenticate_or_raise(dict(request.headers)) # type: ignore + ), + ) + + @trace_method("FastAPI.create_database", OpenTelemetryGranularity.OPERATION) + async def create_database( + self, + request: Request, + tenant: str, + ) -> None: + def process_create_database( + tenant: str, headers: Headers, raw_body: bytes + ) -> None: + db = validate_model(CreateDatabase, orjson.loads(raw_body)) + + # NOTE(rescrv, iron will auth): Implemented. + self.sync_auth_request( + headers, + AuthzAction.CREATE_DATABASE, + tenant, + db.name, + None, + ) + + self._set_request_context(request=request) + + return self._api.create_database(db.name, tenant) + + await to_thread.run_sync( + process_create_database, + tenant, + request.headers, + await request.body(), + limiter=self._capacity_limiter, + ) + + @trace_method("FastAPI.get_database", OpenTelemetryGranularity.OPERATION) + async def get_database( + self, + request: Request, + database_name: str, + tenant: str, + ) -> Database: + # NOTE(rescrv, iron will auth): Implemented. + await self.auth_request( + request.headers, + AuthzAction.GET_DATABASE, + tenant, + database_name, + None, + ) + + return cast( + Database, + await to_thread.run_sync( + self._api.get_database, + database_name, + tenant, + limiter=self._capacity_limiter, + ), + ) + + @trace_method("FastAPI.delete_database", OpenTelemetryGranularity.OPERATION) + async def delete_database( + self, + request: Request, + database_name: str, + tenant: str, + ) -> None: + # NOTE(rescrv, iron will auth): Implemented. + await self.auth_request( + request.headers, + AuthzAction.DELETE_DATABASE, + tenant, + database_name, + None, + ) + + await to_thread.run_sync( + self._api.delete_database, + database_name, + tenant, + limiter=self._capacity_limiter, + ) + + @trace_method("FastAPI.create_tenant", OpenTelemetryGranularity.OPERATION) + async def create_tenant( + self, + request: Request, + ) -> None: + def process_create_tenant(request: Request, raw_body: bytes) -> None: + tenant = validate_model(CreateTenant, orjson.loads(raw_body)) + + # NOTE(rescrv, iron will auth): Implemented. + self.sync_auth_request( + request.headers, + AuthzAction.CREATE_TENANT, + tenant.name, + None, + None, + ) + + return self._api.create_tenant(tenant.name) + + await to_thread.run_sync( + process_create_tenant, + request, + await request.body(), + limiter=self._capacity_limiter, + ) + + @trace_method("FastAPI.get_tenant", OpenTelemetryGranularity.OPERATION) + async def get_tenant( + self, + request: Request, + tenant: str, + ) -> Tenant: + # NOTE(rescrv, iron will auth): Implemented. + await self.auth_request( + request.headers, + AuthzAction.GET_TENANT, + tenant, + None, + None, + ) + + return cast( + Tenant, + await to_thread.run_sync( + self._api.get_tenant, + tenant, + limiter=self._capacity_limiter, + ), + ) + + @trace_method("FastAPI.list_databases", OpenTelemetryGranularity.OPERATION) + async def list_databases( + self, + request: Request, + tenant: str, + limit: Optional[int] = None, + offset: Optional[int] = None, + ) -> Sequence[Database]: + # NOTE(rescrv, iron will auth): Implemented. + await self.auth_request( + request.headers, + AuthzAction.LIST_DATABASES, + tenant, + None, + None, + ) + + return cast( + Sequence[Database], + await to_thread.run_sync( + self._api.list_databases, + limit, + offset, + tenant, + limiter=self._capacity_limiter, + ), + ) + + @trace_method("FastAPI.list_collections", OpenTelemetryGranularity.OPERATION) + async def list_collections( + self, + request: Request, + tenant: str, + database_name: str, + limit: Optional[int] = None, + offset: Optional[int] = None, + ) -> Sequence[CollectionModel]: + def process_list_collections( + limit: Optional[int], offset: Optional[int], tenant: str, database_name: str + ) -> Sequence[CollectionModel]: + # NOTE(rescrv, iron will auth): Implemented. + self.sync_auth_request( + request.headers, + AuthzAction.LIST_COLLECTIONS, + tenant, + database_name, + None, + ) + + self._set_request_context(request=request) + + add_attributes_to_current_span({"tenant": tenant}) + return self._api.list_collections( + tenant=tenant, database=database_name, limit=limit, offset=offset + ) + + api_collection_models = cast( + Sequence[CollectionModel], + await to_thread.run_sync( + process_list_collections, + limit, + offset, + tenant, + database_name, + limiter=self._capacity_limiter, + ), + ) + + return api_collection_models + + @trace_method("FastAPI.count_collections", OpenTelemetryGranularity.OPERATION) + async def count_collections( + self, + request: Request, + tenant: str, + database_name: str, + ) -> int: + # NOTE(rescrv, iron will auth): Implemented. + await self.auth_request( + request.headers, + AuthzAction.COUNT_COLLECTIONS, + tenant, + database_name, + None, + ) + + add_attributes_to_current_span({"tenant": tenant}) + + return cast( + int, + await to_thread.run_sync( + self._api.count_collections, + tenant, + database_name, + limiter=self._capacity_limiter, + ), + ) + + @trace_method("FastAPI.create_collection", OpenTelemetryGranularity.OPERATION) + async def create_collection( + self, + request: Request, + tenant: str, + database_name: str, + ) -> CollectionModel: + def process_create_collection( + request: Request, tenant: str, database: str, raw_body: bytes + ) -> CollectionModel: + create = validate_model(CreateCollection, orjson.loads(raw_body)) + if not create.configuration: + if create.metadata: + configuration = ( + create_collection_configuration_from_legacy_collection_metadata( + create.metadata + ) + ) + else: + configuration = None + else: + configuration = load_create_collection_configuration_from_json( + create.configuration + ) + + # NOTE(rescrv, iron will auth): Implemented. + self.sync_auth_request( + request.headers, + AuthzAction.CREATE_COLLECTION, + tenant, + database, + create.name, + ) + + self._set_request_context(request=request) + + add_attributes_to_current_span({"tenant": tenant}) + + return self._api.create_collection( + name=create.name, + configuration=configuration, + metadata=create.metadata, + get_or_create=create.get_or_create, + tenant=tenant, + database=database, + ) + + api_collection_model = cast( + CollectionModel, + await to_thread.run_sync( + process_create_collection, + request, + tenant, + database_name, + await request.body(), + limiter=self._capacity_limiter, + ), + ) + return api_collection_model + + @trace_method("FastAPI.get_collection", OpenTelemetryGranularity.OPERATION) + async def get_collection( + self, + request: Request, + tenant: str, + database_name: str, + collection_name: str, + ) -> CollectionModel: + # NOTE(rescrv, iron will auth): Implemented. + await self.auth_request( + request.headers, + AuthzAction.GET_COLLECTION, + tenant, + database_name, + collection_name, + ) + + add_attributes_to_current_span({"tenant": tenant}) + + api_collection_model = cast( + CollectionModel, + await to_thread.run_sync( + self._api.get_collection, + collection_name, + tenant, + database_name, + limiter=self._capacity_limiter, + ), + ) + return api_collection_model + + @trace_method("FastAPI.get_collection_by_id", OpenTelemetryGranularity.OPERATION) + async def get_collection_by_id( + self, + request: Request, + tenant: str, + database_name: str, + collection_id: str, + ) -> CollectionModel: + # NOTE(rescrv, iron will auth): Implemented. + await self.auth_request( + request.headers, + AuthzAction.GET_COLLECTION, + tenant, + database_name, + collection_id, + ) + + add_attributes_to_current_span({"tenant": tenant}) + + api_collection_model = cast( + CollectionModel, + await to_thread.run_sync( + self._api.get_collection_by_id, + _uuid(collection_id), + tenant, + database_name, + limiter=self._capacity_limiter, + ), + ) + return api_collection_model + + @trace_method("FastAPI.update_collection", OpenTelemetryGranularity.OPERATION) + async def update_collection( + self, + tenant: str, + database_name: str, + collection_id: str, + request: Request, + ) -> None: + def process_update_collection( + request: Request, collection_id: str, raw_body: bytes + ) -> None: + update = validate_model(UpdateCollection, orjson.loads(raw_body)) + # NOTE(rescrv, iron will auth): Implemented. + self.sync_auth_request( + request.headers, + AuthzAction.UPDATE_COLLECTION, + tenant, + database_name, + collection_id, + ) + configuration = ( + None + if not update.new_configuration + else load_update_collection_configuration_from_json( + update.new_configuration + ) + ) + self._set_request_context(request=request) + add_attributes_to_current_span({"tenant": tenant}) + return self._api._modify( + id=_uuid(collection_id), + new_name=update.new_name, + new_metadata=update.new_metadata, + new_configuration=configuration, + tenant=tenant, + database=database_name, + ) + + await to_thread.run_sync( + process_update_collection, + request, + collection_id, + await request.body(), + limiter=self._capacity_limiter, + ) + + @trace_method("FastAPI.delete_collection", OpenTelemetryGranularity.OPERATION) + async def delete_collection( + self, + request: Request, + collection_name: str, + tenant: str, + database_name: str, + ) -> None: + # NOTE(rescrv, iron will auth): Implemented. + await self.auth_request( + request.headers, + AuthzAction.DELETE_COLLECTION, + tenant, + database_name, + collection_name, + ) + add_attributes_to_current_span({"tenant": tenant}) + + await to_thread.run_sync( + self._api.delete_collection, + collection_name, + tenant, + database_name, + limiter=self._capacity_limiter, + ) + + @trace_method("FastAPI.attach_function", OpenTelemetryGranularity.OPERATION) + @rate_limit + async def attach_function( + self, + request: Request, + tenant: str, + database_name: str, + collection_id: str, + ) -> Dict[str, Any]: + try: + + def process_attach_function( + request: Request, raw_body: bytes + ) -> Dict[str, Any]: + body = orjson.loads(raw_body) + # NOTE: Auth check for attaching functions + self.sync_auth_request( + request.headers, + AuthzAction.UPDATE_COLLECTION, # Using UPDATE_COLLECTION as the auth action + tenant, + database_name, + collection_id, + ) + self._set_request_context(request=request) + + name = body.get("name") + function_id = body.get("function_id") + output_collection = body.get("output_collection") + params = body.get("params") + + attached_fn = self._api.attach_function( + function_id=function_id, + name=name, + input_collection_id=_uuid(collection_id), + output_collection=output_collection, + params=params, + tenant=tenant, + database=database_name, + ) + + return { + "attached_function": { + "id": str(attached_fn.id), + "name": attached_fn.name, + "function_name": attached_fn.function_name, + "output_collection": attached_fn.output_collection, + "params": attached_fn.params, + } + } + + raw_body = await request.body() + return await to_thread.run_sync( + process_attach_function, + request, + raw_body, + limiter=self._capacity_limiter, + ) + except Exception: + raise + + @trace_method("FastAPI.get_attached_function", OpenTelemetryGranularity.OPERATION) + @rate_limit + async def get_attached_function( + self, + request: Request, + tenant: str, + database_name: str, + collection_id: str, + function_name: str, + ) -> Dict[str, Any]: + # NOTE: Auth check for getting attached functions + await self.auth_request( + request.headers, + AuthzAction.GET_COLLECTION, # Using GET_COLLECTION as the auth action + tenant, + database_name, + collection_id, + ) + add_attributes_to_current_span({"tenant": tenant}) + + attached_fn = await to_thread.run_sync( + self._api.get_attached_function, + function_name, + _uuid(collection_id), + tenant, + database_name, + limiter=self._capacity_limiter, + ) + + return { + "attached_function": { + "id": str(attached_fn.id), + "name": attached_fn.name, + "function_name": attached_fn.function_name, + "output_collection": attached_fn.output_collection, + "params": attached_fn.params, + } + } + + @trace_method("FastAPI.add", OpenTelemetryGranularity.OPERATION) + @rate_limit + async def add( + self, + request: Request, + tenant: str, + database_name: str, + collection_id: str, + ) -> bool: + try: + + def process_add(request: Request, raw_body: bytes) -> bool: + add = validate_model(AddEmbedding, orjson.loads(raw_body)) + # NOTE(rescrv, iron will auth): Implemented. + self.sync_auth_request( + request.headers, + AuthzAction.ADD, + tenant, + database_name, + collection_id, + ) + self._set_request_context(request=request) + add_attributes_to_current_span({"tenant": tenant}) + return self._api._add( + collection_id=_uuid(collection_id), + ids=add.ids, + embeddings=cast( + Embeddings, + convert_list_embeddings_to_np(add.embeddings) + if add.embeddings + else None, + ), + metadatas=add.metadatas, # type: ignore + documents=add.documents, # type: ignore + uris=add.uris, # type: ignore + tenant=tenant, + database=database_name, + ) + + return cast( + bool, + await to_thread.run_sync( + process_add, + request, + await request.body(), + limiter=self._capacity_limiter, + ), + ) + except InvalidDimensionException as e: + raise HTTPException(status_code=500, detail=str(e)) + + @trace_method("FastAPI.update", OpenTelemetryGranularity.OPERATION) + @rate_limit + async def update( + self, + request: Request, + tenant: str, + database_name: str, + collection_id: str, + ) -> None: + def process_update(request: Request, raw_body: bytes) -> bool: + update = validate_model(UpdateEmbedding, orjson.loads(raw_body)) + + # NOTE(rescrv, iron will auth): Implemented. + self.sync_auth_request( + request.headers, + AuthzAction.UPDATE, + tenant, + database_name, + collection_id, + ) + self._set_request_context(request=request) + add_attributes_to_current_span({"tenant": tenant}) + + return self._api._update( + collection_id=_uuid(collection_id), + ids=update.ids, + embeddings=convert_list_embeddings_to_np(update.embeddings) + if update.embeddings + else None, + metadatas=update.metadatas, # type: ignore + documents=update.documents, # type: ignore + uris=update.uris, # type: ignore + tenant=tenant, + database=database_name, + ) + + await to_thread.run_sync( + process_update, + request, + await request.body(), + limiter=self._capacity_limiter, + ) + + @trace_method("FastAPI.upsert", OpenTelemetryGranularity.OPERATION) + @rate_limit + async def upsert( + self, + request: Request, + tenant: str, + database_name: str, + collection_id: str, + ) -> None: + def process_upsert(request: Request, raw_body: bytes) -> bool: + upsert = validate_model(AddEmbedding, orjson.loads(raw_body)) + + # NOTE(rescrv, iron will auth): Implemented. + self.sync_auth_request( + request.headers, + AuthzAction.UPSERT, + tenant, + database_name, + collection_id, + ) + self._set_request_context(request=request) + add_attributes_to_current_span({"tenant": tenant}) + + return self._api._upsert( + collection_id=_uuid(collection_id), + ids=upsert.ids, + embeddings=cast( + Embeddings, + convert_list_embeddings_to_np(upsert.embeddings) + if upsert.embeddings + else None, + ), + metadatas=upsert.metadatas, # type: ignore + documents=upsert.documents, # type: ignore + uris=upsert.uris, # type: ignore + tenant=tenant, + database=database_name, + ) + + await to_thread.run_sync( + process_upsert, + request, + await request.body(), + limiter=self._capacity_limiter, + ) + + @trace_method("FastAPI.get", OpenTelemetryGranularity.OPERATION) + @rate_limit + async def get( + self, + collection_id: str, + tenant: str, + database_name: str, + request: Request, + ) -> GetResult: + def process_get(request: Request, raw_body: bytes) -> GetResult: + get = validate_model(GetEmbedding, orjson.loads(raw_body)) + # NOTE(rescrv, iron will auth): Implemented. + self.sync_auth_request( + request.headers, + AuthzAction.GET, + tenant, + database_name, + collection_id, + ) + self._set_request_context(request=request) + add_attributes_to_current_span({"tenant": tenant}) + return self._api._get( + collection_id=_uuid(collection_id), + ids=get.ids, + where=get.where, + limit=get.limit, + offset=get.offset, + where_document=get.where_document, + include=get.include, + tenant=tenant, + database=database_name, + ) + + get_result = cast( + GetResult, + await to_thread.run_sync( + process_get, + request, + await request.body(), + limiter=self._capacity_limiter, + ), + ) + + if get_result["embeddings"] is not None: + get_result["embeddings"] = [ + cast(Embedding, embedding).tolist() + for embedding in get_result["embeddings"] + ] + + return get_result + + @trace_method("FastAPI.delete", OpenTelemetryGranularity.OPERATION) + @rate_limit + async def delete( + self, + collection_id: str, + tenant: str, + database_name: str, + request: Request, + ) -> DeleteResult: + def process_delete(request: Request, raw_body: bytes) -> DeleteResult: + delete = validate_model(DeleteEmbedding, orjson.loads(raw_body)) + # NOTE(rescrv, iron will auth): Implemented. + self.sync_auth_request( + request.headers, + AuthzAction.DELETE, + tenant, + database_name, + collection_id, + ) + self._set_request_context(request=request) + add_attributes_to_current_span({"tenant": tenant}) + return self._api._delete( + collection_id=_uuid(collection_id), + ids=delete.ids, + where=delete.where, + where_document=delete.where_document, + limit=delete.limit, + tenant=tenant, + database=database_name, + ) + + return await to_thread.run_sync( + process_delete, + request, + await request.body(), + limiter=self._capacity_limiter, + ) + + @trace_method("FastAPI.count", OpenTelemetryGranularity.OPERATION) + @rate_limit + async def count( + self, + request: Request, + tenant: str, + database_name: str, + collection_id: str, + ) -> int: + # NOTE(rescrv, iron will auth): Implemented. + await self.auth_request( + request.headers, + AuthzAction.COUNT, + tenant, + database_name, + collection_id, + ) + add_attributes_to_current_span({"tenant": tenant}) + + return cast( + int, + await to_thread.run_sync( + self._api._count, + _uuid(collection_id), + tenant, + database_name, + limiter=self._capacity_limiter, + ), + ) + + @trace_method("FastAPI.reset", OpenTelemetryGranularity.OPERATION) + @rate_limit + async def reset( + self, + request: Request, + ) -> bool: + # NOTE(rescrv, iron will auth): Implemented. + await self.auth_request( + request.headers, + AuthzAction.RESET, + None, + None, + None, + ) + + return cast( + bool, + await to_thread.run_sync( + self._api.reset, + limiter=self._capacity_limiter, + ), + ) + + @trace_method("FastAPI.get_nearest_neighbors", OpenTelemetryGranularity.OPERATION) + @rate_limit + async def get_nearest_neighbors( + self, + tenant: str, + database_name: str, + collection_id: str, + request: Request, + ) -> QueryResult: + @trace_method( + "internal.get_nearest_neighbors", OpenTelemetryGranularity.OPERATION + ) + def process_query(request: Request, raw_body: bytes) -> QueryResult: + query = validate_model(QueryEmbedding, orjson.loads(raw_body)) + + # NOTE(rescrv, iron will auth): Implemented. + self.sync_auth_request( + request.headers, + AuthzAction.QUERY, + tenant, + database_name, + collection_id, + ) + self._set_request_context(request=request) + add_attributes_to_current_span({"tenant": tenant}) + + return self._api._query( + collection_id=_uuid(collection_id), + query_embeddings=cast( + Embeddings, + convert_list_embeddings_to_np(query.query_embeddings) + if query.query_embeddings + else None, + ), + n_results=query.n_results, + where=query.where, + where_document=query.where_document, + include=query.include, + tenant=tenant, + database=database_name, + ) + + nnresult = cast( + QueryResult, + await to_thread.run_sync( + process_query, + request, + await request.body(), + limiter=self._capacity_limiter, + ), + ) + + if nnresult["embeddings"] is not None: + nnresult["embeddings"] = [ + [cast(Embedding, embedding).tolist() for embedding in result] + for result in nnresult["embeddings"] + ] + + return nnresult + + async def pre_flight_checks(self) -> Dict[str, Any]: + def process_pre_flight_checks() -> Dict[str, Any]: + return { + "max_batch_size": self._api.get_max_batch_size(), + } + + return cast( + Dict[str, Any], + await to_thread.run_sync( + process_pre_flight_checks, + limiter=self._capacity_limiter, + ), + ) + + # ========================================================================= + # OLD ROUTES FOR BACKWARDS COMPATIBILITY — WILL BE REMOVED + # ========================================================================= + def setup_v1_routes(self) -> None: + self.router.add_api_route("/api/v1", self.root, methods=["GET"]) + self.router.add_api_route("/api/v1/reset", self.reset, methods=["POST"]) + self.router.add_api_route("/api/v1/version", self.version, methods=["GET"]) + self.router.add_api_route("/api/v1/heartbeat", self.heartbeat, methods=["GET"]) + self.router.add_api_route( + "/api/v1/pre-flight-checks", self.pre_flight_checks, methods=["GET"] + ) + + self.router.add_api_route( + "/api/v1/databases", + self.create_database_v1, + methods=["POST"], + response_model=None, + openapi_extra=self.get_openapi_extras_for_body_model(CreateDatabase), + ) + + self.router.add_api_route( + "/api/v1/databases/{database}", + self.get_database_v1, + methods=["GET"], + response_model=None, + ) + + self.router.add_api_route( + "/api/v1/tenants", + self.create_tenant_v1, + methods=["POST"], + response_model=None, + openapi_extra=self.get_openapi_extras_for_body_model(CreateTenant), + ) + + self.router.add_api_route( + "/api/v1/tenants/{tenant}", + self.get_tenant_v1, + methods=["GET"], + response_model=None, + ) + + self.router.add_api_route( + "/api/v1/collections", + self.list_collections_v1, + methods=["GET"], + response_model=None, + ) + self.router.add_api_route( + "/api/v1/count_collections", + self.count_collections_v1, + methods=["GET"], + response_model=None, + ) + self.router.add_api_route( + "/api/v1/collections", + self.create_collection_v1, + methods=["POST"], + response_model=None, + openapi_extra=self.get_openapi_extras_for_body_model(CreateCollection), + ) + + self.router.add_api_route( + "/api/v1/collections/{collection_id}/add", + self.add_v1, + methods=["POST"], + status_code=status.HTTP_201_CREATED, + response_model=None, + openapi_extra=self.get_openapi_extras_for_body_model(AddEmbedding), + ) + self.router.add_api_route( + "/api/v1/collections/{collection_id}/update", + self.update_v1, + methods=["POST"], + response_model=None, + openapi_extra=self.get_openapi_extras_for_body_model(UpdateEmbedding), + ) + self.router.add_api_route( + "/api/v1/collections/{collection_id}/upsert", + self.upsert_v1, + methods=["POST"], + response_model=None, + openapi_extra=self.get_openapi_extras_for_body_model(AddEmbedding), + ) + self.router.add_api_route( + "/api/v1/collections/{collection_id}/get", + self.get_v1, + methods=["POST"], + response_model=None, + openapi_extra=self.get_openapi_extras_for_body_model(GetEmbedding), + ) + self.router.add_api_route( + "/api/v1/collections/{collection_id}/delete", + self.delete_v1, + methods=["POST"], + response_model=DeleteResult, + openapi_extra=self.get_openapi_extras_for_body_model(DeleteEmbedding), + ) + self.router.add_api_route( + "/api/v1/collections/{collection_id}/count", + self.count_v1, + methods=["GET"], + response_model=None, + ) + self.router.add_api_route( + "/api/v1/collections/{collection_id}/query", + self.get_nearest_neighbors_v1, + methods=["POST"], + response_model=None, + openapi_extra=self.get_openapi_extras_for_body_model(QueryEmbedding), + ) + self.router.add_api_route( + "/api/v1/collections/{collection_name}", + self.get_collection_v1, + methods=["GET"], + response_model=None, + ) + self.router.add_api_route( + "/api/v1/collections/{collection_id}", + self.update_collection_v1, + methods=["PUT"], + response_model=None, + openapi_extra=self.get_openapi_extras_for_body_model(UpdateCollection), + ) + self.router.add_api_route( + "/api/v1/collections/{collection_name}", + self.delete_collection_v1, + methods=["DELETE"], + response_model=None, + ) + + @trace_method( + "auth_and_get_tenant_and_database_for_request_v1", + OpenTelemetryGranularity.OPERATION, + ) + @rate_limit + async def auth_and_get_tenant_and_database_for_request( + self, + headers: Headers, + action: AuthzAction, + tenant: Optional[str], + database: Optional[str], + collection: Optional[str], + ) -> Tuple[Optional[str], Optional[str]]: + """ + Authenticates and authorizes the request based on the given headers + and other parameters. If the request cannot be authenticated or cannot + be authorized (with the configured providers), raises an HTTP 401. + + If the request is authenticated and authorized, returns the tenant and + database to be used for the request. These will differ from the passed + tenant and database if and only if: + - The request is authenticated + - chroma_overwrite_singleton_tenant_database_access_from_auth = True + - The passed tenant or database are None or default_{tenant, database} + (can be overwritten separately) + - The user has access to a single tenant and/or single database. + """ + return await to_thread.run_sync( + # NOTE(rescrv, iron will auth): v1 + self.sync_auth_and_get_tenant_and_database_for_request, + headers, + action, + tenant, + database, + collection, + ) + + # NOTE(rescrv, iron will auth): v1 + def sync_auth_and_get_tenant_and_database_for_request( + self, + headers: Headers, + action: AuthzAction, + tenant: Optional[str], + database: Optional[str], + collection: Optional[str], + ) -> Tuple[Optional[str], Optional[str]]: + if not self.authn_provider: + add_attributes_to_current_span( + { + "tenant": tenant, + "database": database, + "collection": collection, + } + ) + return (tenant, database) + + user_identity = self.authn_provider.authenticate_or_raise(dict(headers)) + + ( + new_tenant, + new_database, + ) = self.authn_provider.singleton_tenant_database_if_applicable(user_identity) + + if (not tenant or tenant == DEFAULT_TENANT) and new_tenant: + tenant = new_tenant + if (not database or database == DEFAULT_DATABASE) and new_database: + database = new_database + + if not self.authz_provider: + return (tenant, database) + + authz_resource = AuthzResource( + tenant=tenant, + database=database, + collection=collection, + ) + + self.authz_provider.authorize_or_raise(user_identity, action, authz_resource) + add_attributes_to_current_span( + { + "tenant": tenant, + "database": database, + "collection": collection, + } + ) + return (tenant, database) + + @trace_method("FastAPI.create_database_v1", OpenTelemetryGranularity.OPERATION) + @rate_limit + async def create_database_v1( + self, + request: Request, + tenant: str = DEFAULT_TENANT, + ) -> None: + def process_create_database( + tenant: str, headers: Headers, raw_body: bytes + ) -> None: + db = validate_model(CreateDatabase, orjson.loads(raw_body)) + + ( + maybe_tenant, + maybe_database, + # NOTE(rescrv, iron will auth): v1 + ) = self.sync_auth_and_get_tenant_and_database_for_request( + headers, + AuthzAction.CREATE_DATABASE, + tenant, + db.name, + None, + ) + if maybe_tenant: + tenant = maybe_tenant + if maybe_database: + db.name = maybe_database + + return self._api.create_database(db.name, tenant) + + await to_thread.run_sync( + process_create_database, + tenant, + request.headers, + await request.body(), + limiter=self._capacity_limiter, + ) + + @trace_method("FastAPI.get_database_v1", OpenTelemetryGranularity.OPERATION) + @rate_limit + async def get_database_v1( + self, + request: Request, + database: str, + tenant: str = DEFAULT_TENANT, + ) -> Database: + ( + maybe_tenant, + maybe_database, + ) = await self.auth_and_get_tenant_and_database_for_request( + request.headers, + AuthzAction.GET_DATABASE, + tenant, + database, + None, + ) + if maybe_tenant: + tenant = maybe_tenant + if maybe_database: + database = maybe_database + + return cast( + Database, + await to_thread.run_sync( + self._api.get_database, + database, + tenant, + limiter=self._capacity_limiter, + ), + ) + + @trace_method("FastAPI.create_tenant_v1", OpenTelemetryGranularity.OPERATION) + @rate_limit + async def create_tenant_v1( + self, + request: Request, + ) -> None: + def process_create_tenant(request: Request, raw_body: bytes) -> None: + tenant = validate_model(CreateTenant, orjson.loads(raw_body)) + + # NOTE(rescrv, iron will auth): v1 + maybe_tenant, _ = self.sync_auth_and_get_tenant_and_database_for_request( + request.headers, + AuthzAction.CREATE_TENANT, + tenant.name, + None, + None, + ) + if maybe_tenant: + tenant.name = maybe_tenant + + return self._api.create_tenant(tenant.name) + + await to_thread.run_sync( + process_create_tenant, + request, + await request.body(), + limiter=self._capacity_limiter, + ) + + @trace_method("FastAPI.get_tenant_v1", OpenTelemetryGranularity.OPERATION) + @rate_limit + async def get_tenant_v1( + self, + request: Request, + tenant: str, + ) -> Tenant: + maybe_tenant, _ = await self.auth_and_get_tenant_and_database_for_request( + request.headers, + AuthzAction.GET_TENANT, + tenant, + None, + None, + ) + if maybe_tenant: + tenant = maybe_tenant + + return cast( + Tenant, + await to_thread.run_sync( + self._api.get_tenant, + tenant, + limiter=self._capacity_limiter, + ), + ) + + @trace_method("FastAPI.list_collections_v1", OpenTelemetryGranularity.OPERATION) + @rate_limit + async def list_collections_v1( + self, + request: Request, + limit: Optional[int] = None, + offset: Optional[int] = None, + tenant: str = DEFAULT_TENANT, + database: str = DEFAULT_DATABASE, + ) -> Sequence[CollectionModel]: + ( + maybe_tenant, + maybe_database, + ) = await self.auth_and_get_tenant_and_database_for_request( + request.headers, + AuthzAction.LIST_COLLECTIONS, + tenant, + database, + None, + ) + if maybe_tenant: + tenant = maybe_tenant + if maybe_database: + database = maybe_database + + api_collection_models = cast( + Sequence[CollectionModel], + await to_thread.run_sync( + self._api.list_collections, + limit, + offset, + tenant, + database, + limiter=self._capacity_limiter, + ), + ) + + return api_collection_models + + @trace_method("FastAPI.count_collections_v1", OpenTelemetryGranularity.OPERATION) + @rate_limit + async def count_collections_v1( + self, + request: Request, + tenant: str = DEFAULT_TENANT, + database: str = DEFAULT_DATABASE, + ) -> int: + ( + maybe_tenant, + maybe_database, + ) = await self.auth_and_get_tenant_and_database_for_request( + request.headers, + AuthzAction.COUNT_COLLECTIONS, + tenant, + database, + None, + ) + if maybe_tenant: + tenant = maybe_tenant + if maybe_database: + database = maybe_database + + return cast( + int, + await to_thread.run_sync( + self._api.count_collections, + tenant, + database, + limiter=self._capacity_limiter, + ), + ) + + @trace_method("FastAPI.create_collection_v1", OpenTelemetryGranularity.OPERATION) + @rate_limit + async def create_collection_v1( + self, + request: Request, + tenant: str = DEFAULT_TENANT, + database: str = DEFAULT_DATABASE, + ) -> CollectionModel: + def process_create_collection( + request: Request, tenant: str, database: str, raw_body: bytes + ) -> CollectionModel: + create = validate_model(CreateCollection, orjson.loads(raw_body)) + configuration = ( + CreateCollectionConfiguration() + if not create.configuration + else load_create_collection_configuration_from_json( + create.configuration + ) + ) + + ( + maybe_tenant, + maybe_database, + # NOTE(rescrv, iron will auth): v1 + ) = self.sync_auth_and_get_tenant_and_database_for_request( + request.headers, + AuthzAction.CREATE_COLLECTION, + tenant, + database, + create.name, + ) + if maybe_tenant: + tenant = maybe_tenant + if maybe_database: + database = maybe_database + + return self._api.create_collection( + name=create.name, + configuration=configuration, + metadata=create.metadata, + get_or_create=create.get_or_create, + tenant=tenant, + database=database, + ) + + api_collection_model = cast( + CollectionModel, + await to_thread.run_sync( + process_create_collection, + request, + tenant, + database, + await request.body(), + limiter=self._capacity_limiter, + ), + ) + return api_collection_model + + @trace_method("FastAPI.get_collection_v1", OpenTelemetryGranularity.OPERATION) + @rate_limit + async def get_collection_v1( + self, + request: Request, + collection_name: str, + tenant: str = DEFAULT_TENANT, + database: str = DEFAULT_DATABASE, + ) -> CollectionModel: + ( + maybe_tenant, + maybe_database, + ) = await self.auth_and_get_tenant_and_database_for_request( + request.headers, + AuthzAction.GET_COLLECTION, + tenant, + database, + collection_name, + ) + if maybe_tenant: + tenant = maybe_tenant + if maybe_database: + database = maybe_database + + async def inner(): + api_collection_model = cast( + CollectionModel, + await to_thread.run_sync( + self._api.get_collection, + collection_name, + tenant, + database, + limiter=self._capacity_limiter, + ), + ) + return api_collection_model + + return await inner() + + @trace_method("FastAPI.update_collection_v1", OpenTelemetryGranularity.OPERATION) + @rate_limit + async def update_collection_v1( + self, + collection_id: str, + request: Request, + ) -> None: + def process_update_collection( + request: Request, collection_id: str, raw_body: bytes + ) -> None: + update = validate_model(UpdateCollection, orjson.loads(raw_body)) + # NOTE(rescrv, iron will auth): v1 + self.sync_auth_and_get_tenant_and_database_for_request( + request.headers, + AuthzAction.UPDATE_COLLECTION, + None, + None, + collection_id, + ) + configuration = ( + None + if not update.new_configuration + else load_update_collection_configuration_from_json( + update.new_configuration + ) + ) + return self._api._modify( + id=_uuid(collection_id), + new_name=update.new_name, + new_metadata=update.new_metadata, + new_configuration=configuration, + ) + + await to_thread.run_sync( + process_update_collection, + request, + collection_id, + await request.body(), + limiter=self._capacity_limiter, + ) + + @trace_method("FastAPI.delete_collection_v1", OpenTelemetryGranularity.OPERATION) + @rate_limit + async def delete_collection_v1( + self, + request: Request, + collection_name: str, + tenant: str = DEFAULT_TENANT, + database: str = DEFAULT_DATABASE, + ) -> None: + ( + maybe_tenant, + maybe_database, + ) = await self.auth_and_get_tenant_and_database_for_request( + request.headers, + AuthzAction.DELETE_COLLECTION, + tenant, + database, + collection_name, + ) + if maybe_tenant: + tenant = maybe_tenant + if maybe_database: + database = maybe_database + + await to_thread.run_sync( + self._api.delete_collection, + collection_name, + tenant, + database, + limiter=self._capacity_limiter, + ) + + @trace_method("FastAPI.add_v1", OpenTelemetryGranularity.OPERATION) + @rate_limit + async def add_v1( + self, + request: Request, + collection_id: str, + ) -> bool: + try: + + def process_add(request: Request, raw_body: bytes) -> bool: + add = validate_model(AddEmbedding, orjson.loads(raw_body)) + # NOTE(rescrv, iron will auth): v1 + self.sync_auth_and_get_tenant_and_database_for_request( + request.headers, + AuthzAction.ADD, + None, + None, + collection_id, + ) + return self._api._add( + collection_id=_uuid(collection_id), + ids=add.ids, + embeddings=cast( + Embeddings, + convert_list_embeddings_to_np(add.embeddings) + if add.embeddings + else None, + ), + metadatas=add.metadatas, # type: ignore + documents=add.documents, # type: ignore + uris=add.uris, # type: ignore + ) + + return cast( + bool, + await to_thread.run_sync( + process_add, + request, + await request.body(), + limiter=self._capacity_limiter, + ), + ) + except InvalidDimensionException as e: + raise HTTPException(status_code=500, detail=str(e)) + + @trace_method("FastAPI.update_v1", OpenTelemetryGranularity.OPERATION) + async def update_v1( + self, + request: Request, + collection_id: str, + ) -> None: + def process_update(request: Request, raw_body: bytes) -> bool: + update = validate_model(UpdateEmbedding, orjson.loads(raw_body)) + + # NOTE(rescrv, iron will auth): v1 + self.sync_auth_and_get_tenant_and_database_for_request( + request.headers, + AuthzAction.UPDATE, + None, + None, + collection_id, + ) + + return self._api._update( + collection_id=_uuid(collection_id), + ids=update.ids, + embeddings=convert_list_embeddings_to_np(update.embeddings) + if update.embeddings + else None, + metadatas=update.metadatas, # type: ignore + documents=update.documents, # type: ignore + uris=update.uris, # type: ignore + ) + + await to_thread.run_sync( + process_update, + request, + await request.body(), + limiter=self._capacity_limiter, + ) + + @trace_method("FastAPI.upsert_v1", OpenTelemetryGranularity.OPERATION) + @rate_limit + async def upsert_v1( + self, + request: Request, + collection_id: str, + ) -> None: + def process_upsert(request: Request, raw_body: bytes) -> bool: + upsert = validate_model(AddEmbedding, orjson.loads(raw_body)) + + # NOTE(rescrv, iron will auth): v1 + self.sync_auth_and_get_tenant_and_database_for_request( + request.headers, + AuthzAction.UPSERT, + None, + None, + collection_id, + ) + + return self._api._upsert( + collection_id=_uuid(collection_id), + ids=upsert.ids, + embeddings=cast( + Embeddings, + convert_list_embeddings_to_np(upsert.embeddings) + if upsert.embeddings + else None, + ), + metadatas=upsert.metadatas, # type: ignore + documents=upsert.documents, # type: ignore + uris=upsert.uris, # type: ignore + ) + + await to_thread.run_sync( + process_upsert, + request, + await request.body(), + limiter=self._capacity_limiter, + ) + + @trace_method("FastAPI.get_v1", OpenTelemetryGranularity.OPERATION) + @rate_limit + async def get_v1( + self, + collection_id: str, + request: Request, + ) -> GetResult: + def process_get(request: Request, raw_body: bytes) -> GetResult: + get = validate_model(GetEmbedding, orjson.loads(raw_body)) + # NOTE(rescrv, iron will auth): v1 + self.sync_auth_and_get_tenant_and_database_for_request( + request.headers, + AuthzAction.GET, + None, + None, + collection_id, + ) + return self._api._get( + collection_id=_uuid(collection_id), + ids=get.ids, + where=get.where, + limit=get.limit, + offset=get.offset, + where_document=get.where_document, + include=get.include, + ) + + get_result = cast( + GetResult, + await to_thread.run_sync( + process_get, + request, + await request.body(), + limiter=self._capacity_limiter, + ), + ) + + if get_result["embeddings"] is not None: + get_result["embeddings"] = [ + cast(Embedding, embedding).tolist() + for embedding in get_result["embeddings"] + ] + + return get_result + + @trace_method("FastAPI.delete_v1", OpenTelemetryGranularity.OPERATION) + @rate_limit + async def delete_v1( + self, + collection_id: str, + request: Request, + ) -> DeleteResult: + def process_delete(request: Request, raw_body: bytes) -> DeleteResult: + delete = validate_model(DeleteEmbedding, orjson.loads(raw_body)) + # NOTE(rescrv, iron will auth): v1 + self.sync_auth_and_get_tenant_and_database_for_request( + request.headers, + AuthzAction.DELETE, + None, + None, + collection_id, + ) + return self._api._delete( + collection_id=_uuid(collection_id), + ids=delete.ids, + where=delete.where, + where_document=delete.where_document, + limit=delete.limit, + ) + + return await to_thread.run_sync( + process_delete, + request, + await request.body(), + limiter=self._capacity_limiter, + ) + + @trace_method("FastAPI.count_v1", OpenTelemetryGranularity.OPERATION) + @rate_limit + async def count_v1( + self, + request: Request, + collection_id: str, + ) -> int: + await self.auth_and_get_tenant_and_database_for_request( + request.headers, + AuthzAction.COUNT, + None, + None, + collection_id, + ) + + return cast( + int, + await to_thread.run_sync( + self._api._count, + _uuid(collection_id), + limiter=self._capacity_limiter, + ), + ) + + @trace_method("FastAPI.reset_v1", OpenTelemetryGranularity.OPERATION) + @rate_limit + async def reset_v1( + self, + request: Request, + ) -> bool: + await self.auth_and_get_tenant_and_database_for_request( + request.headers, + AuthzAction.RESET, + None, + None, + None, + ) + + return cast( + bool, + await to_thread.run_sync( + self._api.reset, + limiter=self._capacity_limiter, + ), + ) + + @trace_method( + "FastAPI.get_nearest_neighbors_v1", OpenTelemetryGranularity.OPERATION + ) + @rate_limit + async def get_nearest_neighbors_v1( + self, + collection_id: str, + request: Request, + ) -> QueryResult: + def process_query(request: Request, raw_body: bytes) -> QueryResult: + query = validate_model(QueryEmbedding, orjson.loads(raw_body)) + + # NOTE(rescrv, iron will auth): v1 + self.sync_auth_and_get_tenant_and_database_for_request( + request.headers, + AuthzAction.QUERY, + None, + None, + collection_id, + ) + + return self._api._query( + collection_id=_uuid(collection_id), + query_embeddings=cast( + Embeddings, + convert_list_embeddings_to_np(query.query_embeddings) + if query.query_embeddings + else None, + ), + n_results=query.n_results, + where=query.where, + where_document=query.where_document, + include=query.include, + ) + + nnresult = cast( + QueryResult, + await to_thread.run_sync( + process_query, + request, + await request.body(), + limiter=self._capacity_limiter, + ), + ) + + if nnresult["embeddings"] is not None: + nnresult["embeddings"] = [ + [cast(Embedding, embedding).tolist() for embedding in result] + for result in nnresult["embeddings"] + ] + + return nnresult + + # ========================================================================= diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/server/fastapi/__pycache__/__init__.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/server/fastapi/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..924eeeebfaf57c21387ddf54569b5ce3a09b9d79 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/server/fastapi/__pycache__/__init__.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/server/fastapi/__pycache__/types.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/server/fastapi/__pycache__/types.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d049f64d53e1b7ca278aeac25fb001e874773275 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/server/fastapi/__pycache__/types.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/server/fastapi/types.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/server/fastapi/types.py new file mode 100644 index 0000000000000000000000000000000000000000..98fb6b1d37fd8c455b3d414f2c4ab1f71acdf691 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/server/fastapi/types.py @@ -0,0 +1,79 @@ +from pydantic import BaseModel, Field +from typing import Any, Dict, List, Optional +from chromadb.api.types import ( + CollectionMetadata, + Include, + IncludeMetadataDocuments, + IncludeMetadataDocumentsDistances, +) + + +class AddEmbedding(BaseModel): + # Pydantic doesn't handle Union types cleanly like Embeddings which has + # Union[int, float] so we use Any here to ensure data is parsed + # to its original type. + embeddings: Optional[List[Any]] = None + metadatas: Optional[List[Optional[Dict[Any, Any]]]] = None + documents: Optional[List[Optional[str]]] = None + uris: Optional[List[Optional[str]]] = None + ids: List[str] + + +class UpdateEmbedding(BaseModel): + embeddings: Optional[List[Any]] = None + metadatas: Optional[List[Optional[Dict[Any, Any]]]] = None + documents: Optional[List[Optional[str]]] = None + uris: Optional[List[Optional[str]]] = None + ids: List[str] + + +class QueryEmbedding(BaseModel): + # TODO: Pydantic doesn't bode well with recursive types so we use generic Dicts + # for Where and WhereDocument. This is not ideal, but it works for now since + # there is a lot of downstream validation. + where: Optional[Dict[Any, Any]] = None + where_document: Optional[Dict[Any, Any]] = None + query_embeddings: List[Any] + n_results: int = 10 + include: Include = IncludeMetadataDocumentsDistances + + +class GetEmbedding(BaseModel): + ids: Optional[List[str]] = None + where: Optional[Dict[Any, Any]] = None + where_document: Optional[Dict[Any, Any]] = None + limit: Optional[int] = None + offset: Optional[int] = None + include: Include = IncludeMetadataDocuments + + +class DeleteEmbedding(BaseModel): + ids: Optional[List[str]] = None + where: Optional[Dict[Any, Any]] = None + where_document: Optional[Dict[Any, Any]] = None + limit: Optional[int] = Field(default=None, ge=0) + + +class CreateCollection(BaseModel): + name: str + # TODO: Make CollectionConfiguration a Pydantic model + # In 0.5.4 we added the configuration field to the CreateCollection model + # This field is optional, for backwards compatibility with older versions + # we default to None. + configuration: Optional[Dict[str, Any]] = None + metadata: Optional[CollectionMetadata] = None + get_or_create: bool = False + + +class UpdateCollection(BaseModel): + new_name: Optional[str] = None + new_metadata: Optional[CollectionMetadata] = None + new_configuration: Optional[Dict[str, Any]] = None + + +class CreateDatabase(BaseModel): + name: str + + +class CreateTenant(BaseModel): + name: str diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/telemetry/README.md b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/telemetry/README.md new file mode 100644 index 0000000000000000000000000000000000000000..efaff31aa6f5a47fbb6a9aebb9a790680005c569 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/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/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/telemetry/__init__.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/telemetry/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/telemetry/__pycache__/__init__.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/telemetry/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..aad473155a916ea8419ede7549ed7a6bec3138d7 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/telemetry/__pycache__/__init__.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/telemetry/opentelemetry/__init__.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/telemetry/opentelemetry/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..c51904c5ecf8076f98d1c3c398dc5f9c9fb52603 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/telemetry/opentelemetry/__init__.py @@ -0,0 +1,187 @@ +import asyncio +import os +from functools import wraps +from enum import Enum +from typing import Any, Callable, Dict, Optional, Sequence, Union, TypeVar + +from opentelemetry import trace +from opentelemetry.sdk.resources import SERVICE_NAME, Resource +from opentelemetry.sdk.trace import TracerProvider +from opentelemetry.sdk.trace.export import ( + BatchSpanProcessor, +) +from opentelemetry.exporter.otlp.proto.grpc.trace_exporter import OTLPSpanExporter + +from chromadb.config import Component +from chromadb.config import System + + +class OpenTelemetryGranularity(Enum): + """The granularity of the OpenTelemetry spans.""" + + NONE = "none" + """No spans are emitted.""" + + OPERATION = "operation" + """Spans are emitted for each operation.""" + + OPERATION_AND_SEGMENT = "operation_and_segment" + """Spans are emitted for each operation and segment.""" + + ALL = "all" + """Spans are emitted for almost every method call.""" + + # Greater is more restrictive. So "all" < "operation" (and everything else), + # "none" > everything. + def __lt__(self, other: Any) -> bool: + """Compare two granularities.""" + order = [ + OpenTelemetryGranularity.ALL, + OpenTelemetryGranularity.OPERATION_AND_SEGMENT, + OpenTelemetryGranularity.OPERATION, + OpenTelemetryGranularity.NONE, + ] + return order.index(self) < order.index(other) + + +class OpenTelemetryClient(Component): + def __init__(self, system: System): + super().__init__(system) + otel_init( + system.settings.chroma_otel_service_name, + system.settings.chroma_otel_collection_endpoint, + system.settings.chroma_otel_collection_headers, + OpenTelemetryGranularity( + system.settings.chroma_otel_granularity + if system.settings.chroma_otel_granularity + else "none" + ), + ) + + +tracer: Optional[trace.Tracer] = None +granularity: OpenTelemetryGranularity = OpenTelemetryGranularity("none") + + +def otel_init( + otel_service_name: Optional[str], + otel_collection_endpoint: Optional[str], + otel_collection_headers: Optional[Dict[str, str]], + otel_granularity: OpenTelemetryGranularity, +) -> None: + """Initializes module-level state for OpenTelemetry. + + Parameters match the environment variables which configure OTel as documented + at https://docs.trychroma.com/deployment/observability. + - otel_service_name: The name of the service for OTel tagging and aggregation. + - otel_collection_endpoint: The endpoint to which OTel spans are sent + (e.g. api.honeycomb.com). + - otel_collection_headers: The headers to send with OTel spans + (e.g. {"x-honeycomb-team": "abc123"}). + - otel_granularity: The granularity of the spans to emit. + """ + if otel_granularity == OpenTelemetryGranularity.NONE: + return + resource = Resource(attributes={SERVICE_NAME: str(otel_service_name)}) + provider = TracerProvider(resource=resource) + provider.add_span_processor( + BatchSpanProcessor( + # TODO: we may eventually want to make this configurable. + OTLPSpanExporter( + endpoint=str(otel_collection_endpoint), + headers=otel_collection_headers, + ) + ) + ) + trace.set_tracer_provider(provider) + + global tracer, granularity + tracer = trace.get_tracer(__name__) + granularity = otel_granularity + + +T = TypeVar("T", bound=Callable) # type: ignore[type-arg] + + +def trace_method( + trace_name: str, + trace_granularity: OpenTelemetryGranularity, + attributes: Optional[ + Dict[ + str, + Union[ + str, + bool, + float, + int, + Sequence[str], + Sequence[bool], + Sequence[float], + Sequence[int], + ], + ] + ] = None, +) -> Callable[[T], T]: + """A decorator that traces a method.""" + + def decorator(f: T) -> T: + if asyncio.iscoroutinefunction(f): + + @wraps(f) + async def async_wrapper(*args, **kwargs): # type: ignore[no-untyped-def] + global tracer, granularity + if trace_granularity < granularity: + return await f(*args, **kwargs) + if not tracer: + return await f(*args, **kwargs) + with tracer.start_as_current_span(trace_name, attributes=attributes): + add_attributes_to_current_span( + {"pod_name": os.environ.get("HOSTNAME")} + ) + return await f(*args, **kwargs) + + return async_wrapper # type: ignore + else: + + @wraps(f) + def wrapper(*args, **kwargs): # type: ignore[no-untyped-def] + global tracer, granularity + if trace_granularity < granularity: + return f(*args, **kwargs) + if not tracer: + return f(*args, **kwargs) + with tracer.start_as_current_span(trace_name, attributes=attributes): + add_attributes_to_current_span( + {"pod_name": os.environ.get("HOSTNAME")} + ) + return f(*args, **kwargs) + + return wrapper # type: ignore + + return decorator + + +def add_attributes_to_current_span( + attributes: Dict[ + str, + Union[ + str, + bool, + float, + int, + Sequence[str], + Sequence[bool], + Sequence[float], + Sequence[int], + None, + ], + ] +) -> None: + """Add attributes to the current span.""" + global tracer, granularity + if granularity == OpenTelemetryGranularity.NONE: + return + if not tracer: + return + span = trace.get_current_span() + span.set_attributes({k: v for k, v in attributes.items() if v is not None}) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/telemetry/opentelemetry/__pycache__/__init__.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/telemetry/opentelemetry/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b387a7c97c55abfe828a4d80d82dad38c8ff359c Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/telemetry/opentelemetry/__pycache__/__init__.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/telemetry/opentelemetry/__pycache__/fastapi.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/telemetry/opentelemetry/__pycache__/fastapi.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..dc695f5eb3a4220f3b8089f921336d3e9256bed4 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/telemetry/opentelemetry/__pycache__/fastapi.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/telemetry/opentelemetry/__pycache__/grpc.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/telemetry/opentelemetry/__pycache__/grpc.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c18a62ddac560e9041cd1f6a995b26b954350e5f Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/telemetry/opentelemetry/__pycache__/grpc.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/telemetry/opentelemetry/fastapi.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/telemetry/opentelemetry/fastapi.py new file mode 100644 index 0000000000000000000000000000000000000000..3381ee0aec3940dc76949208e64cc2f3f6970ce3 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/telemetry/opentelemetry/fastapi.py @@ -0,0 +1,10 @@ +from typing import List, Optional +from fastapi import FastAPI +from opentelemetry.instrumentation.fastapi import FastAPIInstrumentor + + +def instrument_fastapi(app: FastAPI, excluded_urls: Optional[List[str]] = None) -> None: + """Instrument FastAPI to emit OpenTelemetry spans.""" + FastAPIInstrumentor.instrument_app( + app, excluded_urls=",".join(excluded_urls) if excluded_urls else None + ) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/telemetry/opentelemetry/grpc.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/telemetry/opentelemetry/grpc.py new file mode 100644 index 0000000000000000000000000000000000000000..e417c3d3d671c55dc89318c8c6a224631a734ed6 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/telemetry/opentelemetry/grpc.py @@ -0,0 +1,95 @@ +import binascii +import collections + +import grpc +from opentelemetry.trace import StatusCode, SpanKind + + +class _ClientCallDetails( + collections.namedtuple( + "_ClientCallDetails", ("method", "timeout", "metadata", "credentials") + ), + grpc.ClientCallDetails, +): + pass + + +def _encode_span_id(span_id: int) -> str: + return binascii.hexlify(span_id.to_bytes(8, "big")).decode() + + +def _encode_trace_id(trace_id: int) -> str: + return binascii.hexlify(trace_id.to_bytes(16, "big")).decode() + + +# Using OtelInterceptor with gRPC: +# 1. Instantiate the interceptor: interceptors = [OtelInterceptor()] +# 2. Intercept the channel: channel = grpc.intercept_channel(channel, *interceptors) + + +class OtelInterceptor( + grpc.UnaryUnaryClientInterceptor, + grpc.UnaryStreamClientInterceptor, + grpc.StreamUnaryClientInterceptor, + grpc.StreamStreamClientInterceptor, +): + def _intercept_call(self, continuation, client_call_details, request_or_iterator): + from chromadb.telemetry.opentelemetry import tracer + + if tracer is None: + return continuation(client_call_details, request_or_iterator) + with tracer.start_as_current_span( + f"RPC {client_call_details.method}", kind=SpanKind.CLIENT + ) as span: + # Prepare metadata for propagation + metadata = ( + client_call_details.metadata[:] if client_call_details.metadata else [] + ) + metadata.extend( + [ + ( + "chroma-traceid", + _encode_trace_id(span.get_span_context().trace_id), + ), + ("chroma-spanid", _encode_span_id(span.get_span_context().span_id)), + ] + ) + # Update client call details with new metadata + new_client_details = _ClientCallDetails( + client_call_details.method, + client_call_details.timeout, + tuple(metadata), # Ensure metadata is a tuple + client_call_details.credentials, + ) + try: + result = continuation(new_client_details, request_or_iterator) + # Set attributes based on the result + if hasattr(result, "details") and result.details(): + span.set_attribute("rpc.detail", result.details()) + span.set_attribute("rpc.status_code", result.code().name.lower()) + span.set_attribute("rpc.status_code_value", result.code().value[0]) + # Set span status based on gRPC call result + if result.code() != grpc.StatusCode.OK: + span.set_status(StatusCode.ERROR, description=str(result.code())) + return result + except Exception as e: + # Log exception details and re-raise + span.set_attribute("rpc.error", str(e)) + span.set_status(StatusCode.ERROR, description=str(e)) + raise + + 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/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/telemetry/product/__init__.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/telemetry/product/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..c24adba0993cdb20d1b0d15f808141e052684d5a --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/telemetry/product/__init__.py @@ -0,0 +1,97 @@ +from abc import abstractmethod +import os +from typing import ClassVar, Dict, Any +import uuid +import chromadb +from chromadb.config import Component +from pathlib import Path +from enum import Enum + +TELEMETRY_WHITELISTED_SETTINGS = [ + "chroma_api_impl", + "is_persistent", + "chroma_server_ssl_enabled", + "chroma_server_api_default_path", +] + + +class ServerContext(Enum): + NONE = "None" + FASTAPI = "FastAPI" + + +class ProductTelemetryEvent: + max_batch_size: ClassVar[int] = 1 + batch_size: int + + def __init__(self, batch_size: int = 1): + self.batch_size = batch_size + + @property + def properties(self) -> Dict[str, Any]: + return self.__dict__ + + @property + def name(self) -> str: + return self.__class__.__name__ + + # A batch key is used to determine whether two events can be batched together. + # If a TelemetryEvent's max_batch_size > 1, batch_key() and batch() MUST be + # implemented. + # Otherwise they are ignored. + @property + def batch_key(self) -> str: + return self.name + + def batch(self, other: "ProductTelemetryEvent") -> "ProductTelemetryEvent": + raise NotImplementedError + + +class ProductTelemetryClient(Component): + USER_ID_PATH = str(Path.home() / ".cache" / "chroma" / "telemetry_user_id") + UNKNOWN_USER_ID = "UNKNOWN" + SERVER_CONTEXT: ServerContext = ServerContext.NONE + _curr_user_id = None + + @abstractmethod + def capture(self, event: ProductTelemetryEvent) -> None: + pass + + @property + def context(self) -> Dict[str, Any]: + chroma_version = chromadb.__version__ + settings = chromadb.get_settings() + telemetry_settings = {} + for whitelisted in TELEMETRY_WHITELISTED_SETTINGS: + telemetry_settings[whitelisted] = settings[whitelisted] + + hosted = self._system.settings.chroma_server_host == "api.trychroma.com" + + self._context = { + "chroma_version": chroma_version, + "server_context": self.SERVER_CONTEXT.value, + "hosted": hosted, + **telemetry_settings, + } + return self._context + + @property + def user_id(self) -> str: + if self._curr_user_id: + return self._curr_user_id + + # File access may fail due to permissions or other reasons. We don't want to + # crash so we catch all exceptions. + try: + if not os.path.exists(self.USER_ID_PATH): + os.makedirs(os.path.dirname(self.USER_ID_PATH), exist_ok=True) + with open(self.USER_ID_PATH, "w") as f: + new_user_id = str(uuid.uuid4()) + f.write(new_user_id) + self._curr_user_id = new_user_id + else: + with open(self.USER_ID_PATH, "r") as f: + self._curr_user_id = f.read() + except Exception: + self._curr_user_id = self.UNKNOWN_USER_ID + return self._curr_user_id diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/telemetry/product/__pycache__/__init__.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/telemetry/product/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7a33d50ec8e10a518a2a15d2a3e6e6eb3cfb06a9 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/telemetry/product/__pycache__/__init__.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/telemetry/product/__pycache__/events.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/telemetry/product/__pycache__/events.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7b0c543694ab72338113127e463940dfdea89e79 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/telemetry/product/__pycache__/events.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/telemetry/product/__pycache__/posthog.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/telemetry/product/__pycache__/posthog.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7faf9107a0011f304596d596b22c75dabac35614 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/telemetry/product/__pycache__/posthog.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/telemetry/product/events.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/telemetry/product/events.py new file mode 100644 index 0000000000000000000000000000000000000000..ff4a2b24b18fe771ce28e2474805b0805127c106 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/telemetry/product/events.py @@ -0,0 +1,256 @@ +import os +from typing import cast, ClassVar +from chromadb.telemetry.product import ProductTelemetryEvent + + +class ClientStartEvent(ProductTelemetryEvent): + def __init__(self) -> None: + super().__init__() + # Lazy import to avoid circular imports + from chromadb import is_in_colab + + self.in_colab = is_in_colab() + + +class ServerStartEvent(ProductTelemetryEvent): + is_cli: bool + + def __init__(self) -> None: + super().__init__() + self.is_cli = os.environ.get("CHROMA_CLI", "False") == "True" + + +# TODO: Re-enable embedding function tracking in create_collection +class ClientCreateCollectionEvent(ProductTelemetryEvent): + collection_uuid: str + # embedding_function: str + + def __init__(self, collection_uuid: str): # , embedding_function: str): + super().__init__() + self.collection_uuid = collection_uuid + + # embedding_function_names = get_builtins() + + # self.embedding_function = ( + # embedding_function + # if embedding_function in embedding_function_names + # else "custom" + # ) + + +class CollectionAddEvent(ProductTelemetryEvent): + max_batch_size: ClassVar[int] = 3000 + batch_size: int + collection_uuid: str + add_amount: int + with_documents: int + with_metadata: int + with_uris: int + + def __init__( + self, + collection_uuid: str, + add_amount: int, + with_documents: int, + with_metadata: int, + with_uris: int, + batch_size: int = 1, + ): + super().__init__() + self.collection_uuid = collection_uuid + self.add_amount = add_amount + self.with_documents = with_documents + self.with_metadata = with_metadata + self.with_uris = with_uris + self.batch_size = batch_size + + @property + def batch_key(self) -> str: + return self.collection_uuid + self.name + + def batch(self, other: "ProductTelemetryEvent") -> "CollectionAddEvent": + if not self.batch_key == other.batch_key: + raise ValueError("Cannot batch events") + other = cast(CollectionAddEvent, other) + total_amount = self.add_amount + other.add_amount + return CollectionAddEvent( + collection_uuid=self.collection_uuid, + add_amount=total_amount, + with_documents=self.with_documents + other.with_documents, + with_metadata=self.with_metadata + other.with_metadata, + with_uris=self.with_uris + other.with_uris, + batch_size=self.batch_size + other.batch_size, + ) + + +class CollectionUpdateEvent(ProductTelemetryEvent): + max_batch_size: ClassVar[int] = 300 + batch_size: int + collection_uuid: str + update_amount: int + with_embeddings: int + with_metadata: int + with_documents: int + with_uris: int + + def __init__( + self, + collection_uuid: str, + update_amount: int, + with_embeddings: int, + with_metadata: int, + with_documents: int, + with_uris: int, + batch_size: int = 1, + ): + super().__init__() + self.collection_uuid = collection_uuid + self.update_amount = update_amount + self.with_embeddings = with_embeddings + self.with_metadata = with_metadata + self.with_documents = with_documents + self.with_uris = with_uris + self.batch_size = batch_size + + @property + def batch_key(self) -> str: + return self.collection_uuid + self.name + + def batch(self, other: "ProductTelemetryEvent") -> "CollectionUpdateEvent": + if not self.batch_key == other.batch_key: + raise ValueError("Cannot batch events") + other = cast(CollectionUpdateEvent, other) + total_amount = self.update_amount + other.update_amount + return CollectionUpdateEvent( + collection_uuid=self.collection_uuid, + update_amount=total_amount, + with_documents=self.with_documents + other.with_documents, + with_metadata=self.with_metadata + other.with_metadata, + with_embeddings=self.with_embeddings + other.with_embeddings, + with_uris=self.with_uris + other.with_uris, + batch_size=self.batch_size + other.batch_size, + ) + + +class CollectionQueryEvent(ProductTelemetryEvent): + max_batch_size: ClassVar[int] = 3000 + batch_size: int + collection_uuid: str + query_amount: int + filtered_ids_amount: int + with_metadata_filter: int + with_document_filter: int + n_results: int + include_metadatas: int + include_documents: int + include_uris: int + include_distances: int + + def __init__( + self, + collection_uuid: str, + query_amount: int, + filtered_ids_amount: int, + with_metadata_filter: int, + with_document_filter: int, + n_results: int, + include_metadatas: int, + include_documents: int, + include_uris: int, + include_distances: int, + batch_size: int = 1, + ): + super().__init__() + self.collection_uuid = collection_uuid + self.query_amount = query_amount + self.filtered_ids_amount = filtered_ids_amount + self.with_metadata_filter = with_metadata_filter + self.with_document_filter = with_document_filter + self.n_results = n_results + self.include_metadatas = include_metadatas + self.include_documents = include_documents + self.include_uris = include_uris + self.include_distances = include_distances + self.batch_size = batch_size + + @property + def batch_key(self) -> str: + return self.collection_uuid + self.name + + def batch(self, other: "ProductTelemetryEvent") -> "CollectionQueryEvent": + if not self.batch_key == other.batch_key: + raise ValueError("Cannot batch events") + other = cast(CollectionQueryEvent, other) + total_amount = self.query_amount + other.query_amount + return CollectionQueryEvent( + collection_uuid=self.collection_uuid, + query_amount=total_amount, + filtered_ids_amount=self.filtered_ids_amount + other.filtered_ids_amount, + with_metadata_filter=self.with_metadata_filter + other.with_metadata_filter, + with_document_filter=self.with_document_filter + other.with_document_filter, + n_results=self.n_results + other.n_results, + include_metadatas=self.include_metadatas + other.include_metadatas, + include_documents=self.include_documents + other.include_documents, + include_uris=self.include_uris + other.include_uris, + include_distances=self.include_distances + other.include_distances, + batch_size=self.batch_size + other.batch_size, + ) + + +class CollectionGetEvent(ProductTelemetryEvent): + max_batch_size: ClassVar[int] = 300 + batch_size: int + collection_uuid: str + ids_count: int + limit: int + include_metadata: int + include_documents: int + include_uris: int + + def __init__( + self, + collection_uuid: str, + ids_count: int, + limit: int, + include_metadata: int, + include_documents: int, + include_uris: int, + batch_size: int = 1, + ): + super().__init__() + self.collection_uuid = collection_uuid + self.ids_count = ids_count + self.limit = limit + self.include_metadata = include_metadata + self.include_documents = include_documents + self.include_uris = include_uris + self.batch_size = batch_size + + @property + def batch_key(self) -> str: + return self.collection_uuid + self.name + str(self.limit) + + def batch(self, other: "ProductTelemetryEvent") -> "CollectionGetEvent": + if not self.batch_key == other.batch_key: + raise ValueError("Cannot batch events") + other = cast(CollectionGetEvent, other) + total_amount = self.ids_count + other.ids_count + return CollectionGetEvent( + collection_uuid=self.collection_uuid, + ids_count=total_amount, + limit=self.limit, + include_metadata=self.include_metadata + other.include_metadata, + include_documents=self.include_documents + other.include_documents, + include_uris=self.include_uris + other.include_uris, + batch_size=self.batch_size + other.batch_size, + ) + + +class CollectionDeleteEvent(ProductTelemetryEvent): + collection_uuid: str + delete_amount: int + + def __init__(self, collection_uuid: str, delete_amount: int): + super().__init__() + self.collection_uuid = collection_uuid + self.delete_amount = delete_amount diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/telemetry/product/posthog.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/telemetry/product/posthog.py new file mode 100644 index 0000000000000000000000000000000000000000..5341dfcd04d004cb61b73643ceaec9b17d65e918 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/telemetry/product/posthog.py @@ -0,0 +1,11 @@ +from chromadb.telemetry.product import ( + ProductTelemetryClient, + ProductTelemetryEvent, +) +from overrides import override + + +class Posthog(ProductTelemetryClient): + @override + def capture(self, event: ProductTelemetryEvent) -> None: + pass diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/__init__.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/__pycache__/__init__.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1ae74eb2c3868ba2366f97126d95d7b9169a016f Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/__pycache__/__init__.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/__pycache__/conftest.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/__pycache__/conftest.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f364335a58449b363503864f41f3133a3d0b5a4e Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/__pycache__/conftest.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/__pycache__/test_chroma.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/__pycache__/test_chroma.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5d0c9325153c117d09354eb07de2d96ceef397ce Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/__pycache__/test_chroma.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/__pycache__/test_cli.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/__pycache__/test_cli.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7b6d537bb8863c4829decb9e8fc67d71860b20f6 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/__pycache__/test_cli.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/__pycache__/test_client.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/__pycache__/test_client.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..38635dc1d0fb94611fccbfd54dbdfbf1dec69952 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/__pycache__/test_client.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/__pycache__/test_config.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/__pycache__/test_config.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7553c58feca4f2317972609e7ba7722342c2eca3 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/__pycache__/test_config.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/__pycache__/test_multithreaded.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/__pycache__/test_multithreaded.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1a551aa8b9426fb93da0b8a69ae5c863a6c34b8c Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/__pycache__/test_multithreaded.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/api/__pycache__/test_collection.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/api/__pycache__/test_collection.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..51e4f0fac823088d616334f84e3c6d67fe1be1d6 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/api/__pycache__/test_collection.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/api/__pycache__/test_count_api.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/api/__pycache__/test_count_api.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..773b13df9760d96434e67ebd3e1e59ad8451113e Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/api/__pycache__/test_count_api.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/api/__pycache__/test_delete_database.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/api/__pycache__/test_delete_database.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..881b2ca367a960f6784caf8a476985887f1acf77 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/api/__pycache__/test_delete_database.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/api/__pycache__/test_fork_count_api.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/api/__pycache__/test_fork_count_api.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e440d4127d894a460acca90ff1b20f79555e9913 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/api/__pycache__/test_fork_count_api.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/api/__pycache__/test_get_database.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/api/__pycache__/test_get_database.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6ddcff6fd37937b9805d3fc064f597b329c257fc Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/api/__pycache__/test_get_database.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/api/__pycache__/test_indexing_status.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/api/__pycache__/test_indexing_status.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..cae00c9bf3b468a8422098c95bf87feffd634f98 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/api/__pycache__/test_indexing_status.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/api/__pycache__/test_invalid_update.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/api/__pycache__/test_invalid_update.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ce30e5e38f56afa386b0c4580248430be30f31b8 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/api/__pycache__/test_invalid_update.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/api/__pycache__/test_limit_offset.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/api/__pycache__/test_limit_offset.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e3a3353d9554457b9112e97e60cce22444e51a92 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/api/__pycache__/test_limit_offset.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/api/__pycache__/test_list_databases.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/api/__pycache__/test_list_databases.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..96dce450d87ae88a955a43fced9d36bca0de8de5 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/api/__pycache__/test_list_databases.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/api/__pycache__/test_numpy_list_inputs.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/api/__pycache__/test_numpy_list_inputs.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..58e5de97e4c69b75271bfdf0d9fa8f146719238d Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/api/__pycache__/test_numpy_list_inputs.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/api/__pycache__/test_search_api.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/api/__pycache__/test_search_api.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6afa2a33976207ba239b000357e4c33d493e050d Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/api/__pycache__/test_search_api.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/api/__pycache__/test_shared_system_client.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/api/__pycache__/test_shared_system_client.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e112aa69e9c72b6d33cb4ef8748cfa8e66eda21a Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/api/__pycache__/test_shared_system_client.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/api/__pycache__/test_types.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/api/__pycache__/test_types.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..32097ec15fbcb52755ac3c30b45eced48ce07cb8 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/api/__pycache__/test_types.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/api/test_collection.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/api/test_collection.py new file mode 100644 index 0000000000000000000000000000000000000000..d1309cb696dc3434e90363e4fe75040c5706e78b --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/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/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/api/test_count_api.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/api/test_count_api.py new file mode 100644 index 0000000000000000000000000000000000000000..bfb7338584775719db9019ae59299cc057a5de2e --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/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/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/api/test_delete_database.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/api/test_delete_database.py new file mode 100644 index 0000000000000000000000000000000000000000..d34a220fd534a20ef07affbeed781669f0813f46 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/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/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/api/test_fork_count_api.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/api/test_fork_count_api.py new file mode 100644 index 0000000000000000000000000000000000000000..5421ee9f688bd13689d715685df5fd93e4a487f1 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/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/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/api/test_get_database.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/api/test_get_database.py new file mode 100644 index 0000000000000000000000000000000000000000..634ac82d73993a64307375786384157c52f4a1bb --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/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/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/api/test_indexing_status.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/api/test_indexing_status.py new file mode 100644 index 0000000000000000000000000000000000000000..ca3c3cc9ecbca95841b27ec72cd9a1dc66e57a3b --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/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/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/api/test_invalid_update.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/api/test_invalid_update.py new file mode 100644 index 0000000000000000000000000000000000000000..2ae78ff1f27a406669953074749046f361da59dd --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/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/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/api/test_limit_offset.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/api/test_limit_offset.py new file mode 100644 index 0000000000000000000000000000000000000000..4ddc0c7d4fbcad523477ab23de9dec875a8fd3c3 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/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/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/api/test_list_databases.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/api/test_list_databases.py new file mode 100644 index 0000000000000000000000000000000000000000..15a7566c4196bdc4b58ff982e08877e29904bef9 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/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/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/api/test_numpy_list_inputs.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/api/test_numpy_list_inputs.py new file mode 100644 index 0000000000000000000000000000000000000000..7a6e66ad4b408e29a1e692aab61ed5781356f8d1 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/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/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/api/test_schema.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/api/test_schema.py new file mode 100644 index 0000000000000000000000000000000000000000..37a2dbb12b7985bc08b3607d7ec62013c99dcc9b --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/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/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/api/test_schema_e2e.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/api/test_schema_e2e.py new file mode 100644 index 0000000000000000000000000000000000000000..1dde67b84a71a9f2b9770c4c773c9f15a06ff4de --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/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/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/api/test_search_api.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/api/test_search_api.py new file mode 100644 index 0000000000000000000000000000000000000000..436c614c478d5cd5cf7ba5a5d6a89cfd4aeab506 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/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/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/api/test_shared_system_client.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/api/test_shared_system_client.py new file mode 100644 index 0000000000000000000000000000000000000000..395a733ff0e5f197ad3a53a8a153adf4b6a581fb --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/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/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/api/test_types.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/api/test_types.py new file mode 100644 index 0000000000000000000000000000000000000000..89ba965afd8816e9687c1d912cf9c0198c7bf8df --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/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/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/auth/__pycache__/test_auth_utils.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/auth/__pycache__/test_auth_utils.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d8f876b8feb4b385632549a47d88feb7b52d1762 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/auth/__pycache__/test_auth_utils.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/auth/__pycache__/test_rbac_authz.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/auth/__pycache__/test_rbac_authz.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..71bc4519ee88d5399457a22d1d92ca10afebc91c Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/auth/__pycache__/test_rbac_authz.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/auth/test_auth_utils.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/auth/test_auth_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..b6580deacd8c45f735073468d6f760d5e9919a00 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/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/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/auth/test_rbac_authz.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/auth/test_rbac_authz.py new file mode 100644 index 0000000000000000000000000000000000000000..938fc4dd80bf6b76bd482158760f5ac18bc259ee --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/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/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/client/__init__.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/client/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/client/__pycache__/__init__.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/client/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ac94e7b2c508818cb003f9d398433748ef67a17f Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/client/__pycache__/__init__.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/client/__pycache__/create_http_client_with_basic_auth.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/client/__pycache__/create_http_client_with_basic_auth.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..662314a907168826cee888356f93c7c9694c950c Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/client/__pycache__/create_http_client_with_basic_auth.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/client/__pycache__/test_cloud_client.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/client/__pycache__/test_cloud_client.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..09fbb84f535a3d157397d40c419b3571c55c3fb7 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/client/__pycache__/test_cloud_client.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/client/__pycache__/test_create_http_client.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/client/__pycache__/test_create_http_client.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9052ee30bffa9c2b07d8c5cc2e7a479bef02754b Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/client/__pycache__/test_create_http_client.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/client/__pycache__/test_database_tenant.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/client/__pycache__/test_database_tenant.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8fb6ad3879733e3de0058143fcc5baea54f8f8e5 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/client/__pycache__/test_database_tenant.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/client/__pycache__/test_database_tenant_auth.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/client/__pycache__/test_database_tenant_auth.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..38a0cdfa9db8031999d3a366610412c09c86b3b0 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/client/__pycache__/test_database_tenant_auth.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/client/__pycache__/test_multiple_clients_concurrency.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/client/__pycache__/test_multiple_clients_concurrency.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a8e7c91d3654de1d16f64db93505e5e135123b24 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/client/__pycache__/test_multiple_clients_concurrency.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/client/create_http_client_with_basic_auth.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/client/create_http_client_with_basic_auth.py new file mode 100644 index 0000000000000000000000000000000000000000..e4bf7e1c077a99ab39a43cf6b929328586a865f7 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/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/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/client/test_cloud_client.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/client/test_cloud_client.py new file mode 100644 index 0000000000000000000000000000000000000000..23c788476c6bf2072334929248f89756dd4dd46c --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/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/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/client/test_create_http_client.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/client/test_create_http_client.py new file mode 100644 index 0000000000000000000000000000000000000000..b4e0823d0eea64bf3f0d3759cc5e796fe10c8136 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/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/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/client/test_database_tenant.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/client/test_database_tenant.py new file mode 100644 index 0000000000000000000000000000000000000000..81d9948d7180a4610c9e5418d4ff24d479ca8512 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/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/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/client/test_database_tenant_auth.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/client/test_database_tenant_auth.py new file mode 100644 index 0000000000000000000000000000000000000000..07a142d86c0dc0b5b5a459a87c2f7eb88d063dc4 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/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/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/client/test_multiple_clients_concurrency.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/client/test_multiple_clients_concurrency.py new file mode 100644 index 0000000000000000000000000000000000000000..5050cd4a71abc945c9ce4f796ab809e6449ce907 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/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/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/configurations/__pycache__/test_collection_configuration.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/configurations/__pycache__/test_collection_configuration.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2156fee3f8862f0c0227704e1609321011603c5e Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/configurations/__pycache__/test_collection_configuration.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/configurations/__pycache__/test_configurations.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/configurations/__pycache__/test_configurations.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..34049d01d6d4a75a7a784bcd390e090492109065 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/configurations/__pycache__/test_configurations.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/configurations/test_collection_configuration.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/configurations/test_collection_configuration.py new file mode 100644 index 0000000000000000000000000000000000000000..89ffc6c7b04147edc804e253232e86e656d3628e --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/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/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/configurations/test_configurations.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/configurations/test_configurations.py new file mode 100644 index 0000000000000000000000000000000000000000..639b614d534a873b8719c2f67ffa140d507dae74 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/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/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/conftest.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/conftest.py new file mode 100644 index 0000000000000000000000000000000000000000..eec478af4a7f6a3b4a2c959f533711a82ebd759e --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/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/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/data_loader/__pycache__/test_data_loader.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/data_loader/__pycache__/test_data_loader.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..bd3299b8b69c3b5aae575ff8321645fa712f8da8 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/data_loader/__pycache__/test_data_loader.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/data_loader/test_data_loader.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/data_loader/test_data_loader.py new file mode 100644 index 0000000000000000000000000000000000000000..10e4c69ccd8d36f1db18bb981dea592e78cae9a4 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/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/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/db/__pycache__/test_log_purge.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/db/__pycache__/test_log_purge.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..aabce6bca4c404b9a0bf31c8ad2c027f3a68115a Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/db/__pycache__/test_log_purge.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/db/test_log_purge.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/db/test_log_purge.py new file mode 100644 index 0000000000000000000000000000000000000000..e2ffc0349cc0f7e4768b3c2b35ec4465b9600b34 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/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/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/distributed/README.md b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/distributed/README.md new file mode 100644 index 0000000000000000000000000000000000000000..112e13b66130243f0c3d5d15dc94e07ea4691630 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/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/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/distributed/__pycache__/test_log_backpressure.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/distributed/__pycache__/test_log_backpressure.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e2383ddf4163ad94c64aab10c771ad05ff6b8c18 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/distributed/__pycache__/test_log_backpressure.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/distributed/__pycache__/test_repair_collection_log_offset.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/distributed/__pycache__/test_repair_collection_log_offset.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ae49d076e4df32bac2271c8efc034c9782512a3e Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/distributed/__pycache__/test_repair_collection_log_offset.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/distributed/__pycache__/test_reroute.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/distributed/__pycache__/test_reroute.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..bdd96ce7292a69d3242a8dc9e240244f99ca02e4 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/distributed/__pycache__/test_reroute.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/distributed/__pycache__/test_sanity.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/distributed/__pycache__/test_sanity.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..bc983bcf46eafafaebec10c24ec41cbcb5b54f2c Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/distributed/__pycache__/test_sanity.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/distributed/__pycache__/test_statistics_wrapper.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/distributed/__pycache__/test_statistics_wrapper.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..36de9050fbcce6b5c06bd2c2b898028c6056ad03 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/distributed/__pycache__/test_statistics_wrapper.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/distributed/__pycache__/test_task_api.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/distributed/__pycache__/test_task_api.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2acb747fcf4dac4e39df66b3944841335a93a047 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/distributed/__pycache__/test_task_api.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/distributed/test_log_backpressure.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/distributed/test_log_backpressure.py new file mode 100644 index 0000000000000000000000000000000000000000..fa979f6a7d7b904f5266a5ba51cbd616b5c725e7 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/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/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/distributed/test_repair_collection_log_offset.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/distributed/test_repair_collection_log_offset.py new file mode 100644 index 0000000000000000000000000000000000000000..a7f8a0b4417b90c0c2adb017413adc33a4ac1151 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/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/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/distributed/test_reroute.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/distributed/test_reroute.py new file mode 100644 index 0000000000000000000000000000000000000000..04c1c8a974cc05205e2e1e9ea348e43d632e762d --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/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/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/distributed/test_sanity.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/distributed/test_sanity.py new file mode 100644 index 0000000000000000000000000000000000000000..38ade43cabd5f63b8b8bbc28df3e309518bd300e --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/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/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/distributed/test_statistics_wrapper.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/distributed/test_statistics_wrapper.py new file mode 100644 index 0000000000000000000000000000000000000000..cc83dad8fc4234d69ef768502b45a45f6b124a7b --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/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/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/distributed/test_task_api.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/distributed/test_task_api.py new file mode 100644 index 0000000000000000000000000000000000000000..7a6ed6baea274192d664b3a17600a5c27fc18920 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/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/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/ef/__pycache__/test_chroma_bm25_embedding_function.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/ef/__pycache__/test_chroma_bm25_embedding_function.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..10bfefd404cab7242b397cb2b07a1abc35920455 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/ef/__pycache__/test_chroma_bm25_embedding_function.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/ef/__pycache__/test_custom_ef.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/ef/__pycache__/test_custom_ef.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..95c87d3601d7ea644eed11f19c1111e99554d5e1 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/ef/__pycache__/test_custom_ef.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/ef/__pycache__/test_default_ef.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/ef/__pycache__/test_default_ef.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b43aae29984f471faba9951f4c9f726aef426402 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/ef/__pycache__/test_default_ef.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/ef/__pycache__/test_ef.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/ef/__pycache__/test_ef.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9ea5c86aa094533c14193210ec90705d5cb4f7b6 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/ef/__pycache__/test_ef.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/ef/__pycache__/test_morph_ef.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/ef/__pycache__/test_morph_ef.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f8d135206f280ef8095e03cd8664777018b18207 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/ef/__pycache__/test_morph_ef.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/ef/__pycache__/test_multimodal_ef.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/ef/__pycache__/test_multimodal_ef.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b087aca3f45dbe2d9575013c28600860a5a372d8 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/ef/__pycache__/test_multimodal_ef.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/ef/__pycache__/test_ollama_ef.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/ef/__pycache__/test_ollama_ef.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..bf8a4b3a504af6a25e96aa08af5b69f8bd2e8199 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/ef/__pycache__/test_ollama_ef.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/ef/__pycache__/test_onnx_mini_lm_l6_v2.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/ef/__pycache__/test_onnx_mini_lm_l6_v2.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..cad1120c74893ab0353b219fb94ba69b8fa36411 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/ef/__pycache__/test_onnx_mini_lm_l6_v2.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/ef/__pycache__/test_openai_ef.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/ef/__pycache__/test_openai_ef.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..abd71f21e449576c43524d60491873fec4d1b9c4 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/ef/__pycache__/test_openai_ef.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/ef/__pycache__/test_voyageai_ef.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/ef/__pycache__/test_voyageai_ef.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3eb8610b2400586c44a30e008160f7fda47a5cb2 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/ef/__pycache__/test_voyageai_ef.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/ef/test_chroma_bm25_embedding_function.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/ef/test_chroma_bm25_embedding_function.py new file mode 100644 index 0000000000000000000000000000000000000000..6a73a9b99d7d9535178a08d006aaf39415033fec --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/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/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/ef/test_custom_ef.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/ef/test_custom_ef.py new file mode 100644 index 0000000000000000000000000000000000000000..c3290cdeb84c0c37d47f0e5f8e6758a6cec6b986 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/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/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/ef/test_default_ef.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/ef/test_default_ef.py new file mode 100644 index 0000000000000000000000000000000000000000..accedc6b5f373c16df2e4dfc36fa1b4f1ed4ce68 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/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/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/ef/test_ef.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/ef/test_ef.py new file mode 100644 index 0000000000000000000000000000000000000000..bd02a8e08218403b808fb6301d251a675df17cb5 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/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/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/ef/test_morph_ef.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/ef/test_morph_ef.py new file mode 100644 index 0000000000000000000000000000000000000000..6045b1a147e37b50feb2d5287ea8d0e245d4bf4a --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/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/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/ef/test_multimodal_ef.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/ef/test_multimodal_ef.py new file mode 100644 index 0000000000000000000000000000000000000000..e34c14d87a76022dce552df1509a979b782ebfdf --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/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/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/ef/test_ollama_ef.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/ef/test_ollama_ef.py new file mode 100644 index 0000000000000000000000000000000000000000..9705497b6d79a76825b9abe547f6ab576ee74b5b --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/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/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/ef/test_onnx_mini_lm_l6_v2.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/ef/test_onnx_mini_lm_l6_v2.py new file mode 100644 index 0000000000000000000000000000000000000000..edee2fa2f16754641cab5d0d5502a5ec009bb538 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/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/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/ef/test_openai_ef.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/ef/test_openai_ef.py new file mode 100644 index 0000000000000000000000000000000000000000..600613997adba65b27b73b2aaf778b065710ca76 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/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/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/ef/test_voyageai_ef.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/ef/test_voyageai_ef.py new file mode 100644 index 0000000000000000000000000000000000000000..fbf1c615b183c5102936b15023b9bb518a289d34 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/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/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/openssl.cnf b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/openssl.cnf new file mode 100644 index 0000000000000000000000000000000000000000..54e3c5bfdb1e88df66b3ae397427616d256bd8e5 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/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/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/property/__pycache__/invariants.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/property/__pycache__/invariants.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1999d632cf0c170581f02e9791fe1d482f9f429e Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/property/__pycache__/invariants.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/property/__pycache__/strategies.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/property/__pycache__/strategies.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..94f6006953a9af1dc1f97a0c4ab139942722ac55 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/property/__pycache__/strategies.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/property/__pycache__/test_add.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/property/__pycache__/test_add.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0c40136a4881aef28ca40c6fd9e9b323eaafe72b Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/property/__pycache__/test_add.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/property/__pycache__/test_add_gc.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/property/__pycache__/test_add_gc.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5018badd33d439634aa241db9604f2400117c611 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/property/__pycache__/test_add_gc.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/property/__pycache__/test_add_mcmr.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/property/__pycache__/test_add_mcmr.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0dcdbb361be0a769590f7ca8593d2100c1097c4f Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/property/__pycache__/test_add_mcmr.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/property/__pycache__/test_base64_conversion.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/property/__pycache__/test_base64_conversion.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..926433815967a82fa21f9b8a36c3ceb85c9115ec Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/property/__pycache__/test_base64_conversion.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/property/__pycache__/test_client_url.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/property/__pycache__/test_client_url.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3367f061fd7763f4ccac39cabf96e086b03fa0a6 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/property/__pycache__/test_client_url.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/property/__pycache__/test_collections.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/property/__pycache__/test_collections.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..dcac73170bb4f3fd626d7fc76c90229f1e17e8d3 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/property/__pycache__/test_collections.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/property/__pycache__/test_collections_with_database_tenant.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/property/__pycache__/test_collections_with_database_tenant.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..661e7224c681799d002ce69d4a8fdb46b03065b4 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/property/__pycache__/test_collections_with_database_tenant.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/property/__pycache__/test_collections_with_database_tenant_overwrite.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/property/__pycache__/test_collections_with_database_tenant_overwrite.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..89f6856546bde9591e6ca8e0ca84d9160a666cec Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/property/__pycache__/test_collections_with_database_tenant_overwrite.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/property/__pycache__/test_cross_version_persist.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/property/__pycache__/test_cross_version_persist.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..93f33f9766a1a41f745c644f966a92625edf33ea Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/property/__pycache__/test_cross_version_persist.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/property/__pycache__/test_embeddings.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/property/__pycache__/test_embeddings.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..235c2d707d91d9412ba61152ba45d076d53d2c36 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/property/__pycache__/test_embeddings.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/property/__pycache__/test_filtering.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/property/__pycache__/test_filtering.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..bfe6fedc73a0d691ff92e7507afecddcd7cbfdbd Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/property/__pycache__/test_filtering.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/property/__pycache__/test_fork.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/property/__pycache__/test_fork.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..699c1ab58f07f9fdc2c83f471d46c781848d9a05 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/property/__pycache__/test_fork.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/property/__pycache__/test_persist.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/property/__pycache__/test_persist.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8c4e39f05d5aa613f12e79a14ddfe0fe5d95b9f7 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/property/__pycache__/test_persist.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/property/__pycache__/test_restart_persist.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/property/__pycache__/test_restart_persist.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b0908bd0ab6cd40e12d9f06ce1edf7f47f9448ed Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/property/__pycache__/test_restart_persist.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/property/__pycache__/test_schema.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/property/__pycache__/test_schema.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..868eb5952dc7b3b181ea27c210d43d70484277fa Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/property/__pycache__/test_schema.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/property/invariants.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/property/invariants.py new file mode 100644 index 0000000000000000000000000000000000000000..9604ea457b7800176e828eb51fc78b5239b8cfd5 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/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/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/property/strategies.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/property/strategies.py new file mode 100644 index 0000000000000000000000000000000000000000..46cf4d2f7316d20cda01eebc41fee27babc4a8de --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/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/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/property/test_add.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/property/test_add.py new file mode 100644 index 0000000000000000000000000000000000000000..098f2b48efa720642893af2edda212704805a27f --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/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/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/property/test_add_gc.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/property/test_add_gc.py new file mode 100644 index 0000000000000000000000000000000000000000..f897febb553363a7b287b8e159f27451964b75c8 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/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/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/property/test_add_mcmr.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/property/test_add_mcmr.py new file mode 100644 index 0000000000000000000000000000000000000000..8b84aa03584903923f3689a0c923592160d8fa91 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/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/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/property/test_base64_conversion.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/property/test_base64_conversion.py new file mode 100644 index 0000000000000000000000000000000000000000..a9b1f27b4564b4602a1616d54da1107f5d4f1e95 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/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/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/property/test_client_url.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/property/test_client_url.py new file mode 100644 index 0000000000000000000000000000000000000000..5c243e978c8252233d36ed0655638c9be6f6974f --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/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/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/property/test_collections.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/property/test_collections.py new file mode 100644 index 0000000000000000000000000000000000000000..c1e4ed6ff0b8e4c19724e761ec809f9259b45148 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/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/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/property/test_collections_with_database_tenant.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/property/test_collections_with_database_tenant.py new file mode 100644 index 0000000000000000000000000000000000000000..93eeda3701ecdf8e687013a4760099add486fceb --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/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/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/property/test_collections_with_database_tenant_overwrite.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/property/test_collections_with_database_tenant_overwrite.py new file mode 100644 index 0000000000000000000000000000000000000000..9d83d83cd925a630bf442f5502bca198e3c06378 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/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/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/property/test_cross_version_persist.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/property/test_cross_version_persist.py new file mode 100644 index 0000000000000000000000000000000000000000..f7514309f52341d0f6d5aee0318b8d14c8e5ed2d --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/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/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/property/test_embeddings.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/property/test_embeddings.py new file mode 100644 index 0000000000000000000000000000000000000000..9279ca1a7e62ca029a831a269fe82b20a89527df --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/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/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/property/test_filtering.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/property/test_filtering.py new file mode 100644 index 0000000000000000000000000000000000000000..2f62d28356cef12beae50ebc0cf0bd5093c0754d --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/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/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/property/test_fork.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/property/test_fork.py new file mode 100644 index 0000000000000000000000000000000000000000..c78659813191720dc01e55430ae9eed2b6766cf9 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/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/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/property/test_persist.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/property/test_persist.py new file mode 100644 index 0000000000000000000000000000000000000000..973cd1e35e936fbfbac0e6ce03497d6cbf74ef9c --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/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/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/property/test_restart_persist.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/property/test_restart_persist.py new file mode 100644 index 0000000000000000000000000000000000000000..4d343d2c650afccf490bcae89747ed962bdd9ae1 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/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/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/property/test_schema.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/property/test_schema.py new file mode 100644 index 0000000000000000000000000000000000000000..5d10eac38b084324fadd7779abc73f7f3dddab88 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/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/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/segment/distributed/__pycache__/test_memberlist_provider.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/segment/distributed/__pycache__/test_memberlist_provider.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..71d06e2abd2db0b91e047eae5b5d7f875a5ace47 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/segment/distributed/__pycache__/test_memberlist_provider.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/segment/distributed/__pycache__/test_rendezvous_hash.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/segment/distributed/__pycache__/test_rendezvous_hash.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a29d014982c102715f53a08fc33444ae558e0dfb Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/segment/distributed/__pycache__/test_rendezvous_hash.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/segment/distributed/test_memberlist_provider.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/segment/distributed/test_memberlist_provider.py new file mode 100644 index 0000000000000000000000000000000000000000..d93aa1b227a3429539910726e9484795e599eb8d --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/segment/distributed/test_memberlist_provider.py @@ -0,0 +1,123 @@ +# Tests the CustomResourceMemberlist provider +from dataclasses import asdict +import threading +from chromadb.test.conftest import skip_if_not_cluster +from kubernetes import client, config +from chromadb.config import System, Settings +from chromadb.segment.distributed import Memberlist, Member +from chromadb.segment.impl.distributed.segment_directory import ( + CustomResourceMemberlistProvider, + KUBERNETES_GROUP, + KUBERNETES_NAMESPACE, +) +import time + + +# Used for testing to update the memberlist CRD +def update_memberlist(n: int, memberlist_name: str = "test-memberlist") -> Memberlist: + config.load_config() + api_instance = client.CustomObjectsApi() + + members = [ + Member(id=f"test-{i}", ip=f"10.0.0.{i}", node="node-{i}") + for i in range(1, n + 1) + ] + + body = { + "kind": "MemberList", + "metadata": {"name": memberlist_name}, + "spec": { + "members": [ + {"member_id": m.id, "member_ip": m.ip, "member_node_name": m.node} + for m in members + ] + }, + } + + _ = api_instance.patch_namespaced_custom_object( + group=KUBERNETES_GROUP, + version="v1", + namespace=KUBERNETES_NAMESPACE, + plural="memberlists", + name=memberlist_name, + body=body, + ) + + return members + + +def compare_memberlists(m1: Memberlist, m2: Memberlist) -> bool: + m1_as_dict = sorted([asdict(m) for m in m1], key=lambda x: x["id"]) + m2_as_dict = sorted([asdict(m) for m in m2], key=lambda x: x["id"]) + return m1_as_dict == m2_as_dict + + +@skip_if_not_cluster() +def test_can_get_memberlist() -> None: + # This test assumes that the memberlist CRD is already created with the name "test-memberlist" + system = System(Settings(allow_reset=True)) + provider = system.instance(CustomResourceMemberlistProvider) + provider.set_memberlist_name("test-memberlist") + system.reset_state() + system.start() + + # Update the memberlist + members = update_memberlist(3) + + # Check that the memberlist is updated after a short delay + time.sleep(2) + assert compare_memberlists(provider.get_memberlist(), members) + + system.stop() + + +@skip_if_not_cluster() +def test_can_update_memberlist_multiple_times() -> None: + # This test assumes that the memberlist CRD is already created with the name "test-memberlist" + system = System(Settings(allow_reset=True)) + provider = system.instance(CustomResourceMemberlistProvider) + provider.set_memberlist_name("test-memberlist") + system.reset_state() + system.start() + + # Update the memberlist + members = update_memberlist(3) + + # Check that the memberlist is updated after a short delay + time.sleep(2) + assert compare_memberlists(provider.get_memberlist(), members) + + # Update the memberlist again + members = update_memberlist(5) + + # Check that the memberlist is updated after a short delay + time.sleep(2) + assert compare_memberlists(provider.get_memberlist(), members) + + system.stop() + + +@skip_if_not_cluster() +def test_stop_memberlist_kills_thread() -> None: + # This test assumes that the memberlist CRD is already created with the name "test-memberlist" + system = System(Settings(allow_reset=True)) + provider = system.instance(CustomResourceMemberlistProvider) + provider.set_memberlist_name("test-memberlist") + system.reset_state() + system.start() + + # Make sure a background thread is running + assert len(threading.enumerate()) == 2 + + # Update the memberlist + members = update_memberlist(3) + + # Check that the memberlist is updated after a short delay + time.sleep(2) + assert compare_memberlists(provider.get_memberlist(), members) + + # Stop the system + system.stop() + + # Check to make sure only one thread is running + assert len(threading.enumerate()) == 1 diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/segment/distributed/test_rendezvous_hash.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/segment/distributed/test_rendezvous_hash.py new file mode 100644 index 0000000000000000000000000000000000000000..a8e9ad1e473c7a581e8f75084df0f23983ff33db --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/segment/distributed/test_rendezvous_hash.py @@ -0,0 +1,64 @@ +from chromadb.utils.rendezvous_hash import assign, murmur3hasher +from math import sqrt + + +def test_rendezvous_hash() -> None: + # Tests the assign works as expected + members = ["a", "b", "c"] + key = "key" + + def mock_hasher(member: str, key: str) -> int: + return members.index(member) # Highest index wins + + assert assign(key, members, mock_hasher, 1)[0] == "c" + + +def test_even_distribution() -> None: + member_count = 10 + num_keys = 1000 + nodes = [str(i) for i in range(member_count)] + + expected = num_keys / len(nodes) + # Std deviation of a binomial distribution is sqrt(n * p * (1 - p)) + # where n is the number of trials, and p is the probability of success + stddev = sqrt(num_keys * (1 / len(nodes)) * (1 - 1 / len(nodes))) + # https://en.wikipedia.org/wiki/68%E2%80%9395%E2%80%9399.7_rule + # For a 99.7% confidence interval + tolerance = 3 * stddev + + # Test if keys are evenly distributed across nodes + key_distribution = {node: 0 for node in nodes} + for i in range(num_keys): + key = f"key_{i}" + node = assign(key, nodes, murmur3hasher, 1)[0] + key_distribution[node] += 1 + + # Check if keys are somewhat evenly distributed + for node in nodes: + assert abs(key_distribution[node] - expected) < tolerance + + +def test_multi_assign_even_distribution() -> None: + member_count = 10 + num_keys = 10000 + replication = 3 + nodes = [str(i) for i in range(member_count)] + expected = num_keys / len(nodes) * replication + + stddev = sqrt(num_keys * replication * (1 / len(nodes)) * (1 - 1 / len(nodes))) + tolerance = 3 * stddev + + # Test if keys are evenly distributed across nodes + key_distribution = {node: 0 for node in nodes} + for i in range(num_keys): + key = f"key_{i}" + nodes_assigned = assign(key, nodes, murmur3hasher, replication) + # Should be three unique nodes + assert len(set(nodes_assigned)) == replication + for node in nodes_assigned: + key_distribution[node] += 1 + + # Check if keys are somewhat evenly distributed + for node in nodes: + # 3k keys expected for each node (10000 keys / 10 nodes * 3 replication) + assert abs(key_distribution[node] - expected) < tolerance diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/stress/__pycache__/test_many_collections.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/stress/__pycache__/test_many_collections.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ecf5e68df7add8ec035c8508fe0180fd0aa1243e Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/stress/__pycache__/test_many_collections.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/stress/test_many_collections.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/stress/test_many_collections.py new file mode 100644 index 0000000000000000000000000000000000000000..aad219b187a8a31821721db04061a03ab1d58867 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/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/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/test_api.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/test_api.py new file mode 100644 index 0000000000000000000000000000000000000000..33e931acc3dc2d59b4d27dd530da3ad05b094ab3 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/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/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/test_chroma.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/test_chroma.py new file mode 100644 index 0000000000000000000000000000000000000000..298fab10c18db18f1caf6647687dcb7367a3556a --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/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/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/test_cli.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/test_cli.py new file mode 100644 index 0000000000000000000000000000000000000000..85de1a059d94219641226044076dab709b6f861d --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/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/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/test_client.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/test_client.py new file mode 100644 index 0000000000000000000000000000000000000000..b21ec15be5682bf234db5e5ff8373c5e8db19847 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/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/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/test_config.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/test_config.py new file mode 100644 index 0000000000000000000000000000000000000000..f92a1723cebed8e32a132537b91dba7d40ce13c9 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/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/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/test_multithreaded.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/test_multithreaded.py new file mode 100644 index 0000000000000000000000000000000000000000..1859b1f7d3ac0a668d170dc8005fcfe448028c52 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/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/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/utils/__pycache__/cross_version.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/utils/__pycache__/cross_version.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..13b98db24d56cd87da69998dcca05345725cf627 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/utils/__pycache__/cross_version.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/utils/__pycache__/distance_functions.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/utils/__pycache__/distance_functions.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3569cc18be2879705ab12836d88ad276b22912bf Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/utils/__pycache__/distance_functions.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/utils/__pycache__/test_embedding_function_schemas.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/utils/__pycache__/test_embedding_function_schemas.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2afc813c7031937c837c61bee4ea93fc6150d3e4 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/utils/__pycache__/test_embedding_function_schemas.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/utils/__pycache__/test_result_df_transform.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/utils/__pycache__/test_result_df_transform.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ad43ce53471d99e18662466087dc14834f98f0d8 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/utils/__pycache__/test_result_df_transform.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/utils/__pycache__/test_wait_for_version_increase.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/utils/__pycache__/test_wait_for_version_increase.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3f65d23d9933d6488bb74de9a19650542c898272 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/utils/__pycache__/test_wait_for_version_increase.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/utils/__pycache__/wait_for_version_increase.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/utils/__pycache__/wait_for_version_increase.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..23c80b46d573d9bbacc0105eafb16c2c19489bcf Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/utils/__pycache__/wait_for_version_increase.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/utils/cross_version.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/utils/cross_version.py new file mode 100644 index 0000000000000000000000000000000000000000..c4b6dad21fcaf20f31baa2109ddd9e50be107c16 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/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/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/utils/distance_functions.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/utils/distance_functions.py new file mode 100644 index 0000000000000000000000000000000000000000..50c0fc927e0e47ec26cf823c0aac63140e0ebabc --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/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/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/utils/test_embedding_function_schemas.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/utils/test_embedding_function_schemas.py new file mode 100644 index 0000000000000000000000000000000000000000..b57d1bbc237de856928e0a423b92646497a2dbc7 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/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/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/utils/test_result_df_transform.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/utils/test_result_df_transform.py new file mode 100644 index 0000000000000000000000000000000000000000..8c6600b95c3a3df45e585dab97dc389990760bc6 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/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/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/utils/test_wait_for_version_increase.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/utils/test_wait_for_version_increase.py new file mode 100644 index 0000000000000000000000000000000000000000..d9d87a0acc9e2f8995d176691240f0673ee60628 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/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/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/utils/wait_for_version_increase.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/test/utils/wait_for_version_increase.py new file mode 100644 index 0000000000000000000000000000000000000000..ed4965b047f1875ff5d83617ead32f0ad3041e22 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/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/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/utils/__init__.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/utils/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..64f7239d7f0a44987939276b6c7e3b0b547e545d --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/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/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/utils/__pycache__/__init__.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/utils/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..70b8a692d66726688dffc2376c374dd96aa706c7 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/utils/__pycache__/__init__.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/utils/__pycache__/async_to_sync.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/utils/__pycache__/async_to_sync.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..938295286470a56e490b8338a7d273d3c3102af8 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/utils/__pycache__/async_to_sync.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/utils/__pycache__/batch_utils.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/utils/__pycache__/batch_utils.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..074b15d92853041c8793d523b607706839fab7bc Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/utils/__pycache__/batch_utils.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/utils/__pycache__/data_loaders.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/utils/__pycache__/data_loaders.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b4f492565cd0e455f1da42817649a32b4549ca8f Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/utils/__pycache__/data_loaders.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/utils/__pycache__/delete_file.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/utils/__pycache__/delete_file.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..33c539a23d1878d17f40845bed6937545f25069e Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/utils/__pycache__/delete_file.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/utils/__pycache__/directory.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/utils/__pycache__/directory.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..921408c65b6dfa869ff40ee0c3b8eac43fd4f477 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/utils/__pycache__/directory.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/utils/__pycache__/distance_functions.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/utils/__pycache__/distance_functions.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d669ddaa8719d14513bbbf0006757210dc432a0e Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/utils/__pycache__/distance_functions.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/utils/__pycache__/fastapi.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/utils/__pycache__/fastapi.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..113d233b72881d7fa7c360144c7d39da34e78f3f Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/utils/__pycache__/fastapi.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/utils/__pycache__/lru_cache.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/utils/__pycache__/lru_cache.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0de4d364e2fd64a213ca107cc0ee5248d4daf649 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/utils/__pycache__/lru_cache.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/utils/__pycache__/messageid.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/utils/__pycache__/messageid.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ece1affde35d6604abc999b29a57b9e88aab43cc Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/utils/__pycache__/messageid.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/utils/__pycache__/read_write_lock.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/utils/__pycache__/read_write_lock.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..03050a572ef143cb513d81423c18b61ffd1c9d4e Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/utils/__pycache__/read_write_lock.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/utils/__pycache__/rendezvous_hash.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/utils/__pycache__/rendezvous_hash.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d1533630b2b90cad8520d9f0c92c03b28ec49643 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/utils/__pycache__/rendezvous_hash.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/utils/__pycache__/results.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/utils/__pycache__/results.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..79030a3b403ea7df7ba06f5d0e2f6cea91403eb0 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/utils/__pycache__/results.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/utils/__pycache__/sparse_embedding_utils.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/utils/__pycache__/sparse_embedding_utils.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..cef56c88e873c8513c9839bf74df1ba8a50c70fb Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/utils/__pycache__/sparse_embedding_utils.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/utils/__pycache__/statistics.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/utils/__pycache__/statistics.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..799c2a55cff0ad73e2d58701f87d7f22e9c3610d Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/utils/__pycache__/statistics.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/utils/async_to_sync.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/utils/async_to_sync.py new file mode 100644 index 0000000000000000000000000000000000000000..0ee077bd24c17bb2c2b350f4796ff634c4b1a612 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/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/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/utils/batch_utils.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/utils/batch_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..5b824745340b659520931fabee1dd6a2c0faa75c --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/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/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/utils/data_loaders.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/utils/data_loaders.py new file mode 100644 index 0000000000000000000000000000000000000000..252c7bb9aab5010a52790bf8f3c99210a9725e62 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/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/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/utils/delete_file.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/utils/delete_file.py new file mode 100644 index 0000000000000000000000000000000000000000..ac3a12a479b91abc650271dcb299505365c3ffae --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/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/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/utils/directory.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/utils/directory.py new file mode 100644 index 0000000000000000000000000000000000000000..1942cd6de5d5d462dee2d71ca0039112eb230a50 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/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/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/utils/distance_functions.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/utils/distance_functions.py new file mode 100644 index 0000000000000000000000000000000000000000..d128507dcfaffd07d12d100851d8b13744dd69f7 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/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/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/utils/embedding_functions/__init__.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/utils/embedding_functions/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..d1052dab0a36be804049d58b6897b4c7605025b3 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/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/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/utils/embedding_functions/__pycache__/__init__.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/utils/embedding_functions/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6433894ced4f3f08837870c1b974217c63286109 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/utils/embedding_functions/__pycache__/__init__.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/utils/embedding_functions/__pycache__/amazon_bedrock_embedding_function.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/utils/embedding_functions/__pycache__/amazon_bedrock_embedding_function.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1f9c51fdc0cc59e9c367896be67771f6ab56e9f0 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/utils/embedding_functions/__pycache__/amazon_bedrock_embedding_function.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/utils/embedding_functions/__pycache__/baseten_embedding_function.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/utils/embedding_functions/__pycache__/baseten_embedding_function.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5b40ed57a089f125072ad2cb9c0f4fe6d5e8e279 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/utils/embedding_functions/__pycache__/baseten_embedding_function.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/utils/embedding_functions/__pycache__/bm25_embedding_function.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/utils/embedding_functions/__pycache__/bm25_embedding_function.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..df1cf172139133c9f99dd96d6b60a98164870345 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/utils/embedding_functions/__pycache__/bm25_embedding_function.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/utils/embedding_functions/__pycache__/chroma_bm25_embedding_function.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/utils/embedding_functions/__pycache__/chroma_bm25_embedding_function.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..491aab796a686b1ad49441fe89c147d066df40bb Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/utils/embedding_functions/__pycache__/chroma_bm25_embedding_function.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/utils/embedding_functions/__pycache__/chroma_cloud_qwen_embedding_function.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/utils/embedding_functions/__pycache__/chroma_cloud_qwen_embedding_function.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ac94b2f19d9e6abf40e3632c7e2b82b8d45295fa Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/utils/embedding_functions/__pycache__/chroma_cloud_qwen_embedding_function.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/utils/embedding_functions/__pycache__/chroma_cloud_splade_embedding_function.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/utils/embedding_functions/__pycache__/chroma_cloud_splade_embedding_function.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a6049aeafef560c584fb0c6a5235f82774e8f500 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/utils/embedding_functions/__pycache__/chroma_cloud_splade_embedding_function.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/utils/embedding_functions/__pycache__/chroma_langchain_embedding_function.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/utils/embedding_functions/__pycache__/chroma_langchain_embedding_function.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d731b635b1b32c692b9f4ee1faf66260ae7209dc Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/utils/embedding_functions/__pycache__/chroma_langchain_embedding_function.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/utils/embedding_functions/__pycache__/cloudflare_workers_ai_embedding_function.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/utils/embedding_functions/__pycache__/cloudflare_workers_ai_embedding_function.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1e277ec9dd76287afb671ba89d68d46ed5cf4923 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/utils/embedding_functions/__pycache__/cloudflare_workers_ai_embedding_function.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/utils/embedding_functions/__pycache__/cohere_embedding_function.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/utils/embedding_functions/__pycache__/cohere_embedding_function.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d611fa9e2fa5993ebde27ee9fe47750a9811ebdc Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/utils/embedding_functions/__pycache__/cohere_embedding_function.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/utils/embedding_functions/__pycache__/fastembed_sparse_embedding_function.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/utils/embedding_functions/__pycache__/fastembed_sparse_embedding_function.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..273e71f984a9e925ab0276dbe6afa68b0e7e7879 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/utils/embedding_functions/__pycache__/fastembed_sparse_embedding_function.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/utils/embedding_functions/__pycache__/google_embedding_function.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/utils/embedding_functions/__pycache__/google_embedding_function.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7d72fcbfadb590ef3e318633d532df667ba6dea7 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/utils/embedding_functions/__pycache__/google_embedding_function.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/utils/embedding_functions/__pycache__/huggingface_embedding_function.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/utils/embedding_functions/__pycache__/huggingface_embedding_function.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d84f8c358bf5574044508f89865986d8468e19ef Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/utils/embedding_functions/__pycache__/huggingface_embedding_function.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/utils/embedding_functions/__pycache__/huggingface_sparse_embedding_function.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/utils/embedding_functions/__pycache__/huggingface_sparse_embedding_function.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a380011727b88a2406f673312487aa57f2f92bfc Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/utils/embedding_functions/__pycache__/huggingface_sparse_embedding_function.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/utils/embedding_functions/__pycache__/instructor_embedding_function.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/utils/embedding_functions/__pycache__/instructor_embedding_function.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7c1443331a2843b79b070659e091dd11c59f661f Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/utils/embedding_functions/__pycache__/instructor_embedding_function.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/utils/embedding_functions/__pycache__/jina_embedding_function.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/utils/embedding_functions/__pycache__/jina_embedding_function.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..865b7f8faaae9e8eb3ccc8489f9e51298281a02c Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/utils/embedding_functions/__pycache__/jina_embedding_function.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/utils/embedding_functions/__pycache__/mistral_embedding_function.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/utils/embedding_functions/__pycache__/mistral_embedding_function.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e41f54ab6c22f652f7c50cc190523645795cd3bc Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/utils/embedding_functions/__pycache__/mistral_embedding_function.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/utils/embedding_functions/__pycache__/morph_embedding_function.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/utils/embedding_functions/__pycache__/morph_embedding_function.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b4ba5c0703b3bad11f409d4261636e3a0aba91ed Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/utils/embedding_functions/__pycache__/morph_embedding_function.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/utils/embedding_functions/__pycache__/nomic_embedding_function.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/utils/embedding_functions/__pycache__/nomic_embedding_function.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e134de0724a613a3ab6d565260848b546dcedcb5 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/utils/embedding_functions/__pycache__/nomic_embedding_function.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/utils/embedding_functions/__pycache__/ollama_embedding_function.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/utils/embedding_functions/__pycache__/ollama_embedding_function.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5543664182170db28c4c065deaf0fdd9bc0a996d Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/utils/embedding_functions/__pycache__/ollama_embedding_function.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/utils/embedding_functions/__pycache__/onnx_mini_lm_l6_v2.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/utils/embedding_functions/__pycache__/onnx_mini_lm_l6_v2.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7fd96fc14354840ea81e115644bcc4cc973d1bf7 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/utils/embedding_functions/__pycache__/onnx_mini_lm_l6_v2.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/utils/embedding_functions/__pycache__/open_clip_embedding_function.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/utils/embedding_functions/__pycache__/open_clip_embedding_function.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9af6fec251427f859f2efb30220a715326e7881d Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/utils/embedding_functions/__pycache__/open_clip_embedding_function.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/utils/embedding_functions/__pycache__/openai_embedding_function.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/utils/embedding_functions/__pycache__/openai_embedding_function.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..98b5ed947b086c624194aab6e04ffbe29ff1271b Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/utils/embedding_functions/__pycache__/openai_embedding_function.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/utils/embedding_functions/__pycache__/perplexity_embedding_function.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/utils/embedding_functions/__pycache__/perplexity_embedding_function.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4762e7068245e7d692862ffd00528e66d90f2cfe Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/utils/embedding_functions/__pycache__/perplexity_embedding_function.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/utils/embedding_functions/__pycache__/roboflow_embedding_function.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/utils/embedding_functions/__pycache__/roboflow_embedding_function.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..51fab8730b2215874dc6179e619dd2566c89432d Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/utils/embedding_functions/__pycache__/roboflow_embedding_function.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/utils/embedding_functions/__pycache__/sentence_transformer_embedding_function.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/utils/embedding_functions/__pycache__/sentence_transformer_embedding_function.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e53f5714155030cf4b9ce453726eee683abeda64 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/utils/embedding_functions/__pycache__/sentence_transformer_embedding_function.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/utils/embedding_functions/__pycache__/text2vec_embedding_function.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/utils/embedding_functions/__pycache__/text2vec_embedding_function.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3a66a3fde27a5ba7bdae7f40d19b4d496e05bc84 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/utils/embedding_functions/__pycache__/text2vec_embedding_function.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/utils/embedding_functions/__pycache__/together_ai_embedding_function.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/utils/embedding_functions/__pycache__/together_ai_embedding_function.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..bd0dcc3004badb84f090f33bb20a75a03089bb00 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/utils/embedding_functions/__pycache__/together_ai_embedding_function.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/utils/embedding_functions/__pycache__/utils.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/utils/embedding_functions/__pycache__/utils.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9bed907f0b747649310862aafbaa3e009e2914f5 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/utils/embedding_functions/__pycache__/utils.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/utils/embedding_functions/__pycache__/voyageai_embedding_function.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/utils/embedding_functions/__pycache__/voyageai_embedding_function.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3225a8a8cb7b99330c50bdcba54f0d22d6520a03 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/utils/embedding_functions/__pycache__/voyageai_embedding_function.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/utils/embedding_functions/amazon_bedrock_embedding_function.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/utils/embedding_functions/amazon_bedrock_embedding_function.py new file mode 100644 index 0000000000000000000000000000000000000000..91d10769cf699947ccb45f00a7a728b745611d74 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/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/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/utils/embedding_functions/baseten_embedding_function.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/utils/embedding_functions/baseten_embedding_function.py new file mode 100644 index 0000000000000000000000000000000000000000..96829c69726e51747ea561d94e396a2113aef7e0 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/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/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/utils/embedding_functions/bm25_embedding_function.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/utils/embedding_functions/bm25_embedding_function.py new file mode 100644 index 0000000000000000000000000000000000000000..5fd10339f7546cafca7816a2b22967dd59075365 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/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/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/utils/embedding_functions/chroma_bm25_embedding_function.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/utils/embedding_functions/chroma_bm25_embedding_function.py new file mode 100644 index 0000000000000000000000000000000000000000..56362bc8c1e98d4573554c3c0934330fa3dff24b --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/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/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/utils/embedding_functions/chroma_cloud_qwen_embedding_function.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/utils/embedding_functions/chroma_cloud_qwen_embedding_function.py new file mode 100644 index 0000000000000000000000000000000000000000..69f3e5d715e6c41d01e915a81aec8d2fb75461b9 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/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/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/utils/embedding_functions/chroma_cloud_splade_embedding_function.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/utils/embedding_functions/chroma_cloud_splade_embedding_function.py new file mode 100644 index 0000000000000000000000000000000000000000..5627a6ef0982ebd2a671034a5e8b19aebe27ccb8 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/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/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/utils/embedding_functions/chroma_langchain_embedding_function.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/utils/embedding_functions/chroma_langchain_embedding_function.py new file mode 100644 index 0000000000000000000000000000000000000000..ed5c22db18a8017ac711762a6ca2609e466225a1 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/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/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/utils/embedding_functions/cloudflare_workers_ai_embedding_function.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/utils/embedding_functions/cloudflare_workers_ai_embedding_function.py new file mode 100644 index 0000000000000000000000000000000000000000..d587f471a656c3ff93b3b9cb3063f5296a7ea128 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/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/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/utils/embedding_functions/cohere_embedding_function.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/utils/embedding_functions/cohere_embedding_function.py new file mode 100644 index 0000000000000000000000000000000000000000..9e1a6664f937986bcc82287e0ff4a3b0695b4107 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/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/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/utils/embedding_functions/fastembed_sparse_embedding_function.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/utils/embedding_functions/fastembed_sparse_embedding_function.py new file mode 100644 index 0000000000000000000000000000000000000000..53fb570fbefa3dab6fc8a08aee90501a66c2acc3 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/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/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/utils/embedding_functions/google_embedding_function.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/utils/embedding_functions/google_embedding_function.py new file mode 100644 index 0000000000000000000000000000000000000000..67796dab8e446cf61e9ce49a911bcb1830da1f01 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/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/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/utils/embedding_functions/huggingface_embedding_function.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/utils/embedding_functions/huggingface_embedding_function.py new file mode 100644 index 0000000000000000000000000000000000000000..fd980a17742b810ab71ecc270de6d9bd3ad47ba9 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/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/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/utils/embedding_functions/huggingface_sparse_embedding_function.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/utils/embedding_functions/huggingface_sparse_embedding_function.py new file mode 100644 index 0000000000000000000000000000000000000000..0bbbea321d7c47a5d3e1763b1e728e8fac1f18a9 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/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/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/utils/embedding_functions/instructor_embedding_function.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/utils/embedding_functions/instructor_embedding_function.py new file mode 100644 index 0000000000000000000000000000000000000000..13de23058647d9406fe8ceb1509bb02c2af0b2a7 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/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/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/utils/embedding_functions/jina_embedding_function.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/utils/embedding_functions/jina_embedding_function.py new file mode 100644 index 0000000000000000000000000000000000000000..150285b2e695cd4e8d55caa49edb98d7e09f1f23 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/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/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/utils/embedding_functions/mistral_embedding_function.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/utils/embedding_functions/mistral_embedding_function.py new file mode 100644 index 0000000000000000000000000000000000000000..1d1b10e2e4dc3b392b178a8c203a7e8a419fde01 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/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/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/utils/embedding_functions/morph_embedding_function.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/utils/embedding_functions/morph_embedding_function.py new file mode 100644 index 0000000000000000000000000000000000000000..6004914e0e1fe261bd0296af1b7af4e30ef98321 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/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/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/utils/embedding_functions/nomic_embedding_function.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/utils/embedding_functions/nomic_embedding_function.py new file mode 100644 index 0000000000000000000000000000000000000000..be8cb883d716a1dedfc47a417bf0f3a72fcf67ba --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/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/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/utils/embedding_functions/ollama_embedding_function.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/utils/embedding_functions/ollama_embedding_function.py new file mode 100644 index 0000000000000000000000000000000000000000..fb5ab214bfe179bce27e8f1022778f0828657a60 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/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/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/utils/embedding_functions/onnx_mini_lm_l6_v2.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/utils/embedding_functions/onnx_mini_lm_l6_v2.py new file mode 100644 index 0000000000000000000000000000000000000000..a937ed00683c35b0242fd21da116b153cbac017e --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/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/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/utils/embedding_functions/open_clip_embedding_function.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/utils/embedding_functions/open_clip_embedding_function.py new file mode 100644 index 0000000000000000000000000000000000000000..42401fc25ff3124460161d44bb9dae1db3353f8a --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/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/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/utils/embedding_functions/openai_embedding_function.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/utils/embedding_functions/openai_embedding_function.py new file mode 100644 index 0000000000000000000000000000000000000000..26d0c7f2553eb70b6136f04ddb4c7e2def7348fd --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/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/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/utils/embedding_functions/perplexity_embedding_function.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/utils/embedding_functions/perplexity_embedding_function.py new file mode 100644 index 0000000000000000000000000000000000000000..f1bbdcfa0dc279876f951f2f2ad301ed16ee7ccd --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/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/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/utils/embedding_functions/roboflow_embedding_function.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/utils/embedding_functions/roboflow_embedding_function.py new file mode 100644 index 0000000000000000000000000000000000000000..1366941069812c87bdc17622bd6487d15500f59f --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/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/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/utils/embedding_functions/schemas/README.md b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/utils/embedding_functions/schemas/README.md new file mode 100644 index 0000000000000000000000000000000000000000..d060817257dddb8f234189120fd81fa05702b51d --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/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/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/utils/embedding_functions/schemas/__init__.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/utils/embedding_functions/schemas/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..4f7596cdc255b69de40eaff1daf26aaaa5a24a3d --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/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/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/utils/embedding_functions/schemas/__pycache__/__init__.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/utils/embedding_functions/schemas/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..12f7f7f2ac1e03fdf1a500addb9a9a88c35e17e0 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/utils/embedding_functions/schemas/__pycache__/__init__.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/utils/embedding_functions/schemas/__pycache__/bm25_tokenizer.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/utils/embedding_functions/schemas/__pycache__/bm25_tokenizer.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b15e6f847305648de797576fdd1231bcc9d39f49 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/utils/embedding_functions/schemas/__pycache__/bm25_tokenizer.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/utils/embedding_functions/schemas/__pycache__/registry.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/utils/embedding_functions/schemas/__pycache__/registry.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..43bcce10891a9197e9395efb0a18d7ca1181369e Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/utils/embedding_functions/schemas/__pycache__/registry.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/utils/embedding_functions/schemas/__pycache__/schema_utils.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/utils/embedding_functions/schemas/__pycache__/schema_utils.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..33fd1e5063180dd4f0fe13d937da073e8099ea57 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/utils/embedding_functions/schemas/__pycache__/schema_utils.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/utils/embedding_functions/schemas/bm25_tokenizer.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/utils/embedding_functions/schemas/bm25_tokenizer.py new file mode 100644 index 0000000000000000000000000000000000000000..895f2edd5b0ea6d0efdfdc890f10bb29ef53486f --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/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/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/utils/embedding_functions/schemas/registry.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/utils/embedding_functions/schemas/registry.py new file mode 100644 index 0000000000000000000000000000000000000000..02de07a0a9205997b114c51abe52bc6faf9c435f --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/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/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/utils/embedding_functions/schemas/schema_utils.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/utils/embedding_functions/schemas/schema_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..a9c14cf384ebd96b3d7cb278d7c5fea34c44dd7d --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/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/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/utils/embedding_functions/sentence_transformer_embedding_function.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/utils/embedding_functions/sentence_transformer_embedding_function.py new file mode 100644 index 0000000000000000000000000000000000000000..2ddcef6bf2cfe698e0aa8a23beb98a72c45badb7 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/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/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/utils/embedding_functions/text2vec_embedding_function.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/utils/embedding_functions/text2vec_embedding_function.py new file mode 100644 index 0000000000000000000000000000000000000000..1de67f66e40a4d23943a8b798bf5679cce39c460 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/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/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/utils/embedding_functions/together_ai_embedding_function.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/utils/embedding_functions/together_ai_embedding_function.py new file mode 100644 index 0000000000000000000000000000000000000000..7489731eb69d000b4d8dce5ab33fc5dcae330bfe --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/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/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/utils/embedding_functions/utils.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/utils/embedding_functions/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..aa045e1de92cc8bcea990f8d7f05053c2b4ef5fb --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/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/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/utils/embedding_functions/voyageai_embedding_function.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/utils/embedding_functions/voyageai_embedding_function.py new file mode 100644 index 0000000000000000000000000000000000000000..c67647988d2550e33b7d3ead38c39fc189acb2f7 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/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/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/utils/fastapi.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/utils/fastapi.py new file mode 100644 index 0000000000000000000000000000000000000000..8179cd9c9b6e48822e777bb42f9c169b32c20a7c --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/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/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/utils/lru_cache.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/utils/lru_cache.py new file mode 100644 index 0000000000000000000000000000000000000000..92450e7e83fd7de1b232efca87fad430de19d6f1 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/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/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/utils/messageid.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/utils/messageid.py new file mode 100644 index 0000000000000000000000000000000000000000..7df4bc64f128944d6a5688496111482cb9854bd2 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/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/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/utils/read_write_lock.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/utils/read_write_lock.py new file mode 100644 index 0000000000000000000000000000000000000000..b6d78cc9492676b56ca8466772b86686d62f80d3 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/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/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/utils/rendezvous_hash.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/utils/rendezvous_hash.py new file mode 100644 index 0000000000000000000000000000000000000000..27847b00ef5f4b560a09310e1870c3dea77ffb4c --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/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/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/utils/results.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/utils/results.py new file mode 100644 index 0000000000000000000000000000000000000000..bdc80961ef647a2b70adebee3d54db0673ddb528 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/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/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/utils/sparse_embedding_utils.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/utils/sparse_embedding_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..4e4d726ed14b8f0571f7892d31d5262db8c34afc --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/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/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/utils/statistics.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb/utils/statistics.py new file mode 100644 index 0000000000000000000000000000000000000000..a2847ca46002dcbec8e6e2569c0ffaddc8623916 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/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/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb_rust_bindings/__pycache__/__init__.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb_rust_bindings/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..65952fd4db1f21a02c4d0a46db98f9cda3ec4237 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/chromadb_rust_bindings/__pycache__/__init__.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/click-8.3.3.dist-info/licenses/LICENSE.txt b/micromamba_root/envs/pytorch_env/Lib/site-packages/click-8.3.3.dist-info/licenses/LICENSE.txt new file mode 100644 index 0000000000000000000000000000000000000000..d12a849186982399c537c5b9a8fd77bf2edd5eab --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/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/micromamba_root/envs/pytorch_env/Lib/site-packages/click/__pycache__/__init__.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/click/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e84fbf75214a08e019928b2b90e89ac17f1ff10e Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/click/__pycache__/__init__.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/click/__pycache__/_compat.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/click/__pycache__/_compat.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..78fd767ca7fd553b1861d5f1f93991673179c100 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/click/__pycache__/_compat.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/click/__pycache__/_termui_impl.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/click/__pycache__/_termui_impl.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d79ac75317f20c34a7220453ef1557ca3d8a6a53 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/click/__pycache__/_termui_impl.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/click/__pycache__/_textwrap.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/click/__pycache__/_textwrap.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6d1e086204c5f58bbf4e6c63f8311355ac022fdc Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/click/__pycache__/_textwrap.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/click/__pycache__/_utils.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/click/__pycache__/_utils.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..54c260de5139e7d4c48d2e7a56c9b927f0ad7d87 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/click/__pycache__/_utils.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/click/__pycache__/_winconsole.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/click/__pycache__/_winconsole.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6423c2825c41a5114427fedf721d77ee3f1cad65 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/click/__pycache__/_winconsole.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/click/__pycache__/decorators.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/click/__pycache__/decorators.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..846e7b8cc4a8dd2ed11fcc8d0a9562b3921367a9 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/click/__pycache__/decorators.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/click/__pycache__/exceptions.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/click/__pycache__/exceptions.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..98faebf91e3614be1b4debcc691706d31fc7e9c7 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/click/__pycache__/exceptions.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/click/__pycache__/formatting.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/click/__pycache__/formatting.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..475fdc9a611784bb50d0eaab7d568c84a26313d5 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/click/__pycache__/formatting.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/click/__pycache__/globals.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/click/__pycache__/globals.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7397ed5a1aef38231c4490fc3fc5d9e0ff6cbc2e Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/click/__pycache__/globals.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/click/__pycache__/parser.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/click/__pycache__/parser.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..84e0184965b697d678d5adafd79dc1eac554c485 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/click/__pycache__/parser.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/click/__pycache__/shell_completion.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/click/__pycache__/shell_completion.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b74dd184f2e7d9d1455473d1c8c4010e86ba4e81 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/click/__pycache__/shell_completion.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/click/__pycache__/termui.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/click/__pycache__/termui.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..26cd23f6eb4cdea6fff7b9fdf2c8c64f80627bff Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/click/__pycache__/termui.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/click/__pycache__/testing.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/click/__pycache__/testing.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b7d9bd47adc6255261650927ea0d9c4e2cb4fc2a Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/click/__pycache__/testing.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/click/__pycache__/types.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/click/__pycache__/types.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..bc11acccf4c7c0f4ef1b2c63b5abca077560d1da Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/click/__pycache__/types.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/click/__pycache__/utils.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/click/__pycache__/utils.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2a891a99d7d16842f5a976376cad483579a13389 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/click/__pycache__/utils.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/colorama-0.4.6.dist-info/licenses/LICENSE.txt b/micromamba_root/envs/pytorch_env/Lib/site-packages/colorama-0.4.6.dist-info/licenses/LICENSE.txt new file mode 100644 index 0000000000000000000000000000000000000000..3105888ec149d10cad51c11d332779e94b548661 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/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/micromamba_root/envs/pytorch_env/Lib/site-packages/colorama/__pycache__/__init__.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/colorama/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4d76bc0e82f40cf9012d6253d6372bd706d6a463 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/colorama/__pycache__/__init__.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/colorama/__pycache__/ansi.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/colorama/__pycache__/ansi.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..661078118ec43f11417909f698826ab11b372cf7 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/colorama/__pycache__/ansi.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/colorama/__pycache__/ansitowin32.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/colorama/__pycache__/ansitowin32.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8347acd0032b9622311aa29338f4009fd22b941c Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/colorama/__pycache__/ansitowin32.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/colorama/__pycache__/initialise.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/colorama/__pycache__/initialise.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5d6f46bb755eb0063dbb03c8761e059f2a85d2c5 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/colorama/__pycache__/initialise.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/colorama/__pycache__/win32.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/colorama/__pycache__/win32.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..544ac0b745631a4f7c530514d9807094a6d485fa Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/colorama/__pycache__/win32.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/colorama/__pycache__/winterm.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/colorama/__pycache__/winterm.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b49b9918a4c04a79a247aaad5a604bb45847349f Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/colorama/__pycache__/winterm.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/colorama/tests/__init__.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/colorama/tests/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..8c5661e93a205bf4fb22404d4fc50f902cc31369 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/colorama/tests/__init__.py @@ -0,0 +1 @@ +# Copyright Jonathan Hartley 2013. BSD 3-Clause license, see LICENSE file. diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/colorama/tests/__pycache__/__init__.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/colorama/tests/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..be6c84c9a124363c2dbe66e4dfcdc738d3b4aa9d Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/colorama/tests/__pycache__/__init__.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/colorama/tests/__pycache__/ansi_test.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/colorama/tests/__pycache__/ansi_test.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..808abf6fb1e8cd667976eaa974d0578bd1d7532d Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/colorama/tests/__pycache__/ansi_test.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/colorama/tests/__pycache__/ansitowin32_test.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/colorama/tests/__pycache__/ansitowin32_test.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..febe545b01ea0efbd0505c195bee112b859632f7 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/colorama/tests/__pycache__/ansitowin32_test.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/colorama/tests/__pycache__/initialise_test.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/colorama/tests/__pycache__/initialise_test.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c8b4c3ff3445001803f5b1beb67bbeeef831171a Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/colorama/tests/__pycache__/initialise_test.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/colorama/tests/__pycache__/isatty_test.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/colorama/tests/__pycache__/isatty_test.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..aebeb5770f648a4d23a435ce3722234758eeeb46 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/colorama/tests/__pycache__/isatty_test.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/colorama/tests/__pycache__/utils.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/colorama/tests/__pycache__/utils.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..eb317deca84e1f879240d2ac334b47a8a0d8f255 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/colorama/tests/__pycache__/utils.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/colorama/tests/__pycache__/winterm_test.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/colorama/tests/__pycache__/winterm_test.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..fe8f64ca1b0912000936df1551a710791fb4e675 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/colorama/tests/__pycache__/winterm_test.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/colorama/tests/ansi_test.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/colorama/tests/ansi_test.py new file mode 100644 index 0000000000000000000000000000000000000000..0a20c80f882066e0e1323b0c7f61e22913c32e35 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/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/micromamba_root/envs/pytorch_env/Lib/site-packages/colorama/tests/ansitowin32_test.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/colorama/tests/ansitowin32_test.py new file mode 100644 index 0000000000000000000000000000000000000000..91ca551f97b4576c680711e826a1855fb944c872 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/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/micromamba_root/envs/pytorch_env/Lib/site-packages/colorama/tests/initialise_test.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/colorama/tests/initialise_test.py new file mode 100644 index 0000000000000000000000000000000000000000..89f9b07511c8fee74686d9cc434bf66345a46d6d --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/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/micromamba_root/envs/pytorch_env/Lib/site-packages/colorama/tests/isatty_test.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/colorama/tests/isatty_test.py new file mode 100644 index 0000000000000000000000000000000000000000..0f84e4befe550d4386d24264648abf1323e682ff --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/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/micromamba_root/envs/pytorch_env/Lib/site-packages/colorama/tests/utils.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/colorama/tests/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..472fafb4403efb9673d5cc724dafd9cf764aac5b --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/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/micromamba_root/envs/pytorch_env/Lib/site-packages/colorama/tests/winterm_test.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/colorama/tests/winterm_test.py new file mode 100644 index 0000000000000000000000000000000000000000..d0955f9e608377940f0d548576964f2fcf3caf48 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/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/micromamba_root/envs/pytorch_env/Lib/site-packages/dataclasses_json/__pycache__/__init__.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/dataclasses_json/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..43077fcd7e0b66f24db39909f4964f13194eee5b Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/dataclasses_json/__pycache__/__init__.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/dataclasses_json/__pycache__/__version__.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/dataclasses_json/__pycache__/__version__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7f1fa565ec0164b07e1a154f45b5124a872d9e48 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/dataclasses_json/__pycache__/__version__.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/dataclasses_json/__pycache__/api.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/dataclasses_json/__pycache__/api.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3b4864031e39d9eec5736bb6c7f6827f4d963b57 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/dataclasses_json/__pycache__/api.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/dataclasses_json/__pycache__/cfg.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/dataclasses_json/__pycache__/cfg.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e354ce41fa9d079f23059b4e71e811b26c654ff7 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/dataclasses_json/__pycache__/cfg.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/dataclasses_json/__pycache__/core.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/dataclasses_json/__pycache__/core.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..35ef5157a782e3674cb5dde732fe299a3f5bbdbc Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/dataclasses_json/__pycache__/core.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/dataclasses_json/__pycache__/mm.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/dataclasses_json/__pycache__/mm.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..dc0d4dd3f3758baaa84dcc16f217232d3c661a45 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/dataclasses_json/__pycache__/mm.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/dataclasses_json/__pycache__/stringcase.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/dataclasses_json/__pycache__/stringcase.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8bf9a74f911e723cca046d112a239de94e55284d Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/dataclasses_json/__pycache__/stringcase.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/dataclasses_json/__pycache__/undefined.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/dataclasses_json/__pycache__/undefined.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..214bd30714b4498e62e69eb1c71395526703ea73 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/dataclasses_json/__pycache__/undefined.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/dataclasses_json/__pycache__/utils.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/dataclasses_json/__pycache__/utils.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3292f142c41519319f81eae8f6880865b6890878 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/dataclasses_json/__pycache__/utils.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/dateutil/__pycache__/__init__.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/dateutil/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..18bfe74410d01d4bbe25ea4e8b5112dddaa75ac8 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/dateutil/__pycache__/__init__.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/dateutil/__pycache__/_common.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/dateutil/__pycache__/_common.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a2a51606ebf5eb478a822be6c8beef1a8c0ecf02 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/dateutil/__pycache__/_common.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/dateutil/__pycache__/_version.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/dateutil/__pycache__/_version.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5a4e832ae65e065d2b00c5a3147b92f975dbcf35 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/dateutil/__pycache__/_version.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/dateutil/__pycache__/relativedelta.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/dateutil/__pycache__/relativedelta.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..346dbfe745b4bb060450c99c5b41eb9e398e73b5 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/dateutil/__pycache__/relativedelta.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/dateutil/__pycache__/rrule.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/dateutil/__pycache__/rrule.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7912adda101e4b3a32d5e7f0946afa2dc928bafd Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/dateutil/__pycache__/rrule.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/dateutil/__pycache__/tzwin.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/dateutil/__pycache__/tzwin.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1f5324efe333672d7adb78891363d40a4f7b3ced Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/dateutil/__pycache__/tzwin.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/dateutil/__pycache__/utils.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/dateutil/__pycache__/utils.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..943f918a125bdd10573f4f0a53f1b63a86c2d42c Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/dateutil/__pycache__/utils.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/dateutil/parser/__pycache__/__init__.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/dateutil/parser/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..34cd104b0d4b7752fbeb96498ef70c057341cfee Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/dateutil/parser/__pycache__/__init__.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/dateutil/parser/__pycache__/_parser.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/dateutil/parser/__pycache__/_parser.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..256ad22487cf4bc45a40bd5f6c7ebf1e5723719a Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/dateutil/parser/__pycache__/_parser.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/dateutil/parser/__pycache__/isoparser.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/dateutil/parser/__pycache__/isoparser.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2af6dfddc97580e1508ec00ccc064c69314e1254 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/dateutil/parser/__pycache__/isoparser.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/dateutil/tz/__pycache__/__init__.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/dateutil/tz/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..396c75cbdf344784a90ff5bfd716466b90a4a032 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/dateutil/tz/__pycache__/__init__.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/dateutil/tz/__pycache__/_common.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/dateutil/tz/__pycache__/_common.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8057edcce44ce22e2df2f44d84ede99509a8549d Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/dateutil/tz/__pycache__/_common.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/dateutil/tz/__pycache__/_factories.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/dateutil/tz/__pycache__/_factories.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..321d650e4c43a3971f34da7c4d3cab58f034f5ce Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/dateutil/tz/__pycache__/_factories.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/dateutil/tz/__pycache__/tz.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/dateutil/tz/__pycache__/tz.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ef7168aa4f991db6420e62dd47c1aa8ac377c182 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/dateutil/tz/__pycache__/tz.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/dateutil/tz/__pycache__/win.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/dateutil/tz/__pycache__/win.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..afd09f432d9185a164fd0f09825be29295fa9ebe Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/dateutil/tz/__pycache__/win.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/dateutil/zoneinfo/__pycache__/__init__.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/dateutil/zoneinfo/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a208ff8ee259cc9de8579a892049dbdfddcd6f59 Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/dateutil/zoneinfo/__pycache__/__init__.cpython-311.pyc differ diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/dateutil/zoneinfo/__pycache__/rebuild.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/dateutil/zoneinfo/__pycache__/rebuild.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..acca89649f8d50c5b81b12d9630f29c1ce68105e Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/dateutil/zoneinfo/__pycache__/rebuild.cpython-311.pyc differ