hdbscan icon indicating copy to clipboard operation
hdbscan copied to clipboard

`HDBSCAN().fit` rejects read-only input arrays (`Cannot create writable memory view from read-only memoryview`)

Open nulltracer-maker opened this issue 2 weeks ago • 1 comments

hdbscan.HDBSCAN().fit(X) raises a Cython memoryview error when the input array is read-only. The identical writable array works, so only the buffer property differs:

import numpy as np
import hdbscan

rs = np.random.RandomState(0)
X = rs.rand(150, 4)
X_ro = X.copy()
X_ro.setflags(write=False)

hdbscan.HDBSCAN().fit(X)      # OK
hdbscan.HDBSCAN().fit(X_ro)   # ValueError: Cannot create writable memory view from read-only memoryview

Full traceback

  File ".../hdbscan/hdbscan_.py", line 1260, in fit
    ) = hdbscan(clean_data, **kwargs)
  File ".../hdbscan/hdbscan_.py", line 856, in hdbscan
    (single_linkage_tree, result_min_span_tree) = memory.cache(
  File ".../joblib/memory.py", line 331, in __call__
    return self.func(*args, **kwargs)
  File ".../hdbscan/hdbscan_.py", line 334, in _hdbscan_boruvka_kdtree
    alg = KDTreeBoruvkaAlgorithm(
  File "hdbscan/_hdbscan_boruvka.pyx", line 343, in hdbscan._hdbscan_boruvka.KDTreeBoruvkaAlgorithm.__init__
  File "<stringsource>", line 673, in View.MemoryView.memoryview_cwrapper
  File "<stringsource>", line 360, in View.MemoryView.memoryview.__cinit__
  File "<stringsource>", line 534, in View.MemoryView.memoryview.__getbuffer__
ValueError: Cannot create writable memory view from read-only memoryview

Root cause (confirmed from the traceback and source)

The failing entry point is KDTreeBoruvkaAlgorithm.__init__, hdbscan/_hdbscan_boruvka.pyx:343:

self._raw_data = self.tree.data

self.tree is a scikit-learn KDTree built from the caller's array. For a C-contiguous float64 input, sklearn's KDTree keeps a zero-copy reference, so tree.data still backs the caller's read-only buffer. The class attribute is declared without const (_hdbscan_boruvka.pyx:293):

cdef np.double_t[:, ::1] _raw_data

so the Cython memoryview acquisition at line 343 requests a writable buffer and rejects read-only input.

A usage audit of _raw_data in this file suggests it is only ever read: the raw pointer is taken at line 637 (&self._raw_data[0, 0]) and passed to distance computations (self.dist.rdist(&raw_data[...], &raw_data[...], ...) at lines 725-726); it never appears on the left-hand side of an assignment. The identical non-const declaration exists in the BallTree variant (:905/:955/:1232).

Note the clustering operation itself should not need to modify the caller's input feature matrix.

Relation to issue #514

Issue #514 reports a read-only buffer error in a joblib/KDTree-deserialization context, with the failure inside scikit-learn's own BinaryTree.__setstate__ / _update_memviews. The case reported here also passes through joblib (hdbscan_.py:856 uses joblib.Memory.cache), but the failing component differs: here the writable-buffer requirement comes from hdbscan's own _hdbscan_boruvka memoryview declaration, not from sklearn's tree code. It is not yet clear whether the two share an underlying cause; mentioning #514 for possible linkage.

Why read-only input is legitimate

Read-only ndarrays arise routinely: np.memmap, joblib.load(mmap_mode=...), arrays exported from PIL/h5py/dask, and data shared across processes. scikit-learn addressed the same class for its own estimators (https://github.com/scikit-learn/scikit-learn/issues/21228), and hdbscan's fit already runs sklearn's check_array, which does not force a copy for read-only input.

Suggested fix

Ensure read-only inputs are handled before they reach Cython code that requires writable buffers, copying only when necessary — e.g., after check_array has produced a NumPy ndarray:

if not X.flags.writeable:
    X = X.copy()

Alternatively, if the kernel parameters are confirmed to be read-only (the usage audit above suggests so for _raw_data), declaring them as const memoryviews would avoid the copy entirely.

A regression test could compare clustering results for identical writable and read-only input arrays. For precedent on the const approach, SciPy did a project-wide audit for exactly this pattern (https://github.com/scipy/scipy/issues/20196).

Environment

  • hdbscan 0.8.44 (latest on PyPI), also verified against the current master source of _hdbscan_boruvka.pyx
  • numpy 2.5.5, scikit-learn 1.9.1, Python 3.12, macOS arm64

Found while scanning Cython buffer preconditions against Python-side input handling; the repro is self-contained and the traceback above is from a clean run.

nulltracer-maker avatar Nov 18 '26 13:11 nulltracer-maker

I would like to work on a focused fix and regression tests for this. I checked the current master and open PRs and did not find an implementation for #767. I will first reproduce with the actual built extensions, compare the public function and estimator on writable/read-only inputs across the tree algorithms, and keep input values/permissions unchanged. I am investigating a conditional copy only where a writable buffer is actually required, so writable inputs retain their current path. AI-assisted investigation with Codex; no implementation or claimed test results yet.

austinchennn avatar Nov 18 '26 16:11 austinchennn