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
2 changes: 1 addition & 1 deletion .release-please-manifest.json
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
{
".": "0.18.2"
".": "0.19.0"
}
31 changes: 31 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,36 @@
# Changelog

## 0.19.0 (2026-12-01)


### ⚠ BREAKING CHANGES

* **jobs:** FutureUnit.get raises JobOutputsNotReady for a unit that isn't finished, where it raised HTTPError 404. catch JobOutputsNotReady or APIError.
* **models:** `embed` on `session.models` handles returns one row per residue unless a reduction is given; v0.18.0 pooled by mean. Pass `reduction="MEAN"` for pooled embeddings, which a GP or UMAP fit needs.

### Features

* **jobs:** read results and prompts through authenticated content routes
* **models:** name every model's inference params on its handle
* **models:** embed per residue unless a reduction is given
* **molecules:** structure ensemble analysis


### Deprecations

* `openprotein.models.folding`: use `openprotein.models.fold`. Deprecated since 0.19.0, removed in 0.20.0
* `openprotein.models.foundational`: use `openprotein.models.foundation`. Deprecated since 0.19.0, removed in 0.20.0
* `topk=` and `topp=` on `PoETModel.generate`, `PoET2Model.generate` and `request_generate_post`: use `top_k=` and `top_p=`. Deprecated since 0.19.0, removed in 0.20.0

### Bug Fixes

* **base:** keep the backend path when it has no trailing slash
* **data:** refuse to read the rows of an assay that isn't ready
* **embeddings:** name poet generate sampling args top_k and top_p
* **embeddings:** send top_k and top_p in poet generate requests
* **jobs:** say why a unit's output can't be read
* **models:** leave the fit_svd reduction to the server unless given

## 0.18.2 (2026-11-24)


Expand Down
114 changes: 114 additions & 0 deletions openprotein/_deprecation.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,12 @@
"""Helper for deprecating public interfaces."""

import importlib
import pkgutil
import sys
import warnings
from collections.abc import Callable
from types import ModuleType
from typing import Any


def warn_deprecated(
Expand Down Expand Up @@ -36,3 +42,111 @@ def warn_deprecated(
FutureWarning,
stacklevel=stacklevel,
)


def alias_package(
old: str, new: ModuleType, *, since: str, removed_in: str
) -> Callable[[str], Any]:
"""
Alias a package under a deprecated name.

Warns once when the old package is imported, then registers every
submodule of `new` in `sys.modules` under the old name, so the old
submodule paths resolve to the same module objects. Call it from the body
of the old package's ``__init__``.

Parameters
----------
old : str
Dotted name of the deprecated package.
new : ModuleType
The package that replaces it.
since : str
Version the old name was deprecated in.
removed_in : str
Version the old name is removed in.

Returns
-------
Callable[[str], Any]
A module ``__getattr__`` for the old package. It warns and returns the
object for each name in ``new.__all__`` and each submodule of `new`,
and raises `AttributeError` for any other name.
"""
warn_deprecated(
old,
f"`{new.__name__}`",
since=since,
removed_in=removed_in,
stacklevel=4,
)
submodules = {module.name for module in pkgutil.iter_modules(new.__path__)}
for name in submodules:
sys.modules[f"{old}.{name}"] = importlib.import_module(f"{new.__name__}.{name}")

def __getattr__(name: str) -> Any:
if name not in new.__all__ and name not in submodules:
raise AttributeError(f"module {old!r} has no attribute {name!r}")
warn_deprecated(
f"{old}.{name}",
f"`{new.__name__}.{name}`",
since=since,
removed_in=removed_in,
)
return getattr(new, name)

return __getattr__


def renamed_keyword(
kwargs: dict[str, Any],
method: str,
old: str,
new: str,
value: Any,
*,
since: str,
removed_in: str,
) -> Any:
"""
Resolve a keyword argument that was renamed, warning if the old name is used.

Call it from the public method so the warning points at that method's caller.

Parameters
----------
kwargs : dict
The method's ``**kwargs``. The old keyword is removed from it.
method : str
Name of the method, for the warning.
old, new : str
The deprecated and current keyword names.
value : Any
The value passed under the current name.
since : str
Version the old name was deprecated in.
removed_in : str
Version the old name is removed in.

Returns
-------
Any
The value to use under the current name.

Raises
------
TypeError
If both names are given.
"""
if old not in kwargs:
return value
warn_deprecated(
f"{method}({old}=...)",
f"`{method}({new}=...)`",
since=since,
removed_in=removed_in,
stacklevel=4,
)
if value is not None:
raise TypeError(f"pass {new}, not both {new} and {old}")
return kwargs.pop(old)
67 changes: 47 additions & 20 deletions openprotein/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,9 @@ def is_retry(self, method, status_code, has_retry_after=False):
# Refresh the access token this many seconds before it expires, to absorb
# clock skew and request latency.
_SKEW_SECONDS = 30

#: Stored-byte reads run at once; also the connection pool size per host.
_DOWNLOAD_WORKERS = 16
_IDEMPOTENCY_KEY_HEADER = "Idempotency-Key"


Expand Down Expand Up @@ -185,6 +188,10 @@ def __init__(
raise AuthError(
"Expected username and password. Or use environment variables `OPENPROTEIN_USERNAME` and `OPENPROTEIN_PASSWORD`. Or provide these variables (`username` and `password`) in ~/.openprotein/config.toml."
)
# urljoin replaces the last path segment of a base without a trailing
# slash, so `.../api` would route every call outside `/api`.
if not backend.endswith("/"):
backend += "/"
self._init_transport(backend, timeout)

# Auth / refresh state. Initialised before any network call so that
Expand Down Expand Up @@ -219,7 +226,7 @@ def _init_transport(self, backend: str, timeout: float) -> None:
status_forcelist=[500, 502, 503, 504, 101, 104],
raise_on_status=False,
)
adapter = HTTPAdapter(max_retries=retry)
adapter = HTTPAdapter(max_retries=retry, pool_maxsize=_DOWNLOAD_WORKERS)
for scheme in ("https://", "http://"):
self.mount(scheme, adapter)
model_retry = _ModelSubmissionRetry(
Expand Down Expand Up @@ -384,9 +391,17 @@ def _adopt(self, record: TokenRecord):
self._expires_at = record.expires_at
self._set_token(self._username, record.access_token)

def _refresh(self):
def _bearer_token(self) -> str | None:
return self.auth._token if isinstance(self.auth, BearerAuth) else None

def _refresh(self, stale: str | None = None):
"""Refresh the access token, serialized across threads and processes.

``stale`` is the access token the caller found expired or rejected. If
the session now holds a different token, another thread has refreshed.
No token at all means another thread's re-login failed, so this one
tries again.

Re-reads the store under the lock first: if another thread/process
already rotated the token, adopt that instead of refreshing again
(replaying a superseded refresh token would revoke the session).
Expand All @@ -396,6 +411,9 @@ def _refresh(self):
self._token_store.lock(),
_surface_server_warnings(),
):
current = self._bearer_token()
if stale is not None and current is not None and current != stale:
return
record = self._token_store.load(self._identity)
if (
record is not None
Expand Down Expand Up @@ -446,8 +464,10 @@ def _should_refresh_proactively(self) -> bool:

def request(self, method: str, url: str, *args, **kwargs):
kwargs.setdefault("timeout", self.timeout)
token = self._bearer_token()
if self._should_refresh_proactively():
self._refresh()
self._refresh(token)
token = self._bearer_token()

# Freeze the JSON body once so a reactive 401 retry resends the same
# payload under the same idempotency key.
Expand All @@ -464,27 +484,34 @@ def request(self, method: str, url: str, *args, **kwargs):
and not self._refreshing
and not self._legacy_mode
):
self._refresh()
response.close()
self._refresh(token)
response = super().request(method, full_url, *args, **kwargs)

_warn_from_server(response)

if (js := kwargs.get("json")) and _total_size(js) > 1e6:
warnings.warn(
"The requested payload is >1MB. There might be some delays or issues in processing. If the request fails, please try again with smaller sizes."
)
# A streamed response holds its connection until closed, and the caller
# only gets to close the one returned.
try:
_warn_from_server(response)

if "cloudfront" in response.headers.get("Server", "").lower():
if response.status_code in (502, 503):
raise CloudFrontError(
f"We're experiencing a temporary backend issue via CloudFront. Please try again later. Error {response.status_code}."
)
elif response.status_code == 504:
raise TimeoutError(
"Your request took too long to process likely due to it's size. Please try breaking it up into smaller requests if possible."
if (js := kwargs.get("json")) and _total_size(js) > 1e6:
warnings.warn(
"The requested payload is >1MB. There might be some delays or issues in processing. If the request fails, please try again with smaller sizes."
)
if not response.ok:
raise HTTPError(response)

if "cloudfront" in response.headers.get("Server", "").lower():
if response.status_code in (502, 503):
raise CloudFrontError(
f"We're experiencing a temporary backend issue via CloudFront. Please try again later. Error {response.status_code}."
)
elif response.status_code == 504:
raise TimeoutError(
"Your request took too long to process likely due to it's size. Please try breaking it up into smaller requests if possible."
)
if not response.ok:
raise HTTPError(response)
except BaseException:
response.close()
raise
return response


Expand Down
30 changes: 30 additions & 0 deletions openprotein/data/assaydataset.py
Original file line number Diff line number Diff line change
Expand Up @@ -213,10 +213,22 @@ def _get_all(self, verbose: bool = False) -> pd.DataFrame:
"""
Get all assay data.

A page after the first that fails to load ends the read, which
returns the rows read before it.

Returns
-------
pd.DataFrame
Dataframe containing all assay data.

Raises
------
JobOutputsNotReady
If the assay isn't ready yet.
JobFailedException
If the job that makes the assay failed or was canceled.
APIError
If the first page fails to load.
"""
step = self.page_size

Expand All @@ -231,6 +243,8 @@ def _get_all(self, verbose: bool = False) -> pd.DataFrame:
num_returned = len(result)
offset += num_returned
except APIError as exc:
if not results:
raise
if verbose:
print(f"Failed to get results: {exc}")
return pd.concat(results)
Expand All @@ -244,7 +258,15 @@ def get_first(self) -> pd.DataFrame:
-------
pd.DataFrame
Dataframe containing the slice of assay data.

Raises
------
JobOutputsNotReady
If the assay isn't ready yet.
JobFailedException
If the job that makes the assay failed or was canceled.
"""
self._require_ready()
rows = []
entries = api.assaydata_page_get(
self.session, self.id, page_offset=0, page_size=1
Expand Down Expand Up @@ -274,7 +296,15 @@ def get_slice(
-------
pd.DataFrame
Dataframe containing the slice of assay data.

Raises
------
JobOutputsNotReady
If the assay isn't ready yet.
JobFailedException
If the job that makes the assay failed or was canceled.
"""
self._require_ready()
rows = []
page_size = self.page_size
for i in range(start, end, page_size):
Expand Down
2 changes: 1 addition & 1 deletion openprotein/data/prompts/_api.py
Original file line number Diff line number Diff line change
Expand Up @@ -94,7 +94,7 @@ def prompts_download(session: APISession, prompt_id: str) -> bytes:
A prompt that isn't ready raises the server's 409; a deleted or unknown id
is a 404.
"""
return read(session, f"{PATH_PREFIX}/{prompt_id}/download").content
return read(session, f"{PATH_PREFIX}/{prompt_id}/content").content


def prompts_sample_post(
Expand Down
4 changes: 2 additions & 2 deletions openprotein/data/prompts/schemas.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,14 +33,14 @@ class PromptMetadata(BaseModel):


class PromptUnitValue(BaseModel):
"""One replicate's presigned value."""
"""One replicate's stored value."""

position: int
value: dict[str, Any]


class PromptRecord(PromptMetadata):
"""One row read in full, carrying each replicate's presigned value.
"""One row read in full, carrying each replicate's stored value.

``value`` is ``None`` until the row's job has produced the replicates.
"""
Expand Down
Loading
Loading