Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix distributed.Client.compute applied to DataArray #3173

Merged
merged 2 commits into from
Aug 1, 2019
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
5 changes: 4 additions & 1 deletion doc/whats-new.rst
Original file line number Diff line number Diff line change
Expand Up @@ -55,8 +55,11 @@ Bug fixes
due to a ``datetime`` issue in NumPy (:issue:`2334`).
By `Graham Inggs <https://github.com/ginggs>`_.
- Fixed bug in ``combine_by_coords()`` causing a `ValueError` if the input had
an unused dimension with coordinates which were not monotonic (:issue`3150`).
an unused dimension with coordinates which were not monotonic (:issue:`3150`).
By `Tom Nicholas <http://github.com/TomNicholas>`_.
- Fixed crash when applying ``distributed.Client.compute()`` to a DataArray
(:issue:`3171`). By `Guido Imperiale <https://github.com/crusaderky>`_.


.. _whats-new.0.12.3:

Expand Down
6 changes: 3 additions & 3 deletions xarray/core/dataarray.py
Original file line number Diff line number Diff line change
Expand Up @@ -300,7 +300,7 @@ def _replace(
self,
variable: Variable = None,
coords=None,
name: Union[Hashable, None, ReprObject] = __default,
name: Optional[Hashable] = __default,
) -> 'DataArray':
if variable is None:
variable = self.variable
Expand All @@ -313,7 +313,7 @@ def _replace(
def _replace_maybe_drop_dims(
self,
variable: Variable,
name: Union[str, None, utils.ReprObject] = __default
name: Optional[Hashable] = __default
) -> 'DataArray':
if variable.dims == self.dims and variable.shape == self.shape:
coords = self._coords.copy()
Expand Down Expand Up @@ -356,7 +356,7 @@ def _to_temp_dataset(self) -> Dataset:
def _from_temp_dataset(
self,
dataset: Dataset,
name: Union[Hashable, ReprObject] = __default
name: Hashable = __default
) -> 'DataArray':
variable = dataset._variables.pop(_THIS_ARRAY)
coords = dataset._variables
Expand Down
10 changes: 10 additions & 0 deletions xarray/core/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -462,12 +462,22 @@ def __repr__(self: Any) -> str:
class ReprObject:
"""Object that prints as the given value, for use with sentinel values.
"""
__slots__ = ('_value', )

def __init__(self, value: str):
self._value = value

def __repr__(self) -> str:
return self._value

def __eq__(self, other) -> bool:
if isinstance(other, ReprObject):
return self._value == other._value
return False

def __hash__(self) -> int:
return hash((ReprObject, self._value))
Copy link
Collaborator

Choose a reason for hiding this comment

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

I don't think this will be stable across processes - I just tried this in two different processes:

In [5]: hash(ReprObject)
Out[5]: 8774331846827

(new process)


In [2]: hash(ReprObject)
Out[2]: 8795055479397

Does that matter here? If so, could we change to hash(('ReprObject', self._value))?

Copy link
Collaborator

Choose a reason for hiding this comment

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

Ah, the hash is never stable across processes, I just tried the same for 'hello'.

Does dask rely on the hash, or an equality (or something else)?

Copy link
Collaborator

Choose a reason for hiding this comment

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

I think it's here: --> 708 variable = ds._variables.pop(_THIS_ARRAY) from #3171

So then both, so this looks good - doesn't need to be consistent across processes

Copy link
Contributor Author

Choose a reason for hiding this comment

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

xarray (actually not dask) relies on the fact that a deep copy of a key object that has gone through a round-trip on the network produces the same hash as the original. The fact that the hash changes (by design; it's an anti-DoS measure) every time you restart the interpteter is irrelevant because the __hash__ method is always invoked locally. It would be, on the other hand, a grave mistake to cache it and then allow the cache to be serialised.

Copy link
Contributor Author

@crusaderky crusaderky Aug 1, 2019

Choose a reason for hiding this comment

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

To elaborate:

BAD - the hash defaults to the id, which will break as soon as the object is shallow-copied

class C:
    pass

GOOD:

class C:
    def __hash__(self):
        return 123  # skip: actual calculation

BAD - it works as long as you do everything locally, but it will break as soon as you pickle the object and unpickle it in a different interpreter. Worth noting that a typical unit test c2 = pickle.loads(pickle.dumps(c)) will NOT spot the issue as the pickling and unpickling happen in the same interpreter.

class C:
    _hash_cache = None

    def __hash__(self):
        if self._hash_cache is None:
            self._hash_cache = 123  # skip: actual, CPU-intensive, calculation
        return self._hash_cache

GOOD AGAIN:

class C:
    _hash_cache = None

    def __hash__(self):
        if self._hash_cache is None:
            self._hash_cache = 123  # skip: actual, CPU-intensive, calculation
        return self._hash_cache

    def __getstate__(self):
        state = self.__dict__.copy()
        state.pop("_hash_cache", None)
        return state

Copy link
Collaborator

Choose a reason for hiding this comment

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

Thanks for the explanation! Out of interest, why is this the case:

BAD - it works as long as you do everything locally, but it will break as soon as you pickle the object and unpickle it in a different interpreter.

...assuming...

The fact that the hash changes every time you restart the interpteter is irrelevant because the hash method is always invoked locally.

Copy link
Member

Choose a reason for hiding this comment

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

I'm a little surprised that these default values end up in pickles, but I guess it can happen.

Copy link
Collaborator

Choose a reason for hiding this comment

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

I'm doubtful the default values would - an attribute on the class wouldn't be in the instance dict until it's assigned to



@contextlib.contextmanager
def close_on_error(f):
Expand Down
16 changes: 16 additions & 0 deletions xarray/tests/test_utils.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
from collections import OrderedDict
from datetime import datetime
from typing import Hashable

import numpy as np
import pandas as pd
Expand Down Expand Up @@ -179,6 +180,21 @@ def test_sorted_keys_dict(self):
def test_repr_object():
obj = utils.ReprObject('foo')
assert repr(obj) == 'foo'
assert isinstance(obj, Hashable)
assert not isinstance(obj, str)


def test_repr_object_magic_methods():
o1 = utils.ReprObject('foo')
o2 = utils.ReprObject('foo')
o3 = utils.ReprObject('bar')
o4 = 'foo'
assert o1 == o2
assert o1 != o3
assert o1 != o4
assert hash(o1) == hash(o2)
assert hash(o1) != hash(o3)
assert hash(o1) != hash(o4)


def test_is_remote_uri():
Expand Down