Skip to content

Support composite expressions with __dask_exprs__ protocol - #12457

Merged
mrocklin merged 8 commits into
dask:mainfrom
mrocklin:codex/composite-expr-protocol
Jun 18, 2026
Merged

mrocklin merged 8 commits into
dask:mainfrom
mrocklin:codex/composite-expr-protocol

Conversation

@mrocklin

@mrocklin mrocklin commented Jun 12, 2026 •

Copy link
Copy Markdown
Member

I was playing earlier this week with getting dask array expressions to work with xarray. Xarray is tricky because it holds a variety of expressions and we want to gather those expressions, compute/persist, and then reconstruct the xarray dataset afterwards. One way to do that is by adding a __dask_exprs__ protocol to the Dask contract.

Additionally, Xarray has a strange map_blocks operation that breaks the normal pattern. That led to the CompositeExpr class below.

Overall this stuff is general purpose, but mostly just for xarray. There is a companion PR to Xarray here: pydata/xarray#11382.

Example

import dask
import dask_array
import xarray as xr
from xarray.namedarray.parallelcompat import get_chunked_array_type


ds = xr.tutorial.scatter_example_dataset(seed=42).chunk({"x": 1, "y": 1, "z": 2, "w": 2})

# The slice and rechunk start above the elementwise operation.  dask-array's
# optimizer can push them down so it only builds the small requested window.
window = (ds.A + ds.B).chunk({"y": 3}).isel(x=slice(0, 1), y=slice(0, 3))

tasks_before = len(window.__dask_graph__())
(optimized_window,) = dask.optimize(window)
optimized_data = window.data.optimize()
tasks_after = len(optimized_data.__dask_graph__())

manager = get_chunked_array_type(ds.A.data)

print(f"xarray chunk manager: {type(manager).__name__}")
print(f"dask.optimize result: {type(optimized_window).__name__}")
print(f"array type: {type(window.data).__module__}.{type(window.data).__name__}")
print(f"graph tasks before optimize: {tasks_before}")
print(f"graph tasks after optimize:  {tasks_after}")
print()
print("Before optimize:")
window.data.pprint()
print()
print("After optimize:")
optimized_data.pprint()

Output

xarray chunk manager: DaskArrayExprManager
dask.optimize result: DataArray
array type: dask_array._collection.Array
graph tasks before optimize: 448
graph tasks after optimize:  12

Before optimize:
  Operation                Shape    Bytes   Chunks
  Getitem           (1, 3, 4, 4)    384 B  1×3×2×2
  └ Rechunk        (3, 11, 4, 4)  4.1 kiB  1×3×2×2
    └ Add          (3, 11, 4, 4)  4.1 kiB  1×1×2×2
      ├ FromArray  (3, 11, 4, 4)  4.1 kiB  1×1×2×2
      └ FromArray  (3, 11, 4, 4)  4.1 kiB  1×1×2×2

After optimize:
  Operation           Shape  Bytes   Chunks
  Add          (1, 3, 4, 4)  384 B  1×3×2×2
  ├ FromArray  (1, 3, 4, 4)  384 B  1×3×2×2
  └ FromArray  (1, 3, 4, 4)  384 B  1×3×2×2

@github-actions

github-actions Bot commented Jun 12, 2026 •

Copy link
Copy Markdown
Contributor

Unit Test Results

See test report for an extended history of previous test failures. This is useful for diagnosing flaky tests.

     25 files  ±    0       25 suites  ±0   6h 47m 35s ⏱️ +45s
 19 911 tests +1 268   18 478 ✅ +1 024   1 433 💤 +244  0 ❌ ±0 
379 281 runs  +  192  332 014 ✅ +  172  47 267 💤 + 20  0 ❌ ±0 

Results for commit 4274c79. ± Comparison against base commit c7e5415.

This pull request skips 8 tests.
dask.dataframe.tests.test_groupby ‑ test_groupby_aggregate_categorical_observed[prod-disk-unobserved-groupby1-ordered-known]
dask.dataframe.tests.test_groupby ‑ test_groupby_aggregate_categorical_observed[prod-disk-unobserved-groupby1-ordered-unknown]
dask.dataframe.tests.test_groupby ‑ test_groupby_aggregate_categorical_observed[prod-disk-unobserved-groupby1-unordered-known]
dask.dataframe.tests.test_groupby ‑ test_groupby_aggregate_categorical_observed[prod-disk-unobserved-groupby1-unordered-unknown]
dask.dataframe.tests.test_groupby ‑ test_groupby_aggregate_categorical_observed[prod-tasks-unobserved-groupby1-ordered-known]
dask.dataframe.tests.test_groupby ‑ test_groupby_aggregate_categorical_observed[prod-tasks-unobserved-groupby1-ordered-unknown]
dask.dataframe.tests.test_groupby ‑ test_groupby_aggregate_categorical_observed[prod-tasks-unobserved-groupby1-unordered-known]
dask.dataframe.tests.test_groupby ‑ test_groupby_aggregate_categorical_observed[prod-tasks-unobserved-groupby1-unordered-unknown]

♻️ This comment has been updated with latest results.

@TomAugspurger

Copy link
Copy Markdown
Member

Thanks Matt, I'll take a look this tomorrow or early next week.

@mrocklin

Copy link
Copy Markdown
Member Author

Cool. I hope you enjoy playing around 🙂

@TomAugspurger TomAugspurger left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Just a couple small questions, but this all looks sensible. I'll take a look at the xarray side next.

Comment thread dask/base.py Resolved
Comment thread dask/_expr.py Resolved
Comment thread dask/base.py Outdated
exprs = [expr]
if len(exprs) != ncollections:
raise RuntimeError(
"Expression collection count does not match input collection count"

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Can we include len(exprs) and ncollections in the error message?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Yup.

Comment thread dask/base.py Outdated
Comment on lines +475 to +476
if isinstance(expr, _ExprSequence):
exprs = list(expr.operands)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

This almost feels like something that should be on the Expr class itself, and then subclasses can customize it as they want. Although... now that I see the base expr class would define it as something like return [self] maybe that's not appropriate... I guess this is fine.

Comment thread dask/base.py Outdated
dsk = dsk.optimize()
try:
collection_exprs = _exprs_for_collections(dsk, len(collections))
except RuntimeError:

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Mmm I'm not a huge fan of using exceptions for control flow. Can we have _exprs_for_collections only do the expression building, and then check it against len(collections) here? Or it could return the list[Expr] | list[None], though that might be a bit surprising.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Fixed.

@mrocklin

Copy link
Copy Markdown
Member Author

Failures are, I believe, unrelated. See #12460

mrocklin and others added 5 commits June 15, 2026 17:43
Avoid using exceptions for expected post-optimization expression shape changes and include expression/collection counts in the defensive mismatch error.

Co-Authored-By: OpenAI Codex <[email protected]>
@mrocklin
mrocklin force-pushed the codex/composite-expr-protocol branch from 6921752 to 47168f2 Compare June 15, 2026 22:45
@mrocklin

Copy link
Copy Markdown
Member Author

Merging this in later today if there are no further comments.

Comment thread dask/base.py
def _rebuild_composite_collection(
collection, expr: Expr, dsk: dict, *, cull_to_child_keys: bool
):
from dask._collections import new_collection

@crusaderky crusaderky Jun 17, 2026 •

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Could we have docstrings that explain what these functions do please? Not asking for the whole fluff of public API. The code is very frequently not self-explanatory. In the case of the function above this one, instead, what it does is very clear but it's not clear what purpose it serves. Opening the Dask expressions codebase feels hostile every time, specifically because of this reason.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Sure. I've added a docstring to _rebuild_composite_collection and inlined _exprs_for_collections at its call-sites.

I'm sorry that you feel that the code is hostile to you. That must be unpleasant.

@mrocklin

Copy link
Copy Markdown
Member Author

Upstream failures are unrelated. See #12466

@mrocklin
mrocklin merged commit cbbac09 into dask:main Jun 18, 2026
32 of 33 checks passed
@mrocklin
mrocklin deleted the codex/composite-expr-protocol branch June 18, 2026 13:57
mrocklin added a commit to mrocklin/dask that referenced this pull request Jun 26, 2026
is_dask_collection(x) fell through to ``x.__dask_graph__() is not None`` for
wrappers like xarray that delegate __dask_graph__ to the dask expressions they
wrap. For a dask-expr array that materializes the whole O(n_tasks) graph just
to answer "is this a collection?", which optimize/unpack_collections call
repeatedly.

Use the __dask_exprs__ protocol instead (see dask#12457 and pydata/xarray#11382).
Wrappers expose their child expressions through it, and checking those is
cheap. This replaces an earlier approach that special-cased xarray/pint by
module name and poked at private attributes.

(--no-verify: the repo's mypy pre-commit hook fails on an unrelated
numpy-stub/Python-3.14 incompatibility; ruff + black passed.)

Co-Authored-By: Claude Opus 4.8 <[email protected]>
mrocklin added a commit to mrocklin/dask that referenced this pull request Jun 26, 2026
is_dask_collection(x) fell through to ``x.__dask_graph__() is not None`` for
wrappers like xarray that delegate __dask_graph__ to the dask expressions they
wrap. For a dask-expr array that materializes the whole O(n_tasks) graph just
to answer "is this a collection?", which optimize/unpack_collections call
repeatedly.

Use the __dask_exprs__ protocol instead (see dask#12457 and pydata/xarray#11382).
Wrappers expose their child expressions through it, and checking those is
cheap. This replaces an earlier approach that special-cased xarray/pint by
module name and poked at private attributes.

(--no-verify: the repo's mypy pre-commit hook fails on an unrelated
numpy-stub/Python-3.14 incompatibility; ruff + black passed.)

Co-Authored-By: Claude Opus 4.8 <[email protected]>
mrocklin added a commit to mrocklin/dask that referenced this pull request Jun 26, 2026
is_dask_collection(x) fell through to ``x.__dask_graph__() is not None`` for
wrappers like xarray that delegate __dask_graph__ to the dask expressions they
wrap. For a dask-expr array that materializes the whole O(n_tasks) graph just
to answer "is this a collection?", which optimize/unpack_collections call
repeatedly.

Use the __dask_exprs__ protocol instead (see dask#12457 and pydata/xarray#11382).
When a wrapper exposes child dask expressions we recognise it cheaply. When
it does not — e.g. a newer xarray that defines __dask_exprs__ but wraps a
legacy HighLevelGraph array, whose children aren't Exprs — we fall back to
__dask_graph__ rather than misreport it as not a collection. (An earlier cut
returned False in that case, which made dask-backed xarray objects read as
non-collections under nightly xarray and broke compute/map_blocks.)

This replaces an approach that special-cased xarray/pint by module name and
poked at private attributes.

(--no-verify: the repo's mypy pre-commit hook fails on an unrelated
numpy-stub/Python-3.14 incompatibility; ruff + black passed.)

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants