← Back to Pull requests

feat(dbscan): add manhattan, minkowski, chebyshev and cosine distance metrics #3815

Merged
Alexandr-Solovev merged 21 files (1259 lines) on Nov 04, 2026 07:49 UTC
View on GitHub
Alexandr-Solovev Alexandr-Solovev commented on Sep 28, 2026 11:43 UTC
Author

Description

DBSCAN is hardcoded to the squared Euclidean distance. This PR exposes the neighborhood metric through the descriptor, with the same API as HDBSCAN:

const auto desc = dbscan::descriptor<float, dbscan::method::brute_force>{ epsilon, min_observations }
                      .set_metric(dbscan::distance_metric::minkowski)
                      .set_degree(3.0);

distance_metric is euclidean (default, unchanged), manhattan, minkowski (degree > 0), chebyshev or cosine, on CPU and GPU, in both memory modes and through GPU SPMD. epsilon is in the units of the selected metric.

How it works

Each metric is compared in a form monotone in the true distance: Euclidean squared, Minkowski raised to p, the rest as is; epsilon is mapped into that form once.

  • CPU, full matrix: the existing service_kernel_math.h engines (EuclideanDistances, MinkowskiDistances, ChebyshevDistances, CosineDistances with the zero-row fix-up).

  • CPU, memory saving: the HDBSCAN point functors (ManhattanDist, ChebyshevDist, and MinkowskiDist::poweredPointDist, new and wrapped by pointDist), distancePow2 for Euclidean.

  • GPU: the fused kernels take a neighborhood_metric {kind, degree, threshold}, and the accumulation is selected at compile time through one dispatch_distance_kind helper, so the Euclidean kernel is the same code as before. Kernel signatures stay non-template. Cosine runs on rows normalized once with compute_squared_l2_norms, so it accumulates a negated dot product and zero rows sit at distance 1. No distance matrix is built.
  • Notes


  • Cosine zero rows follow scikit-learn and HDBSCAN: distance 1 from every other row. A row always counts in its own neighborhood, by index.

  • set_degree rejects non-positive and NaN values (domain_error); an unknown metric throws invalid_argument.
  • API/ABI


    New public enum dbscan::distance_metric and descriptor accessors set/get_metric, set/get_degree (new exported symbols; the descriptor is pimpl, so no layout change). DAAL Parameter is unchanged; metric and degree are internal kernel arguments.

    Tests


  • Every metric (Minkowski with p = 3 and 0.5) on random blobs in 2, 5 and 20 columns, with and without weights, both memory modes, float and double: core flags, clusters and border rows checked against the DBSCAN definition on double-precision distances computed in the test from the metric definitions, with epsilon placed in a wide gap between pairwise distances.

  • The same check in GPU SPMD over 2 and 3 ranks.

  • Cosine zero rows against sklearn.cluster.DBSCAN(metric="cosine").

  • Bad arguments: non-positive and NaN degree, out-of-range metric.
  • Documentation


  • The developer guide gains a Supported distance metrics section: the metric family, epsilon in the units of the selected metric, and the cosine zero-row rule.

  • The API reference gains .. onedal_enumclass:: oneapi::dal::dbscan::distance_metric.

  • New examples dbscan_brute_force_metrics_batch.cpp (oneAPI C++ and DPC++) run every metric on hdbscan_dense.csv, each with its own epsilon, and are listed in the DBSCAN examples page.
  • Breaking changes


    None. euclidean stays the default. The only change to the Euclidean path: a row counts in its own neighborhood by index, so round-off can no longer push its self-distance above epsilon when epsilon is close to zero.

    Replaces the closed #3623.

    🤖 Generated with Claude Code

    Diff: 1259 lines (+1061 / -198) across 21 files Reviewer: Alexandr-Solovev Review duration: 53046m
    All Vouch review confidence checks passed
    Residual risk 0.14 = Change Risk (0.86) × (1 − Review Confidence (0.84)). Review depth and reviewer attention state are adequate.
    Model 1 · Change Risk (XGBoost)
    Score: 0.86 · 1259 lines diff across 21 files
    0.86
    Model 2 · Review Depth (DistilBERT)
    Depth Score: 0.90 · 5 substantive comment(s)
    0.90
    Model 3 · Review Timing & Attention
    Session adequacy: 100% · Reviewer familiarity: 50%
    83%
    Bedrock Claude 3 · Risk Narration
    (disconnected)
    Groq
    Groq Risk Narration
    AWS Bedrock is currently disconnected. Generate high-confidence PR triage narration on-demand using Groq.
    Model 1 · Change Risk Attribution
    SHAP Weights
    Diff Size diff_size
    0.400
    Self Review self_review
    0.140
    Mass File Touch mass_file_touch
    0.080
    Real PR Conversation Timeline
    43 items
    Copilot Copilot commented on code on Oct 07, 2026 15:48 UTC
    Code Review
    cpp/daal/src/algorithms/dbscan/dbscan_utils.h:1
    @@ -390,11 +390,131 @@ struct NTask
         daal::tls<TlsNTask<FPType, cpu> *> * tlsNTask;
     };
     
    +/// Threshold that a powered (unrooted) distance must not exceed for a point to
    +/// lie inside the `eps` neighborhood.
    +///
    +/// The neighborhood search never needs a true distance, only its comparison
    +/// against `eps`, so each metric is evaluated in the cheapest form that stays
    +/// monotone in the true distance and `eps` is mapped into that same space.
    +/// Euclidean distances stay squared and Minkowski distances stay raised to the
    +/// power `p`; Manhattan, Chebyshev and cosine distances take no root to begin
    +/// with, so for them the threshold is `eps` itself.
    +///
    +/// @param[in] metric The pairwise distance metric in use
    +/// @param[in] eps    The neighborhood radius, in the units of `metric`
    +/// @param[in] p      The Minkowski degree; ignored by every other metric
    +/// @return The value that powered distances are compared against
    +template <typename FPType, CpuType cpu>
    +inline FPType poweredEpsilon(PairwiseDistanceType metric, FPType eps, FPType p)
    +{
    +    switch (metric)
    +    {
    +    case PairwiseDistanceType::euclidean: return eps * eps;
    +    case PairwiseDistanceType::minkowski: return MathInst<FPType, cpu>::sPowx(eps, p);
    +    default: return eps;
    +    }
    +}
    +
    +/// Powered point-to-point distance functors for the memory-saving neighborhood
    +/// search.
    +///
    +/// Each functor returns exactly the quantity that the matching
    +/// `PairwiseDistances` batch engine writes into its result buffer, so both
    +/// search paths share `poweredEpsilon` as their cut-off. They are functors
    +/// rather than a single function taking a runtime metric tag so that the
    +/// dispatch happens once per query instead of once per candidate pair.
    +template <typename FPType, CpuType cpu>
    +struct EuclideanPoweredDistance
    +{
    +    FPType operator()(const FPType * a, const FPType * b, size_t dim) const
    +    {
    +        FPType sum = 0;
    +        for (size_t i = 0; i < dim; ++i)
    +        {
    +            const FPType diff = b[i] - a[i];
    +            sum += diff * diff;
    +        }
    +        return sum;
    +    }
    +};
    +
    +template <typename FPType, CpuType cpu>
    +struct ManhattanPoweredDistance
    +{
    +    FPType operator()(const FPType * a, const FPType * b, size_t dim) const
    +    {
    +        FPType sum = 0;
    +        for (size_t i = 0; i < dim; ++i)
    +        {
    +            sum += MathInst<FPType, cpu>::sFabs(b[i] - a[i]);
    +        }
    +        return sum;
    +    }
    +};
    +
    +template <typename FPType, CpuType cpu>
    +struct MinkowskiPoweredDistance
    +{
    +    explicit MinkowskiPoweredDistance(FPType p) : _p(p) {}
    +
    +    FPType operator()(const FPType * a, const FPType * b, size_t dim) const
    +    {
    +        FPType sum = 0;
    +        for (size_t i = 0; i < dim; ++i)
    +        {
    +            sum += MathInst<FPType, cpu>::sPowx(MathInst<FPType, cpu>::sFabs(b[i] - a[i]), _p);
    +        }
    +        return sum;
    +    }
    +
    +    FPType _p;
    +};
    +
    +template <typename FPType, CpuType cpu>
    +struct ChebyshevPoweredDistance
    +{
    +    FPType operator()(const FPType * a, const FPType * b, size_t dim) const
    +    {
    +        FPType res = 0;
    +        for (size_t i = 0; i < dim; ++i)
    +        {
    +            const FPType diff = MathInst<FPType, cpu>::sFabs(b[i] - a[i]);
    +            if (diff > res)
    +            {
    +                res = diff;
    +            }
    +        }
    +        return res;
    +    }
    +};
    +
    +template <typename FPType, CpuType cpu>
    +struct CosinePoweredDistance
    +{
    +    FPType operator()(const FPType * a, const FPType * b, size_t dim) const
    +    {
    +        FPType dot = 0;
    +        FPType aa  = 0;
    +        FPType bb  = 0;
    +        for (size_t i = 0; i < dim; ++i)
    +        {
    +            dot += a[i] * b[i];
    +            aa += a[i] * a[i];
    +            bb += b[i] * b[i];
    +        }
    +        const FPType norm = MathInst<FPType, cpu>::sSqrt(aa) * MathInst<FPType, cpu>::sSqrt(bb);
    +        // A zero row has no direction, so there is no angle between it and
    +        // anything else. Report maximum separation instead of dividing by zero.
    +        return norm > FPType(0) ? FPType(1) - dot / norm : FPType(1);

    Returning 1 makes a zero row a neighbor of every point, including itself, whenever epsilon >= 1; it can then become a core point despite the documented rule that zero rows are never neighbors. This also disagrees with the full-matrix CPU path, whose zero-norm division yields NaN and is rejected by the cutoff. Use a representation that is outside every accepted radius and make the CPU batch and GPU implementations follow the same policy.

    Copilot Copilot commented on code on Oct 07, 2026 15:48 UTC
    Code Review
    cpp/oneapi/dal/algo/dbscan/backend/gpu/distance_metric_op.hpp:1
    @@ -0,0 +1,198 @@
    +/*******************************************************************************
    +* Copyright contributors to the oneDAL project
    +*
    +* Licensed under the Apache License, Version 2.0 (the "License");
    +* you may not use this file except in compliance with the License.
    +* You may obtain a copy of the License at
    +*
    +*     http://www.apache.org/licenses/LICENSE-2.0
    +*
    +* Unless required by applicable law or agreed to in writing, software
    +* distributed under the License is distributed on an "AS IS" BASIS,
    +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    +* See the License for the specific language governing permissions and
    +* limitations under the License.
    +*******************************************************************************/
    +
    +#pragma once
    +
    +#include <cmath>
    +
    +#include "oneapi/dal/algo/dbscan/common.hpp"
    +#include "oneapi/dal/backend/common.hpp"
    +#include "oneapi/dal/detail/error_messages.hpp"
    +#include "oneapi/dal/exceptions.hpp"
    +
    +namespace oneapi::dal::dbscan::backend {
    +
    +#ifdef ONEDAL_DATA_PARALLEL
    +
    +/// Per-pair accumulator shared by the DBSCAN GPU metric operations.
    +///
    +/// `sum` carries the running distance term for every metric. Cosine additionally
    +/// needs the two row norms; the other metrics never touch those slots, so the
    +/// compiler drops them.
    +template <typename Float>
    +struct metric_accumulator {
    +    Float sum = Float(0);
    +    Float lhs_norm = Float(0);
    +    Float rhs_norm = Float(0);
    +};
    +
    +/// Device-side metric operations for the DBSCAN brute-force GPU kernels.
    +///
    +/// The neighborhood search only ever compares a distance against `epsilon`, so
    +/// each operation evaluates the cheapest form that stays monotone in the true
    +/// distance and carries `epsilon` mapped into that same space as `threshold`.
    +/// Keeping the threshold inside the operation means exactly one place knows how
    +/// a metric is powered, so no caller can pass a raw radius by mistake.
    +///
    +/// `partial_is_lower_bound` says whether a partially accumulated value is a
    +/// lower bound on the final distance. The wide kernels use it to abandon a
    +/// candidate pair as soon as the running value crosses `threshold`; cosine has
    +/// no such bound, because its partial dot product can still move either way.
    +///
    +/// The operations are plain aggregates so they are trivially device-copyable and
    +/// can be captured straight into a SYCL kernel.
    +template <typename Float>
    +struct euclidean_metric_op {
    +    static constexpr bool partial_is_lower_bound = true;
    +
    +    Float threshold;
    +
    +    void step(metric_accumulator<Float>& acc, Float a, Float b) const {
    +        const Float diff = a - b;
    +        acc.sum += diff * diff;
    +    }
    +
    +    template <typename SubGroup>
    +    Float reduce(const SubGroup& sg, const metric_accumulator<Float>& acc) const {
    +        return sycl::reduce_over_group(sg, acc.sum, sycl::plus<Float>());
    +    }
    +
    +    Float finish(const metric_accumulator<Float>& acc) const {
    +        return acc.sum;
    +    }
    +};
    +
    +template <typename Float>
    +struct manhattan_metric_op {
    +    static constexpr bool partial_is_lower_bound = true;
    +
    +    Float threshold;
    +
    +    void step(metric_accumulator<Float>& acc, Float a, Float b) const {
    +        acc.sum += sycl::fabs(a - b);
    +    }
    +
    +    template <typename SubGroup>
    +    Float reduce(const SubGroup& sg, const metric_accumulator<Float>& acc) const {
    +        return sycl::reduce_over_group(sg, acc.sum, sycl::plus<Float>());
    +    }
    +
    +    Float finish(const metric_accumulator<Float>& acc) const {
    +        return acc.sum;
    +    }
    +};
    +
    +template <typename Float>
    +struct minkowski_metric_op {
    +    static constexpr bool partial_is_lower_bound = true;
    +
    +    Float threshold;
    +    Float degree;
    +
    +    void step(metric_accumulator<Float>& acc, Float a, Float b) const {
    +        acc.sum += sycl::pow(sycl::fabs(a - b), degree);
    +    }
    +
    +    template <typename SubGroup>
    +    Float reduce(const SubGroup& sg, const metric_accumulator<Float>& acc) const {
    +        return sycl::reduce_over_group(sg, acc.sum, sycl::plus<Float>());
    +    }
    +
    +    Float finish(const metric_accumulator<Float>& acc) const {
    +        return acc.sum;
    +    }
    +};
    +
    +template <typename Float>
    +struct chebyshev_metric_op {
    +    static constexpr bool partial_is_lower_bound = true;
    +
    +    Float threshold;
    +
    +    void step(metric_accumulator<Float>& acc, Float a, Float b) const {
    +        acc.sum = sycl::fmax(acc.sum, sycl::fabs(a - b));
    +    }
    +
    +    template <typename SubGroup>
    +    Float reduce(const SubGroup& sg, const metric_accumulator<Float>& acc) const {
    +        return sycl::reduce_over_group(sg, acc.sum, sycl::maximum<Float>());
    +    }
    +
    +    Float finish(const metric_accumulator<Float>& acc) const {
    +        return acc.sum;
    +    }
    +};
    +
    +template <typename Float>
    +struct cosine_metric_op {
    +    static constexpr bool partial_is_lower_bound = false;
    +
    +    Float threshold;
    +
    +    void step(metric_accumulator<Float>& acc, Float a, Float b) const {
    +        acc.sum += a * b;
    +        acc.lhs_norm += a * a;
    +        acc.rhs_norm += b * b;
    +    }
    +
    +    template <typename SubGroup>
    +    Float reduce(const SubGroup& sg, const metric_accumulator<Float>& acc) const {
    +        metric_accumulator<Float> total;
    +        total.sum = sycl::reduce_over_group(sg, acc.sum, sycl::plus<Float>());
    +        total.lhs_norm = sycl::reduce_over_group(sg, acc.lhs_norm, sycl::plus<Float>());
    +        total.rhs_norm = sycl::reduce_over_group(sg, acc.rhs_norm, sycl::plus<Float>());
    +        return finish(total);
    +    }
    +
    +    Float finish(const metric_accumulator<Float>& acc) const {
    +        const Float norm = sycl::sqrt(acc.lhs_norm) * sycl::sqrt(acc.rhs_norm);
    +        // A zero row has no direction, so there is no angle between it and
    +        // anything else. Report maximum separation instead of dividing by zero.
    +        return norm > Float(0) ? Float(1) - acc.sum / norm : Float(1);

    A zero row is assigned distance 1, so at epsilon >= 1 the GPU includes it in neighborhoods and may mark it core. That contradicts the stated rule that a zero row is maximally distant and never a neighbor, and 1 is not the maximum cosine distance (2). Align this sentinel and the accepted epsilon range with both CPU paths.

    Copilot Copilot commented on code on Oct 07, 2026 15:48 UTC
    Code Review
    cpp/oneapi/dal/algo/dbscan/common.cpp:1
    @@ -92,6 +94,29 @@ void descriptor_base<Task>::set_mem_save_mode_impl(bool value) {
         impl_->mem_save_mode = value;
     }
     
    +template <typename Task>
    +distance_metric descriptor_base<Task>::get_metric() const {
    +    return impl_->metric;
    +}
    +
    +template <typename Task>
    +double descriptor_base<Task>::get_degree() const {
    +    return impl_->degree;
    +}
    +
    +template <typename Task>
    +void descriptor_base<Task>::set_metric_impl(distance_metric value) {
    +    impl_->metric = value;
    +}
    +
    +template <typename Task>
    +void descriptor_base<Task>::set_degree_impl(double value) {
    +    if (value <= 0.0) {

    NaN passes this check because every ordered comparison with it is false, so set_degree(NaN) violates the documented degree > 0 invariant and later turns Minkowski thresholds and distances into NaNs. Reject unordered values by expressing the invariant directly; add a matching bad-argument case.

    Copilot Copilot commented on code on Oct 07, 2026 15:48 UTC
    Code Review
    cpp/oneapi/dal/algo/dbscan/test/batch.cpp:1
    @@ -206,6 +206,250 @@ TEMPLATE_LIST_TEST_M(dbscan_batch_test,
         this->run_checks(x, table{}, epsilon, min_observations, r);
     }
     
    +// The metric tests below use column counts on both sides of the narrow/wide
    +// threshold of the GPU neighborhood kernels, which is four columns, so that both
    +// the sub-group and the scalar distance loops are covered.
    +
    +TEMPLATE_LIST_TEST_M(dbscan_batch_test,
    +                     "dbscan narrow metric test",
    +                     "[dbscan][batch]",
    +                     dbscan_types) {
    +    SKIP_IF(this->not_float64_friendly());
    +    using float_t = std::tuple_element_t<0, TestType>;
    +
    +    // Pairwise distances: (p0, p1) = 1.41 / 2 / 1 / 1.26,
    +    //                     (p1, p2) = 2.83 / 4 / 2 / 2.52,
    +    //                     (p0, p2) = 4.24 / 6 / 3 / 3.78
    +    // for euclidean / manhattan / chebyshev / minkowski(3) respectively.
    +    constexpr float_t data[] = { 0.0, 0.0, 1.0, 1.0, 3.0, 3.0 };
    +    const auto x = homogen_table::wrap(data, 3, 2);
    +
    +    constexpr std::int64_t min_observations = 2;
    +
    +    constexpr std::int32_t pair_and_noise[] = { 0, 0, -1 };
    +    const auto r_pair_and_noise = homogen_table::wrap(pair_and_noise, 3, 1);
    +
    +    constexpr std::int32_t all_noise[] = { -1, -1, -1 };
    +    const auto r_all_noise = homogen_table::wrap(all_noise, 3, 1);
    +
    +    constexpr std::int32_t one_cluster[] = { 0, 0, 0 };
    +    const auto r_one_cluster = homogen_table::wrap(one_cluster, 3, 1);
    +
    +    // Only the two closest points fall inside a radius of 1.5, and only under a
    +    // metric that does not add the two coordinate differences up.
    +    this->run_metric_checks(x,
    +                            1.5,
    +                            min_observations,
    +                            distance_metric::euclidean,
    +                            2.0,
    +                            r_pair_and_noise);
    +    this->run_metric_checks(x,
    +                            1.5,
    +                            min_observations,
    +                            distance_metric::chebyshev,
    +                            2.0,
    +                            r_pair_and_noise);
    +    this->run_metric_checks(x,
    +                            1.5,
    +                            min_observations,
    +                            distance_metric::minkowski,
    +                            3.0,
    +                            r_pair_and_noise);
    +    this->run_metric_checks(x, 1.5, min_observations, distance_metric::manhattan, 2.0, r_all_noise);
    +
    +    // A radius of 2.5 additionally links the middle point to the far one, but
    +    // only for chebyshev.
    +    this->run_metric_checks(x,
    +                            2.5,
    +                            min_observations,
    +                            distance_metric::euclidean,
    +                            2.0,
    +                            r_pair_and_noise);
    +    this->run_metric_checks(x,
    +                            2.5,
    +                            min_observations,
    +                            distance_metric::manhattan,
    +                            2.0,
    +                            r_pair_and_noise);
    +    this->run_metric_checks(x,
    +                            2.5,
    +                            min_observations,
    +                            distance_metric::minkowski,
    +                            3.0,
    +                            r_pair_and_noise);
    +    this->run_metric_checks(x,
    +                            2.5,
    +                            min_observations,
    +                            distance_metric::chebyshev,
    +                            2.0,
    +                            r_one_cluster);
    +}
    +
    +TEMPLATE_LIST_TEST_M(dbscan_batch_test,
    +                     "dbscan wide metric test",
    +                     "[dbscan][batch]",
    +                     dbscan_types) {
    +    SKIP_IF(this->not_float64_friendly());
    +    using float_t = std::tuple_element_t<0, TestType>;
    +
    +    // Pairwise distances: (p0, p1) = 2.24 / 5 / 1 / 1.71,
    +    //                     (p0, p2) = 4    / 4 / 4 / 4,
    +    //                     (p1, p2) = 3.61 / 7 / 3 / 3.14
    +    // for euclidean / manhattan / chebyshev / minkowski(3) respectively.
    +    constexpr float_t data[] = { 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 1.0, 1.0,
    +                                 1.0, 1.0, 4.0, 0.0, 0.0, 0.0, 0.0 };
    +    const auto x = homogen_table::wrap(data, 3, 5);
    +
    +    constexpr std::int64_t min_observations = 2;
    +
    +    constexpr std::int32_t pair_and_noise[] = { 0, 0, -1 };
    +    const auto r_pair_and_noise = homogen_table::wrap(pair_and_noise, 3, 1);
    +
    +    constexpr std::int32_t all_noise[] = { -1, -1, -1 };
    +    const auto r_all_noise = homogen_table::wrap(all_noise, 3, 1);
    +
    +    constexpr std::int32_t one_cluster[] = { 0, 0, 0 };
    +    const auto r_one_cluster = homogen_table::wrap(one_cluster, 3, 1);
    +
    +    this->run_metric_checks(x,
    +                            2.5,
    +                            min_observations,
    +                            distance_metric::euclidean,
    +                            2.0,
    +                            r_pair_and_noise);
    +    this->run_metric_checks(x,
    +                            2.5,
    +                            min_observations,
    +                            distance_metric::chebyshev,
    +                            2.0,
    +                            r_pair_and_noise);
    +    this->run_metric_checks(x,
    +                            2.5,
    +                            min_observations,
    +                            distance_metric::minkowski,
    +                            3.0,
    +                            r_pair_and_noise);
    +    this->run_metric_checks(x, 2.5, min_observations, distance_metric::manhattan, 2.0, r_all_noise);
    +
    +    this->run_metric_checks(x,
    +                            3.5,
    +                            min_observations,
    +                            distance_metric::euclidean,
    +                            2.0,
    +                            r_pair_and_noise);
    +    this->run_metric_checks(x, 3.5, min_observations, distance_metric::manhattan, 2.0, r_all_noise);
    +    this->run_metric_checks(x,
    +                            3.5,
    +                            min_observations,
    +                            distance_metric::chebyshev,
    +                            2.0,
    +                            r_one_cluster);
    +    this->run_metric_checks(x,
    +                            3.5,
    +                            min_observations,
    +                            distance_metric::minkowski,
    +                            3.0,
    +                            r_one_cluster);
    +}
    +
    +TEMPLATE_LIST_TEST_M(dbscan_batch_test,
    +                     "dbscan minkowski degree matches the dedicated metrics",
    +                     "[dbscan][batch]",
    +                     dbscan_types) {
    +    SKIP_IF(this->not_float64_friendly());
    +    using float_t = std::tuple_element_t<0, TestType>;
    +
    +    constexpr float_t data[] = { 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 1.0, 1.0,
    +                                 1.0, 1.0, 4.0, 0.0, 0.0, 0.0, 0.0 };
    +    const auto x = homogen_table::wrap(data, 3, 5);
    +
    +    constexpr std::int64_t min_observations = 2;
    +    const double epsilon = GENERATE_COPY(1.5, 2.5, 3.5, 4.5);
    +
    +    INFO("run the reference metric");
    +    const auto reference =
    +        oneapi::dal::test::engine::compute(this->get_policy(),
    +                                           this->get_metric_descriptor(epsilon,
    +                                                                       min_observations,
    +                                                                       distance_metric::euclidean,
    +                                                                       2.0,
    +                                                                       true),
    +                                           x,
    +                                           table{});
    +
    +    INFO("minkowski with degree 2 reproduces euclidean");
    +    this->run_metric_checks(x,
    +                            epsilon,
    +                            min_observations,
    +                            distance_metric::minkowski,
    +                            2.0,
    +                            reference.get_responses());
    +
    +    INFO("run the reference metric");
    +    const auto manhattan_reference =
    +        oneapi::dal::test::engine::compute(this->get_policy(),
    +                                           this->get_metric_descriptor(epsilon,
    +                                                                       min_observations,
    +                                                                       distance_metric::manhattan,
    +                                                                       2.0,
    +                                                                       true),
    +                                           x,
    +                                           table{});
    +
    +    INFO("minkowski with degree 1 reproduces manhattan");
    +    this->run_metric_checks(x,
    +                            epsilon,
    +                            min_observations,
    +                            distance_metric::minkowski,
    +                            1.0,
    +                            manhattan_reference.get_responses());
    +}
    +
    +TEMPLATE_LIST_TEST_M(dbscan_batch_test,
    +                     "dbscan cosine metric test",
    +                     "[dbscan][batch]",
    +                     dbscan_types) {
    +    SKIP_IF(this->not_float64_friendly());
    +    using float_t = std::tuple_element_t<0, TestType>;
    +
    +    constexpr std::int64_t min_observations = 2;
    +    constexpr double epsilon = 0.1;
    +
    +    constexpr std::int32_t responses[] = { 0, 0, -1 };
    +    const auto r = homogen_table::wrap(responses, 3, 1);
    +
    +    // The first two rows are collinear, so the cosine distance between them is
    +    // zero however far apart they are in the euclidean sense. The third row is
    +    // orthogonal to both, at the maximum cosine distance of one.

    Cosine distance ranges from 0 to 2; orthogonal vectors have distance 1, while opposite vectors reach the maximum 2. Calling one the maximum conflicts with the metric documentation and obscures the zero-row boundary bug.

    This issue also appears on line 450 of the same file.

    copilot-pull-request-reviewer[bot] copilot-pull-request-reviewer[bot] commented on Oct 07, 2026 15:48 UTC
    Reviewer

    <!-- ccr-overview-v2 -->

    🟡 Changes recommended

    Zero-vector cosine handling violates its documented contract across backends, and NaN Minkowski degrees bypass validation.

    <details open>
    <summary><strong>4 open findings</strong></summary>

  • <picture><source media="(prefers-color-scheme: dark)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/medium-v2-dark.svg"><source media="(prefers-color-scheme: light)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/medium-v2-light.svg"><img src="https://github.githubassets.com/static/images/icons/copilot-code-review/medium-v2-light.png" alt="Medium severity" width="62" height="18" align="texttop"></picture> [Zero-row sentinel incorrectly makes rows neighbors](#discussion_r4208946891) · New

  • <picture><source media="(prefers-color-scheme: dark)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/medium-v2-dark.svg"><source media="(prefers-color-scheme: light)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/medium-v2-light.svg"><img src="https://github.githubassets.com/static/images/icons/copilot-code-review/medium-v2-light.png" alt="Medium severity" width="62" height="18" align="texttop"></picture> [GPU zero-row distance uses incorrect sentinel](#discussion_r4208946974) · New

  • <picture><source media="(prefers-color-scheme: dark)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/medium-v2-dark.svg"><source media="(prefers-color-scheme: light)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/medium-v2-light.svg"><img src="https://github.githubassets.com/static/images/icons/copilot-code-review/medium-v2-light.png" alt="Medium severity" width="62" height="18" align="texttop"></picture> [Reject NaN degree values](#discussion_r4208947034) · New

  • <picture><source media="(prefers-color-scheme: dark)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/low-v2-dark.svg"><source media="(prefers-color-scheme: light)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/low-v2-light.svg"><img src="https://github.githubassets.com/static/images/icons/copilot-code-review/low-v2-light.png" alt="Low severity" width="62" height="18" align="texttop"></picture> [Documentation incorrectly defines maximum cosine distance](#discussion_r4208947081) · New

  • </details>

    <details>
    <summary><strong>What changed in this PR</strong></summary>

    Adds configurable DBSCAN distance metrics across the public API, CPU/GPU backends, tests, and documentation.

    Changes:

  • Adds Euclidean, Manhattan, Minkowski, Chebyshev, and cosine metrics.

  • Implements metric-specific CPU and GPU neighborhood searches.

  • Adds validation, documentation, and metric coverage.
  • | File | Description |
    | ---- | ----------- |
    | docs/​source/​onedal/​algorithms/​clustering/​dbscan.rst | Documents supported metrics. |
    | docs/​source/​api/​algorithms/​clustering/​dbscan.rst | Exposes the metric enum. |
    | cpp/​oneapi/​dal/​algo/​dbscan/​test/​fixture.hpp | Adds metric test helpers. |
    | cpp/​oneapi/​dal/​algo/​dbscan/​test/​batch.cpp | Adds metric behavior tests. |
    | cpp/​oneapi/​dal/​algo/​dbscan/​test/​badarg.cpp | Adds argument validation tests. |
    | cpp/​oneapi/​dal/​algo/​dbscan/​common.hpp | Adds the public metric API. |
    | cpp/​oneapi/​dal/​algo/​dbscan/​common.cpp | Stores and validates metric settings. |
    | cpp/​oneapi/​dal/​algo/​dbscan/​backend/​gpu/​kernels_fp.hpp | Templates GPU kernels by metric. |
    | cpp/​oneapi/​dal/​algo/​dbscan/​backend/​gpu/​kernel_fp_impl.hpp | Applies metric operations in GPU kernels. |
    | cpp/​oneapi/​dal/​algo/​dbscan/​backend/​gpu/​distance_metric_op.hpp | Implements GPU metric operations. |
    | cpp/​oneapi/​dal/​algo/​dbscan/​backend/​gpu/​compute_kernel_brute_force_dpc.cpp | Dispatches GPU computation by metric. |
    | cpp/​oneapi/​dal/​algo/​dbscan/​backend/​cpu/​compute_kernel_common.hpp | Maps public metrics to DAAL types. |
    | cpp/​oneapi/​dal/​algo/​dbscan/​backend/​cpu/​compute_kernel_brute_force.cpp | Passes metric settings to CPU kernels. |
    | cpp/​daal/​src/​algorithms/​dbscan/​dbscan_utils.h | Implements CPU metric neighborhood searches. |
    | cpp/​daal/​src/​algorithms/​dbscan/​dbscan_kernel.h | Extends internal kernel arguments. |
    | cpp/​daal/​src/​algorithms/​dbscan/​dbscan_dense_default_batch_impl.i | Configures CPU engines with metrics. |
    </details>

    🧠 Review effort: Balanced

    ---

    💡 <a href="/uxlfoundation/oneDAL/new/main?filename=.github/skills/code-review/SKILL.md" class="Link--inTextBlock" target="_blank" rel="noopener noreferrer">Add a code-review agent skill</a> or configure MCP servers for context-aware, tailored reviews. <a href="https://docs.github.com/copilot/how-tos/use-copilot-agents/request-a-code-review/use-code-review?tool=webui#mcp-servers-and-agent-skills" class="Link--inTextBlock" target="_blank" rel="noopener noreferrer">Learn more in the docs.</a>

    Alexandr-Solovev Alexandr-Solovev commented on code on Oct 07, 2026 16:47 UTC
    Code Review
    cpp/daal/src/algorithms/dbscan/dbscan_utils.h:1
    @@ -390,11 +390,131 @@ struct NTask
         daal::tls<TlsNTask<FPType, cpu> *> * tlsNTask;
     };
     
    +/// Threshold that a powered (unrooted) distance must not exceed for a point to
    +/// lie inside the `eps` neighborhood.
    +///
    +/// The neighborhood search never needs a true distance, only its comparison
    +/// against `eps`, so each metric is evaluated in the cheapest form that stays
    +/// monotone in the true distance and `eps` is mapped into that same space.
    +/// Euclidean distances stay squared and Minkowski distances stay raised to the
    +/// power `p`; Manhattan, Chebyshev and cosine distances take no root to begin
    +/// with, so for them the threshold is `eps` itself.
    +///
    +/// @param[in] metric The pairwise distance metric in use
    +/// @param[in] eps    The neighborhood radius, in the units of `metric`
    +/// @param[in] p      The Minkowski degree; ignored by every other metric
    +/// @return The value that powered distances are compared against
    +template <typename FPType, CpuType cpu>
    +inline FPType poweredEpsilon(PairwiseDistanceType metric, FPType eps, FPType p)
    +{
    +    switch (metric)
    +    {
    +    case PairwiseDistanceType::euclidean: return eps * eps;
    +    case PairwiseDistanceType::minkowski: return MathInst<FPType, cpu>::sPowx(eps, p);
    +    default: return eps;
    +    }
    +}
    +
    +/// Powered point-to-point distance functors for the memory-saving neighborhood
    +/// search.
    +///
    +/// Each functor returns exactly the quantity that the matching
    +/// `PairwiseDistances` batch engine writes into its result buffer, so both
    +/// search paths share `poweredEpsilon` as their cut-off. They are functors
    +/// rather than a single function taking a runtime metric tag so that the
    +/// dispatch happens once per query instead of once per candidate pair.
    +template <typename FPType, CpuType cpu>
    +struct EuclideanPoweredDistance
    +{
    +    FPType operator()(const FPType * a, const FPType * b, size_t dim) const
    +    {
    +        FPType sum = 0;
    +        for (size_t i = 0; i < dim; ++i)
    +        {
    +            const FPType diff = b[i] - a[i];
    +            sum += diff * diff;
    +        }
    +        return sum;
    +    }
    +};
    +
    +template <typename FPType, CpuType cpu>
    +struct ManhattanPoweredDistance
    +{
    +    FPType operator()(const FPType * a, const FPType * b, size_t dim) const
    +    {
    +        FPType sum = 0;
    +        for (size_t i = 0; i < dim; ++i)
    +        {
    +            sum += MathInst<FPType, cpu>::sFabs(b[i] - a[i]);
    +        }
    +        return sum;
    +    }
    +};
    +
    +template <typename FPType, CpuType cpu>
    +struct MinkowskiPoweredDistance
    +{
    +    explicit MinkowskiPoweredDistance(FPType p) : _p(p) {}
    +
    +    FPType operator()(const FPType * a, const FPType * b, size_t dim) const
    +    {
    +        FPType sum = 0;
    +        for (size_t i = 0; i < dim; ++i)
    +        {
    +            sum += MathInst<FPType, cpu>::sPowx(MathInst<FPType, cpu>::sFabs(b[i] - a[i]), _p);
    +        }
    +        return sum;
    +    }
    +
    +    FPType _p;
    +};
    +
    +template <typename FPType, CpuType cpu>
    +struct ChebyshevPoweredDistance
    +{
    +    FPType operator()(const FPType * a, const FPType * b, size_t dim) const
    +    {
    +        FPType res = 0;
    +        for (size_t i = 0; i < dim; ++i)
    +        {
    +            const FPType diff = MathInst<FPType, cpu>::sFabs(b[i] - a[i]);
    +            if (diff > res)
    +            {
    +                res = diff;
    +            }
    +        }
    +        return res;
    +    }
    +};
    +
    +template <typename FPType, CpuType cpu>
    +struct CosinePoweredDistance
    +{
    +    FPType operator()(const FPType * a, const FPType * b, size_t dim) const
    +    {
    +        FPType dot = 0;
    +        FPType aa  = 0;
    +        FPType bb  = 0;
    +        for (size_t i = 0; i < dim; ++i)
    +        {
    +            dot += a[i] * b[i];
    +            aa += a[i] * a[i];
    +            bb += b[i] * b[i];
    +        }
    +        const FPType norm = MathInst<FPType, cpu>::sSqrt(aa) * MathInst<FPType, cpu>::sSqrt(bb);
    +        // A zero row has no direction, so there is no angle between it and
    +        // anything else. Report maximum separation instead of dividing by zero.
    +        return norm > FPType(0) ? FPType(1) - dot / norm : FPType(1);

    Agreed the paths disagreed, but I matched scikit-learn rather than making zero rows never neighbours. sklearn's cosine_distances puts a zero row at distance 1 from every other row and 0 from itself, so at eps >= 1 it is a neighbour and can be core. Fixed in e8493e3f1: every path now gives 1 against a non-zero row and 0 against a zero row. The full-matrix path overwrites the 0/0 entries from CosineDistances, which HDBSCAN and KNN share, so they are untouched. The docs now state this.

    Alexandr-Solovev Alexandr-Solovev commented on code on Oct 07, 2026 16:47 UTC
    Code Review
    cpp/oneapi/dal/algo/dbscan/backend/gpu/distance_metric_op.hpp:1
    @@ -0,0 +1,198 @@
    +/*******************************************************************************
    +* Copyright contributors to the oneDAL project
    +*
    +* Licensed under the Apache License, Version 2.0 (the "License");
    +* you may not use this file except in compliance with the License.
    +* You may obtain a copy of the License at
    +*
    +*     http://www.apache.org/licenses/LICENSE-2.0
    +*
    +* Unless required by applicable law or agreed to in writing, software
    +* distributed under the License is distributed on an "AS IS" BASIS,
    +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    +* See the License for the specific language governing permissions and
    +* limitations under the License.
    +*******************************************************************************/
    +
    +#pragma once
    +
    +#include <cmath>
    +
    +#include "oneapi/dal/algo/dbscan/common.hpp"
    +#include "oneapi/dal/backend/common.hpp"
    +#include "oneapi/dal/detail/error_messages.hpp"
    +#include "oneapi/dal/exceptions.hpp"
    +
    +namespace oneapi::dal::dbscan::backend {
    +
    +#ifdef ONEDAL_DATA_PARALLEL
    +
    +/// Per-pair accumulator shared by the DBSCAN GPU metric operations.
    +///
    +/// `sum` carries the running distance term for every metric. Cosine additionally
    +/// needs the two row norms; the other metrics never touch those slots, so the
    +/// compiler drops them.
    +template <typename Float>
    +struct metric_accumulator {
    +    Float sum = Float(0);
    +    Float lhs_norm = Float(0);
    +    Float rhs_norm = Float(0);
    +};
    +
    +/// Device-side metric operations for the DBSCAN brute-force GPU kernels.
    +///
    +/// The neighborhood search only ever compares a distance against `epsilon`, so
    +/// each operation evaluates the cheapest form that stays monotone in the true
    +/// distance and carries `epsilon` mapped into that same space as `threshold`.
    +/// Keeping the threshold inside the operation means exactly one place knows how
    +/// a metric is powered, so no caller can pass a raw radius by mistake.
    +///
    +/// `partial_is_lower_bound` says whether a partially accumulated value is a
    +/// lower bound on the final distance. The wide kernels use it to abandon a
    +/// candidate pair as soon as the running value crosses `threshold`; cosine has
    +/// no such bound, because its partial dot product can still move either way.
    +///
    +/// The operations are plain aggregates so they are trivially device-copyable and
    +/// can be captured straight into a SYCL kernel.
    +template <typename Float>
    +struct euclidean_metric_op {
    +    static constexpr bool partial_is_lower_bound = true;
    +
    +    Float threshold;
    +
    +    void step(metric_accumulator<Float>& acc, Float a, Float b) const {
    +        const Float diff = a - b;
    +        acc.sum += diff * diff;
    +    }
    +
    +    template <typename SubGroup>
    +    Float reduce(const SubGroup& sg, const metric_accumulator<Float>& acc) const {
    +        return sycl::reduce_over_group(sg, acc.sum, sycl::plus<Float>());
    +    }
    +
    +    Float finish(const metric_accumulator<Float>& acc) const {
    +        return acc.sum;
    +    }
    +};
    +
    +template <typename Float>
    +struct manhattan_metric_op {
    +    static constexpr bool partial_is_lower_bound = true;
    +
    +    Float threshold;
    +
    +    void step(metric_accumulator<Float>& acc, Float a, Float b) const {
    +        acc.sum += sycl::fabs(a - b);
    +    }
    +
    +    template <typename SubGroup>
    +    Float reduce(const SubGroup& sg, const metric_accumulator<Float>& acc) const {
    +        return sycl::reduce_over_group(sg, acc.sum, sycl::plus<Float>());
    +    }
    +
    +    Float finish(const metric_accumulator<Float>& acc) const {
    +        return acc.sum;
    +    }
    +};
    +
    +template <typename Float>
    +struct minkowski_metric_op {
    +    static constexpr bool partial_is_lower_bound = true;
    +
    +    Float threshold;
    +    Float degree;
    +
    +    void step(metric_accumulator<Float>& acc, Float a, Float b) const {
    +        acc.sum += sycl::pow(sycl::fabs(a - b), degree);
    +    }
    +
    +    template <typename SubGroup>
    +    Float reduce(const SubGroup& sg, const metric_accumulator<Float>& acc) const {
    +        return sycl::reduce_over_group(sg, acc.sum, sycl::plus<Float>());
    +    }
    +
    +    Float finish(const metric_accumulator<Float>& acc) const {
    +        return acc.sum;
    +    }
    +};
    +
    +template <typename Float>
    +struct chebyshev_metric_op {
    +    static constexpr bool partial_is_lower_bound = true;
    +
    +    Float threshold;
    +
    +    void step(metric_accumulator<Float>& acc, Float a, Float b) const {
    +        acc.sum = sycl::fmax(acc.sum, sycl::fabs(a - b));
    +    }
    +
    +    template <typename SubGroup>
    +    Float reduce(const SubGroup& sg, const metric_accumulator<Float>& acc) const {
    +        return sycl::reduce_over_group(sg, acc.sum, sycl::maximum<Float>());
    +    }
    +
    +    Float finish(const metric_accumulator<Float>& acc) const {
    +        return acc.sum;
    +    }
    +};
    +
    +template <typename Float>
    +struct cosine_metric_op {
    +    static constexpr bool partial_is_lower_bound = false;
    +
    +    Float threshold;
    +
    +    void step(metric_accumulator<Float>& acc, Float a, Float b) const {
    +        acc.sum += a * b;
    +        acc.lhs_norm += a * a;
    +        acc.rhs_norm += b * b;
    +    }
    +
    +    template <typename SubGroup>
    +    Float reduce(const SubGroup& sg, const metric_accumulator<Float>& acc) const {
    +        metric_accumulator<Float> total;
    +        total.sum = sycl::reduce_over_group(sg, acc.sum, sycl::plus<Float>());
    +        total.lhs_norm = sycl::reduce_over_group(sg, acc.lhs_norm, sycl::plus<Float>());
    +        total.rhs_norm = sycl::reduce_over_group(sg, acc.rhs_norm, sycl::plus<Float>());
    +        return finish(total);
    +    }
    +
    +    Float finish(const metric_accumulator<Float>& acc) const {
    +        const Float norm = sycl::sqrt(acc.lhs_norm) * sycl::sqrt(acc.rhs_norm);
    +        // A zero row has no direction, so there is no angle between it and
    +        // anything else. Report maximum separation instead of dividing by zero.
    +        return norm > Float(0) ? Float(1) - acc.sum / norm : Float(1);

    Same fix in e8493e3f1: the GPU op now matches both CPU paths and scikit-learn (1 against a non-zero row, 0 against a zero row). epsilon is unchanged; any value is valid, and eps >= 2 simply makes every pair a neighbour.

    Alexandr-Solovev Alexandr-Solovev commented on code on Oct 07, 2026 16:47 UTC
    Code Review
    cpp/oneapi/dal/algo/dbscan/common.cpp:1
    @@ -92,6 +94,29 @@ void descriptor_base<Task>::set_mem_save_mode_impl(bool value) {
         impl_->mem_save_mode = value;
     }
     
    +template <typename Task>
    +distance_metric descriptor_base<Task>::get_metric() const {
    +    return impl_->metric;
    +}
    +
    +template <typename Task>
    +double descriptor_base<Task>::get_degree() const {
    +    return impl_->degree;
    +}
    +
    +template <typename Task>
    +void descriptor_base<Task>::set_metric_impl(distance_metric value) {
    +    impl_->metric = value;
    +}
    +
    +template <typename Task>
    +void descriptor_base<Task>::set_degree_impl(double value) {
    +    if (value <= 0.0) {

    Fixed in e8493e3f1: the check is now !(value > 0.0), and the bad-argument test covers NaN.

    Alexandr-Solovev Alexandr-Solovev commented on code on Oct 07, 2026 16:47 UTC
    Code Review
    cpp/oneapi/dal/algo/dbscan/test/batch.cpp:1
    @@ -206,6 +206,250 @@ TEMPLATE_LIST_TEST_M(dbscan_batch_test,
         this->run_checks(x, table{}, epsilon, min_observations, r);
     }
     
    +// The metric tests below use column counts on both sides of the narrow/wide
    +// threshold of the GPU neighborhood kernels, which is four columns, so that both
    +// the sub-group and the scalar distance loops are covered.
    +
    +TEMPLATE_LIST_TEST_M(dbscan_batch_test,
    +                     "dbscan narrow metric test",
    +                     "[dbscan][batch]",
    +                     dbscan_types) {
    +    SKIP_IF(this->not_float64_friendly());
    +    using float_t = std::tuple_element_t<0, TestType>;
    +
    +    // Pairwise distances: (p0, p1) = 1.41 / 2 / 1 / 1.26,
    +    //                     (p1, p2) = 2.83 / 4 / 2 / 2.52,
    +    //                     (p0, p2) = 4.24 / 6 / 3 / 3.78
    +    // for euclidean / manhattan / chebyshev / minkowski(3) respectively.
    +    constexpr float_t data[] = { 0.0, 0.0, 1.0, 1.0, 3.0, 3.0 };
    +    const auto x = homogen_table::wrap(data, 3, 2);
    +
    +    constexpr std::int64_t min_observations = 2;
    +
    +    constexpr std::int32_t pair_and_noise[] = { 0, 0, -1 };
    +    const auto r_pair_and_noise = homogen_table::wrap(pair_and_noise, 3, 1);
    +
    +    constexpr std::int32_t all_noise[] = { -1, -1, -1 };
    +    const auto r_all_noise = homogen_table::wrap(all_noise, 3, 1);
    +
    +    constexpr std::int32_t one_cluster[] = { 0, 0, 0 };
    +    const auto r_one_cluster = homogen_table::wrap(one_cluster, 3, 1);
    +
    +    // Only the two closest points fall inside a radius of 1.5, and only under a
    +    // metric that does not add the two coordinate differences up.
    +    this->run_metric_checks(x,
    +                            1.5,
    +                            min_observations,
    +                            distance_metric::euclidean,
    +                            2.0,
    +                            r_pair_and_noise);
    +    this->run_metric_checks(x,
    +                            1.5,
    +                            min_observations,
    +                            distance_metric::chebyshev,
    +                            2.0,
    +                            r_pair_and_noise);
    +    this->run_metric_checks(x,
    +                            1.5,
    +                            min_observations,
    +                            distance_metric::minkowski,
    +                            3.0,
    +                            r_pair_and_noise);
    +    this->run_metric_checks(x, 1.5, min_observations, distance_metric::manhattan, 2.0, r_all_noise);
    +
    +    // A radius of 2.5 additionally links the middle point to the far one, but
    +    // only for chebyshev.
    +    this->run_metric_checks(x,
    +                            2.5,
    +                            min_observations,
    +                            distance_metric::euclidean,
    +                            2.0,
    +                            r_pair_and_noise);
    +    this->run_metric_checks(x,
    +                            2.5,
    +                            min_observations,
    +                            distance_metric::manhattan,
    +                            2.0,
    +                            r_pair_and_noise);
    +    this->run_metric_checks(x,
    +                            2.5,
    +                            min_observations,
    +                            distance_metric::minkowski,
    +                            3.0,
    +                            r_pair_and_noise);
    +    this->run_metric_checks(x,
    +                            2.5,
    +                            min_observations,
    +                            distance_metric::chebyshev,
    +                            2.0,
    +                            r_one_cluster);
    +}
    +
    +TEMPLATE_LIST_TEST_M(dbscan_batch_test,
    +                     "dbscan wide metric test",
    +                     "[dbscan][batch]",
    +                     dbscan_types) {
    +    SKIP_IF(this->not_float64_friendly());
    +    using float_t = std::tuple_element_t<0, TestType>;
    +
    +    // Pairwise distances: (p0, p1) = 2.24 / 5 / 1 / 1.71,
    +    //                     (p0, p2) = 4    / 4 / 4 / 4,
    +    //                     (p1, p2) = 3.61 / 7 / 3 / 3.14
    +    // for euclidean / manhattan / chebyshev / minkowski(3) respectively.
    +    constexpr float_t data[] = { 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 1.0, 1.0,
    +                                 1.0, 1.0, 4.0, 0.0, 0.0, 0.0, 0.0 };
    +    const auto x = homogen_table::wrap(data, 3, 5);
    +
    +    constexpr std::int64_t min_observations = 2;
    +
    +    constexpr std::int32_t pair_and_noise[] = { 0, 0, -1 };
    +    const auto r_pair_and_noise = homogen_table::wrap(pair_and_noise, 3, 1);
    +
    +    constexpr std::int32_t all_noise[] = { -1, -1, -1 };
    +    const auto r_all_noise = homogen_table::wrap(all_noise, 3, 1);
    +
    +    constexpr std::int32_t one_cluster[] = { 0, 0, 0 };
    +    const auto r_one_cluster = homogen_table::wrap(one_cluster, 3, 1);
    +
    +    this->run_metric_checks(x,
    +                            2.5,
    +                            min_observations,
    +                            distance_metric::euclidean,
    +                            2.0,
    +                            r_pair_and_noise);
    +    this->run_metric_checks(x,
    +                            2.5,
    +                            min_observations,
    +                            distance_metric::chebyshev,
    +                            2.0,
    +                            r_pair_and_noise);
    +    this->run_metric_checks(x,
    +                            2.5,
    +                            min_observations,
    +                            distance_metric::minkowski,
    +                            3.0,
    +                            r_pair_and_noise);
    +    this->run_metric_checks(x, 2.5, min_observations, distance_metric::manhattan, 2.0, r_all_noise);
    +
    +    this->run_metric_checks(x,
    +                            3.5,
    +                            min_observations,
    +                            distance_metric::euclidean,
    +                            2.0,
    +                            r_pair_and_noise);
    +    this->run_metric_checks(x, 3.5, min_observations, distance_metric::manhattan, 2.0, r_all_noise);
    +    this->run_metric_checks(x,
    +                            3.5,
    +                            min_observations,
    +                            distance_metric::chebyshev,
    +                            2.0,
    +                            r_one_cluster);
    +    this->run_metric_checks(x,
    +                            3.5,
    +                            min_observations,
    +                            distance_metric::minkowski,
    +                            3.0,
    +                            r_one_cluster);
    +}
    +
    +TEMPLATE_LIST_TEST_M(dbscan_batch_test,
    +                     "dbscan minkowski degree matches the dedicated metrics",
    +                     "[dbscan][batch]",
    +                     dbscan_types) {
    +    SKIP_IF(this->not_float64_friendly());
    +    using float_t = std::tuple_element_t<0, TestType>;
    +
    +    constexpr float_t data[] = { 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 1.0, 1.0,
    +                                 1.0, 1.0, 4.0, 0.0, 0.0, 0.0, 0.0 };
    +    const auto x = homogen_table::wrap(data, 3, 5);
    +
    +    constexpr std::int64_t min_observations = 2;
    +    const double epsilon = GENERATE_COPY(1.5, 2.5, 3.5, 4.5);
    +
    +    INFO("run the reference metric");
    +    const auto reference =
    +        oneapi::dal::test::engine::compute(this->get_policy(),
    +                                           this->get_metric_descriptor(epsilon,
    +                                                                       min_observations,
    +                                                                       distance_metric::euclidean,
    +                                                                       2.0,
    +                                                                       true),
    +                                           x,
    +                                           table{});
    +
    +    INFO("minkowski with degree 2 reproduces euclidean");
    +    this->run_metric_checks(x,
    +                            epsilon,
    +                            min_observations,
    +                            distance_metric::minkowski,
    +                            2.0,
    +                            reference.get_responses());
    +
    +    INFO("run the reference metric");
    +    const auto manhattan_reference =
    +        oneapi::dal::test::engine::compute(this->get_policy(),
    +                                           this->get_metric_descriptor(epsilon,
    +                                                                       min_observations,
    +                                                                       distance_metric::manhattan,
    +                                                                       2.0,
    +                                                                       true),
    +                                           x,
    +                                           table{});
    +
    +    INFO("minkowski with degree 1 reproduces manhattan");
    +    this->run_metric_checks(x,
    +                            epsilon,
    +                            min_observations,
    +                            distance_metric::minkowski,
    +                            1.0,
    +                            manhattan_reference.get_responses());
    +}
    +
    +TEMPLATE_LIST_TEST_M(dbscan_batch_test,
    +                     "dbscan cosine metric test",
    +                     "[dbscan][batch]",
    +                     dbscan_types) {
    +    SKIP_IF(this->not_float64_friendly());
    +    using float_t = std::tuple_element_t<0, TestType>;
    +
    +    constexpr std::int64_t min_observations = 2;
    +    constexpr double epsilon = 0.1;
    +
    +    constexpr std::int32_t responses[] = { 0, 0, -1 };
    +    const auto r = homogen_table::wrap(responses, 3, 1);
    +
    +    // The first two rows are collinear, so the cosine distance between them is
    +    // zero however far apart they are in the euclidean sense. The third row is
    +    // orthogonal to both, at the maximum cosine distance of one.

    Fixed in e8493e3f1: the comment now says orthogonal rows are at cosine distance one. The zero-row test also covers eps = 1 and min_observations = 1 now.

    coderabbitai[bot] coderabbitai[bot] commented on Oct 22, 2026 10:36 UTC
    Bot

    <!-- coderabbit-ai-generated:v1 -->

    <!-- This is an auto-generated comment: summarize by coderabbit.ai -->
    <!-- review_stack_entry_start -->

    <a href="https://app.coderabbit.ai/change-stack/uxlfoundation/oneDAL/pull/3815?scope=ghh_OusAJGA4HG8ljoOV0wJvVx8NmnZIjc2DdjmxOu0xZWA&amp;cs_source=review_comment"><picture><source media="(prefers-color-scheme: dark)" srcset="https://storage.googleapis.com/coderabbit_public_assets/review-stack-in-coderabbit-ui-dark.svg?v=3"><source media="(prefers-color-scheme: light)" srcset="https://storage.googleapis.com/coderabbit_public_assets/review-stack-in-coderabbit-ui.svg?v=3"><img src="https://storage.googleapis.com/coderabbit_public_assets/review-stack-in-coderabbit-ui.svg?v=3" alt="Review in Change Stack →" height="32"></picture></a>

    <!-- review_stack_entry_end -->
    <!-- This is an auto-generated comment: review paused by coderabbit.ai -->

    [!NOTE]

    ## Reviews paused

    > It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

    > - Last reviewed commit: 5df38ba1e25dfd2a55f1eeabd5d06eb310ba7930

    - Latest commit, not reviewed: 6c1dd474b32a71ad80d797cb16766d5ef302449b

    > Use the following commands to manage reviews:

    - @coderabbitai resume to resume automatic reviews.

    - @coderabbitai review to trigger a single review.

    > Use the checkboxes below for quick actions:

    - [ ] <!-- {"checkboxId":"7f6cc2e2-2e4e-497a-8c31-c9e4573e93d1"} --> Resume reviews

    - [ ] <!-- {"checkboxId":"e9bb8d72-00e8-4f67-9cb2-caf3b22574fe"} --> Trigger review

    <!-- end of auto-generated comment: review paused by coderabbit.ai -->
    <!-- recent_review_status_start -->

    No actionable comments were generated in the recent review.

    <!-- recent_review_status_end -->
    <!-- walkthrough_start -->

    <details>
    <summary><strong>Summary</strong></summary>
    <dl>
    <dd>

    <!-- This is an auto-generated comment: release notes by coderabbit.ai -->

    Summary by CodeRabbit

    New Features
    DBSCAN supports Euclidean, Manhattan, Minkowski, Chebyshev, and cosine distance metrics on CPU and GPU, in both memory modes.
    Choose a distance metric and, for Minkowski, configure its degree. The neighborhood radius is interpreted in the selected metric’s units. Cosine distance also handles zero-valued observations.
    Documentation
    Added guidance and C++ and SYCL examples for running DBSCAN with different distance metrics.

    <!-- end of auto-generated comment: release notes by coderabbit.ai -->
    DBSCAN adds Euclidean, Manhattan, Minkowski, Chebyshev, and cosine distance options, with configurable Minkowski degree. CPU and GPU paths use metric-specific distances and thresholds. The change adds reference-based tests, documentation, examples, and shared pairwise-distance utilities used by HDBSCAN.

    Changes: DBSCAN distance metrics

    |Layer / File(s)|Summary|
    |:---|:---|
    |Metric API and descriptor <br> cpp/oneapi/dal/algo/dbscan/common.hpp, cpp/oneapi/dal/algo/dbscan/common.cpp|The descriptor exposes five distance metrics and a degree. It defaults to Euclidean and 2.0. It rejects degrees that are non-positive or non-finite.|
    |CPU neighborhood distance execution <br> cpp/daal/src/algorithms/dbscan/
    , cpp/oneapi/dal/algo/dbscan/backend/cpu/, cpp/daal/src/algorithms/service_kernel_math.h, cpp/daal/src/algorithms/hdbscan/hdbscan_centers_impl.i, cpp/oneapi/dal/algo/dbscan/BUILD|The CPU backend passes the selected metric and degree to DBSCAN. The neighborhood engine dispatches distance queries by metric and transforms epsilon for comparisons. Shared pairwise-distance utilities provide metric implementations for DBSCAN and HDBSCAN medoid computation.|
    |GPU neighborhood distance execution <br> cpp/oneapi/dal/algo/dbscan/backend/gpu/
    |GPU core-search and queue-update kernels accumulate distances according to the selected metric and compare them with a transformed threshold. Cosine distance calculations use normalized input rows.|
    |Metric tests, documentation, and examples <br> cpp/oneapi/dal/algo/dbscan/test/, docs/source/api/algorithms/clustering/dbscan.rst, docs/source/onedal/algorithms/clustering/dbscan.rst, docs/source/includes/clustering/dbscan-examples.rst, examples/oneapi/cpp/source/dbscan/, examples/oneapi/dpc/source/dbscan/|Tests compare DBSCAN results with reference distances and cover cosine inputs with zero rows. Documentation and C++ and DPC++ examples describe and exercise the supported metrics.|

    Possibly related issues

  • uxlfoundation/oneDAL#3918: This issue notes that PR #3815 extends shared HDBSCAN distance functors and identifies HDBSCAN degree validation as a remaining gap. The changes reuse shared pairwise-distance creation but do not change HDBSCAN degree validation.
  • </dd>
    </dl>
    </details>

    <!-- walkthrough_end -->
    <!-- change_assessment_start -->
    <!-- change_assessment_commit:"5df38ba1e25dfd2a55f1eeabd5d06eb310ba7930" -->
    <!-- change_assessment_priority:{"version":1,"urgency":"p2","manual":false} -->

    <!-- change_assessment_end -->
    <details>
    <summary><strong>Merge Risk:</strong> <strong><picture><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/risk-low-16.svg" width="16" height="16" align="absmiddle" alt=""></picture> Low</strong> · previous review <code>5df38</code></summary>
    <dl>
    <dd>

    <!-- final_review_risk_start -->
    <!-- final_review_risk_label
    Merge Risk: 🔵 Low · up to 5df38
    -->
    <!-- final_review_risk_coverage:{"sourceCommitId":"5df38ba1e25dfd2a55f1eeabd5d06eb310ba7930","coveredCommitId":"5df38ba1e25dfd2a55f1eeabd5d06eb310ba7930","kind":"reviewed"} -->

    Memory-saving Minkowski DBSCAN may fault for some row widths on Intel AVX-512 builds. The concern is limited to that configuration and has already been reported; the other inspected metric paths are consistent.
    <!-- final_review_risk_end -->

    </dd>
    </dl>
    </details>

    <details>
    <summary><strong>Security architecture risk:</strong> <strong><picture><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/risk-low-16.svg" width="16" height="16" align="absmiddle" alt=""></picture> Low</strong> · up to <code>c10c2</code></summary>
    <dl>
    <dd>

    <!-- architecture_review_start -->
    <!-- architecture_review_label

    Security Architecture Review

    Security architecture risk: 🔵 Low · up to c10c2
    -->

    The change broadens DBSCAN’s numeric API within its existing execution paths. No introduced security flaw was identified, although distributed failure behavior was assessed from source rather than runtime fault testing.

    Retained concerns
    No architecture-level concerns identified.

    <details>
    <summary><strong>Security review details</strong></summary>
    <dl>
    <dd>

    Security Blast Radius

  • _inferred_ — The examined change affects clustering results and computation over caller-supplied tables, including participating SPMD ranks. The traced metric-selection path does not introduce a service identity, credential, filesystem, or authorization transition; this conclusion is limited to the inspected library paths.
  • Trust Boundaries and Controls

  • _observed_ — The relevant caller-to-library controls are numeric validation and closed backend conversion. Degree validation is centralized in descriptor storage, and each backend independently rejects unsupported metric values before metric-specific kernel selection.
  • </dd>
    </dl>
    </details>
    <!-- architecture_review_end -->

    </dd>
    </dl>
    </details>
    <!-- pre_merge_checks_walkthrough_start -->

    <details>
    <summary><strong>Pre-merge checks: <sup><picture><img src="https://storage.googleapis.com/coderabbit_public_assets/pre-merge-checks-counter-passed-14-v2.svg" width="14" height="14" align="middle" alt="Passed" title="Passed"></picture></sup> 4</strong></summary>
    <dl>
    <dd>

    | Check name | Status | Explanation |
    | :------------------------ | :--------------------------------------------------------------------------------------------: | :-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
    | Title check | !Passed | The title clearly and concisely identifies the primary change: adding Manhattan, Minkowski, Chebyshev, and cosine distance metrics to DBSCAN. |
    | Linked Issues check | !Passed | Issue #3623 is closed and provides historical context only. No active directly linked issue remains. No linked-issue coding requirements apply. |
    | Out of Scope Changes check | !Passed | The changes match the current DBSCAN metric objective. They add metric and degree accessors, implement the metrics in CPU, GPU, memory-saving, and SPMD paths, add validation and tests, and update docu… |
    | Description check | !Passed | The description covers the required structure well. It gives a full summary of the change, with a usage example for set_metric and set_degree and a 'How it works' section for the CPU and GPU paths. It… |

    <details>
    <summary><strong>Full details: Out of Scope Changes check</strong></summary>
    <dl>
    <dd>

    Explanation

    The changes match the current DBSCAN metric objective. They add metric and degree accessors, implement the metrics in CPU, GPU, memory-saving, and SPMD paths, add validation and tests, and update documentation and examples. The shared distance-primitives and HDBSCAN factory changes support this implementation. No unrelated change is demonstrated.

    </dd>
    </dl>
    </details>

    <details>
    <summary><strong>Full details: Description check</strong></summary>
    <dl>
    <dd>

    Explanation

    The description covers the required structure well. It gives a full summary of the change, with a usage example for set_metric and set_degree and a 'How it works' section for the CPU and GPU paths. It lists tests (metrics, degrees, dimensions, weights, memory modes, float and double, GPU SPMD, cosine zero rows vs. scikit-learn, bad arguments), documentation updates (developer guide section, API reference enum, new batch examples), and an API/ABI and breaking-change statement. The template's checklist is not filled in. Its items cover commenting, documentation, signed-off-by commit message, merge conflicts, local testing, green CI, extended tests, and performance measurements. The description does not mark these items or justify any unchecked ones. It also does not state whether the PR is still a draft, and it does not list a scikit-learn_bench PR or performance measurements for the affected DBSCAN path. The PR objectives say the author reports passing host tests on a specific commit, but the description does not mention CI status. The description is mostly complete, so the check passes. The missing checklist and performance information are non-critical for this assessment.

    </dd>
    </dl>
    </details>

    </dd>
    </dl>
    </details>

    <!-- pre_merge_checks_walkthrough_end -->
    <!-- finishing_touch_checkbox_start -->

    <details>
    <summary><strong>Finishing Touches</strong></summary>
    <dl>
    <dd>

    <details open>
    <summary><strong>Simplify code</strong></summary>
    <dl>
    <dd>

  • <!-- {"checkboxId": "f120d606-b0e2-4b7d-8316-181794555b43", "radioGroupId": "simplify-output-choice-group-unknown_comment_id"} --> Create a new PR
  • </dd>
    </dl>
    </details>

    </dd>
    </dl>
    </details>

    <!-- finishing_touch_checkbox_end -->

    <!-- autopilot:start -->

  • <!-- {"checkboxId":"2708ad07-9f24-4260-9c11-7dc76a49f2e3"} --> <strong title="Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts">Autofix</strong> · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

  • <!-- autopilot:end -->
    <!-- announcements_start -->

    [!TIP]

    <details>

    <summary><strong>🎯 Customize your risk assessments</strong></summary>

    <dl>

    <dd>

    > Guide how CodeRabbit assesses merge risk and security architecture risk. Highlight sensitive changes and explain your security boundaries using Merge Risk Instructions and Security Risk Instructions in your review settings. Security architecture risk assessments require the Advanced plan or above.

    > </dd>

    </dl>

    </details>

    > <details>

    <summary><strong>✅ Automatic approvals, with your rules</strong></summary>

    <dl>

    <dd>

    > Let CodeRabbit approve pull requests once required threads are resolved, pre-merge checks pass, and your risk limits are met. Enable Automatic approvals in review settings, with overrides for teams or file paths.

    > </dd>

    </dl>

    </details>

    <!-- announcements_end -->
    <!-- tips_start -->

    Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

    <details>
    <summary><strong>Share</strong></summary>
    <dl>
    <dd>

  • X

  • Mastodon

  • Reddit

  • LinkedIn
  • </dd>
    </dl>
    </details>

    <!-- tips_end -->
    <!-- verify_invitation_start -->

    CodeRabbit Verify

  • <!-- {"checkboxId":"run-qa-agent"} --> Run CodeRabbit Verify to test the changes in this pull request.

  • <!-- verify_invitation_end -->
    <!-- recent_review_start -->

    <h6>
    <details>
    <summary><strong><picture><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/info.svg" width="12" height="12" align="absmiddle" alt=""></picture> Recent review info</strong></summary>
    <dl>
    <dd>

    <!-- review_info_content -->
    <details>
    <summary><strong><picture><source media="(prefers-color-scheme: dark)" srcset="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/cog-dark.svg"><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/cog.svg" width="16" height="16" align="absmiddle" alt=""></picture> Run configuration</strong></summary>
    <dl>
    <dd>

  • Source mode: Auto

  • Repository: Unavailable

  • Branch: Unavailable

  • File: No configuration file from this repository applied

  • Commit: Unavailable

  • Layers: Organization UI

  • Review profile: CHILL

  • Plan: Advanced

  • Run ID: 138b3f73-6760-4bc4-8c24-b4185d1c6fe6
  • </dd>
    </dl>
    </details>

    <details>
    <summary><strong><picture><source media="(prefers-color-scheme: dark)" srcset="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/git-commit-horizontal-dark.svg"><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/git-commit-horizontal.svg" width="16" height="16" align="absmiddle" alt=""></picture> Commits</strong></summary>
    <dl>
    <dd>

    Reviewing files that changed from the base of the PR and between a452c2bb47d61749d071e302efa852c707f87710 and 5df38ba1e25dfd2a55f1eeabd5d06eb310ba7930.

    </dd>
    </dl>
    </details>

    <details>
    <summary><strong><picture><source media="(prefers-color-scheme: dark)" srcset="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/file-plus-corner-dark.svg"><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/file-plus-corner.svg" width="16" height="16" align="absmiddle" alt=""></picture> Files selected for processing: 6</strong></summary>
    <dl>
    <dd>

    cpp/daal/src/algorithms/dbscan/dbscan_utils.h
    cpp/daal/src/algorithms/service_kernel_math.h
    cpp/oneapi/dal/algo/dbscan/backend/cpu/compute_kernel_brute_force.cpp
    cpp/oneapi/dal/algo/dbscan/common.cpp
    cpp/oneapi/dal/algo/dbscan/common.hpp

  • cpp/oneapi/dal/algo/dbscan/test/fixture.hpp
  • </dd>
    </dl>
    </details>

    Included review availability: This review used your included allowance. Your plan provides up to 4 included reviews per hour; 2 remain after this review.

    </dd>
    </dl>
    </details>
    </h6>

    <!-- recent_review_end -->

    napetrov napetrov commented on Oct 27, 2026 20:48 UTC
    Reviewer

    Thanks for the metric additions. The shared poweredEpsilon and the memory-mode tests read well.

    Question, the one item to settle before approval: the self-diagonal is forced to zero on CPU (queryFullImpl, queryImpl) and on GPU (j == wg_id). For a zero row under cosine, that puts the row in its own neighborhood even when eps < 1. The test handles zero rows like scikit-learn expects {0,1,2,2} for eps 0.1, min_observations 1. Could you confirm that against sklearn.cluster.DBSCAN(eps=0.1, min_samples=1, metric="cosine") on the same 4x2 fixture? I have not run sklearn here. If sklearn labels those zero rows as noise, zero rows need an exception to the self-inclusion rule, or the test comment needs correcting.

    Nit: set_degree validates even for non-Minkowski metrics, but the doc says the degree is ignored. Please align them.

    Alexandr-Solovev Alexandr-Solovev commented on Oct 28, 2026 06:22 UTC
    Author

    @napetrov thanks, checked both points.

    Zero rows under cosine. Confirmed against scikit-learn 1.9.1 with DBSCAN(eps, min_samples, metric="cosine") on the test's fixtures, the 4x2 and the 4x5 one (the wide one gives the same labels):

    | eps | min_samples | sklearn labels | test expects |
    |---|---|---|---|
    | 0.1 | 1 | [0 1 2 2] | {0, 1, 2, 2} |
    | 0.1 | 2 | [-1 -1 0 0] | {-1, -1, 0, 0} |
    | 1.0 | 4 | [0 0 0 0] | {0, 0, 0, 0} |

    Mechanism: sklearn.metrics.pairwise.cosine_distances(X, Y) sets the diagonal to 0 when X is Y, so a zero row is its own neighbor (self-distance 0 <= eps) even though its distance to the other zero row is 1. With min_samples=1 it is therefore a core point and gets its own cluster, which is what the test expects, and it also matches the DBSCAN definition (the eps-neighborhood contains the point itself; sklearn's min_samples doc says "including the point itself").

    One caveat for the record: when pairwise_distances_chunked splits the rows into chunks (roughly above 11k rows with the default working_memory), sklearn does not zero the diagonal and the same zero rows come out as noise (-1); I reproduced that on 20002 rows. So sklearn is inconsistent across input sizes there, and forcing the self-distance to 0 is the consistent choice. The test comment now names the path it reproduces.

    set_degree vs. doc. Kept the eager validation, like the other setters (set_epsilon, set_min_observations), and aligned the doc: the degree must be positive and finite for every metric and only the Minkowski metric reads it. Both common.hpp and docs/source/onedal/algorithms/clustering/dbscan.rst say so now. Commit 7b0f6ea29, after a merge of current main; //cpp/oneapi/dal/algo/dbscan:tests (host) passes.

    Vika-F Vika-F commented on code on Oct 30, 2026 16:12 UTC
    Code Review
    cpp/oneapi/dal/algo/dbscan/common.hpp:1
    @@ -22,6 +22,26 @@
     
     namespace oneapi::dal::dbscan {
     
    +namespace v1 {
    +
    +/// Distance metric used for the epsilon-neighborhood search in DBSCAN.
    +enum class distance_metric {

    Maybe I've missed this during a HDBSCAN review, but now I have questions:
    Why distances support here is done differently than in KNN? In KNN distance type is provided as part of the descriptor's template, and here it is a runtime information.
    Is it possible now not to duplicate those kind of enums. I.e. HDBSCAN has the same enum. It would be better to have a shared enum defining distance types and just implement checks on descriptor's set methods in case some algorithm does not provide support for some distance types.

    Vika-F Vika-F commented on code on Oct 30, 2026 16:20 UTC
    Code Review
    cpp/daal/src/algorithms/dbscan/dbscan_utils.h:1
    @@ -508,6 +634,11 @@ class NeighborhoodEngine<defaultDense, FPType, cpu>
                     const FPType * const weights = weightsRows.get() ? weightsRows.get() : onesWeights;
     
                     metric.computeBatch(inData, outData, i1, iSize, j1, jSize, local);
    +                if (sameTable)
    +                {
    +                    // A row is always in its own neighborhood.
    +                    for (size_t k = (i1 > j1 ? i1 : j1); k < (i2 < j2 ? i2 : j2); k++) local[(k - i1) * jSize + (k - j1)] = FPType(0);

    To make it more readable:

                        // A row is always in its own neighborhood.
                        const size_t kStart = max(i1, j1);
                        const size_t kEnd = min(i2, j2);
                        for (size_t k = kStart; k < kEnd; k++) local[(k - i1) * jSize + (k - j1)] = FPType(0);
    

    Vika-F Vika-F commented on code on Oct 30, 2026 16:27 UTC
    Code Review
    cpp/daal/src/algorithms/dbscan/dbscan_utils.h:1
    @@ -431,6 +501,62 @@ class NeighborhoodEngine<defaultDense, FPType, cpu>
         }
     
         services::Status queryFull(Neighborhood<FPType, cpu> * neighs, bool doReset = false)
    +    {
    +        switch (_metric)
    +        {
    +        case PairwiseDistanceType::euclidean:

    HDBSCAN's createPairwiseDistances code can be reused here with minor modifications allowing to provide two tables as input arguments instead of one.

    Vika-F Vika-F commented on code on Oct 30, 2026 16:52 UTC
    Code Review
    cpp/daal/src/algorithms/dbscan/dbscan_utils.h:1
    @@ -431,6 +501,62 @@ class NeighborhoodEngine<defaultDense, FPType, cpu>
         }
     
         services::Status queryFull(Neighborhood<FPType, cpu> * neighs, bool doReset = false)
    +    {
    +        switch (_metric)
    +        {
    +        case PairwiseDistanceType::euclidean:
    +        {
    +            EuclideanDistances<FPType, cpu> metric(*_inTable, *_outTable);
    +            return queryFullImpl(metric, neighs, doReset);
    +        }
    +        case PairwiseDistanceType::manhattan:
    +        {
    +            MinkowskiDistances<FPType, cpu> metric(*_inTable, *_outTable, true, 1.0);
    +            return queryFullImpl(metric, neighs, doReset);
    +        }
    +        case PairwiseDistanceType::minkowski:
    +        {
    +            MinkowskiDistances<FPType, cpu> metric(*_inTable, *_outTable, true, (double)_p);
    +            return queryFullImpl(metric, neighs, doReset);
    +        }
    +        case PairwiseDistanceType::chebyshev:
    +        {
    +            ChebyshevDistances<FPType, cpu> metric(*_inTable, *_outTable);
    +            return queryFullImpl(metric, neighs, doReset);
    +        }
    +        case PairwiseDistanceType::cosine:
    +        {
    +            ZeroRowCosineDistances<FPType, cpu> metric(*_inTable, *_outTable);
    +            return queryFullImpl(metric, neighs, doReset);
    +        }
    +        }
    +
    +        return services::Status(services::ErrorMethodNotSupported);
    +    }
    +
    +    services::Status query(size_t * indices, size_t n, Neighborhood<FPType, cpu> * neighs, bool doReset = false)
    +    {
    +        // Each distance is in the same form as the matching `queryFull` engine, so both paths share `poweredEpsilon`.
    +        const hdbscan::internal::MinkowskiDist<FPType> minkowski(_p);
    +        switch (_metric)
    +        {
    +        case PairwiseDistanceType::euclidean: return queryImpl(distancePow2<FPType, cpu>, indices, n, neighs, doReset);
    +        case PairwiseDistanceType::manhattan:
    +            return queryImpl(hdbscan::internal::ManhattanDist<FPType>::template pointDist<cpu>, indices, n, neighs, doReset);
    +        case PairwiseDistanceType::minkowski:
    +            return queryImpl([&](const FPType * a, const FPType * b, size_t dim) { return minkowski.template poweredPointDist<cpu>(a, b, dim); },
    +                             indices, n, neighs, doReset);
    +        case PairwiseDistanceType::chebyshev:
    +            return queryImpl(hdbscan::internal::ChebyshevDist<FPType>::template pointDist<cpu>, indices, n, neighs, doReset);
    +        case PairwiseDistanceType::cosine: return queryImpl(cosinePointDist<FPType, cpu>, indices, n, neighs, doReset);

    I still do not get, why do we need a separate implementation of the distances (MinkowskiDist, etc) laying in HDBSCAN?
    Can we just add those pointDist functions into already existing implementations of pairwise distances in service_kernel_math.h and use those in all the algorithms?

    Vika-F Vika-F commented on code on Oct 30, 2026 17:07 UTC
    Code Review
    cpp/daal/src/algorithms/dbscan/dbscan_utils.h:1
    @@ -390,11 +391,79 @@ struct NTask
         daal::tls<TlsNTask<FPType, cpu> *> * tlsNTask;
     };
     
    +/// Maps `eps` to the space the distances are compared in: squared for Euclidean, raised to `p`
    +/// for Minkowski, unchanged for the metrics that take no root.
    +///
    +/// @param[in] metric Distance metric
    +/// @param[in] eps    Neighborhood radius in the units of `metric`
    +/// @param[in] p      Minkowski degree; ignored by the other metrics
    +/// @return The threshold the unrooted distances are compared against
    +template <typename FPType, CpuType cpu>
    +inline FPType poweredEpsilon(PairwiseDistanceType metric, FPType eps, FPType p)
    +{
    +    switch (metric)
    +    {
    +    case PairwiseDistanceType::euclidean: return eps * eps;
    +    case PairwiseDistanceType::minkowski: return MathInst<FPType, cpu>::sPowx(eps, p);
    +    default: return eps;
    +    }
    +}
    +
    +/// Cosine distance of two rows for the memory-saving search; a zero row is at distance 1 from
    +/// every other row, as in scikit-learn.
    +template <typename FPType, CpuType cpu>
    +FPType cosinePointDist(const FPType * a, const FPType * b, size_t dim)
    +{
    +    FPType dot = FPType(0);
    +    FPType aa  = FPType(0);
    +    FPType bb  = FPType(0);
    +    PRAGMA_OMP_SIMD_ARGS(reduction(+ : dot, aa, bb))
    +    for (size_t i = 0; i < dim; ++i)
    +    {
    +        dot += a[i] * b[i];
    +        aa += a[i] * a[i];
    +        bb += b[i] * b[i];
    +    }
    +    const FPType norm = MathInst<FPType, cpu>::sSqrt(aa) * MathInst<FPType, cpu>::sSqrt(bb);
    +    return (norm > FPType(0)) ? FPType(1) - dot / norm : FPType(1);
    +}
    +
    +/// `CosineDistances` with scikit-learn's value for zero rows: distance 1 from every other row.
    +template <typename FPType, CpuType cpu>
    +class ZeroRowCosineDistances : public CosineDistances<FPType, cpu>
    +{
    +    using super = CosineDistances<FPType, cpu>;
    +
    +public:
    +    ZeroRowCosineDistances(const NumericTable & a, const NumericTable & b) : super(a, b) {}
    +
    +    services::Status computeBatch(const FPType * const a, const FPType * const b, size_t aOffset, size_t aSize, size_t bOffset, size_t bSize,
    +                                  FPType * const res) override
    +    {
    +        services::Status s = super::computeBatch(a, b, aOffset, aSize, bOffset, bSize, res);
    +        // `init` stores the row norms, so a zero norm marks a zero row.
    +        const FPType * const aNorms = this->normBufferA.get() + aOffset;
    +        const FPType * const bNorms = (&this->_a == &this->_b) ? this->normBufferA.get() + bOffset : this->normBufferB.get() + bOffset;
    +        for (size_t i = 0; i < aSize; i++)
    +        {
    +            if (aNorms[i] != FPType(0)) continue;
    +            for (size_t j = 0; j < bSize; j++) res[i * bSize + j] = FPType(1);

    memset?

    Vika-F Vika-F commented on code on Oct 30, 2026 17:08 UTC
    Code Review
    cpp/daal/src/algorithms/dbscan/dbscan_utils.h:1
    @@ -390,11 +391,79 @@ struct NTask
         daal::tls<TlsNTask<FPType, cpu> *> * tlsNTask;
     };
     
    +/// Maps `eps` to the space the distances are compared in: squared for Euclidean, raised to `p`
    +/// for Minkowski, unchanged for the metrics that take no root.
    +///
    +/// @param[in] metric Distance metric
    +/// @param[in] eps    Neighborhood radius in the units of `metric`
    +/// @param[in] p      Minkowski degree; ignored by the other metrics
    +/// @return The threshold the unrooted distances are compared against
    +template <typename FPType, CpuType cpu>
    +inline FPType poweredEpsilon(PairwiseDistanceType metric, FPType eps, FPType p)
    +{
    +    switch (metric)
    +    {
    +    case PairwiseDistanceType::euclidean: return eps * eps;
    +    case PairwiseDistanceType::minkowski: return MathInst<FPType, cpu>::sPowx(eps, p);
    +    default: return eps;
    +    }
    +}
    +
    +/// Cosine distance of two rows for the memory-saving search; a zero row is at distance 1 from
    +/// every other row, as in scikit-learn.
    +template <typename FPType, CpuType cpu>
    +FPType cosinePointDist(const FPType * a, const FPType * b, size_t dim)
    +{
    +    FPType dot = FPType(0);
    +    FPType aa  = FPType(0);
    +    FPType bb  = FPType(0);
    +    PRAGMA_OMP_SIMD_ARGS(reduction(+ : dot, aa, bb))
    +    for (size_t i = 0; i < dim; ++i)
    +    {
    +        dot += a[i] * b[i];
    +        aa += a[i] * a[i];
    +        bb += b[i] * b[i];
    +    }
    +    const FPType norm = MathInst<FPType, cpu>::sSqrt(aa) * MathInst<FPType, cpu>::sSqrt(bb);
    +    return (norm > FPType(0)) ? FPType(1) - dot / norm : FPType(1);
    +}
    +
    +/// `CosineDistances` with scikit-learn's value for zero rows: distance 1 from every other row.
    +template <typename FPType, CpuType cpu>
    +class ZeroRowCosineDistances : public CosineDistances<FPType, cpu>
    +{
    +    using super = CosineDistances<FPType, cpu>;
    +
    +public:
    +    ZeroRowCosineDistances(const NumericTable & a, const NumericTable & b) : super(a, b) {}
    +
    +    services::Status computeBatch(const FPType * const a, const FPType * const b, size_t aOffset, size_t aSize, size_t bOffset, size_t bSize,
    +                                  FPType * const res) override
    +    {
    +        services::Status s = super::computeBatch(a, b, aOffset, aSize, bOffset, bSize, res);
    +        // `init` stores the row norms, so a zero norm marks a zero row.
    +        const FPType * const aNorms = this->normBufferA.get() + aOffset;
    +        const FPType * const bNorms = (&this->_a == &this->_b) ? this->normBufferA.get() + bOffset : this->normBufferB.get() + bOffset;
    +        for (size_t i = 0; i < aSize; i++)
    +        {
    +            if (aNorms[i] != FPType(0)) continue;

    Should there be some tolerance? i.e. fabs(aNorms[i]) < tol?

    Vika-F Vika-F commented on code on Oct 30, 2026 17:11 UTC
    Code Review
    cpp/daal/src/algorithms/dbscan/dbscan_utils.h:1
    @@ -390,11 +391,79 @@ struct NTask
         daal::tls<TlsNTask<FPType, cpu> *> * tlsNTask;
     };
     
    +/// Maps `eps` to the space the distances are compared in: squared for Euclidean, raised to `p`
    +/// for Minkowski, unchanged for the metrics that take no root.
    +///
    +/// @param[in] metric Distance metric
    +/// @param[in] eps    Neighborhood radius in the units of `metric`
    +/// @param[in] p      Minkowski degree; ignored by the other metrics
    +/// @return The threshold the unrooted distances are compared against
    +template <typename FPType, CpuType cpu>
    +inline FPType poweredEpsilon(PairwiseDistanceType metric, FPType eps, FPType p)
    +{
    +    switch (metric)
    +    {
    +    case PairwiseDistanceType::euclidean: return eps * eps;
    +    case PairwiseDistanceType::minkowski: return MathInst<FPType, cpu>::sPowx(eps, p);
    +    default: return eps;
    +    }
    +}
    +
    +/// Cosine distance of two rows for the memory-saving search; a zero row is at distance 1 from
    +/// every other row, as in scikit-learn.
    +template <typename FPType, CpuType cpu>
    +FPType cosinePointDist(const FPType * a, const FPType * b, size_t dim)
    +{
    +    FPType dot = FPType(0);
    +    FPType aa  = FPType(0);
    +    FPType bb  = FPType(0);
    +    PRAGMA_OMP_SIMD_ARGS(reduction(+ : dot, aa, bb))
    +    for (size_t i = 0; i < dim; ++i)
    +    {
    +        dot += a[i] * b[i];
    +        aa += a[i] * a[i];
    +        bb += b[i] * b[i];
    +    }
    +    const FPType norm = MathInst<FPType, cpu>::sSqrt(aa) * MathInst<FPType, cpu>::sSqrt(bb);
    +    return (norm > FPType(0)) ? FPType(1) - dot / norm : FPType(1);
    +}
    +
    +/// `CosineDistances` with scikit-learn's value for zero rows: distance 1 from every other row.
    +template <typename FPType, CpuType cpu>
    +class ZeroRowCosineDistances : public CosineDistances<FPType, cpu>

    It is better to move this definition to the place where CosineDistances is defined.

    coderabbitai[bot] coderabbitai[bot] commented on code on Nov 02, 2026 07:25 UTC
    Code Review
    cpp/daal/src/algorithms/dbscan/dbscan_utils.h:1
    @@ -431,6 +451,40 @@ class NeighborhoodEngine<defaultDense, FPType, cpu>
         }
     
         services::Status queryFull(Neighborhood<FPType, cpu> * neighs, bool doReset = false)
    +    {
    +        services::SharedPtr<PairwiseDistances<FPType, cpu> > metric(createPairwiseDistances<FPType, cpu>(*_inTable, *_outTable, _metric, (double)_p));
    +        DAAL_CHECK_MALLOC(metric.get());
    +        return queryFullImpl(*metric, neighs, doReset);
    +    }
    +
    +    services::Status query(size_t * indices, size_t n, Neighborhood<FPType, cpu> * neighs, bool doReset = false)
    +    {
    +        // Each distance is in the same form as the matching `queryFull` engine, so both paths share `poweredEpsilon`.
    +        switch (_metric)
    +        {
    +        case PairwiseDistanceType::euclidean: return queryImpl(distancePow2<FPType, cpu>, indices, n, neighs, doReset);
    +        case PairwiseDistanceType::manhattan:
    +        case PairwiseDistanceType::minkowski:
    +        {
    +            const double p = (_metric == PairwiseDistanceType::manhattan) ? 1.0 : (double)_p;
    +            const MinkowskiDistances<FPType, cpu> metric(*_inTable, *_outTable, true, p);
    +            return queryImpl([&](const FPType * a, const FPType * b, size_t dim) { return metric.computeDistance(a, b, dim); }, indices, n, neighs,
    +                             doReset);

    <!-- coderabbit-ai-generated:v1 -->

    <picture><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/major-16.svg" width="16" height="16" align="absmiddle" alt=""></picture> Major · Stability & Availability · Quick win

    <details>
    <summary><picture><source media="(prefers-color-scheme: dark)" srcset="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/review-details-dark.svg"><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/review-details.svg" width="16" height="16" align="absmiddle" alt=""></picture> Supported by static analysis</summary>
    <dl>
    <dd>

    Script executed:

    printf '%s\n' '--- service_kernel_math.h ---'
    nl -ba cpp/daal/src/algorithms/service_kernel_math.h | sed -n '715,810p'
    printf '%s\n' '--- dbscan_utils.h indexed query ---'
    nl -ba cpp/daal/src/algorithms/dbscan/dbscan_utils.h | sed -n '450,480p;635,670p'
    

    Repository: uxlfoundation/oneDAL

    Length of output: 6979

    ---

    </dd>
    </dl>
    </details>

    Use unaligned loads for AVX-512 Minkowski inputs.

    The indexed path passes &outData[j outDim] to MinkowskiDistances::computeDistance. A valid 17-float row advances by 68 bytes, so later rows can be unaligned. The AVX-512 specialization dereferences those rows through __m512 or __m512d*, which can cause undefined behavior or a fault. Use _mm512_loadu_ps and _mm512_loadu_pd for every input vector load.

    <details>
    <summary>Suggested fix</summary>
    <dl>
    <dd>

    -    const __m512 * ptr512x = (__m512 *)x;
    -    const __m512 * ptr512y = (__m512 *)y;
    -
    ...
    -            d += _mm512_reduce_add_ps(_mm512_abs_ps(_mm512_sub_ps(ptr512x[i], ptr512y[i])));
    +            d += _mm512_reduce_add_ps(
    +                _mm512_abs_ps(_mm512_sub_ps(_mm512_loadu_ps(x + i * vecSize), _mm512_loadu_ps(y + i * vecSize))));
    ...
    -            _mm512_storeu_ps(tmp, _mm512_abs_ps(_mm512_sub_ps(ptr512x[i], ptr512y[i])));
    +            _mm512_storeu_ps(tmp, _mm512_abs_ps(
    +                _mm512_sub_ps(_mm512_loadu_ps(x + i * vecSize), _mm512_loadu_ps(y + i * vecSize))));
    ...
    -    const __m512d * ptr512x = (__m512d *)x;
    -    const __m512d * ptr512y = (__m512d *)y;
    -
    ...
    -            d += _mm512_reduce_add_pd(_mm512_abs_pd(_mm512_sub_pd(ptr512x[i], ptr512y[i])));
    +            d += _mm512_reduce_add_pd(
    +                _mm512_abs_pd(_mm512_sub_pd(_mm512_loadu_pd(x + i * vecSize), _mm512_loadu_pd(y + i * vecSize))));
    ...
    -            _mm512_storeu_pd(tmp, _mm512_abs_pd(_mm512_sub_pd(ptr512x[i], ptr512y[i])));
    +            _mm512_storeu_pd(tmp, _mm512_abs_pd(
    +                _mm512_sub_pd(_mm512_loadu_pd(x + i * vecSize), _mm512_loadu_pd(y + i * vecSize))));
    

    </dd>
    </dl>
    </details>

    <!-- fingerprinting:phantom:medusa:wombat -->

    <!-- cr-indicator-types:potential_issue -->

    <!-- cr-comment:v1:315dbcd7476e276a79cd9632 -->

    <!-- This is an auto-generated reply by CodeRabbit -->

    ✅ Addressed in commit 104d229

    coderabbitai[bot] coderabbitai[bot] commented on Nov 02, 2026 07:25 UTC
    Reviewer

    <!-- coderabbit-ai-generated:v1 -->

    <!-- This is an auto-generated comment by CodeRabbit for review status -->

    <!-- coderabbit-ai-generated:v1 -->

    <!-- This is an auto-generated comment by CodeRabbit for review status -->

    <!-- coderabbit-review-publication v1 publication=4ed2ec0a-fbed-487b-8ace-f79b17d919f4 attempt=c262714a-b29c-4a05-babc-aa1d72bb38e7 batch=1/1 -->

    Alexandr-Solovev Alexandr-Solovev commented on code on Nov 02, 2026 08:05 UTC
    Code Review
    cpp/daal/src/algorithms/dbscan/dbscan_utils.h:1
    @@ -508,6 +634,11 @@ class NeighborhoodEngine<defaultDense, FPType, cpu>
                     const FPType * const weights = weightsRows.get() ? weightsRows.get() : onesWeights;
     
                     metric.computeBatch(inData, outData, i1, iSize, j1, jSize, local);
    +                if (sameTable)
    +                {
    +                    // A row is always in its own neighborhood.
    +                    for (size_t k = (i1 > j1 ? i1 : j1); k < (i2 < j2 ? i2 : j2); k++) local[(k - i1) * jSize + (k - j1)] = FPType(0);

    done

    Alexandr-Solovev Alexandr-Solovev commented on code on Nov 02, 2026 08:06 UTC
    Code Review
    cpp/daal/src/algorithms/dbscan/dbscan_utils.h:1
    @@ -390,11 +391,79 @@ struct NTask
         daal::tls<TlsNTask<FPType, cpu> *> * tlsNTask;
     };
     
    +/// Maps `eps` to the space the distances are compared in: squared for Euclidean, raised to `p`
    +/// for Minkowski, unchanged for the metrics that take no root.
    +///
    +/// @param[in] metric Distance metric
    +/// @param[in] eps    Neighborhood radius in the units of `metric`
    +/// @param[in] p      Minkowski degree; ignored by the other metrics
    +/// @return The threshold the unrooted distances are compared against
    +template <typename FPType, CpuType cpu>
    +inline FPType poweredEpsilon(PairwiseDistanceType metric, FPType eps, FPType p)
    +{
    +    switch (metric)
    +    {
    +    case PairwiseDistanceType::euclidean: return eps * eps;
    +    case PairwiseDistanceType::minkowski: return MathInst<FPType, cpu>::sPowx(eps, p);
    +    default: return eps;
    +    }
    +}
    +
    +/// Cosine distance of two rows for the memory-saving search; a zero row is at distance 1 from
    +/// every other row, as in scikit-learn.
    +template <typename FPType, CpuType cpu>
    +FPType cosinePointDist(const FPType * a, const FPType * b, size_t dim)
    +{
    +    FPType dot = FPType(0);
    +    FPType aa  = FPType(0);
    +    FPType bb  = FPType(0);
    +    PRAGMA_OMP_SIMD_ARGS(reduction(+ : dot, aa, bb))
    +    for (size_t i = 0; i < dim; ++i)
    +    {
    +        dot += a[i] * b[i];
    +        aa += a[i] * a[i];
    +        bb += b[i] * b[i];
    +    }
    +    const FPType norm = MathInst<FPType, cpu>::sSqrt(aa) * MathInst<FPType, cpu>::sSqrt(bb);
    +    return (norm > FPType(0)) ? FPType(1) - dot / norm : FPType(1);
    +}
    +
    +/// `CosineDistances` with scikit-learn's value for zero rows: distance 1 from every other row.
    +template <typename FPType, CpuType cpu>
    +class ZeroRowCosineDistances : public CosineDistances<FPType, cpu>

    done

    Alexandr-Solovev Alexandr-Solovev commented on code on Nov 02, 2026 08:06 UTC
    Code Review
    cpp/daal/src/algorithms/dbscan/dbscan_utils.h:1
    @@ -390,11 +391,79 @@ struct NTask
         daal::tls<TlsNTask<FPType, cpu> *> * tlsNTask;
     };
     
    +/// Maps `eps` to the space the distances are compared in: squared for Euclidean, raised to `p`
    +/// for Minkowski, unchanged for the metrics that take no root.
    +///
    +/// @param[in] metric Distance metric
    +/// @param[in] eps    Neighborhood radius in the units of `metric`
    +/// @param[in] p      Minkowski degree; ignored by the other metrics
    +/// @return The threshold the unrooted distances are compared against
    +template <typename FPType, CpuType cpu>
    +inline FPType poweredEpsilon(PairwiseDistanceType metric, FPType eps, FPType p)
    +{
    +    switch (metric)
    +    {
    +    case PairwiseDistanceType::euclidean: return eps * eps;
    +    case PairwiseDistanceType::minkowski: return MathInst<FPType, cpu>::sPowx(eps, p);
    +    default: return eps;
    +    }
    +}
    +
    +/// Cosine distance of two rows for the memory-saving search; a zero row is at distance 1 from
    +/// every other row, as in scikit-learn.
    +template <typename FPType, CpuType cpu>
    +FPType cosinePointDist(const FPType * a, const FPType * b, size_t dim)
    +{
    +    FPType dot = FPType(0);
    +    FPType aa  = FPType(0);
    +    FPType bb  = FPType(0);
    +    PRAGMA_OMP_SIMD_ARGS(reduction(+ : dot, aa, bb))
    +    for (size_t i = 0; i < dim; ++i)
    +    {
    +        dot += a[i] * b[i];
    +        aa += a[i] * a[i];
    +        bb += b[i] * b[i];
    +    }
    +    const FPType norm = MathInst<FPType, cpu>::sSqrt(aa) * MathInst<FPType, cpu>::sSqrt(bb);
    +    return (norm > FPType(0)) ? FPType(1) - dot / norm : FPType(1);
    +}
    +
    +/// `CosineDistances` with scikit-learn's value for zero rows: distance 1 from every other row.
    +template <typename FPType, CpuType cpu>
    +class ZeroRowCosineDistances : public CosineDistances<FPType, cpu>
    +{
    +    using super = CosineDistances<FPType, cpu>;
    +
    +public:
    +    ZeroRowCosineDistances(const NumericTable & a, const NumericTable & b) : super(a, b) {}
    +
    +    services::Status computeBatch(const FPType * const a, const FPType * const b, size_t aOffset, size_t aSize, size_t bOffset, size_t bSize,
    +                                  FPType * const res) override
    +    {
    +        services::Status s = super::computeBatch(a, b, aOffset, aSize, bOffset, bSize, res);
    +        // `init` stores the row norms, so a zero norm marks a zero row.
    +        const FPType * const aNorms = this->normBufferA.get() + aOffset;
    +        const FPType * const bNorms = (&this->_a == &this->_b) ? this->normBufferA.get() + bOffset : this->normBufferB.get() + bOffset;
    +        for (size_t i = 0; i < aSize; i++)
    +        {
    +            if (aNorms[i] != FPType(0)) continue;
    +            for (size_t j = 0; j < bSize; j++) res[i * bSize + j] = FPType(1);

    done

    Alexandr-Solovev Alexandr-Solovev commented on code on Nov 02, 2026 08:09 UTC
    Code Review
    cpp/daal/src/algorithms/dbscan/dbscan_utils.h:1
    @@ -431,6 +501,62 @@ class NeighborhoodEngine<defaultDense, FPType, cpu>
         }
     
         services::Status queryFull(Neighborhood<FPType, cpu> * neighs, bool doReset = false)
    +    {
    +        switch (_metric)
    +        {
    +        case PairwiseDistanceType::euclidean:

    done

    Alexandr-Solovev Alexandr-Solovev commented on code on Nov 02, 2026 08:13 UTC
    Code Review
    cpp/oneapi/dal/algo/dbscan/common.hpp:1
    @@ -22,6 +22,26 @@
     
     namespace oneapi::dal::dbscan {
     
    +namespace v1 {
    +
    +/// Distance metric used for the epsilon-neighborhood search in DBSCAN.
    +enum class distance_metric {

    KNN takes the distance as a template because it is a whole separate algorithm (minkowski_distance::descriptor) with its own kernels. In DBSCAN the metric only picks a small distance functor inside one kernel, with degree as the only extra parameter. A runtime enum is simpler here: it matches sklearn's metric= argument, the HDBSCAN descriptor, and the DAAL kernel, which already switches at runtime.

    I agree one shared enum is better. I can't do it in this PR, though: HDBSCAN's distance_metric is already part of the public ABI since 2026.2.0, can be changed in major release.

    Alexandr-Solovev Alexandr-Solovev commented on code on Nov 02, 2026 08:13 UTC
    Code Review
    cpp/daal/src/algorithms/dbscan/dbscan_utils.h:1
    @@ -431,6 +501,62 @@ class NeighborhoodEngine<defaultDense, FPType, cpu>
         }
     
         services::Status queryFull(Neighborhood<FPType, cpu> * neighs, bool doReset = false)
    +    {
    +        switch (_metric)
    +        {
    +        case PairwiseDistanceType::euclidean:
    +        {
    +            EuclideanDistances<FPType, cpu> metric(*_inTable, *_outTable);
    +            return queryFullImpl(metric, neighs, doReset);
    +        }
    +        case PairwiseDistanceType::manhattan:
    +        {
    +            MinkowskiDistances<FPType, cpu> metric(*_inTable, *_outTable, true, 1.0);
    +            return queryFullImpl(metric, neighs, doReset);
    +        }
    +        case PairwiseDistanceType::minkowski:
    +        {
    +            MinkowskiDistances<FPType, cpu> metric(*_inTable, *_outTable, true, (double)_p);
    +            return queryFullImpl(metric, neighs, doReset);
    +        }
    +        case PairwiseDistanceType::chebyshev:
    +        {
    +            ChebyshevDistances<FPType, cpu> metric(*_inTable, *_outTable);
    +            return queryFullImpl(metric, neighs, doReset);
    +        }
    +        case PairwiseDistanceType::cosine:
    +        {
    +            ZeroRowCosineDistances<FPType, cpu> metric(*_inTable, *_outTable);
    +            return queryFullImpl(metric, neighs, doReset);
    +        }
    +        }
    +
    +        return services::Status(services::ErrorMethodNotSupported);
    +    }
    +
    +    services::Status query(size_t * indices, size_t n, Neighborhood<FPType, cpu> * neighs, bool doReset = false)
    +    {
    +        // Each distance is in the same form as the matching `queryFull` engine, so both paths share `poweredEpsilon`.
    +        const hdbscan::internal::MinkowskiDist<FPType> minkowski(_p);
    +        switch (_metric)
    +        {
    +        case PairwiseDistanceType::euclidean: return queryImpl(distancePow2<FPType, cpu>, indices, n, neighs, doReset);
    +        case PairwiseDistanceType::manhattan:
    +            return queryImpl(hdbscan::internal::ManhattanDist<FPType>::template pointDist<cpu>, indices, n, neighs, doReset);
    +        case PairwiseDistanceType::minkowski:
    +            return queryImpl([&](const FPType * a, const FPType * b, size_t dim) { return minkowski.template poweredPointDist<cpu>(a, b, dim); },
    +                             indices, n, neighs, doReset);
    +        case PairwiseDistanceType::chebyshev:
    +            return queryImpl(hdbscan::internal::ChebyshevDist<FPType>::template pointDist<cpu>, indices, n, neighs, doReset);
    +        case PairwiseDistanceType::cosine: return queryImpl(cosinePointDist<FPType, cpu>, indices, n, neighs, doReset);

    Fixed

    Alexandr-Solovev Alexandr-Solovev commented on code on Nov 02, 2026 08:14 UTC
    Code Review
    cpp/daal/src/algorithms/dbscan/dbscan_utils.h:1
    @@ -390,11 +391,79 @@ struct NTask
         daal::tls<TlsNTask<FPType, cpu> *> * tlsNTask;
     };
     
    +/// Maps `eps` to the space the distances are compared in: squared for Euclidean, raised to `p`
    +/// for Minkowski, unchanged for the metrics that take no root.
    +///
    +/// @param[in] metric Distance metric
    +/// @param[in] eps    Neighborhood radius in the units of `metric`
    +/// @param[in] p      Minkowski degree; ignored by the other metrics
    +/// @return The threshold the unrooted distances are compared against
    +template <typename FPType, CpuType cpu>
    +inline FPType poweredEpsilon(PairwiseDistanceType metric, FPType eps, FPType p)
    +{
    +    switch (metric)
    +    {
    +    case PairwiseDistanceType::euclidean: return eps * eps;
    +    case PairwiseDistanceType::minkowski: return MathInst<FPType, cpu>::sPowx(eps, p);
    +    default: return eps;
    +    }
    +}
    +
    +/// Cosine distance of two rows for the memory-saving search; a zero row is at distance 1 from
    +/// every other row, as in scikit-learn.
    +template <typename FPType, CpuType cpu>
    +FPType cosinePointDist(const FPType * a, const FPType * b, size_t dim)
    +{
    +    FPType dot = FPType(0);
    +    FPType aa  = FPType(0);
    +    FPType bb  = FPType(0);
    +    PRAGMA_OMP_SIMD_ARGS(reduction(+ : dot, aa, bb))
    +    for (size_t i = 0; i < dim; ++i)
    +    {
    +        dot += a[i] * b[i];
    +        aa += a[i] * a[i];
    +        bb += b[i] * b[i];
    +    }
    +    const FPType norm = MathInst<FPType, cpu>::sSqrt(aa) * MathInst<FPType, cpu>::sSqrt(bb);
    +    return (norm > FPType(0)) ? FPType(1) - dot / norm : FPType(1);
    +}
    +
    +/// `CosineDistances` with scikit-learn's value for zero rows: distance 1 from every other row.
    +template <typename FPType, CpuType cpu>
    +class ZeroRowCosineDistances : public CosineDistances<FPType, cpu>
    +{
    +    using super = CosineDistances<FPType, cpu>;
    +
    +public:
    +    ZeroRowCosineDistances(const NumericTable & a, const NumericTable & b) : super(a, b) {}
    +
    +    services::Status computeBatch(const FPType * const a, const FPType * const b, size_t aOffset, size_t aSize, size_t bOffset, size_t bSize,
    +                                  FPType * const res) override
    +    {
    +        services::Status s = super::computeBatch(a, b, aOffset, aSize, bOffset, bSize, res);
    +        // `init` stores the row norms, so a zero norm marks a zero row.
    +        const FPType * const aNorms = this->normBufferA.get() + aOffset;
    +        const FPType * const bNorms = (&this->_a == &this->_b) ? this->normBufferA.get() + bOffset : this->normBufferB.get() + bOffset;
    +        for (size_t i = 0; i < aSize; i++)
    +        {
    +            if (aNorms[i] != FPType(0)) continue;

    No tolerance on purpose: a norm is exactly zero only when the row has no direction at all. Any row with a non-zero norm has a valid cosine, so a tolerance would just drop good rows

    Alexandr-Solovev Alexandr-Solovev commented on Nov 02, 2026 08:15 UTC
    Author

    /intelci: run

    Vika-F Vika-F commented on code on Nov 02, 2026 10:46 UTC
    Code Review
    cpp/daal/src/algorithms/dbscan/dbscan_utils.h:1
    @@ -431,6 +451,40 @@ class NeighborhoodEngine<defaultDense, FPType, cpu>
         }
     
         services::Status queryFull(Neighborhood<FPType, cpu> * neighs, bool doReset = false)
    +    {
    +        services::SharedPtr<PairwiseDistances<FPType, cpu> > metric(createPairwiseDistances<FPType, cpu>(*_inTable, *_outTable, _metric, (double)_p));
    +        DAAL_CHECK_MALLOC(metric.get());
    +        return queryFullImpl(*metric, neighs, doReset);
    +    }
    +
    +    services::Status query(size_t * indices, size_t n, Neighborhood<FPType, cpu> * neighs, bool doReset = false)
    +    {
    +        // Each distance is in the same form as the matching `queryFull` engine, so both paths share `poweredEpsilon`.
    +        switch (_metric)

    In my understanding his switch could be also replaced with something like:

    services::SharedPtr<PairwiseDistances<FPType, cpu> > metric(createPairwiseDistances<FPType, cpu>(*_inTable, *_outTable, _metric, (double)_p));
    DAAL_CHECK_MALLOC(metric.get());
    return queryImpl([&](const FPType * a, const FPType * b, size_t dim) { return metric.computeDistance(a, b, dim); }, indices, n, neighs, doReset);
    

    Vika-F Vika-F commented on code on Nov 02, 2026 12:29 UTC
    Code Review
    cpp/daal/src/algorithms/dbscan/dbscan_utils.h:1
    @@ -431,6 +451,40 @@ class NeighborhoodEngine<defaultDense, FPType, cpu>
         }
     
         services::Status queryFull(Neighborhood<FPType, cpu> * neighs, bool doReset = false)
    +    {
    +        services::SharedPtr<PairwiseDistances<FPType, cpu> > metric(createPairwiseDistances<FPType, cpu>(*_inTable, *_outTable, _metric, (double)_p));
    +        DAAL_CHECK_MALLOC(metric.get());
    +        return queryFullImpl(*metric, neighs, doReset);
    +    }
    +
    +    services::Status query(size_t * indices, size_t n, Neighborhood<FPType, cpu> * neighs, bool doReset = false)
    +    {
    +        // Each distance is in the same form as the matching `queryFull` engine, so both paths share `poweredEpsilon`.
    +        switch (_metric)
    +        {
    +        case PairwiseDistanceType::euclidean: return queryImpl(distancePow2<FPType, cpu>, indices, n, neighs, doReset);
    +        case PairwiseDistanceType::manhattan:
    +        case PairwiseDistanceType::minkowski:
    +        {
    +            const double p = (_metric == PairwiseDistanceType::manhattan) ? 1.0 : (double)_p;
    +            const MinkowskiDistances<FPType, cpu> metric(*_inTable, *_outTable, true, p);
    +            return queryImpl([&](const FPType * a, const FPType * b, size_t dim) { return metric.computeDistance(a, b, dim); }, indices, n, neighs,
    +                             doReset);

    @Alexandr-Solovev I think coderabbitai is right here. I'd only add values for x + i vecSize and y + i vecSize in order not to calculate those multiple times.

    Alexandr-Solovev Alexandr-Solovev commented on code on Nov 02, 2026 14:35 UTC
    Code Review
    cpp/daal/src/algorithms/dbscan/dbscan_utils.h:1
    @@ -431,6 +451,40 @@ class NeighborhoodEngine<defaultDense, FPType, cpu>
         }
     
         services::Status queryFull(Neighborhood<FPType, cpu> * neighs, bool doReset = false)
    +    {
    +        services::SharedPtr<PairwiseDistances<FPType, cpu> > metric(createPairwiseDistances<FPType, cpu>(*_inTable, *_outTable, _metric, (double)_p));
    +        DAAL_CHECK_MALLOC(metric.get());
    +        return queryFullImpl(*metric, neighs, doReset);
    +    }
    +
    +    services::Status query(size_t * indices, size_t n, Neighborhood<FPType, cpu> * neighs, bool doReset = false)
    +    {
    +        // Each distance is in the same form as the matching `queryFull` engine, so both paths share `poweredEpsilon`.
    +        switch (_metric)

    Done in 104d229f1: PairwiseDistances now has a virtual computeDistance for one pair of rows, so query builds its engine with createPairwiseDistances exactly like queryFull. The batch loops of MinkowskiDistances and ChebyshevDistances call it by qualified name, so they keep inlining it.

    Alexandr-Solovev Alexandr-Solovev commented on code on Nov 02, 2026 14:35 UTC
    Code Review
    cpp/daal/src/algorithms/dbscan/dbscan_utils.h:1
    @@ -431,6 +451,40 @@ class NeighborhoodEngine<defaultDense, FPType, cpu>
         }
     
         services::Status queryFull(Neighborhood<FPType, cpu> * neighs, bool doReset = false)
    +    {
    +        services::SharedPtr<PairwiseDistances<FPType, cpu> > metric(createPairwiseDistances<FPType, cpu>(*_inTable, *_outTable, _metric, (double)_p));
    +        DAAL_CHECK_MALLOC(metric.get());
    +        return queryFullImpl(*metric, neighs, doReset);
    +    }
    +
    +    services::Status query(size_t * indices, size_t n, Neighborhood<FPType, cpu> * neighs, bool doReset = false)
    +    {
    +        // Each distance is in the same form as the matching `queryFull` engine, so both paths share `poweredEpsilon`.
    +        switch (_metric)
    +        {
    +        case PairwiseDistanceType::euclidean: return queryImpl(distancePow2<FPType, cpu>, indices, n, neighs, doReset);
    +        case PairwiseDistanceType::manhattan:
    +        case PairwiseDistanceType::minkowski:
    +        {
    +            const double p = (_metric == PairwiseDistanceType::manhattan) ? 1.0 : (double)_p;
    +            const MinkowskiDistances<FPType, cpu> metric(*_inTable, *_outTable, true, p);
    +            return queryImpl([&](const FPType * a, const FPType * b, size_t dim) { return metric.computeDistance(a, b, dim); }, indices, n, neighs,
    +                             doReset);

    Done in 104d229f1: both specializations use _mm512_loadu_ps/_mm512_loadu_pd with the row pointers hoisted into xi/yi.

    Alexandr-Solovev Alexandr-Solovev commented on Nov 02, 2026 14:35 UTC
    Author

    @Vika-F thanks for the review. Both remaining inline items are in 104d229f1; //cpp/oneapi/dal/algo/{dbscan,hdbscan,knn}:tests pass on host with all ISAs compiled.

    On the duplicated enum: agreed, and I would like to converge on one oneapi::dal::distance_metric. hdbscan::distance_metric shipped in 2026.2.0, so turning it into an alias of a shared enum changes the mangled name of set_metric_impl and is an ABI break, which has to wait for 2027.0. That is a follow-up: a shared enum with deprecated aliases in both algorithms. DBSCAN's values and order here are identical to HDBSCAN's so that switch stays mechanical.

    On DAAL vs oneDAL: the public DAAL dbscan::Parameter is intentionally unchanged, so DAAL users keep the same API and defaults. The metric only travels from the oneAPI descriptor into the internal kernel, the way HDBSCAN works without any DAAL interface at all. I agree that retiring the DAAL API for algorithms with a oneDAL counterpart is the right direction; that is a deprecation discussion of its own, so I would keep it out of this PR.

    coderabbitai[bot] coderabbitai[bot] commented on code on Nov 02, 2026 14:36 UTC
    Code Review
    cpp/daal/src/algorithms/dbscan/dbscan_utils.h:1
    @@ -431,6 +451,40 @@ class NeighborhoodEngine<defaultDense, FPType, cpu>
         }
     
         services::Status queryFull(Neighborhood<FPType, cpu> * neighs, bool doReset = false)
    +    {
    +        services::SharedPtr<PairwiseDistances<FPType, cpu> > metric(createPairwiseDistances<FPType, cpu>(*_inTable, *_outTable, _metric, (double)_p));
    +        DAAL_CHECK_MALLOC(metric.get());
    +        return queryFullImpl(*metric, neighs, doReset);
    +    }
    +
    +    services::Status query(size_t * indices, size_t n, Neighborhood<FPType, cpu> * neighs, bool doReset = false)
    +    {
    +        // Each distance is in the same form as the matching `queryFull` engine, so both paths share `poweredEpsilon`.
    +        switch (_metric)
    +        {
    +        case PairwiseDistanceType::euclidean: return queryImpl(distancePow2<FPType, cpu>, indices, n, neighs, doReset);
    +        case PairwiseDistanceType::manhattan:
    +        case PairwiseDistanceType::minkowski:
    +        {
    +            const double p = (_metric == PairwiseDistanceType::manhattan) ? 1.0 : (double)_p;
    +            const MinkowskiDistances<FPType, cpu> metric(*_inTable, *_outTable, true, p);
    +            return queryImpl([&](const FPType * a, const FPType * b, size_t dim) { return metric.computeDistance(a, b, dim); }, indices, n, neighs,
    +                             doReset);

    <!-- coderabbit-ai-generated:v1 -->

    Seems like the humans are having a chat. I'll hop back into my burrow for now. If you need me again, just tag @coderabbitai in a new comment, and I'll come hopping out!

    <!-- This is an auto-generated mute comment by CodeRabbit -->

    Alexandr-Solovev Alexandr-Solovev commented on Nov 03, 2026 09:11 UTC
    Author

    /intelci: run

    Vika-F Vika-F commented on code on Nov 03, 2026 11:03 UTC
    Code Review
    cpp/daal/src/algorithms/service_kernel_math.h:1
    @@ -464,6 +473,13 @@ class CosineDistances : public EuclideanDistances<FPType, cpu>
     
         services::Status finalize(const size_t n, FPType * a) override { return services::Status(); }
     
    +    FPType computeDistance(const FPType * x, const FPType * y, const size_t n) const override
    +    {
    +        FPType dot, norm;
    +        dotAndNorm(x, y, n, dot, norm);
    +        return FPType(1) - dot / norm;

    Should there be a zero check?

            return (norm > FPType(0)) ? FPType(1) - dot / norm : FPType(1);
    

    Vika-F Vika-F commented on code on Nov 03, 2026 11:06 UTC
    Code Review
    cpp/daal/src/algorithms/service_kernel_math.h:1
    @@ -491,6 +507,63 @@ class CosineDistances : public EuclideanDistances<FPType, cpu>
             }
             return services::Status();
         }
    +
    +protected:
    +    /// `dot` is x.y and `norm` is |x||y|.
    +    static void dotAndNorm(const FPType * x, const FPType * y, const size_t n, FPType & dot, FPType & norm)
    +    {
    +        FPType xy = FPType(0);
    +        FPType xx = FPType(0);
    +        FPType yy = FPType(0);
    +        PRAGMA_OMP_SIMD_ARGS(reduction(+ : xy, xx, yy))
    +        for (size_t i = 0; i < n; ++i)
    +        {
    +            xy += x[i] * y[i];
    +            xx += x[i] * x[i];
    +            yy += y[i] * y[i];
    +        }
    +        dot  = xy;
    +        norm = MathInst<FPType, cpu>::sSqrt(xx) * MathInst<FPType, cpu>::sSqrt(yy);

            norm = MathInst<FPType, cpu>::sSqrt(xx * yy);
    

    Alexandr-Solovev Alexandr-Solovev commented on Nov 03, 2026 14:27 UTC
    Author

    /intelci: run

    Alexandr-Solovev Alexandr-Solovev commented on Nov 03, 2026 15:21 UTC
    Author

    /intelci: run

    Alexandr-Solovev Alexandr-Solovev commented on Nov 03, 2026 18:53 UTC
    Author

    /intelci: run

    Alexandr-Solovev Alexandr-Solovev commented on Nov 04, 2026 06:14 UTC
    Author

    /intelci: run

    Assignees
    Alexandr-Solovev Alexandr-Solovev
    Labels
    risk: low confidence: 83.7% reviewed
    Vouch Risk Breakdown
    AI-powered review risk analysis
    Change Risk
    Change Risk · Model 1 (XGBoost)
    Predicted defect probability (0.00–1.00) based on diff churn, modified sensitive files, and author risk history.
    Score: 85.5% (HIGH) · Higher = larger blast radius
    85.5%
    Review Confidence
    Review Confidence · Models 2 & 3
    Scrutiny score (0.00–1.00) combining DistilBERT semantic review depth with reviewer familiarity and session dwell time.
    Score: 83.7% · Lower = rushed or shallow review
    83.7%
    Residual Risk
    Residual Risk · Core Equation
    Residual = Change × (1 − Confidence)
    Unmitigated risk surviving review. ≥ 0.65 triggers an automated re-queue to protect production.
    Score: 14.0% · Safe to merge
    14.0%