Skip to content

Commit 413174d

Browse files
authored
[BLD] Python & misc lint fixes (chroma-core#2046)
1 parent df65e5a commit 413174d

File tree

87 files changed

+4488
-3372
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

87 files changed

+4488
-3372
lines changed

Diff for: .github/workflows/chroma-lint.yml

+12-2
Original file line numberDiff line numberDiff line change
@@ -13,5 +13,15 @@ jobs:
1313
- name: Install pre-commit
1414
run: python -m pip install -r requirements_dev.txt
1515
- name: Run pre-commit
16-
# todo: remove || true once lint issues are resolved
17-
run: pre-commit run --all-files || true
16+
run: |
17+
pre-commit run --all-files trailing-whitespace
18+
pre-commit run --all-files mixed-line-ending
19+
pre-commit run --all-files end-of-file-fixer
20+
pre-commit run --all-files requirements-txt-fixer
21+
pre-commit run --all-files check-xml
22+
pre-commit run --all-files check-merge-conflict
23+
pre-commit run --all-files check-case-conflict
24+
pre-commit run --all-files check-docstring-first
25+
pre-commit run --all-files black
26+
pre-commit run --all-files flake8
27+
pre-commit run --all-files prettier

Diff for: .github/workflows/release-helm-chart.yml

+1-1
Original file line numberDiff line numberDiff line change
@@ -27,4 +27,4 @@ jobs:
2727
workflow_id: 'copy-oss-helm.yaml',
2828
ref: 'main'
2929
})
30-
console.log(result)
30+
console.log(result)

Diff for: .pre-commit-config.yaml

+22-4
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,12 @@
1-
exclude: 'chromadb/proto/(chroma_pb2|coordinator_pb2)\.(py|pyi|py_grpc\.py)' # Generated files
1+
exclude: 'chromadb/proto/(chroma_pb2|coordinator_pb2|logservice_pb2)\.(py|pyi|py_grpc\.py)' # Generated files
22
repos:
33
- repo: https://github.com/pre-commit/pre-commit-hooks
44
rev: v4.5.0
55
hooks:
66
- id: trailing-whitespace
77
- id: mixed-line-ending
88
- id: end-of-file-fixer
9+
exclude: "go/migrations"
910
- id: requirements-txt-fixer
1011
- id: check-yaml
1112
args: ["--allow-multiple-documents"]
@@ -32,9 +33,26 @@ repos:
3233
rev: "v1.2.0"
3334
hooks:
3435
- id: mypy
35-
args: [--strict, --ignore-missing-imports, --follow-imports=silent, --disable-error-code=type-abstract, --config-file=./pyproject.toml]
36-
additional_dependencies: ["types-requests", "pydantic", "overrides", "hypothesis", "pytest", "pypika", "numpy", "types-protobuf", "kubernetes"]
37-
36+
args:
37+
[
38+
--strict,
39+
--ignore-missing-imports,
40+
--follow-imports=silent,
41+
--disable-error-code=type-abstract,
42+
--config-file=./pyproject.toml,
43+
]
44+
additional_dependencies:
45+
[
46+
"types-requests",
47+
"pydantic",
48+
"overrides",
49+
"hypothesis",
50+
"pytest",
51+
"pypika",
52+
"numpy",
53+
"types-protobuf",
54+
"kubernetes",
55+
]
3856

3957
- repo: https://github.com/pre-commit/mirrors-prettier
4058
rev: "v3.1.0"

Diff for: .vscode/settings.json

+1-1
Original file line numberDiff line numberDiff line change
@@ -132,4 +132,4 @@
132132
"unordered_set": "cpp",
133133
"algorithm": "cpp"
134134
},
135-
}
135+
}

Diff for: Dockerfile

+1-1
Original file line numberDiff line numberDiff line change
@@ -38,4 +38,4 @@ ENV CHROMA_TIMEOUT_KEEP_ALIVE 30
3838
EXPOSE 8000
3939

4040
ENTRYPOINT ["/docker_entrypoint.sh"]
41-
CMD [ "--workers ${CHROMA_WORKERS} --host ${CHROMA_HOST_ADDR} --port ${CHROMA_HOST_PORT} --proxy-headers --log-config ${CHROMA_LOG_CONFIG} --timeout-keep-alive ${CHROMA_TIMEOUT_KEEP_ALIVE}"]
41+
CMD [ "--workers ${CHROMA_WORKERS} --host ${CHROMA_HOST_ADDR} --port ${CHROMA_HOST_PORT} --proxy-headers --log-config ${CHROMA_LOG_CONFIG} --timeout-keep-alive ${CHROMA_TIMEOUT_KEEP_ALIVE}"]

Diff for: chromadb/__init__.py

+3-1
Original file line numberDiff line numberDiff line change
@@ -246,7 +246,9 @@ def CloudClient(
246246
# Always use SSL for cloud
247247
settings.chroma_server_ssl_enabled = enable_ssl
248248

249-
settings.chroma_client_auth_provider = "chromadb.auth.token_authn.TokenAuthClientProvider"
249+
settings.chroma_client_auth_provider = (
250+
"chromadb.auth.token_authn.TokenAuthClientProvider"
251+
)
250252
settings.chroma_client_auth_credentials = api_key
251253
settings.chroma_auth_token_transport_header = (
252254
TokenTransportHeader.X_CHROMA_TOKEN.name

Diff for: chromadb/api/models/Collection.py

+2-1
Original file line numberDiff line numberDiff line change
@@ -382,7 +382,8 @@ def modify(
382382
validate_metadata(metadata)
383383
if "hnsw:space" in metadata:
384384
raise ValueError(
385-
"Changing the distance function of a collection once it is created is not supported currently.")
385+
"Changing the distance function of a collection once it is created is not supported currently."
386+
)
386387

387388
self._client._modify(id=self.id, new_name=name, new_metadata=metadata)
388389
if name:

Diff for: chromadb/auth/__init__.py

+21-29
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,7 @@ class ClientAuthProvider(Component):
3333
client requests. Client implementations (in our case, just the FastAPI
3434
client) must inject these headers into their requests.
3535
"""
36+
3637
def __init__(self, system: System) -> None:
3738
super().__init__(system)
3839

@@ -52,6 +53,7 @@ class UserIdentity:
5253
_all_ information known about the user, and the AuthorizationProvider is
5354
responsible for making decisions based on that information.
5455
"""
56+
5557
user_id: str
5658
tenant: Optional[str] = None
5759
databases: Optional[List[str]] = None
@@ -71,20 +73,18 @@ class ServerAuthenticationProvider(Component):
7173
The ServerAuthenticationProvider should return a UserIdentity object if the
7274
request is authenticated for use by the ServerAuthorizationProvider.
7375
"""
76+
7477
def __init__(self, system: System) -> None:
7578
super().__init__(system)
7679
self._ignore_auth_paths: Dict[
7780
str, List[str]
7881
] = system.settings.chroma_server_auth_ignore_paths
7982
self.overwrite_singleton_tenant_database_access_from_auth = (
80-
system.settings.
81-
chroma_overwrite_singleton_tenant_database_access_from_auth
83+
system.settings.chroma_overwrite_singleton_tenant_database_access_from_auth
8284
)
8385

8486
@abstractmethod
85-
def authenticate_or_raise(
86-
self, headers: Headers
87-
) -> UserIdentity:
87+
def authenticate_or_raise(self, headers: Headers) -> UserIdentity:
8888
pass
8989

9090
def ignore_operation(self, verb: str, path: str) -> bool:
@@ -100,13 +100,11 @@ def read_creds_or_creds_file(self) -> List[str]:
100100
_creds = None
101101

102102
if self._system.settings.chroma_server_authn_credentials_file:
103-
_creds_file = str(self._system.settings[
104-
"chroma_server_authn_credentials_file"
105-
])
103+
_creds_file = str(
104+
self._system.settings["chroma_server_authn_credentials_file"]
105+
)
106106
if self._system.settings.chroma_server_authn_credentials:
107-
_creds = str(self._system.settings[
108-
"chroma_server_authn_credentials"
109-
])
107+
_creds = str(self._system.settings["chroma_server_authn_credentials"])
110108
if not _creds_file and not _creds:
111109
raise ValueError(
112110
"No credentials file or credentials found in "
@@ -122,9 +120,7 @@ def read_creds_or_creds_file(self) -> List[str]:
122120
elif _creds_file:
123121
with open(_creds_file, "r") as f:
124122
return f.readlines()
125-
raise ValueError(
126-
"Should never happen"
127-
)
123+
raise ValueError("Should never happen")
128124

129125
def singleton_tenant_database_if_applicable(
130126
self, user: Optional[UserIdentity]
@@ -144,15 +140,13 @@ def singleton_tenant_database_if_applicable(
144140
- If the user has access to multiple tenants and/or databases this
145141
function will return None for the corresponding value(s).
146142
"""
147-
if (not self.overwrite_singleton_tenant_database_access_from_auth or
148-
not user):
143+
if not self.overwrite_singleton_tenant_database_access_from_auth or not user:
149144
return None, None
150145
tenant = None
151146
database = None
152147
if user.tenant and user.tenant != "*":
153148
tenant = user.tenant
154-
if (user.databases and len(user.databases) == 1 and
155-
user.databases[0] != "*"):
149+
if user.databases and len(user.databases) == 1 and user.databases[0] != "*":
156150
database = user.databases[0]
157151
return tenant, database
158152

@@ -161,6 +155,7 @@ class AuthzAction(str, Enum):
161155
"""
162156
The set of actions that can be authorized by the authorization provider.
163157
"""
158+
164159
RESET = "system:reset"
165160
CREATE_TENANT = "tenant:create_tenant"
166161
GET_TENANT = "tenant:get_tenant"
@@ -187,6 +182,7 @@ class AuthzResource:
187182
"""
188183
The resource being accessed in an authorization request.
189184
"""
185+
190186
tenant: Optional[str]
191187
database: Optional[str]
192188
collection: Optional[str]
@@ -202,23 +198,21 @@ class ServerAuthorizationProvider(Component):
202198
ServerAuthorizationProvider should raise an exception if the request is not
203199
authorized.
204200
"""
201+
205202
def __init__(self, system: System) -> None:
206203
super().__init__(system)
207204

208205
@abstractmethod
209-
def authorize_or_raise(self,
210-
user: UserIdentity,
211-
action: AuthzAction,
212-
resource: AuthzResource) -> None:
206+
def authorize_or_raise(
207+
self, user: UserIdentity, action: AuthzAction, resource: AuthzResource
208+
) -> None:
213209
pass
214210

215211
def read_config_or_config_file(self) -> List[str]:
216212
_config_file = None
217213
_config = None
218214
if self._system.settings.chroma_server_authz_config_file:
219-
_config_file = self._system.settings[
220-
"chroma_server_authz_config_file"
221-
]
215+
_config_file = self._system.settings["chroma_server_authz_config_file"]
222216
if self._system.settings.chroma_server_authz_config:
223217
_config = str(self._system.settings["chroma_server_authz_config"])
224218
if not _config_file and not _config:
@@ -231,10 +225,8 @@ def read_config_or_config_file(self) -> List[str]:
231225
"Please provide only one."
232226
)
233227
if _config:
234-
return [c for c in _config.split('\n') if c]
228+
return [c for c in _config.split("\n") if c]
235229
elif _config_file:
236230
with open(_config_file, "r") as f:
237231
return f.readlines()
238-
raise ValueError(
239-
"Should never happen"
240-
)
232+
raise ValueError("Should never happen")

Diff for: chromadb/auth/basic_authn/__init__.py

+16-19
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,5 @@
11
import base64
22
import bcrypt
3-
import importlib
43
import logging
54

65
from fastapi import HTTPException
@@ -31,25 +30,20 @@ class BasicAuthClientProvider(ClientAuthProvider):
3130
Client auth provider for basic auth. The credentials are passed as a
3231
base64-encoded string in the Authorization header prepended with "Basic ".
3332
"""
33+
3434
def __init__(self, system: System) -> None:
3535
super().__init__(system)
3636
self._settings = system.settings
3737
system.settings.require("chroma_client_auth_credentials")
38-
self._creds = SecretStr(
39-
str(system.settings.chroma_client_auth_credentials)
40-
)
38+
self._creds = SecretStr(str(system.settings.chroma_client_auth_credentials))
4139

4240
@override
4341
def authenticate(self) -> ClientAuthHeaders:
4442
encoded = base64.b64encode(
4543
f"{self._creds.get_secret_value()}".encode("utf-8")
46-
).decode(
47-
"utf-8"
48-
)
44+
).decode("utf-8")
4945
return {
50-
"Authorization": SecretStr(
51-
f"Basic {encoded}"
52-
),
46+
"Authorization": SecretStr(f"Basic {encoded}"),
5347
}
5448

5549

@@ -62,6 +56,7 @@ class BasicAuthenticationServerProvider(ServerAuthenticationProvider):
6256
Expects tokens to be passed as a base64-encoded string in the Authorization
6357
header prepended with "Basic".
6458
"""
59+
6560
def __init__(self, system: System) -> None:
6661
super().__init__(system)
6762
self._settings = system.settings
@@ -73,8 +68,12 @@ def __init__(self, system: System) -> None:
7368
if not line.strip():
7469
continue
7570
_raw_creds = [v for v in line.strip().split(":")]
76-
if (_raw_creds and _raw_creds[0] and
77-
len(_raw_creds) != 2 or not all(_raw_creds)):
71+
if (
72+
_raw_creds
73+
and _raw_creds[0]
74+
and len(_raw_creds) != 2
75+
or not all(_raw_creds)
76+
):
7877
raise ValueError(
7978
f"Invalid htpasswd credentials found: {_raw_creds}. "
8079
"Lines must be exactly <username>:<bcrypt passwd>."
@@ -89,12 +88,11 @@ def __init__(self, system: System) -> None:
8988
)
9089
self._creds[username] = SecretStr(password)
9190

92-
@trace_method("BasicAuthenticationServerProvider.authenticate",
93-
OpenTelemetryGranularity.ALL)
91+
@trace_method(
92+
"BasicAuthenticationServerProvider.authenticate", OpenTelemetryGranularity.ALL
93+
)
9494
@override
95-
def authenticate_or_raise(
96-
self, headers: Headers
97-
) -> UserIdentity:
95+
def authenticate_or_raise(self, headers: Headers) -> UserIdentity:
9896
try:
9997
_auth_header = headers["Authorization"]
10098
_auth_header = _auth_header.replace("Basic ", "")
@@ -115,7 +113,6 @@ def authenticate_or_raise(
115113

116114
except Exception as e:
117115
logger.error(
118-
"BasicAuthenticationServerProvider.authenticate "
119-
f"failed: {repr(e)}"
116+
"BasicAuthenticationServerProvider.authenticate " f"failed: {repr(e)}"
120117
)
121118
raise HTTPException(status_code=403, detail="Forbidden")

Diff for: chromadb/auth/simple_rbac_authz/__init__.py

+11-12
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@
1717
)
1818

1919
from hypothesis import Phase, settings
20+
2021
settings.register_profile("ci", phases=[Phase.generate, Phase.target])
2122

2223

@@ -33,12 +34,11 @@ class SimpleRBACAuthorizationProvider(ServerAuthorizationProvider):
3334
For an example of an RBAC configuration file, see
3435
examples/basic_functionality/authz/authz.yaml.
3536
"""
37+
3638
def __init__(self, system: System) -> None:
3739
super().__init__(system)
3840
self._settings = system.settings
39-
self._config = yaml.safe_load(
40-
'\n'.join(self.read_config_or_config_file())
41-
)
41+
self._config = yaml.safe_load("\n".join(self.read_config_or_config_file()))
4242

4343
# We favor preprocessing here to avoid having to parse the config file
4444
# on every request. This AuthorizationProvider does not support
@@ -51,23 +51,22 @@ def __init__(self, system: System) -> None:
5151
_actions = self._config["roles_mapping"][user["role"]]["actions"]
5252
self._permissions[user["id"]] = set(_actions)
5353
logger.info(
54-
"Authorization Provider SimpleRBACAuthorizationProvider "
55-
"initialized"
54+
"Authorization Provider SimpleRBACAuthorizationProvider " "initialized"
5655
)
5756

5857
@trace_method(
5958
"SimpleRBACAuthorizationProvider.authorize",
6059
OpenTelemetryGranularity.ALL,
6160
)
6261
@override
63-
def authorize_or_raise(self,
64-
user: UserIdentity,
65-
action: AuthzAction,
66-
resource: AuthzResource) -> None:
67-
62+
def authorize_or_raise(
63+
self, user: UserIdentity, action: AuthzAction, resource: AuthzResource
64+
) -> None:
6865
policy_decision = False
69-
if (user.user_id in self._permissions and
70-
action in self._permissions[user.user_id]):
66+
if (
67+
user.user_id in self._permissions
68+
and action in self._permissions[user.user_id]
69+
):
7170
policy_decision = True
7271

7372
logger.debug(

0 commit comments

Comments
 (0)