← Back to Pull requests

[bug] Avoid virtual freeDataMemoryImpl calls from CSRNumericTable constructors and destructor #3769

Closed
unknown closed this pull request without merging on Sep 03, 2026 21:04 UTC
View on GitHub
unknown unknown commented on Sep 01, 2026 03:28 UTC
Author

Description

CSRNumericTable makes a virtual call from constructor and destructor bodies, and GCC 13 mis-analyzes it once the call chain is inlined, silently deleting the rest of the construction. Result is wrong data, std::invalid_argument from unrelated code, or a segfault — depending on optimization flags.

This surfaced as recurrent, flaky-looking segfaults in the oneDAL LinuxSklearnex Azure job (definition-7, main), in daal4py examples (bf_knn_classification, tsne, covariance, ridge_regression). The trigger turned out to be environmental, not a oneDAL code change: a Python interpreter package rebuild changed the extension build flags from -O2 to -O3 -flto, and daal4py's extension inherits CFLAGS from the interpreter's sysconfig.

The bug

CSRNumericTable's constructors call setArrays() from their bodies, and both setArrays overloads begin with a virtual freeDataMemoryImpl() call. The destructor calls it directly.

CSRNumericTable(const services::SharedPtr<DataType> & ptr, ..., size_t nColumns, size_t nRows,
                CSRIndexing indexing, services::Status & st)
    : NumericTable(nColumns, nRows, DictionaryIface::equal, st), _indexing(indexing)
{
    _layout = csrArray;
    st |= setArrays<DataType>(ptr, colIndices, rowOffsets);   // -> virtual freeDataMemoryImpl()
    ...
}

Four constructors reach setArrays this way (lines 677, 701, 713, 734), covering both overloads.

This is legal C++: per [class.cdtor]/4, inside the derived constructor body the dynamic type is CSRNumericTable, so freeDataMemoryImpl() resolves to CSRNumericTable::freeDataMemoryImpl. But with -O3 -flto GCC 13.3 inlines create<T> → new CSRNumericTable(...) → setArrays all into one caller, and then gets the dynamic-type analysis wrong. GCC's own -fdump-tree-fre-details output:

Determining dynamic type for call: OBJ_TYPE_REF(_4108;(struct CSRNumericTable)_4090->26B) (_4090);
  instance pointer: _4090  offset: 0 (bits)
  Checking constructor call: __ct_base (_4098, c_nc_862, c_nr_866, 1, &defaultSt);
  Recording type: struct NumericTable at offset 0
  Determined dynamic type.
  Targets of polymorphic call of type 2103:struct CSRNumericTable token 26
    Outer type (dynamic):struct NumericTable offset 0
    This is a complete list.
      <empty>
optimized: converting indirect call to function __builtin_unreachable

Step by step:

1. GCC loads vtable slot 26 from _ZTVN4daal15data_management10interface115CSRNumericTableE + 224B. Slot 26 resolves to CSRNumericTable::freeDataMemoryImpl() (confirmed from libonedal_core relocations).
2. Walking back from the polymorphic call, GCC finds the nearest constructor invocation — the inlined base NumericTable::NumericTable(...) — and records the dynamic type as NumericTable.
3. It looks up a CSRNumericTable token-26 call on a NumericTable object, gets an empty target list, and marks it "complete".
4. A polymorphic call with a provably empty target set is unreachable, so GCC replaces it with __builtin_unreachable().
5. At -O3 that is not a trap. setArrays and the remainder of the construction are deleted: _ptr, _colIndices and _rowOffsets are never assigned, and control falls into adjacent code with the row count still live in a register.

Step 2 is the error — NumericTable is the dynamic type only during the base constructor, and the call happens after it returns and after the derived vptr store. GCC had the correct CSRNumericTable vtable slot in hand and overrode it with the base-constructor inference. So this is a GCC 13 miscompilation, not UB in oneDAL. It is being reported upstream separately; this PR removes oneDAL's exposure to it.

The fix

Keep the constructor bodies free of virtual calls, rather than devirtualizing setArrays().

The assignment part of setArrays() is split out into a non-virtual, protected setArraysImpl(), and the four constructors call that directly. They have nothing to release at that point — all three SharedPtr members are default-constructed and NumericTable's constructor has already set _memStatus to notAllocated — so the freeDataMemoryImpl() call they used to make through setArrays() was a no-op. Removing it is what takes the OBJ_TYPE_REF out of the constructors.

setArrays() itself keeps its unqualified, fully polymorphic freeDataMemoryImpl() call. This matters: oneapi::dal::backend::interop::host_csr_table_adapter derives from CSRNumericTable, overrides freeDataMemoryImpl(), and calls setArrays() from its own constructor body — where the dynamic type is the adapter and the virtual call legitimately resolves to the adapter's override. That dispatch is unchanged.

The destructor keeps a qualified call. Per [class.cdtor]/4 the dynamic type during ~CSRNumericTable() is already CSRNumericTable, so the unqualified call resolved to the same function; qualifying it only removes the OBJ_TYPE_REF that GCC mis-analyzes. Demonstration:

struct Base   { virtual ~Base() { freeImpl(); }
                virtual void freeImpl() { puts("  Base::freeImpl"); } };
struct Derived: Base { void freeImpl() override { Base::freeImpl(); puts("  Derived::freeImpl"); } };
Base* p = new Derived; delete p;      // prints only "Base::freeImpl"

The two calls in allocateDataMemory() are deliberately left virtual — they are not on a construction path.

No ABI change: no new virtual functions, no change to the class layout. setArraysImpl is a non-virtual member template.

Evidence

Measured in make_nt (the daal4py conversion function into which the whole chain inlines):

| build | __builtin_unreachable in make_nt | setArrays inlines |
|---|---|---|
| -O3 -flto, before this PR | 12 (one per instantiated type) | 12, all bodies deleted |
| -O3 -flto -fno-strict-aliasing | 0 | intact |
| -O3 -flto, with this PR | 0 | 12, intact |

Re-measured after the review rework (constructors calling setArraysImpl, setArrays left polymorphic): still 0 __builtin_unreachable in make_nt, and more of the construction survives than with the earlier qualified-call version — 60 CSR member stores versus 48, against 24 on unpatched main. The reproducer below passes 5/5; on unpatched -O3 -flto it fails 5/5 with ValueError: Unsupported NPY type 102. Full suite re-run at exact parity with the -O2 baseline: legacy 1736 passed, daal4py 532 passed, onedal 1693 passed, sklearnex byte-identical.

Pass bisect: 0 unreachables through fre4 (pass 176), 36 appear at fre5 (pass 194, full redundancy elimination). -fno-devirtualize or -fno-strict-aliasing also suppress it, since both disable the analysis that feeds the fold.

Flag sensitivity, before this PR — -O3 and -flto together are necessary and sufficient; -ffat-lto-objects, -flto-partition=none and -fuse-linker-plugin are irrelevant:

| extension build flags | daal4py examples suite |
|---|---|
| -O2 | pass |
| -O3 | pass |
| -O2 -flto | pass |
| -O3 -flto | 4 failures, then SIGSEGV |
| -O3 -flto -ffat-lto-objects | 30 failures, then SIGSEGV |
| -O3 -flto -flto-partition=none | SIGSEGV |

clang 18 full-LTO at -O3 is unaffected. Building the extension under ASAN masks the problem entirely (instrumentation perturbs inlining so the pattern never forms), which is why earlier sanitizer runs came back clean.

Validation

Built daal4py/sklearnex against a patched oneDAL header, GCC 13.3, oneDAL 2026.2.0 host build, Python 3.12.

With the fix, the daal4py examples suite passes under every previously-failing flag set:

-O3 -flto                        115 passed, 23 skipped, 0 failures
-O3 -flto -flto-partition=none   115 passed, 23 skipped, 0 failures
-O3 -flto -ffat-lto-objects      115 passed, 23 skipped, 0 failures   (was 30 failures + SIGSEGV)

Full sklearnex CI suite under the -O3 -flto flag set, with the fix, versus the -O2 baseline:

| suite | with fix | -O2 baseline |
|---|---|---|
| legacy | 1736 passed, 885 skipped, 1 xfailed | 1736 passed |
| daal4py | 532 passed, 32 skipped | 532 passed |
| onedal | 1693 passed, 130 skipped | 1693 passed |
| sklearnex | 252 failed, 8381 passed, 2573 errors | identical |

Exact parity, no segfault. The sklearnex numbers are pre-existing environment noise (sklearn 1.9.0 / numpy 2.5.2 / pandas 3.0.5 against that branch, no DPC) and are byte-identical across every flag variant including plain -O2.

On whether this is inside random variation — it isn't; the reproducer is deterministic in a fresh process, 50 consecutive runs per build:

| extension build flags | unpatched main | with this PR |
|---|---|---|
| -O3 -flto | 0 pass / 50 ValueError: Unsupported NPY type 102 | 50 pass / 50 |
| -O3 -flto -flto-partition=none | 0 pass / 50 SIGSEGV | 50 pass / 50 |

No run in either direction crossed over. The primary discriminator is not a pass rate at all, though: -fdump-tree-optimized either contains the __builtin_unreachable that replaced the call or it doesn't, and that is a static property of the build.

A single test reproduces it deterministically in a fresh process, no accumulated state needed:

pytest tests/test_daal4py_examples.py::TestExCSRMatrix::test_bf_knn_classification

Follow-ups (not in this PR)

Memory leaks are a separate defect. @david-cortes-intel reports leaks in the CSR cases under clang and ICX as well. Neither compiler ever miscompiled this pattern in my measurements — clang 18 full-LTO at -O3 passes the reproducer on unpatched main — so those leaks cannot be this fold, and this PR is not expected to fix them. Worth a separate issue; happy to dig into it with the ASAN report.

The same pattern — constructor body calling setArray(s), which calls virtual freeDataMemoryImpl() — also exists in homogen_numeric_table.h (6 call sites), soa_numeric_table.h (1) and aos_numeric_table.h (2). GCC did not fold those in the cases measured here, so I have not touched them; applying the same setArraysImpl split would be cheap and is worth a separate PR. All the misbehaviour observed in this suite, including the crashes in the dense-path examples, traced to the CSR path alone — those were downstream corruption from CSR tests running earlier in the same process.

---

<details>
<summary>Checklist:</summary>

Completeness and readability

  • I have commented my code, particularly in hard-to-understand areas.

  • I have updated the documentation to reflect the changes or created a separate PR with updates and provided its number in the description, if necessary. — no doc change, public behaviour is unchanged.

  • Git commit message contains an appropriate signed-off-by string.

  • I have resolved any merge conflicts that might occur with the base branch.
  • Testing

  • I have run it locally and tested the changes extensively. — see Validation above.

  • All CI jobs are green or I have provided justification why they aren't. — public CI is green; the internal Pre-Commit error is unrelated to this change (confirmed in review).

  • I have extended testing suite if new functionality was introduced in this PR. — no new functionality; the existing LinuxSklearnex job is the regression test and was failing on main before this change.
  • Performance

  • I have measured performance for affected algorithms using scikit-learn_bench and provided at least a summary table with measured data, if performance change is expected. — no performance change expected.

  • I have provided justification why performance and/or quality metrics have changed or why changes are not expected. — the change replaces three virtual calls with direct calls to the same function in a non-hot construction path. If anything it removes indirect calls; it cannot slow anything down.

  • I have extended the benchmarking suite and provided a corresponding scikit-learn_bench PR if new measurable functionality was introduced in this PR. — not applicable.
  • </details>

    Diff: 650 lines (+487 / -163) across 8 files Reviewer: Vika-F Review duration: 3936m
    All Vouch review confidence checks passed
    Residual risk 0.22 = Change Risk (0.52) × (1 − Review Confidence (0.57)). Review depth and reviewer attention state are adequate.
    Model 1 · Change Risk (XGBoost)
    Score: 0.52 · 650 lines diff across 8 files
    0.52
    Model 2 · Review Depth (DistilBERT)
    Depth Score: 0.17 · 1 substantive comment(s)
    0.17
    Model 3 · Review Timing & Attention
    Session adequacy: 100% · Reviewer familiarity: 35%
    56%
    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.388
    Shallow Review Depth shallow_review_depth
    0.289
    Real PR Conversation Timeline
    1 comments
    "Review active on #3769"
    general weight: 0.35
    Reviewers
    Assignees
    Unassigned
    Labels
    risk: low confidence: 56.8% 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: 52% (MEDIUM) · Higher = larger blast radius
    52%
    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: 56.8% · Lower = rushed or shallow review
    56.8%
    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: 22.5% · Safe to merge
    22.5%