Skip to content

row_number().over(partition_by(key)) memory grows per distinct key (GBs for near-unique keys) #7725

Open

Description

@repelstiltskin

Describe the bug

Peak memory of row_number().over(Window().partition_by(key).order_by(...)) grows with the number of distinct partition keys, by a few KB per key, independent of the number of threads. On frames where the key is nearly unique (e.g. deduplicating rows by an id), this makes a "first row per key" step cost several GB where a groupby on the same frame costs well under 100 MB.

To Reproduce

"""Memory of row_number().over(Window().partition_by(key)) grows with the number of distinct keys."""
import sys
from pathlib import Path

import daft
from daft.functions import row_number


def hwm_mb() -> int:
    for line in Path("/proc/self/status").read_text().splitlines():
        if line.startswith("VmHWM:"):
            return int(line.split()[1]) // 1024
    return -1


def rss_mb() -> int:
    for line in Path("/proc/self/status").read_text().splitlines():
        if line.startswith("VmRSS:"):
            return int(line.split()[1]) // 1024
    return -1


variant, rows, keys = sys.argv[1], int(sys.argv[2]), int(sys.argv[3])
ids = [f"k{i % keys:010d}" for i in range(rows)]
df = daft.from_pydict({"id": ids, "a": [i % 7 for i in range(rows)], "b": [str(i % 101) for i in range(rows)]}).collect()
base = rss_mb()
if variant == "window":
    w = daft.Window().partition_by("id").order_by("a", "b")
    out = df.with_column("r", row_number().over(w)).where(daft.col("r") == 1).exclude("r").collect()
else:  # groupby baseline
    out = df.groupby("id").agg(daft.col("a").min()).collect()
print(f"daft {daft.__version__} {variant:8s} rows={rows} keys={keys} out={len(out)} added_mb={hwm_mb() - base}")

Run with python repro.py <window|groupby> <rows> <keys> (Linux, reads /proc/self/status):

daft 0.7.26 window   rows=500000 keys=5000 out=5000 added_mb=111
daft 0.7.26 window   rows=500000 keys=475000 out=475000 added_mb=1485
daft 0.7.26 groupby  rows=500000 keys=475000 out=475000 added_mb=80

Same rows, ~95x more distinct keys: the window adds ~13x more memory; the groupby over the same keys adds 80 MB. On a wider frame (8 string/date columns, 1M rows, ~950k keys) we measured about +7.2 GB for the window versus about +0.4 GB for the equivalent pandas-style sort + keep-first, and the cost did not change with the native runner's thread count (1, 4 or 16).

Expected behavior

Memory for a window partitioned by a key should scale with the data, not carry a large fixed overhead per partition, so that a single-row partition costs about what its row does.

Workaround

Run the window only over keys that occur more than once (a groupby(key).count() to find them, then semi/anti joins); single-row keys pass through unchanged. This gives the same rows and adds ~0.5 GB instead of ~7 GB on the 1M-key frame.

Component(s)

Window functions (native runner)

Additional context

daft 0.7.26, Python 3.13, Linux x86_64.

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions