diff --git a/src/datajoint/blob.py b/src/datajoint/blob.py index d8bf7a416..c80a17f7f 100644 --- a/src/datajoint/blob.py +++ b/src/datajoint/blob.py @@ -143,8 +143,9 @@ class Blob: Current serialization protocol (``b"mYm\\0"`` or ``b"dj0\\0"``). """ - def __init__(self, squeeze: bool = False) -> None: + def __init__(self, squeeze: bool = False, max_decompressed_size: int | None = None) -> None: self._squeeze = squeeze + self._max_decompressed_size = max_decompressed_size self._blob = None self._pos = 0 self.protocol = None @@ -186,8 +187,14 @@ def unpack(self, blob): pass # assume uncompressed but could be unrecognized compression else: self._pos += len(prefix) - blob_size = self.read_value() - self._blob = compression[prefix](self._blob[self._pos :], int(blob_size)) + blob_size = int(self.read_value()) + limit = self._max_decompressed_size + if limit is not None and blob_size > limit: + raise DataJointError( + f"Compressed blob declares {blob_size} bytes uncompressed, more than " + f"blob.max_decompressed_size ({limit}); it is not decompressed." + ) + self._blob = compression[prefix](self._blob[self._pos :], blob_size) self._pos = 0 blob_format = self.read_zero_terminated_string() if blob_format in ("mYm", "dj0"): @@ -633,7 +640,7 @@ def pack(obj, compress: bool = True) -> bytes: return Blob().pack(obj, compress=compress) -def unpack(blob: bytes, squeeze: bool = False): +def unpack(blob: bytes, squeeze: bool = False, max_decompressed_size: int | None = None): """ Deserialize a binary blob to a Python object. @@ -643,6 +650,9 @@ def unpack(blob: bytes, squeeze: bool = False): Binary data from ``pack()`` or MATLAB mYm serialization. squeeze : bool, optional If True, remove singleton dimensions from arrays. Default False. + max_decompressed_size : int, optional + Refuse a compressed blob whose recorded uncompressed size exceeds this + many bytes, before decompressing it. None (default): no limit. Returns ------- @@ -657,4 +667,4 @@ def unpack(blob: bytes, squeeze: bool = False): [1, 2, 3] """ if blob is not None: - return Blob(squeeze=squeeze).unpack(blob) + return Blob(squeeze=squeeze, max_decompressed_size=max_decompressed_size).unpack(blob) diff --git a/src/datajoint/builtin_codecs/blob.py b/src/datajoint/builtin_codecs/blob.py index ff65161f4..574ce892e 100644 --- a/src/datajoint/builtin_codecs/blob.py +++ b/src/datajoint/builtin_codecs/blob.py @@ -54,8 +54,17 @@ def encode(self, value: Any, *, key: dict | None = None, store_name: str | None return blob.pack(value, compress=True) - def decode(self, stored: bytes, *, key: dict | None = None) -> Any: - """Deserialize blob bytes back to a Python object.""" + def decode(self, stored: bytes, *, key: dict | None = None, context: dict | None = None) -> Any: + """ + Deserialize blob bytes back to a Python object. + + A compressed blob whose recorded uncompressed size exceeds + ``blob.max_decompressed_size`` is refused before it is decompressed. + """ from .. import blob - return blob.unpack(stored, squeeze=False) + config = self._codec_config(key, context) + if config is None: + from ..settings import config # type: ignore[assignment] + assert config is not None + return blob.unpack(stored, squeeze=False, max_decompressed_size=config["blob.max_decompressed_size"]) diff --git a/src/datajoint/declare.py b/src/datajoint/declare.py index 87cef4619..93dce70ca 100644 --- a/src/datajoint/declare.py +++ b/src/datajoint/declare.py @@ -8,6 +8,7 @@ from __future__ import annotations import ast +import inspect import logging import re @@ -173,10 +174,14 @@ def build_attribute_parser() -> pp.ParserElement: foreign_key_parser = build_foreign_key_parser() attribute_parser = build_attribute_parser() +# A name token is a Python identifier, as checked with str.isidentifier() below. +# Python identifiers may contain non-ASCII characters that \w does not match, such +# as combining marks (the vowel sign in Hindi "कि") and U+00B7 MIDDLE DOT, so a name +# token also takes in every non-ASCII character other than white space. _REFERENCE_TOKEN = re.compile( r"""\s*(?: (?P\#.*) - | (?P[^\W\d]\w*) + | (?P(?:[^\W\d]|[^\x00-\x7f\s])(?:\w|[^\x00-\x7f\s])*) | (?P"(?:[^"\\\n]|\\.)*"|'(?:[^'\\\n]|\\.)*') | (?P[.(),=]) )""", @@ -306,14 +311,45 @@ def reference(): return steps +def _lookup_attribute(obj, name: str): + """ + Look up ``name`` on ``obj`` for a ``.name`` step of a foreign-key reference. + + The name is looked up statically first, with ``inspect.getattr_static``, + which runs no code of ``obj``. Module attributes, table classes and their + part tables are found this way. + + The dynamic ``getattr`` is the fallback. It runs only when the static + lookup finds no value: when ``obj`` has no such attribute (a module-level + or class ``__getattr__`` may supply it, as in a module that loads its + tables lazily), or when the attribute is a descriptor such as a property, + whose value only running it gives. References through these resolve as + they did with ``getattr`` alone. + + Raises + ------ + AttributeError + If neither lookup finds the attribute. + """ + try: + value = inspect.getattr_static(obj, name) + except AttributeError: + pass + else: + if not hasattr(type(value), "__get__"): + return value + return getattr(obj, name) + + def resolve_foreign_key_reference(ref_table: str, context: dict): """ Resolve the table reference of a foreign key line in a namespace. The reference is parsed by :func:`parse_foreign_key_reference`, never - evaluated: names are looked up in ``context`` attribute by attribute, a - table class may be instantiated with ``()``, and ``.proj(...)`` is called - with the parsed string arguments. + evaluated: names are looked up in ``context`` attribute by attribute + (statically first; see :func:`_lookup_attribute`), a table class may be + instantiated with ``()``, and ``.proj(...)`` is called with the parsed + string arguments. Parameters ---------- @@ -356,7 +392,7 @@ def is_table_class(obj): ref = context[step[1]] elif step[0] == "attr": try: - ref = getattr(ref, step[1]) + ref = _lookup_attribute(ref, step[1]) except Exception: raise unresolved(f"no attribute {step[1]}") from None elif step[0] == "instance": diff --git a/src/datajoint/diagram.py b/src/datajoint/diagram.py index 598d36d51..8edee00ce 100644 --- a/src/datajoint/diagram.py +++ b/src/datajoint/diagram.py @@ -21,6 +21,7 @@ import io import logging import re +import warnings import networkx as nx @@ -1524,6 +1525,9 @@ def _encapsulate_edge_attributes(graph: nx.MultiDiGraph) -> None: """ Encapsulate edge attr_map in double quotes for pydot compatibility. + A double quote inside, from a column name such as ``a"b`` or ``a'b`` (whose + repr is double-quoted), is escaped, so the DOT source stays valid. + Modifies graph in place. See Also @@ -1532,7 +1536,7 @@ def _encapsulate_edge_attributes(graph: nx.MultiDiGraph) -> None: """ for u, v, k, edgedata in graph.edges(keys=True, data=True): if "attr_map" in edgedata: - graph.edges[u, v, k]["attr_map"] = '"{0}"'.format(edgedata["attr_map"]) + graph.edges[u, v, k]["attr_map"] = '"{0}"'.format(str(edgedata["attr_map"]).replace('"', '\\"')) @staticmethod def _encapsulate_node_names(graph: nx.MultiDiGraph) -> None: @@ -1656,7 +1660,9 @@ def make_dot(self, theme=None): if child != parent ) if renames: - edata["tooltip"] = renames + # pydot quotes the value but leaves backslashes as they are: double + # them, so a column name ending in one does not escape the closing quote + edata["tooltip"] = renames.replace("\\", "\\\\") self._encapsulate_node_names(graph) self._encapsulate_edge_attributes(graph) @@ -1734,13 +1740,24 @@ def _master_of(part_stripped): else: cls = self._resolve_class(name) if cls is not None: - description = cls().describe(context=self.context).split("\n") + try: + with warnings.catch_warnings(): + # describe() warns when alter() cannot read its text back; + # that does not concern the tooltip + warnings.simplefilter("ignore") + description = cls().describe(context=self.context).split("\n") + except DataJointError as error: + # one table that cannot be described must not stop the whole diagram: + # its tooltip shows only its name + logger.debug("No definition in the tooltip of %s: %s", name, error) + description = [name] description = ( ("-" * 30 if q.startswith("---") else (q.replace("->", "→") if "->" in q else q.split(":")[0])) for q in description if not q.startswith("#") ) - node.set_tooltip(" ".join(description)) + # backslashes doubled, as in the edge tooltip + node.set_tooltip(" ".join(description).replace("\\", "\\\\")) # Strip module prefix from label if it matches the cluster label display_name = name if name in part_names: diff --git a/src/datajoint/settings.py b/src/datajoint/settings.py index 981bbc314..d38cce7a2 100644 --- a/src/datajoint/settings.py +++ b/src/datajoint/settings.py @@ -504,6 +504,24 @@ class JobsSettings(BaseSettings): ) +class BlobSettings(BaseSettings): + """Limits applied when blobs are read.""" + + model_config = SettingsConfigDict( + env_prefix="DJ_BLOB_", + case_sensitive=False, + extra="forbid", + validate_assignment=True, + ) + + max_decompressed_size: int | None = Field( + default=None, + ge=0, + description="Refuse a compressed blob whose recorded uncompressed size exceeds this many bytes, " + "before decompressing it. None (default): no limit. *New in 2.3.7.*", + ) + + class ProvenanceSettings(BaseSettings): """Extrinsic provenance capture at pipeline entry points.""" @@ -586,6 +604,7 @@ class Config(BaseSettings): display: DisplaySettings = Field(default_factory=DisplaySettings) jobs: JobsSettings = Field(default_factory=JobsSettings) provenance: ProvenanceSettings = Field(default_factory=ProvenanceSettings) + blob: BlobSettings = Field(default_factory=BlobSettings) # Unified stores configuration (replaces external and object_storage) # ``validation_alias`` redirects pydantic-settings' env source away from the diff --git a/src/datajoint/table.py b/src/datajoint/table.py index dd6e979f8..9b690cbbe 100644 --- a/src/datajoint/table.py +++ b/src/datajoint/table.py @@ -16,7 +16,7 @@ from . import provenance from .condition import make_condition -from .declare import alter, declare +from .declare import alter, declare, parse_foreign_key_reference from .dependencies import extract_master from .errors import ( AccessError, @@ -337,7 +337,7 @@ def alter(self, prompt=True, context=None): frame = inspect.currentframe().f_back context = dict(frame.f_globals, **frame.f_locals) del frame - old_definition = self.describe(context=context) + old_definition = self._describe(context, strict=True) sql, _external_stores, pre_ddl, column_comments = alter( self.definition, old_definition, @@ -1363,11 +1363,35 @@ def describe(self, context=None, printout=False): ------- str The definition string for the table in DataJoint DDL format. + + Warns + ----- + UserWarning + If a projected foreign key attribute read from the database is not a + name a definition can hold, such as a column named ``a-b`` by SQL. The + name is written as is, and ``alter()`` refuses the table. """ if context is None: frame = inspect.currentframe().f_back context = dict(frame.f_globals, **frame.f_locals) del frame + definition = self._describe(context) + if printout: + logger.info("\n" + definition) + return definition + + def _describe(self, context, strict=False): + """ + Write the definition for :meth:`describe` and :meth:`alter`. + + A projected foreign key is written as ``Parent.proj(new="old")``: the old + names are quoted and the new names are not, since keyword names cannot be. + A new name that the foreign key parser does not read back as itself (a + column named ``a-b`` or ``x=1`` by SQL, for example) is written as is, + since no form of the reference holds it. ``alter()`` passes ``strict`` and + raises for such a name rather than parse a different definition; + ``describe()`` warns. + """ if self.full_table_name not in self.connection.dependencies: self.connection.dependencies.load() parents = self.parents(foreign_key_info=True) @@ -1376,6 +1400,7 @@ def describe(self, context=None, printout=False): definition = "# " + table_comment + "\n" if table_comment else "" attributes_thus_far = set() attributes_declared = set() + unreadable = [] # projected names written as is, which the parser does not read back indexes = self.heading.indexes.copy() if self.heading.indexes else {} for attr in self.heading.attributes.values(): if in_key and not attr.in_key: @@ -1413,7 +1438,13 @@ def describe(self, context=None, printout=False): class_name=_one_line(lookup_class_name(parent_name, context) or parent_name), ) else: - # projected foreign key + # projected foreign key; the new names are written as is (the + # referenced names are quoted); note those not read back as themselves + unreadable.extend( + new_name + for new_name, ref in fk_props["attr_map"].items() + if ref != new_name and not _is_projection_name(new_name) + ) definition += "->{options} {class_name}.proj({proj_list})\n".format( options=options_str, class_name=_one_line(lookup_class_name(parent_name, context) or parent_name), @@ -1440,8 +1471,20 @@ def describe(self, context=None, printout=False): definition += "{unique}INDEX ({attrs})\n".format( unique="UNIQUE " if v["unique"] else "", attrs=", ".join(_one_line(a) for a in k) ) - if printout: - logger.info("\n" + definition) + if unreadable: + names = ", ".join(repr(name) for name in unreadable) + if len(unreadable) == 1: + problem = f"the foreign key attribute {names} read from the database is not a name a definition can hold" + else: + problem = f"the foreign key attributes {names} read from the database are not names a definition can hold" + if strict: + raise DataJointError(f"Cannot alter {self.full_table_name}: {problem}.") + warnings.warn( + f"The definition of {self.full_table_name} cannot be read back: {problem}. " + "describe() writes such a name as is, and alter() refuses this table.", + UserWarning, + stacklevel=3, + ) return definition # --- private helper functions ---- @@ -1681,6 +1724,22 @@ def _quoted(text): return '"{}"'.format(_one_line(text).replace("\\", "\\\\").replace('"', '\\"')) +def _is_projection_name(name): + """ + Whether ``name``, written unquoted as a ``.proj()`` keyword argument, is parsed back as itself. + + ``describe()`` writes a projected foreign key as ``Parent.proj(new="old")`` and + ``alter()`` reads it back with :func:`~datajoint.declare.parse_foreign_key_reference`. + Any name that parser reads back unchanged is accepted, Python keywords such as + ``class`` included. + """ + try: + steps = parse_foreign_key_reference(f'Parent.proj({name}="")') + except (ValueError, SyntaxError): + return False + return steps == [("name", "Parent"), ("proj", [], {name: ""})] + + def lookup_class_name(name, context, depth=3): """ Find a table's class in the context given its full table name. diff --git a/tests/integration/test_definition_blob_follow_ups.py b/tests/integration/test_definition_blob_follow_ups.py new file mode 100644 index 000000000..1c320848a --- /dev/null +++ b/tests/integration/test_definition_blob_follow_ups.py @@ -0,0 +1,215 @@ +""" +Definition and blob follow-ups (#1717), on both backends. + +- ``blob.max_decompressed_size`` refuses a compressed blob on fetch whose recorded + uncompressed size exceeds it. Unset, blobs are fetched as before. +- A projected foreign-key attribute named with any Python identifier, a keyword + such as ``class`` or a name with characters that ``\\w`` does not match, is + declared, written by ``describe()`` and read back by ``alter()``. +- A projected foreign-key attribute named in the database with a name no definition + can hold (``x=1``, ``a-b``) is written as is by ``describe()``, with a warning; + ``alter()`` refuses the table, and ``dj.Diagram`` still renders the schema, without + the warning. +- ``dj.Diagram`` renders a table whose ``describe()`` raises, without its definition + in the tooltip, and a referenced column whose name has a double quote or ends in a + backslash. +- A column comment and a referenced column name go through ``describe()`` and + ``alter()``. (Double quotes in comments on PostgreSQL are left to + https://github.com/datajoint/datajoint-python/issues/1729.) +""" + +import html +import time +import warnings + +import numpy as np +import pytest + +import datajoint as dj +from datajoint.errors import DataJointError + + +@pytest.fixture +def schema_fu(connection_by_backend, db_creds_by_backend): + name = f"djtest_def_blob_{db_creds_by_backend['backend']}_{str(int(time.time() * 1000))[-8:]}" + schema = dj.Schema(name, connection=connection_by_backend) + yield schema + schema.drop(prompt=False) + + +@pytest.fixture +def blob_table(schema_fu): + @schema_fu + class Signal(dj.Manual): + definition = """ + signal_id : int32 + --- + samples : + """ + + return Signal + + +def test_blob_size_limit_on_fetch(blob_table): + value = np.zeros(5_000_000, dtype=np.uint8) # about 5 kB compressed + blob_table.insert1({"signal_id": 1, "samples": value}) + np.testing.assert_array_equal((blob_table & {"signal_id": 1}).fetch1("samples"), value) + with dj.config.override(blob__max_decompressed_size=1_000_000): + with pytest.raises(DataJointError, match="max_decompressed_size"): + (blob_table & {"signal_id": 1}).fetch1("samples") + with dj.config.override(blob__max_decompressed_size=10_000_000): + np.testing.assert_array_equal((blob_table & {"signal_id": 1}).fetch1("samples"), value) + + +@pytest.fixture +def projected_tables(schema_fu): + class Parent(dj.Manual): + definition = """ + parent_id : int32 # the parent's id + """ + + class Child(dj.Manual): + definition = """ + child_id : int32 + --- + -> Parent.proj(parent_ref="parent_id") + note : varchar(64) # it's a note # with a hash + """ + + context = {"Parent": Parent, "Child": Child} + schema_fu(Parent, context=context) + schema_fu(Child, context=context) + return Parent, Child, context + + +def test_comment_and_referenced_name_through_describe_and_alter(projected_tables): + """alter() parses describe() of the current table, so both must survive the round trip.""" + _, Child, context = projected_tables + described = Child().describe(context=context) + assert '-> Parent.proj(parent_ref="parent_id")' in described + assert "# it's a note # with a hash" in described + Child.definition = Child.definition.rstrip() + "\n extra = null : int32 # added 'later' # also a hash\n" + Child().alter(prompt=False, context=context) + described = Child().describe(context=context) + assert '-> Parent.proj(parent_ref="parent_id")' in described + assert "# it's a note # with a hash" in described + assert "# added 'later' # also a hash" in described + assert Child().heading.attributes["parent_ref"].comment == "the parent's id" + Child().alter(prompt=False, context=context) # nothing left to alter + + +@pytest.mark.parametrize("new_name", ["class", "from", "किताब_id", "x\u00b7y"]) +def test_projected_name_that_is_a_python_identifier(schema_fu, new_name): + """ + Every Python identifier is a valid projected name: a keyword, or a name with a + character that \\w does not match (a combining vowel sign, U+00B7). alter() reads + it back from describe(), and the diagram shows the table. + """ + + class Parent(dj.Manual): + definition = """ + parent_id : int32 + """ + + class Child(dj.Manual): + definition = f""" + child_id : int32 + --- + -> Parent.proj({new_name}="parent_id") + """ + + context = {"Parent": Parent, "Child": Child} + schema_fu(Parent, context=context) + schema_fu(Child, context=context) + Parent.insert1({"parent_id": 1}) + Child.insert1({"child_id": 1, new_name: 1}) + assert f'-> Parent.proj({new_name}="parent_id")' in Child().describe(context=context) + Child().alter(prompt=False, context=context) # describe() is parsed back; nothing to alter + assert Child.fetch1(new_name) == 1 + assert "Child" in dj.Diagram(schema_fu, context=context).make_svg().data + + +# Column names that SQL accepts and that no definition can hold: the new name of a +# projected foreign key is written unquoted, as a keyword argument name, and the +# parser reads only a Python identifier there. +NAMES_NOT_READ_BACK = ["x=1", 'a"b', "a'b", "a\\b", 'a\\"b', "a-b", "a b", "1st_ref", "a$b"] + + +def _rename_column(connection, table, old_name, new_name): + quote = connection.adapter.quote_identifier + q = quote("")[0] # the backend's identifier quote, doubled inside a quoted name + connection.query( + f"ALTER TABLE {table.full_table_name} RENAME COLUMN {quote(old_name)} TO {quote(new_name.replace(q, q + q))}" + ) + connection.dependencies.load() + + +def _rename_foreign_key_column(connection, table, new_name): + _rename_column(connection, table, "parent_ref", new_name) + + +def _make_svg_describe_warning_as_error(schema, context): + """Render the diagram with the warning of describe() raised as an error, as under ``python -W error``.""" + with warnings.catch_warnings(): + warnings.filterwarnings("error", message="The definition of .* cannot be read back", category=UserWarning) + return dj.Diagram(schema, context=context).make_svg().data + + +@pytest.mark.parametrize("new_name", NAMES_NOT_READ_BACK) +def test_describe_writes_projected_name_not_read_back(projected_tables, connection_by_backend, new_name): + """describe() writes such a name as is and warns; alter() refuses the table instead of parsing that text.""" + _, Child, context = projected_tables + _rename_foreign_key_column(connection_by_backend, Child, new_name) + table = dj.FreeTable(connection_by_backend, Child.full_table_name) + with pytest.warns(UserWarning, match="cannot be read back") as record: + described = table.describe(context=context) + assert repr(new_name) in str(record[0].message) + assert f'.proj({new_name}="parent_id")' in described + assert "note" in described # the rest of the definition is written + with pytest.raises(DataJointError, match="Cannot alter") as error: + table.alter(prompt=False, context=context) + assert repr(new_name) in str(error.value) + + +@pytest.mark.parametrize("new_name", NAMES_NOT_READ_BACK) +def test_diagram_of_schema_with_projected_name_not_read_back(projected_tables, connection_by_backend, new_name): + """ + One table whose definition cannot be read back does not stop the diagram of its + schema, and the warning of describe() is not emitted for the tooltip. + """ + _, Child, _ = projected_tables + _rename_foreign_key_column(connection_by_backend, Child, new_name) + module = dj.VirtualModule("module", Child.database, connection=connection_by_backend) + svg = _make_svg_describe_warning_as_error(module.schema, vars(module)) + assert "Child" in svg and "Parent" in svg + + +@pytest.mark.parametrize("referenced_name", ['p"id', "p\\"], ids=["double quote", "trailing backslash"]) +def test_diagram_with_referenced_column_renamed(projected_tables, connection_by_backend, referenced_name): + """ + A referenced column named by SQL with a double quote, or with a backslash at the + end, goes into the parent's tooltip and the renamed foreign key's edge tooltip. + Each is quoted in the DOT source, and the diagram renders. + """ + Parent, Child, _ = projected_tables + _rename_column(connection_by_backend, Parent, "parent_id", referenced_name) + module = dj.VirtualModule("module", Child.database, connection=connection_by_backend) + assert module.Child().parents(foreign_key_info=True)[0][1]["attr_map"] == {"parent_ref": referenced_name} + svg = _make_svg_describe_warning_as_error(module.schema, vars(module)) + assert "Child" in svg and "Parent" in svg + assert html.escape(f"parent_ref \u2190 {referenced_name}") in svg # the edge tooltip + + +def test_diagram_tooltip_without_definition(schema_fu, projected_tables, monkeypatch): + """A table whose describe() raises gets a tooltip without its definition; the other tables keep theirs.""" + _, Child, context = projected_tables + + def describe(self, context=None, printout=False): + raise DataJointError("cannot describe") + + monkeypatch.setattr(Child, "describe", describe) + diagram = dj.Diagram(schema_fu, context=context) + tooltips = {node.get_name().strip('"'): node.get("tooltip") for node in diagram.make_dot().get_nodes()} + assert tooltips["Child"].strip('"') == "Child" + assert "parent_id" in tooltips["Parent"] + assert "Child" in diagram.make_svg().data diff --git a/tests/unit/test_blob_decompression.py b/tests/unit/test_blob_decompression.py index 9bca71928..2e2231c2b 100644 --- a/tests/unit/test_blob_decompression.py +++ b/tests/unit/test_blob_decompression.py @@ -6,8 +6,11 @@ import numpy as np import pytest -from datajoint.blob import len_u64, pack, unpack +import datajoint.blob as blob_module +from datajoint.blob import len_u64, pack, serialize_lookup, unpack +from datajoint.builtin_codecs.blob import BlobCodec from datajoint.errors import DataJointError +from datajoint.settings import Config PREFIX = b"ZL123\0" @@ -71,3 +74,95 @@ def test_corrupt_stream_is_rejected(): payload = pack(np.arange(1000), compress=False) with pytest.raises(DataJointError, match="Corrupt"): unpack(PREFIX + len_u64(payload) + b"not zlib data") + + +# --------------------------------------------------------------------------- # +# Opt-in cap on the recorded uncompressed size: blob.max_decompressed_size +# --------------------------------------------------------------------------- # +def high_ratio_blob(): + """A blob that records its true size: 50 MB of zeros, about 50 kB compressed.""" + value = np.zeros(50_000_000, dtype=np.uint8) + blob = pack(value) + assert blob.startswith(PREFIX) and len(blob) < 1_000_000 + return value, blob, int(np.frombuffer(blob[len(PREFIX) : len(PREFIX) + 8], dtype=np.uint64)[0]) + + +def test_true_size_high_ratio_blob_decodes_without_a_limit(): + value, blob, _ = high_ratio_blob() + np.testing.assert_array_equal(unpack(blob), value) + + +def test_limit_refuses_blob_before_decompressing_it(): + _, blob, size = high_ratio_blob() + tracemalloc.start() + try: + with pytest.raises(DataJointError, match="max_decompressed_size"): + unpack(blob, max_decompressed_size=size - 1) + _, peak = tracemalloc.get_traced_memory() + finally: + tracemalloc.stop() + assert peak < 5_000_000 + + +def test_limit_at_the_recorded_size_decodes(): + value, blob, size = high_ratio_blob() + np.testing.assert_array_equal(unpack(blob, max_decompressed_size=size), value) + + +def test_limit_does_not_apply_to_uncompressed_blob(): + blob = pack(np.arange(1000), compress=False) + np.testing.assert_array_equal(unpack(blob, max_decompressed_size=10), np.arange(1000)) + + +def test_setting_is_off_by_default(monkeypatch): + monkeypatch.delenv("DJ_BLOB_MAX_DECOMPRESSED_SIZE", raising=False) + assert Config().blob.max_decompressed_size is None + + +def test_setting_from_environment_and_validation(monkeypatch): + monkeypatch.setenv("DJ_BLOB_MAX_DECOMPRESSED_SIZE", "1000") + cfg = Config() + assert cfg["blob.max_decompressed_size"] == 1000 + with pytest.raises(ValueError): + cfg.blob.max_decompressed_size = -1 + + +def test_codec_applies_the_setting_from_its_config(): + value, blob, size = high_ratio_blob() + cfg = Config() + np.testing.assert_array_equal(BlobCodec().decode(blob, context={"config": cfg}), value) + cfg.blob.max_decompressed_size = size - 1 + with pytest.raises(DataJointError, match="max_decompressed_size"): + BlobCodec().decode(blob, context={"config": cfg}) + + +def _mym_double_array(values, dims_dtype): + """A MATLAB mYm blob holding a column of doubles, with dimensions of type ``dims_dtype``.""" + values = np.asarray(values, dtype=np.float64) + type_id = serialize_lookup[np.dtype("float64")]["type_id"] + return ( + b"mYm\0" + + b"A" + + np.array(2, dtype=dims_dtype).tobytes() # number of dimensions + + np.array([1, len(values)], dtype=dims_dtype).tobytes() # shape + + np.array([type_id, 0], dtype=np.uint32).tobytes() # type, not complex + + values.tobytes() + ) + + +@pytest.mark.parametrize("use_32bit_dims", [False, True], ids=["64bit", "32bit"]) +def test_matlab_blob_through_size_checks(monkeypatch, use_32bit_dims): + """mYm blobs from MATLAB: the recorded size is read with the configured width and checked.""" + dims_dtype = np.uint32 if use_32bit_dims else np.uint64 + monkeypatch.setattr(blob_module, "use_32bit_dims", use_32bit_dims) + values = np.arange(100_000, dtype=np.float64) % 7 + payload = _mym_double_array(values, dims_dtype) + blob = PREFIX + np.array(len(payload), dtype=dims_dtype).tobytes() + zlib.compress(payload) + np.testing.assert_array_equal(unpack(blob).ravel(), values) + np.testing.assert_array_equal(unpack(blob, max_decompressed_size=len(payload)).ravel(), values) + with pytest.raises(DataJointError, match="max_decompressed_size"): + unpack(blob, max_decompressed_size=len(payload) - 1) + for declared in (len(payload) - 1, len(payload) + 1): + wrong = PREFIX + np.array(declared, dtype=dims_dtype).tobytes() + zlib.compress(payload) + with pytest.raises(DataJointError, match="size mismatch"): + unpack(wrong) diff --git a/tests/unit/test_foreign_key_reference.py b/tests/unit/test_foreign_key_reference.py index 8d4656699..8caf02d19 100644 --- a/tests/unit/test_foreign_key_reference.py +++ b/tests/unit/test_foreign_key_reference.py @@ -15,7 +15,7 @@ from datajoint.adapters.mysql import MySQLAdapter from datajoint.declare import parse_foreign_key_reference, prepare_declare, resolve_foreign_key_reference from datajoint.errors import DataJointError -from datajoint.table import _one_line, _quoted +from datajoint.table import _is_projection_name, _one_line, _quoted class Parent(dj.Manual): @@ -96,6 +96,7 @@ def test_instantiation(context): ('Projectable().proj(a="b", c="d",)', (), {"a": "b", "c": "d"}), ("(Projectable).proj('x', a='b')", ("x",), {"a": "b"}), (r'Projectable.proj(a="say \"hi\"")', (), {"a": 'say "hi"'}), + ('Projectable.proj(class="projectable_id", from="b")', (), {"class": "projectable_id", "from": "b"}), ], ) def test_projection_arguments_are_string_literals(reference, args, kwargs, context): @@ -170,3 +171,156 @@ def test_describe_text_stays_on_one_line(): text = 'a "quoted" \\ value\nwith a line break' steps = parse_foreign_key_reference("Parent.proj(new={})".format(_quoted(text))) assert steps == [("name", "Parent"), ("proj", [], {"new": _one_line(text)})] + + +@pytest.mark.parametrize( + "name", + ["parent_ref", "class", "from", "lambda", "_private", "Größe", "किताब_id", "x\u00b7y", "\u2118x", "x\u203fy", "__x"], +) +def test_projection_names_written_by_describe_are_read_back(name): + """ + describe() writes Parent.proj(new="old") with the new name unquoted. Every Python + identifier is read back: keywords, and names with characters that \\w does not + match (a combining vowel sign in किताब, U+00B7, U+2118, U+203F). + """ + assert _is_projection_name(name) + steps = parse_foreign_key_reference("Parent.proj({}={})".format(name, _quoted('old "quoted" \\ name'))) + assert steps == [("name", "Parent"), ("proj", [], {name: 'old "quoted" \\ name'})] + + +@pytest.mark.parametrize("name", ["किताब", "x\u00b7y"]) +def test_identifiers_beyond_word_characters_resolve(name, context): + context[name] = Parent + assert resolve_foreign_key_reference(f"{name}.Part", context) is Parent.Part + + +@pytest.mark.parametrize( + "name", + [ + "x=1", + 'a"b', + "a'b", + "a\\b", + 'a\\"b', + "a b", + "1a", + "a#b", + "a)", + 'a="x",b', + "a.b", + "a\nb", + "", + "a-b", + "a$b", + "a b", + "a\uff1db", + "\u0663a", + ], +) +def test_projection_names_not_read_back_are_refused(name): + assert not _is_projection_name(name) + + +class _Lookups: + """An object whose attributes run code when read: a property, and a custom __getattr__ for other names.""" + + Static = Parent + + def __init__(self, calls): + self._calls = calls + + @property + def Computed(self): + self._calls.append("property") + return Parent + + def __getattr__(self, name): + self._calls.append(f"__getattr__ {name}") + if name == "Missing": + raise AttributeError(name) + return Parent + + +def _lazy_module(calls, **attributes): + """A module that supplies the names it does not hold through a module-level __getattr__ (PEP 562).""" + lazy_module = types.ModuleType("lazy_module") + vars(lazy_module).update(attributes) + + def __getattr__(name): + calls.append(f"module __getattr__ {name}") + if name == "Missing": + raise AttributeError(name) + return Parent + + lazy_module.__getattr__ = __getattr__ + return lazy_module + + +def test_static_lookup_runs_no_code(context, calls): + """A name the static lookup finds is resolved without running __getattr__, even when the object has one.""" + context.update(lookups=_Lookups(calls), lazy_module=_lazy_module(calls, Parent=Parent)) + assert resolve_foreign_key_reference("lookups.Static", context) is Parent + assert resolve_foreign_key_reference("lazy_module.Parent.Part", context) is Parent.Part + assert calls == [] + + +class _Intercepting: + """An object whose __getattribute__ runs for every attribute read: it returns another table, or raises.""" + + Static = Parent + + def __init__(self, calls, raises): + self._calls = calls + self._raises = raises + + def __getattribute__(self, name): + object.__getattribute__(self, "_calls").append(f"__getattribute__ {name}") + if object.__getattribute__(self, "_raises"): + raise AttributeError(name) + return Projectable + + +@pytest.mark.parametrize("raises", [False, True], ids=["returns another table", "raises"]) +def test_static_lookup_comes_before_getattr(raises, context, calls): + """getattr alone would run __getattribute__; the static lookup finds the class attribute without running it.""" + intercepting = _Intercepting(calls, raises) + context["intercepting"] = intercepting + assert resolve_foreign_key_reference("intercepting.Static", context) is Parent + assert calls == [] + # what getattr alone gives for the same name + if raises: + with pytest.raises(AttributeError): + getattr(intercepting, "Static") + else: + assert getattr(intercepting, "Static") is Projectable + assert calls == ["__getattribute__ Static"] + + +@pytest.mark.parametrize( + "reference, call", + [ + ("lazy_module.Parent", "module __getattr__ Parent"), + ("lookups.Anything", "__getattr__ Anything"), + ("lookups.Computed", "property"), + ], +) +def test_dynamic_lookup_when_static_lookup_finds_no_value(reference, call, context, calls): + """A module or class __getattr__ and a property still resolve: getattr runs only for them.""" + context.update(lookups=_Lookups(calls), lazy_module=_lazy_module(calls)) + assert resolve_foreign_key_reference(reference, context) is Parent + assert calls == [call] + + +@pytest.mark.parametrize("reference", ["lazy_module.Missing", "lookups.Missing", "module.Missing"]) +def test_attribute_found_by_neither_lookup(reference, context, calls): + context.update(lookups=_Lookups(calls), lazy_module=_lazy_module(calls)) + with pytest.raises(DataJointError, match="could not be resolved: no attribute Missing"): + resolve_foreign_key_reference(reference, context) + + +def test_attribute_lookup_finds_class_and_module_attributes(context): + real_module = types.ModuleType("real_module") + real_module.Parent = Parent + context["real_module"] = real_module + assert resolve_foreign_key_reference("real_module.Parent", context) is Parent + assert resolve_foreign_key_reference("real_module.Parent.Part", context) is Parent.Part