Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 16 additions & 0 deletions clients/python-wrapper/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,21 @@
# Changelog

## Unreleased

:bug: Bugs fixed:

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The changelog lists this only under "Bugs fixed", but the PR also changes what callers see for an unknown keyword argument. For example, branch.commit("msg", allow_emtpy=True) was accepted before and now raises lakefs_sdk.exceptions.ApiTypeError. I think that is the right behaviour, but a user reading the release notes gets no warning. Please add it under :warning: Breaking changes:, as v0.16.0 does, and end the entry with (#10622) like the other entries in this file.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done in 30a8a35: added a :warning: Breaking changes: entry for the new ApiTypeError, and both entries now end with (#10622).


- Send request options such as `_request_timeout` from `Branch.create`,
`Branch.commit` and `Reference.merge_into` to the server instead of
dropping them (#10622)

:warning: Breaking changes:

- `Branch.create`, `Branch.commit` and `Reference.merge_into` raise
`lakefs_sdk.exceptions.ApiTypeError` for a keyword argument that is
neither a field of the request body nor a request option, for example
`branch.commit("msg", allow_emtpy=True)`. They used to ignore it
(#10622)

## v0.17.0

This release bumps a minor version number but might break some of your
Expand Down
21 changes: 15 additions & 6 deletions clients/python-wrapper/lakefs/branch.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@
from lakefs.object import WriteableObject
from lakefs.object import StoredObject
from lakefs.import_manager import ImportManager
from lakefs.reference import Reference, ReferenceType, generate_listing
from lakefs.reference import Reference, ReferenceType, generate_listing, split_body_kwargs
if TYPE_CHECKING:
from lakefs.repository import Repository
from lakefs.models import Change, Commit
Expand Down Expand Up @@ -195,6 +195,10 @@ def create(self, source_reference: ReferenceType, exist_ok: bool = False, **kwar
:param source_reference: The reference to create the branch from (reference ID, object or Commit object)
:param exist_ok: If False will throw an exception if a branch by this name already exists. Otherwise,
return the existing branch without creating a new one
:param kwargs: Branch creation parameters (fields of ``lakefs_sdk.BranchCreation`` such as ``hidden``),
and additional Keyword Arguments to send to the server (such as ``_request_timeout``).
A request that exceeds ``_request_timeout`` raises ``urllib3.exceptions.ReadTimeoutError``,
which is not a ``LakeFSException``
:return: The lakeFS SDK object representing the branch
:raise NotFoundException: if repo, branch or source reference id does not exist
:raise ConflictException: if branch already exists and exist_ok is False
Expand All @@ -208,9 +212,10 @@ def handle_conflict(e: LakeFSException):
return e

reference_id = source_reference if isinstance(source_reference, str) else source_reference.id
branch_creation = lakefs_sdk.BranchCreation(name=self._id, source=reference_id, **kwargs)
creation_kwargs, request_kwargs = split_body_kwargs(lakefs_sdk.BranchCreation, kwargs)
branch_creation = lakefs_sdk.BranchCreation(name=self._id, source=reference_id, **creation_kwargs)
with api_exception_handler(handle_conflict):
self._client.sdk_client.branches_api.create_branch(self.repo_id, branch_creation)
self._client.sdk_client.branches_api.create_branch(self.repo_id, branch_creation, **request_kwargs)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not introduced here, but this PR is what makes it reachable from these methods. A request that hits the timeout raises urllib3.exceptions.ReadTimeoutError, which is not a LakeFSException, because api_exception_handler converts only lakefs_sdk.ApiException. I ran branch.create("main", _request_timeout=0.5) against a server that never answers and got that exception after 0.5s. The customer in the linked issue wraps calls to bound their duration, so except LakeFSException will miss it. Can we open a follow-up issue, and name the exception in the kwargs docstring until then?

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is nasty: raising a new exception type is actually a breaking change!1

Could we instead additionally convert these errors? If we did it now, it wouldn't be a breaking change.

In contrast, in an "exceptions" language like Python, Java, or C++, new exception types leak up through the call stack (in Java only unchecked exceptions). So adding a new exception type forces checking every caller even though the type does not change. typing cannot spec exceptions, apparently by design. So it's a breaking change.

Footnotes

  1. In a "results" language like C, or Rust, this change would not be breaking. A caller has to opt into receiving the new error type, and then it can handle the new error type. And because each caller up the stack checks its error type, handling the new error type stops escalation, and not handling the new error type changes the return type. Results have static scope, so either old code "works" (assuming errors are correctly handled) or it fails to compile. ↩

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Opened #10630 for converting request timeouts into a LakeFSException, with Ariel's suggestion as the proposal: a subclass that also subclasses the urllib3 timeout error, so existing handlers keep catching it. Until then the kwargs docstrings of create, commit and merge_into name urllib3.exceptions.ReadTimeoutError (30a8a35).

return self

@property
Expand All @@ -233,17 +238,21 @@ def commit(self, message: str, metadata: Optional[dict] = None, **kwargs) -> Ref

:param message: Commit message
:param metadata: Metadata to attach to the commit
:param kwargs: Additional Keyword Arguments for commit creation
:param kwargs: Commit creation parameters (fields of ``lakefs_sdk.CommitCreation`` such as ``allow_empty``),
and additional Keyword Arguments to send to the server (such as ``_request_timeout``).
A request that exceeds ``_request_timeout`` raises ``urllib3.exceptions.ReadTimeoutError``,
which is not a ``LakeFSException``
:return: The new reference after the commit
:raise NotFoundException: if branch by this id does not exist
:raise ForbiddenException: if commit is not allowed on this branch
:raise NotAuthorizedException: if user is not authorized to perform this operation
:raise ServerException: for any other errors
"""
commits_creation = lakefs_sdk.CommitCreation(message=message, metadata=metadata, **kwargs)
creation_kwargs, request_kwargs = split_body_kwargs(lakefs_sdk.CommitCreation, kwargs)
commits_creation = lakefs_sdk.CommitCreation(message=message, metadata=metadata, **creation_kwargs)

with api_exception_handler():
c = self._client.sdk_client.commits_api.commit(self.repo_id, self._id, commits_creation)
c = self._client.sdk_client.commits_api.commit(self.repo_id, self._id, commits_creation, **request_kwargs)
Comment thread
AliRamberg marked this conversation as resolved.
Resolved
return Reference(self._repo, c.id, self._client)

def delete(self, **kwargs) -> None:
Expand Down
27 changes: 23 additions & 4 deletions clients/python-wrapper/lakefs/reference.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@

from __future__ import annotations

from typing import Optional, Generator, Union, TYPE_CHECKING, overload
from typing import Any, Optional, Generator, Union, TYPE_CHECKING, overload

from typing_extensions import deprecated

Expand Down Expand Up @@ -166,19 +166,24 @@ def merge_into(self, destination_branch: ReferenceType, **kwargs) -> str:
Merge this reference into destination branch

:param destination_branch: The merge destination (either ID or branch object)
:param kwargs: Additional Keyword Arguments to send to the server
:param kwargs: Merge parameters (fields of ``lakefs_sdk.Merge`` such as ``message`` or ``allow_empty``),
and additional Keyword Arguments to send to the server (such as ``_request_timeout``).
A request that exceeds ``_request_timeout`` raises ``urllib3.exceptions.ReadTimeoutError``,
which is not a ``LakeFSException``
:return: The reference id of the merge commit
:raise NotFoundException: if reference by this id does not exist, or branch doesn't exist
:raise NotAuthorizedException: if user is not authorized to perform this operation
:raise ServerException: for any other errors
"""
branch_id = destination_branch if isinstance(destination_branch, str) else destination_branch.id
merge_kwargs, request_kwargs = split_body_kwargs(lakefs_sdk.Merge, kwargs)
with api_exception_handler():
merge = lakefs_sdk.Merge(**kwargs)
merge = lakefs_sdk.Merge(**merge_kwargs)
res = self._client.sdk_client.refs_api.merge_into_branch(self.repo_id,
self._id,
branch_id,
merge=merge)
merge=merge,
**request_kwargs)
return res.reference

def object(self, path: str) -> StoredObject: # pylint: disable=C0103
Expand Down Expand Up @@ -219,4 +224,18 @@ def generate_listing(func, *args, max_amount: Optional[int] = None, **kwargs):
return


def split_body_kwargs(model: Any, kwargs: dict[str, Any]) -> tuple[dict[str, Any], dict[str, Any]]:

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The wrapper now has two ways to separate body fields from request options. Repository.create pops storage_id by hand at repository.py:57 (added in #9704), and this PR adds split_body_kwargs for three other methods. The helper is the better of the two, since a new field on the model needs no wrapper change. Could Repository.create call split_body_kwargs(lakefs_sdk.RepositoryCreation, kwargs) and drop the pop, here or in a follow-up?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done here in 30a8a35: Repository.create calls split_body_kwargs(lakefs_sdk.RepositoryCreation, kwargs) and the storage_id pop is gone. A side effect: read_only=True now reaches the request body instead of raising ApiTypeError.

"""
Split keyword arguments between a lakefs-sdk request body model and the API call that sends it

:param model: The lakefs-sdk request body model class
:param kwargs: The keyword arguments to split
:return: The arguments named by a field of the model (by name or alias), and all other arguments
"""
names = set(model.__fields__) | {field.alias for field in model.__fields__.values()}
body = {k: v for k, v in kwargs.items() if k in names}
request = {k: v for k, v in kwargs.items() if k not in names}
return body, request


ReferenceType = Union[str, Reference, Commit]
11 changes: 6 additions & 5 deletions clients/python-wrapper/lakefs/repository.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@
ConflictException,
LakeFSException,
)
from lakefs.reference import Reference, generate_listing
from lakefs.reference import Reference, generate_listing, split_body_kwargs


class Repository(_BaseLakeFSObject):
Expand Down Expand Up @@ -49,17 +49,18 @@ def create(self,
:param include_samples: Whether to include sample data in repository creation
:param exist_ok: If False will throw an exception if a repository by this name already exists. Otherwise,
return the existing repository without creating a new one
:param kwargs: Additional Keyword Arguments to send to the server
:param kwargs: Repository creation parameters (fields of ``lakefs_sdk.RepositoryCreation`` such as
``storage_id``), and additional Keyword Arguments to send to the server (such as ``_request_timeout``)
:return: The lakeFS SDK object representing the repository
:raise NotAuthorizedException: if user is not authorized to perform this operation
:raise ServerException: for any other errors
"""
storage_id = kwargs.pop("storage_id", None)
creation_kwargs, request_kwargs = split_body_kwargs(lakefs_sdk.RepositoryCreation, kwargs)
repository_creation = lakefs_sdk.RepositoryCreation(name=self._id,
storage_namespace=storage_namespace,
default_branch=default_branch,
sample_data=include_samples,
storage_id=storage_id)
**creation_kwargs)

def handle_conflict(e: LakeFSException):
if isinstance(e, ConflictException) and exist_ok:
Expand All @@ -70,7 +71,7 @@ def handle_conflict(e: LakeFSException):
return e

with api_exception_handler(handle_conflict):
repo = self._client.sdk_client.repositories_api.create_repository(repository_creation, **kwargs)
repo = self._client.sdk_client.repositories_api.create_repository(repository_creation, **request_kwargs)
self._properties = RepositoryProperties(**repo.dict())
return self

Expand Down
36 changes: 32 additions & 4 deletions clients/python-wrapper/tests/utests/test_branch.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,14 +30,16 @@ def test_branch_create(monkeypatch):
branch = get_test_branch()
source = "main"
with monkeypatch.context():
def monkey_create_branch(_self, repo_name, branch_creation, *_):
def monkey_create_branch(_self, repo_name, branch_creation, **kwargs):
assert repo_name == branch.repo_id
assert branch_creation.name == branch.id
assert branch_creation.source == source
assert branch_creation.hidden
assert kwargs == {"_request_timeout": 5}
return lakefs_sdk.BranchCreation(name=branch.id, source=source)

monkeypatch.setattr(lakefs_sdk.BranchesApi, "create_branch", monkey_create_branch)
branch.create(source)
branch.create(source, hidden=True, _request_timeout=5)


def test_branch_create_already_exists(monkeypatch):
Expand Down Expand Up @@ -82,12 +84,14 @@ def test_branch_commit(monkeypatch):
commit_id = "1234"
commit_message = "test message"
with monkeypatch.context():
def monkey_commit(repo_name, branch_name, commits_creation, *_):
def monkey_commit(repo_name, branch_name, commits_creation, **kwargs):
assert repo_name == branch.repo_id
assert branch_name == branch.id
assert commits_creation.message == commit_message
assert commits_creation.metadata == md
assert commits_creation.allow_empty
assert commits_creation.var_date == 123
assert kwargs == {"_request_timeout": 5}
return lakefs_sdk.Commit(
id=commit_id,
parents=[""],
Expand All @@ -98,10 +102,34 @@ def monkey_commit(repo_name, branch_name, commits_creation, *_):
)

monkeypatch.setattr(branch._client.sdk_client.commits_api, "commit", monkey_commit)
res = branch.commit(commit_message, metadata=md, allow_empty=True, ignored_field="test")
res = branch.commit(commit_message, metadata=md, allow_empty=True, date=123, _request_timeout=5)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The removed ignored_field="test" case was the only test of what happens to an unknown keyword, and nothing replaces it. The new tests stub the SDK method with a function that accepts any **kwargs, so they cannot fail if unknown keywords stop raising. Please add one case that patches ApiClient.call_api instead of commits_api.commit and expects ApiTypeError for something like branch.commit("msg", allow_emtpy=True). That case would also prove the real SDK method accepts _request_timeout.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Added test_branch_commit_keyword_arguments in 30a8a35. It patches ApiClient.call_api, so the generated commit method runs: _request_timeout=5 reaches call_api, and allow_emtpy=True raises ApiTypeError without sending a request. Run against master's wrapper code it fails with [None] == [5].

assert res.id == commit_id


def test_branch_commit_keyword_arguments(monkeypatch):
branch = get_test_branch()
request_timeouts = []
with monkeypatch.context():
def monkey_call_api(_self, *_, **kwargs):
request_timeouts.append(kwargs["_request_timeout"])
return lakefs_sdk.Commit(
id="1234",
parents=[""],
committer="Committer",
message="msg",
creation_date=0,
meta_range_id="",
)

monkeypatch.setattr(lakefs_sdk.ApiClient, "call_api", monkey_call_api)
branch.commit("msg", _request_timeout=5)
assert request_timeouts == [5]

with expect_exception_context(lakefs_sdk.exceptions.ApiTypeError):
branch.commit("msg", allow_emtpy=True)
assert request_timeouts == [5]


def test_branch_delete(monkeypatch):
branch = get_test_branch()
with monkeypatch.context():
Expand Down
18 changes: 18 additions & 0 deletions clients/python-wrapper/tests/utests/test_reference.py
Original file line number Diff line number Diff line change
Expand Up @@ -162,3 +162,21 @@ def monkey_list_objects(*_, **__):
item.checksum # pylint: disable=pointless-statement

assert item.path == f"path-{i}"


def test_reference_merge_into(monkeypatch):
ref = get_test_ref()
destination = "main"
with monkeypatch.context():
def monkey_merge_into_branch(repo_name, source_ref, destination_branch, merge, **kwargs):
assert repo_name == ref.repo_id
assert source_ref == ref.id
assert destination_branch == destination
assert merge.message == "merge message"
assert merge.allow_empty
assert kwargs == {"_request_timeout": 5}
return lakefs_sdk.MergeResult(reference="merge-commit")

monkeypatch.setattr(ref._client.sdk_client.refs_api, "merge_into_branch", monkey_merge_into_branch)
res = ref.merge_into(destination, message="merge message", allow_empty=True, _request_timeout=5)
assert res == "merge-commit"
Loading