Skip to content
Open
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
175 changes: 114 additions & 61 deletions src/ga4gh/vrs/dataproxy.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
"""provides an abstract class for all data access required for VRS, and a concrete implementation based on seqrepo.

See https://vr-spec.readthedocs.io/en/1.1/impl-guide/required_data.html
See https://vrs.ga4gh.org/en/latest/conventions/required_data.html
"""

import datetime

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.

Optional cleanup: with _get_metadata gone from the SeqRepo base, _isoformat (near the bottom of the module) and this import datetime look unused. Their only caller was "added": _isoformat(seqinfo["added"]). Both could probably go, along with the doctest.

Expand Down Expand Up @@ -56,11 +56,6 @@ def get_sequence(
) -> str:
"""Return the specified sequence or subsequence

start and end are optional

If the given sequence does not exist, KeyError is raised. If start is after end,
DataProxyValidationError may be raised.

For example:

>>> dp.get_sequence("NM_000551.3", 0, 10)
Expand All @@ -75,26 +70,20 @@ def get_sequence(
"""

@abstractmethod
def get_metadata(self, identifier: str) -> dict:
"""For a given identifier, return a structure (dict) containing sequence length, aliases, and other optional info

If the given sequence does not exist, KeyError is raised.
def get_length(self, identifier: str) -> int:
"""Return the sequence length.

For example:
:param identifier: Sequence identifier to resolve.
:return: Sequence length.
:raises KeyError: If the sequence identifier is not found.
"""

>>> dp.get_metadata("NM_000551.3")
{'added': '2016-08-24T05:03:11Z',
'aliases': ['MD5:215137b1973c1a5afcf86be7d999574a',
'RefSeq:NM_000551.3',
'SEGUID:T12L0p2X5E8DbnL0+SwI4Wc1S6g',
'SHA1:4f5d8bd29d97e44f036e72f4f92c08e167354ba8',
'ga4gh:SQ.v_QTc1p-MUYdgrRv4LMT6ByXIOsdw3C_',
'gi:319655736'],
'alphabet': 'ACGT',
'length': 4560}
@abstractmethod
def get_aliases(self, identifier: str) -> list[str]:

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.

I know the ! marks this as an intentional break. One idea for downstream users: a deprecated, non-abstract get_metadata built from get_length/get_aliases (with a DeprecationWarning) would let external callers migrate gradually. Subclasses that only implement get_metadata will still fail to instantiate, so either way a note in the changelog or migration docs would help.

"""Return the known sequence aliases.

:param identifier: Sequence identifier to resolve.
:return: Sequence metadata, including length and aliases.
:return: List of known sequence aliases.
:raises KeyError: If the sequence identifier is not found.
"""

Expand Down Expand Up @@ -142,10 +131,11 @@ def translate_sequence_identifier(
:raises KeyError: If the sequence identifier is not found.
"""
try:
md = self.get_metadata(identifier)
# Deduplicate while preserving the backend's alias order.
aliases = list(dict.fromkeys(self.get_aliases(identifier)))
except (ValueError, KeyError, IndexError) as e:
raise KeyError(identifier) from e
aliases = list(set(md["aliases"])) # ensure uniqueness

if namespace is not None:
nsd = namespace + ":"
aliases = [a for a in aliases if a.startswith(nsd)]
Expand Down Expand Up @@ -242,8 +232,7 @@ def validate_location_bounds(
"""
# same cache key as derive_refget_accession
sequence_id = coerce_namespace(sequence_id)
md = self.get_metadata(sequence_id)
seq_len = md["length"]
seq_len = self.get_length(sequence_id)
bad = []
for name, pos in (("start", start_pos), ("end", end_pos)):
values = pos.root if isinstance(pos, Range) else [pos]
Expand All @@ -256,7 +245,10 @@ def validate_location_bounds(
for name, pos in bad
)
# Name the sequence as given, plus the refget accession it resolved to
refget_ac = next((a for a in md["aliases"] if a.startswith("ga4gh:")), None)
refget_ac = next(
(a for a in self.get_aliases(sequence_id) if a.startswith("ga4gh:")),

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.

Small thing: before, the aliases here came from the same metadata fetch that gave the length. Now this is a second backend call on the error path, so if get_aliases fails (a cache miss plus a network error on the REST proxy, or a third-party proxy backed by a different service), a KeyError / RequestException replaces the DataProxyValidationError that callers are catching. Wrapping this lookup so a failure just leaves refget_ac = None would keep the validation error intact.

None,
)
seq_name = sequence_id
if refget_ac and refget_ac != sequence_id:
seq_name += f" ({refget_ac})"
Expand All @@ -279,18 +271,6 @@ class _SeqRepoDataProxyBase(_DataProxy):
# wraps seqreqpo classes in order to provide translation to/from
# `ga4gh` identifiers.

@functools.lru_cache
def get_metadata(self, identifier: str) -> dict:
"""Fetch sequence metadata.

:param identifier: Sequence identifier to resolve.
:return: Sequence metadata, including length and aliases.
:raises KeyError: If the sequence identifier is not found.
"""
md = self._get_metadata(identifier)
md["aliases"] = list(a for a in md["aliases"]) # noqa: C400
return md

@functools.lru_cache
def get_sequence(
self, identifier: str, start: int | None = None, end: int | None = None
Expand All @@ -308,19 +288,48 @@ def get_sequence(
validate_start_le_end(identifier, start, end)
return self._get_sequence(identifier, start=start, end=end)

@functools.lru_cache
def get_length(self, identifier: str) -> int:
"""Return the sequence length.

:param identifier: Sequence identifier to resolve.
:return: Sequence length.
:raises KeyError: If the sequence identifier is not found.
"""
return self._get_length(identifier)

@abstractmethod
def _get_metadata(self, identifier: str) -> dict: # pragma: no cover
"""Fetch sequence metadata from the backend.
def _get_length(self, identifier: str) -> int:
"""Return the sequence length.

:param identifier: Sequence identifier to resolve.
:return: Sequence metadata, including length and aliases.
:return: Sequence length.
:raises KeyError: If the sequence identifier is not found.
"""

@functools.lru_cache
def get_aliases(self, identifier: str) -> list[str]:

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.

Because this is lru_cached and returns a list, every caller gets the same list object. If anyone mutates the result (aliases.remove(...), .sort(), .append(...)), every later get_aliases(ac) for the life of the proxy sees the change, including translate_sequence_identifier and the refget_ac lookup in validate_location_bounds. The list(...) copy in the REST _get_aliases doesn't help, because the outer cache stores that copy. Returning a tuple (or copying on return) would rule this out.

"""Return the known sequence aliases.

:param identifier: Sequence identifier to resolve.
:return: List of known sequence aliases.
:raises KeyError: If the sequence identifier is not found.
"""
return self._get_aliases(identifier)

@abstractmethod
def _get_aliases(self, identifier: str) -> list[str]:
"""Return the known sequence aliases.

:param identifier: Sequence identifier to resolve.
:return: List of known sequence aliases.
:raises KeyError: If the sequence identifier is not found.
"""

@abstractmethod
def _get_sequence(
self, identifier: str, start: int | None = None, end: int | None = None
) -> str: # pragma: no cover
) -> str:
"""Fetch a sequence or subsequence from the backend.

:param identifier: Sequence identifier to resolve.
Expand Down Expand Up @@ -356,26 +365,48 @@ def _get_sequence(
"""
return self.sr.fetch_uri(coerce_namespace(identifier), start, end)

def _get_metadata(self, identifier: str) -> dict:
"""Fetch sequence metadata from the backend.
@functools.lru_cache
def _resolve_sequence_id(self, identifier: str) -> str:
"""Resolve an identifier to the internal SeqRepo sequence ID.

:param identifier: Sequence identifier to resolve.
:return: Sequence metadata, including length and aliases.
:raises KeyError: If the sequence identifier is not found.
:return: Internal SeqRepo sequence ID.
:raises KeyError: If the identifier is not found or resolves to multiple sequences.
"""
ns, a = coerce_namespace(identifier).split(":", 2)
r = list(self.sr.aliases.find_aliases(namespace=ns, alias=a))
if len(r) == 0:
namespace, alias = coerce_namespace(identifier).split(":", 1)
seq_ids = {
record["seq_id"]
for record in self.sr.aliases.find_aliases(namespace=namespace, alias=alias)
}
if not seq_ids:
raise KeyError(identifier)
seq_id = r[0]["seq_id"]
seqinfo = self.sr.sequences.fetch_seqinfo(seq_id)

if len(seq_ids) > 1:
msg = f"Identifier resolves to multiple sequences: {identifier}"

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 a behavior change from the old _get_metadata, which took r[0] when an alias matched more than one seq_id. Raising is probably more correct, but two things to consider:

  • find_aliases switches to SQL LIKE when the alias contains %, so a few identifiers that used to resolve will now fail in get_length/get_aliases/SequenceProxy.
  • translate_sequence_identifier re-raises as KeyError(identifier), which drops this message. Callers like derive_refget_accession then log a generic KeyError and can't tell "ambiguous" from "not found".

If the stricter behavior is intended, could the ambiguity message reach the caller (or the change be noted in the changelog)?

raise KeyError(msg)

return seq_ids.pop()

def _get_length(self, identifier: str) -> int:
"""Return the sequence length.

:param identifier: Sequence identifier to resolve.
:return: Sequence length.
:raises KeyError: If the sequence identifier is not found.
"""
seq_id = self._resolve_sequence_id(identifier)
return self.sr.sequences.fetch_seqinfo(seq_id)["len"]

def _get_aliases(self, identifier: str) -> list[str]:
"""Return the known sequence aliases.

:param identifier: Sequence identifier to resolve.
:return: List of known sequence aliases.
:raises KeyError: If the sequence identifier is not found.
"""
seq_id = self._resolve_sequence_id(identifier)
aliases = self.sr.aliases.find_aliases(seq_id=seq_id)
return {
"length": seqinfo["len"],
"alphabet": seqinfo["alpha"],
"added": _isoformat(seqinfo["added"]),
"aliases": [f"{a['namespace']}:{a['alias']}" for a in aliases],
}
return [f"{a['namespace']}:{a['alias']}" for a in aliases]


class SeqRepoRESTDataProxy(_SeqRepoDataProxyBase):
Expand Down Expand Up @@ -418,8 +449,29 @@ def _get_sequence(
resp.raise_for_status()
return resp.text

def _get_length(self, identifier: str) -> int:
"""Return the sequence length.

:param identifier: Sequence identifier to resolve.
:return: Sequence length.
:raises KeyError: If the sequence identifier is not found.
:raises requests.RequestException: If the request fails with an error other than a missing sequence.
"""
return self._get_metadata(identifier)["length"]

def _get_aliases(self, identifier: str) -> list[str]:
"""Return the known sequence aliases.

:param identifier: Sequence identifier to resolve.
:return: List of known sequence aliases.
:raises KeyError: If the sequence identifier is not found.
:raises requests.RequestException: If the request fails with an error other than a missing sequence.
"""
return list(self._get_metadata(identifier)["aliases"])

@functools.lru_cache
def _get_metadata(self, identifier: str) -> dict:

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.

Optional: caching is now layered. get_length/get_aliases are lru_cached, this REST _get_metadata is cached beneath them, and the local proxy adds a cache on _resolve_sequence_id. Each identifier can take up to three cache entries, and every method-level lru_cache holds a strong reference to self. Caching at a single layer (either the public methods or the backend helpers) would probably be enough.

"""Fetch sequence metadata from the backend.
"""Fetch and cache the REST metadata used by length and alias lookups.

:param identifier: Sequence identifier to resolve.
:return: Sequence metadata, including length and aliases.
Expand Down Expand Up @@ -447,10 +499,11 @@ def __init__(self, dp: _DataProxy, alias: str) -> None:

:param dp: Sequence data proxy.
:param alias: Sequence accession or alias.
:raises KeyError: If the sequence identifier is not found.
"""
self.dp = dp
self.alias = alias
self._md = self.dp.get_metadata(self.alias)
self._length = self.dp.get_length(self.alias)

def __str__(self) -> str:
"""Fetch the complete sequence.
Expand All @@ -464,7 +517,7 @@ def __len__(self) -> int:

:return: Sequence length.
"""
return self._md["length"]
return self._length

def __reversed__(self) -> NoReturn:
"""Reject reversed iteration.
Expand Down
Loading
Loading