File size: 43,713 Bytes
b3d711f | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 | 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
|