Skip to content

Testing functionality to catch thread-safety issues, and a fix for one problem it finds - #34057

Draft
itamarst wants to merge 8 commits into
scikit-learn:mainfrom
itamarst:thread-safety-part-1
Draft

itamarst wants to merge 8 commits into
scikit-learn:mainfrom
itamarst:thread-safety-part-1

Conversation

@itamarst

Copy link
Copy Markdown
Contributor

Background

I am working for Quansight on a contract to improve free-threading/threading support in Scikit-Learn.

To ensure thread-safety, it's useful to have test infrastructure that will provide:

  • A way to identify thread-safety issues in code that has previously mostly been run in process pools. Free-threading's lack of GIL makes thread safety issues more likely than in the past.
  • A way to prevent future changes to the code introducing new thread-safety problems.

A good starting point here is focusing on operations that are already parallel, where users might reasonably expect to be able to turn threading on as a joblib backend and have it Just Work. These operations also work in a very particular way: create some tasks, run them in a worker pool, get back the results of the tasks.

What can go wrong in this particular idiom? Switching from a process pool to a thread pool introduces thread-safety issues with the inputs to a Parallel() operation: whereas mutating in a process is fine, mutating in a thread can affect other threads, or future interactions with the object in the main thread.

This suggests a starting point for a invariant to be using in testing: the inputs to a Parallel() operation that can correctly run with both process and thread pools should not change when the function is run.

Note: pytest-run-parallel won't catch these sort of problems, as the problem here is not with shared global state, but with shared temporary and/or internal state.

What this PR does

When pytest is run with a new --thread-safety-testing flag:

  1. Parallel() switches to running using a thread pool.
  2. Arguments passed to functions called in parallel are tracked to see if they changed as part of execution. "Change" is calculated heuristically, with a hash.

This testing mechanism causes many tests to fail, suggesting objects are being mutated in the thread pool. At least in some cases this would suggest data races.

To demonstrate one of the (potential) problems it identifies, I fixed a real problem it identified: in BinaryTree/KDTree, certain C-level attributes were being modified in a non-thread-safe way. In normal Python with a GIL this was maybe safe, depending where the GIL was released. In free-threaded code this is definitely not safe.

In practice these attributes weren't actually used by sklearn, so this wouldn't have impacted users, and removing them altogether seemed the easiest way to solve the problem.

In the short term I will keep going through the identified problems to see if there are any that impact real-world usage. But even if most of the currently found issues are minor, the real value will be having this run in CI in the future, because it will catch many thread-safety regressions before they get merged, as thread pools become more common.

Next steps

I am opening this PR as a draft for discussion purposes. If this approach is acceptable, future steps (in this PR, or more likely spread across multiple PRs) would likely include:

  • Add tests for _parallel_testing.py.
  • Add a CI job that runs with these tests, likely configured with a ratchet so you get green checkmarks so long as changes haven't made the situation worse.
  • Fixing the other (likely) problems this testing approach identifies.
  • Add more edge cases to the hash change detection to catch more problems.

Reference Issues/PRs

None for now.

AI usage disclosure

I did not use "AI" assistance.

Any other comments?

@itamarst itamarst changed the title Testing functionality to catch thread-safety issues, and a fix for one problems it finds Testing functionality to catch thread-safety issues, and a fix for one problem it finds May 19, 2026
@itamarst

itamarst commented May 19, 2026 •

Copy link
Copy Markdown
Contributor Author

As another example of problems identified by this testing mechanism:

seems to be a source of threads mutating a shared object (self, via the context callbacks?).

$ pytest --thread-safety-testing -x sklearn/tests/test_common.py -k GridSearchCV
...
E               AssertionError: Hash for object of type <class 'sklearn.model_selection._search.GridSearchCV'> has
 changed, suggesting potential thread unsafety. Start by checking attributes:
 ['estimator', '_callback_fit_ctx', '_checked_cv_orig']

I need to understand the code significantly better to have a sense of what's going on or how to fix it (naive clone(self) fixes this but breaks code elsewhere), but this plausibly seems like a thread-safety issue worth fixing.

@virchan

virchan commented May 20, 2026

Copy link
Copy Markdown
Member

Thank you for the PR, @itamarst, and for helping improve scikit-learn.

I am opening this PR as a draft for discussion purposes.

Could you please open an issue first? That would be a better place to explain the proposal and discuss the overall scope with the maintainers before continuing further with the implementation.

If possible, including a minimal reproducible example demonstrating the thread-safety issue(s) this proposal aims to address would also be very helpful.

@betatim

betatim commented May 20, 2026

Copy link
Copy Markdown
Member

Figuring out ways to convince ourselves and our users that you can safely use scikit-learn with free threading is important (and hard work!).

My immediate thoughts (besides excitement that someone is excited to tackle this):

  • what Virgil said. In particular as the discussion will outlive any PRs
  • is there a way to do this without needing yet another argument to pass to pytest? I think there is huge value to having only one way to launching "all the tests": pytest. If you want to run less tests or only a specific kind you can learn about CLI arguments to do so. The reason for this preference is that I work on projects that have different ways of launching different tests, and I can never remember which one works where and how to do it. I can remember pytest sklearn/tests/test_free_threading.py (say) as the way to run all the free-threading related tests. And they get run automatically when you just run pytest. Another reason is that I think these tests will "stay with us forever" - at least some version of them will have to be run for as long as there is free-threading support to make sure there are no regressions.
  • Olivier (@ ogrisel) did a bunch of work related to using pytest-parallel, which as you mention is different, but it might still be interesting to look at and see what general discoveries about "free-threading support in scikit-learn" were made in those PRs and issues.

@ogrisel ogrisel added the free-threading PRs and issues related to support for free-threaded CPython (a.k.a. nogil or no-GIL, PEP 703) label May 20, 2026
@jeremiedbb

Copy link
Copy Markdown
Member

Thanks for working on this @itamarst !
As others said I also think that opening an issue to discuss the different aspects of free-threading would be good.

Note: pytest-run-parallel won't catch these sort of problems, as the problem here is not with shared global state, but with shared temporary and/or internal state.

recently I noticed that the free-threading CI job frequently fails. I've fixed a few tests but it seems there are more. I think a good first step would be to make sure the test suite itself is thread safe.

In practice these attributes weren't actually used by sklearn, so this wouldn't have impacted users, and removing them altogether seemed the easiest way to solve the problem.

Well it's not that simple. These are public methods (https://scikit-learn.org/stable/modules/generated/sklearn.neighbors.BallTree.html#sklearn.neighbors.BallTree.get_tree_stats). Removing them would need to go through a deprecation cycle. There was an earlier attempt (#19884) that didn't go through (it was also related with possible performance issues with these fields).

seems to be a source of threads mutating a shared object (self, via the context callbacks?).

I believe this is expected. The estimator holds a attribute that has a tree structure, which grows during fit. different threads modify the tree but involve different nodes. It would be interesting to check that all operations there are thread safe in free-threading python.
Maybe the hash solution will trigger to many false positives ? I believe that it's fine and expected if different threads modify a shared object as long as we avoid race conditions (or add locks if necessary).

@ogrisel

ogrisel commented May 20, 2026 •

Copy link
Copy Markdown
Member

Thanks, @itamarst. That's an interesting way to detect this class of problems but as @jeremiedbb said above it can be subject to false positives: harmless (non-conflicting) mutations of the input arguments that are used as temporary datastructures by the parallel function.

That being said, maybe the mutation of input arguments of a parallel function is a bad code pattern, and we should refactor our code to avoid them to make it easier to maintain this code in the future. But we need a clearer understanding the various tradeoffs that would entail in terms of code complexity and computational overhead.

I ran the tests suite with the new pytest flag introduced in this branch and I confirm there are hundreds of tests failures but I suspect many are duplicates of the same candidate bug. I asked an agent to post process it to deduplicate root causes:

Test report
# Deduplicated Hash-Mismatch AssertionError Report

Source log: `pytest.log`

## Summary

- Total hash-mismatch failure blocks: 110
- Unique call-site + message pairs: 57
- Unique full exception messages: 23

## Deduplicated Failures

### 1. Exception Message

`AssertionError: Hash for object of type <class 'numpy.ndarray'> has changed, suggesting potential thread unsafety. Start by checking attributes: []`

Calls:

- [1x] Location: `sklearn/metrics/tests/test_pairwise.py:892` | Source: `D_parallel = pairwise_distances(`
- [13x] Location: `sklearn/metrics/tests/test_pairwise.py:400` | Source: `S2 = func(X, metric=metric, n_jobs=2, **kwds)`
- [3x] Location: `sklearn/metrics/tests/test_pairwise.py:875` | Source: `distances = pairwise_distances(X, metric=metric, n_jobs=2)`

### 2. Exception Message

`AssertionError: Hash for object of type <class 'numpy.random.mtrand.RandomState'> has changed, suggesting potential thread unsafety. Start by checking attributes: []`

Calls:

- [4x] Location: `sklearn/decomposition/tests/test_online_lda.py:204` | Source: `lda.fit(X)`
- [2x] Location: `sklearn/decomposition/tests/test_online_lda.py:229` | Source: `lda.partial_fit(X)`

### 3. Exception Message

`AssertionError: Hash for object of type <class 'sklearn.callback.tests._utils.MaxIterEstimator'> has changed, suggesting potential thread unsafety. Start by checking attributes: ['_skl_callbacks']`

Calls:

- [2x] Location: `sklearn/callback/tests/test_scoring_monitor.py:394` | Source: `func(`
- [2x] Location: `sklearn/callback/tests/test_callback_support.py:125` | Source: `func(estimator, n_fits, n_jobs, prefer)`

### 4. Exception Message

`AssertionError: Hash for object of type <class 'sklearn.callback.tests._utils.MetaEstimator'> has changed, suggesting potential thread unsafety. Start by checking attributes: ['estimator', '_callback_fit_ctx']`

Calls:

- [2x] Location: `sklearn/callback/tests/test_callback_context.py:340` | Source: `MetaEstimator(est, n_outer=n_outer, n_inner=n_inner, n_jobs=n_jobs).fit()`
- [5x] Location: `sklearn/callback/tests/test_scoring_monitor.py:207` | Source: `meta_est.fit(X=X, y=y)`
- [2x] Location: `sklearn/callback/tests/test_scoring_monitor.py:336` | Source: `meta_est.fit(X=X, y=y)`

### 5. Exception Message

`AssertionError: Hash for object of type <class 'sklearn.callback.tests._utils.MetaEstimator'> has changed, suggesting potential thread unsafety. Start by checking attributes: ['estimator', '_skl_callbacks', '_callback_fit_ctx', '_skl_callbacks_to_teardown']`

Calls:

- [2x] Location: `sklearn/callback/tests/test_callback_context.py:320` | Source: `).set_callbacks(callback).fit()`
- [1x] Location: `sklearn/callback/tests/test_callback_context.py:270` | Source: `meta_estimator.fit()`
- [1x] Location: `sklearn/callback/tests/test_callback_context.py:366` | Source: `meta_estimator.fit()`

### 6. Exception Message

`AssertionError: Hash for object of type <class 'sklearn.metrics._scorer._CurveScorer'> has changed, suggesting potential thread unsafety. Start by checking attributes: ['_score_func', '_metadata_request']`

Calls:

- [1x] Location: `sklearn/tests/test_metaestimators_metadata_routing.py:876` | Source: `method(X, y, **extra_method_args)`

### 7. Exception Message

`AssertionError: Hash for object of type <class 'sklearn.metrics._scorer._MultimetricScorer'> has changed, suggesting potential thread unsafety. Start by checking attributes: ['_scorers']`

Calls:

- [1x] Location: `sklearn/model_selection/tests/test_search.py:2723` | Source: `SearchCV(est, refit="accuracy", cv=2, scoring=scoring, **param_grid_search).fit(`
- [1x] Location: `sklearn/tests/test_metaestimators_metadata_routing.py:876` | Source: `method(X, y, **extra_method_args)`

### 8. Exception Message

`AssertionError: Hash for object of type <class 'sklearn.model_selection._search.GridSearchCV'> has changed, suggesting potential thread unsafety. Start by checking attributes: ['estimator', '_callback_fit_ctx', '_checked_cv_orig']`

Calls:

- [1x] Location: `sklearn/tests/test_calibration.py:1202` | Source: `calibrator.fit(*data, sample_weight=sample_weight)`
- [1x] Location: `sklearn/model_selection/tests/test_search.py:2547` | Source: `model.fit(X_train, y_train, **fit_params)`

### 9. Exception Message

`AssertionError: Hash for object of type <class 'sklearn.model_selection._search.GridSearchCV'> has changed, suggesting potential thread unsafety. Start by checking attributes: ['estimator', 'cv', 'error_score', '_callback_fit_ctx', '_checked_cv_orig']`

Calls:

- [1x] Location: `sklearn/model_selection/tests/test_search.py:1405` | Source: `estimator_repeated.fit(X_repeated, y=y_repeated, sample_weight=None)`

### 10. Exception Message

`AssertionError: Hash for object of type <class 'sklearn.model_selection._search.GridSearchCV'> has changed, suggesting potential thread unsafety. Start by checking attributes: ['estimator', 'error_score', '_callback_fit_ctx', '_checked_cv_orig']`

Calls:

- [1x] Location: `sklearn/model_selection/tests/test_search.py:1697` | Source: `GridSearchCV(p, {"classifier__foo_param": [1, 2, 3]}, cv=2).fit(X, y)`
- [1x] Location: `sklearn/model_selection/tests/test_validation.py:1901` | Source: `check_cross_val_predict_multiclass(est, X, y, method)`
- [4x] Location: `sklearn/tests/test_metaestimators.py:337` | Source: `estimator.fit(X, y)`
- [1x] Location: `sklearn/impute/tests/test_impute.py:560` | Source: `gs.fit(X, Y)`
- [1x] Location: `sklearn/feature_extraction/tests/test_text.py:931` | Source: `pred = grid_search.fit(train_data, target_train).predict(test_data)`
- [1x] Location: `sklearn/feature_extraction/tests/test_text.py:968` | Source: `pred = grid_search.fit(train_data, target_train).predict(test_data)`
- [1x] Location: `sklearn/neighbors/tests/test_kde.py:150` | Source: `search.fit(X)`
- [1x] Location: `sklearn/metrics/tests/test_score_objects.py:1723` | Source: `search.fit(X, y, sample_weight=sample_weight)`

### 11. Exception Message

`AssertionError: Hash for object of type <class 'sklearn.model_selection._search.GridSearchCV'> has changed, suggesting potential thread unsafety. Start by checking attributes: ['estimator', 'error_score', '_skl_callbacks', '_callback_fit_ctx', '_skl_callbacks_to_teardown', '_checked_cv_orig']`

Calls:

- [1x] Location: `sklearn/model_selection/tests/test_search.py:3136` | Source: `search = clone(search).set_callbacks(callback).fit(X, y)`
- [2x] Location: `sklearn/model_selection/tests/test_search.py:3021` | Source: `search = clone(search).set_params(refit=refit).set_callbacks(*callbacks).fit(X, y)`
- [2x] Location: `sklearn/model_selection/tests/test_search.py:3054` | Source: `search = clone(search).set_params(refit=refit).set_callbacks(*callbacks).fit(X, y)`
- [1x] Location: `sklearn/model_selection/tests/test_search.py:3104` | Source: `search.fit(X, y, sample_weight=sample_weight)`

### 12. Exception Message

`AssertionError: Hash for object of type <class 'sklearn.model_selection._search.GridSearchCV'> has changed, suggesting potential thread unsafety. Start by checking attributes: ['estimator', 'error_score', 'param_grid', '_callback_fit_ctx', '_checked_cv_orig']`

Calls:

- [1x] Location: `sklearn/model_selection/tests/test_search.py:256` | Source: `grid_search.fit(X, y)`
- [1x] Location: `sklearn/model_selection/tests/test_search.py:2837` | Source: `grid_search.fit(X, y)`
- [1x] Location: `sklearn/model_selection/tests/test_search.py:2625` | Source: `gs = SearchCV(pipe, refit=True, cv=2, scoring="accuracy", **param_grid_search).fit(`
- [1x] Location: `sklearn/model_selection/tests/test_search.py:2681` | Source: `search_cv.fit(X, y)`

### 13. Exception Message

`AssertionError: Hash for object of type <class 'sklearn.model_selection._search.RandomizedSearchCV'> has changed, suggesting potential thread unsafety. Start by checking attributes: ['estimator', 'error_score', '_callback_fit_ctx', '_checked_cv_orig']`

Calls:

- [4x] Location: `sklearn/tests/test_metaestimators.py:337` | Source: `estimator.fit(X, y)`
- [1x] Location: `sklearn/model_selection/tests/test_search.py:2660` | Source: `random_search.fit(data_train, data_target)`

### 14. Exception Message

`AssertionError: Hash for object of type <class 'sklearn.model_selection._search.RandomizedSearchCV'> has changed, suggesting potential thread unsafety. Start by checking attributes: ['param_distributions', 'estimator', 'error_score', '_callback_fit_ctx', '_checked_cv_orig']`

Calls:

- [1x] Location: `sklearn/model_selection/tests/test_search.py:2625` | Source: `gs = SearchCV(pipe, refit=True, cv=2, scoring="accuracy", **param_grid_search).fit(`
- [1x] Location: `sklearn/model_selection/tests/test_search.py:1083` | Source: `search.fit(X, y)`

### 15. Exception Message

`AssertionError: Hash for object of type <class 'sklearn.model_selection._search.RandomizedSearchCV'> has changed, suggesting potential thread unsafety. Start by checking attributes: ['param_distributions', 'estimator', 'error_score', '_skl_callbacks', '_callback_fit_ctx', '_skl_callbacks_to_teardown', '_checked_cv_orig']`

Calls:

- [1x] Location: `sklearn/model_selection/tests/test_search.py:3136` | Source: `search = clone(search).set_callbacks(callback).fit(X, y)`
- [2x] Location: `sklearn/model_selection/tests/test_search.py:3021` | Source: `search = clone(search).set_params(refit=refit).set_callbacks(*callbacks).fit(X, y)`
- [2x] Location: `sklearn/model_selection/tests/test_search.py:3054` | Source: `search = clone(search).set_params(refit=refit).set_callbacks(*callbacks).fit(X, y)`

### 16. Exception Message

`AssertionError: Hash for object of type <class 'sklearn.model_selection._search_successive_halving.HalvingGridSearchCV'> has changed, suggesting potential thread unsafety. Start by checking attributes: ['estimator', 'error_score', '_callback_fit_ctx', '_checked_cv_orig']`

Calls:

- [4x] Location: `sklearn/tests/test_metaestimators.py:337` | Source: `estimator.fit(X, y)`

### 17. Exception Message

`AssertionError: Hash for object of type <class 'sklearn.model_selection._search_successive_halving.HalvingGridSearchCV'> has changed, suggesting potential thread unsafety. Start by checking attributes: ['estimator', 'error_score', '_skl_callbacks', '_callback_fit_ctx', '_skl_callbacks_to_teardown', '_checked_cv_orig']`

Calls:

- [1x] Location: `sklearn/model_selection/tests/test_search.py:3136` | Source: `search = clone(search).set_callbacks(callback).fit(X, y)`
- [2x] Location: `sklearn/model_selection/tests/test_search.py:3021` | Source: `search = clone(search).set_params(refit=refit).set_callbacks(*callbacks).fit(X, y)`
- [2x] Location: `sklearn/model_selection/tests/test_search.py:3054` | Source: `search = clone(search).set_params(refit=refit).set_callbacks(*callbacks).fit(X, y)`

### 18. Exception Message

`AssertionError: Hash for object of type <class 'sklearn.model_selection._search_successive_halving.HalvingGridSearchCV'> has changed, suggesting potential thread unsafety. Start by checking attributes: ['estimator', 'error_score', 'param_grid', '_callback_fit_ctx', '_checked_cv_orig']`

Calls:

- [1x] Location: `sklearn/model_selection/tests/test_search.py:2625` | Source: `gs = SearchCV(pipe, refit=True, cv=2, scoring="accuracy", **param_grid_search).fit(`

### 19. Exception Message

`AssertionError: Hash for object of type <class 'sklearn.model_selection._search_successive_halving.HalvingRandomSearchCV'> has changed, suggesting potential thread unsafety. Start by checking attributes: ['estimator', 'error_score', '_callback_fit_ctx', '_checked_cv_orig']`

Calls:

- [4x] Location: `sklearn/tests/test_metaestimators.py:337` | Source: `estimator.fit(X, y)`

### 20. Exception Message

`AssertionError: Hash for object of type <class 'sklearn.model_selection._search_successive_halving.HalvingRandomSearchCV'> has changed, suggesting potential thread unsafety. Start by checking attributes: ['estimator', 'error_score', 'param_distributions', '_callback_fit_ctx', '_checked_cv_orig']`

Calls:

- [1x] Location: `sklearn/model_selection/tests/test_successive_halving.py:821` | Source: `search.fit(X, y)`
- [5x] Location: `sklearn/model_selection/tests/test_successive_halving.py:376` | Source: `sh.fit(X, y)`
- [1x] Location: `sklearn/model_selection/tests/test_successive_halving.py:405` | Source: `sh.fit(X, y)`

### 21. Exception Message

`AssertionError: Hash for object of type <class 'sklearn.model_selection._search_successive_halving.HalvingRandomSearchCV'> has changed, suggesting potential thread unsafety. Start by checking attributes: ['estimator', 'error_score', 'param_distributions', '_skl_callbacks', '_callback_fit_ctx', '_skl_callbacks_to_teardown', '_checked_cv_orig']`

Calls:

- [1x] Location: `sklearn/model_selection/tests/test_search.py:3136` | Source: `search = clone(search).set_callbacks(callback).fit(X, y)`
- [2x] Location: `sklearn/model_selection/tests/test_search.py:3021` | Source: `search = clone(search).set_params(refit=refit).set_callbacks(*callbacks).fit(X, y)`
- [2x] Location: `sklearn/model_selection/tests/test_search.py:3054` | Source: `search = clone(search).set_params(refit=refit).set_callbacks(*callbacks).fit(X, y)`

### 22. Exception Message

`AssertionError: Hash for object of type <class 'sklearn.tests.metadata_routing_common.ConsumingScorer'> has changed, suggesting potential thread unsafety. Start by checking attributes: ['_score_func', '_metadata_request']`

Calls:

- [1x] Location: `sklearn/tests/test_metaestimators_metadata_routing.py:916` | Source: `method(X, y, **method_kwargs)`
- [1x] Location: `sklearn/tests/test_metaestimators_metadata_routing.py:956` | Source: `method(X_, y_, **method_kwargs)`

### 23. Exception Message

`AssertionError: Hash for object of type <class 'sklearn.tests.metadata_routing_common.ConsumingScorer'> has changed, suggesting potential thread unsafety. Start by checking attributes: ['_score_func']`

Calls:

- [3x] Location: `sklearn/tests/test_metaestimators_metadata_routing.py:983` | Source: `cross_validate(`

Pytest output post-processing script
pytest -l --thread-safety-testing 2>&1 | tee pytest.log
python deduplicate_hash_mismatch_failures.py --log pytest.log --output pytest_hash_mismatch_report.md
#!/usr/bin/env python3
"""Deduplicate pytest hash-mismatch AssertionError failures.

This script parses a pytest text log, finds failure blocks containing:
"AssertionError: Hash for object of type ... has changed",
then deduplicates by (scikit-learn call line, full exception message).

It writes a Markdown report grouped by full exception message.
"""

from __future__ import annotations

import argparse
import re
from collections import defaultdict
from pathlib import Path


ANSI_ESCAPE_RE = re.compile(r"\x1b\[[0-9;]*[A-Za-z]")
FAILURE_HEADER_RE = re.compile(r"^_{3,} .* _{3,}$")
TEST_HEADER_EXTRACT_RE = re.compile(r"^_{3,}\s*(.*?)\s*_{3,}$")
FILE_LOCATION_RE = re.compile(r"^[A-Za-z0-9_./-]+\.py:\d+:")
FILE_LOCATION_EXTRACT_RE = re.compile(r"^(?P<path>[A-Za-z0-9_./-]+\.py):(?P<line>\d+):")
HASH_MISMATCH_TOKEN = "AssertionError: Hash for object of type"


def read_clean_lines(path: Path) -> list[str]:
    text = path.read_text(encoding="utf-8", errors="replace")
    return [ANSI_ESCAPE_RE.sub("", ln.rstrip("\n")) for ln in text.splitlines()]


def split_failure_blocks(lines: list[str]) -> list[list[str]]:
    blocks: list[list[str]] = []
    i = 0
    n = len(lines)
    while i < n:
        if FAILURE_HEADER_RE.match(lines[i]):
            start = i
            i += 1
            while i < n and not FAILURE_HEADER_RE.match(lines[i]):
                if lines[i].startswith("=") and "short test summary info" in lines[i].lower():
                    break
                i += 1
            blocks.append(lines[start:i])
        else:
            i += 1
    return blocks


def extract_call_site(block: list[str]) -> tuple[str, str | None, int | None]:
    """Return (source_line, file_path, file_line) for the extracted call site."""
    first_file_idx = None
    for idx, ln in enumerate(block):
        if FILE_LOCATION_RE.match(ln):
            first_file_idx = idx
            break

    search_region = block[:first_file_idx] if first_file_idx is not None else block
    call_idx = None
    call = None
    for idx, ln in enumerate(search_region):
        if ln.startswith("> "):
            candidate = ln[2:].strip()
            if not candidate.startswith("raise AssertionError"):
                call = candidate
                call_idx = idx
                break

    if call is None:
        for idx, ln in enumerate(block):
            if ln.startswith("> "):
                candidate = ln[2:].strip()
                if not candidate.startswith("raise AssertionError"):
                    call = candidate
                    call_idx = idx
                    break

    if call is None or call_idx is None:
        return "", None, None

    # Find the closest file location line after the call site line.
    for ln in block[call_idx + 1 :]:
        match = FILE_LOCATION_EXTRACT_RE.match(ln)
        if match is not None:
            return call, match.group("path"), int(match.group("line"))

    # Fallback to first file location in block if no forward match exists.
    for ln in block:
        match = FILE_LOCATION_EXTRACT_RE.match(ln)
        if match is not None:
            return call, match.group("path"), int(match.group("line"))

    return call, None, None


def parse_hash_mismatch_records(lines: list[str]) -> list[tuple[str, str, str | None, int | None, str]]:
    records: list[tuple[str, str, str | None, int | None, str]] = []
    for block in split_failure_blocks(lines):
        header = block[0]
        test_name_match = TEST_HEADER_EXTRACT_RE.match(header)
        test_name = test_name_match.group(1) if test_name_match else header

        message = None
        for ln in block:
            pos = ln.find(HASH_MISMATCH_TOKEN)
            if pos >= 0:
                message = ln[pos:]
                break
        if message is None:
            continue

        call_line, file_path, file_line = extract_call_site(block)
        if not call_line:
            continue

        records.append((test_name, call_line, file_path, file_line, message))
    return records


def render_markdown(
    records: list[tuple[str, str, str | None, int | None, str]], source_log: Path
) -> str:
    pair_counts: dict[tuple[str, str | None, int | None, str], int] = defaultdict(int)
    for _test_name, call, file_path, file_line, msg in records:
        pair_counts[(call, file_path, file_line, msg)] += 1

    grouped: dict[str, list[tuple[str, str | None, int | None, int]]] = defaultdict(list)
    for (call, file_path, file_line, msg), count in sorted(
        pair_counts.items(), key=lambda item: (item[0][3], item[0][0], item[0][1] or "", item[0][2] or 0)
    ):
        grouped[msg].append((call, file_path, file_line, count))

    lines: list[str] = []
    lines.append("# Deduplicated Hash-Mismatch AssertionError Report")
    lines.append("")
    lines.append(f"Source log: `{source_log.name}`")
    lines.append("")
    lines.append("## Summary")
    lines.append("")
    lines.append(f"- Total hash-mismatch failure blocks: {len(records)}")
    lines.append(f"- Unique call-site + message pairs: {len(pair_counts)}")
    lines.append(f"- Unique full exception messages: {len(grouped)}")
    lines.append("")
    lines.append("## Deduplicated Failures")
    lines.append("")

    for idx, message in enumerate(sorted(grouped.keys()), 1):
        lines.append(f"### {idx}. Exception Message")
        lines.append("")
        lines.append(f"`{message}`")
        lines.append("")
        lines.append("Calls:")
        lines.append("")
        for call, file_path, file_line, count in sorted(
            grouped[message], key=lambda it: (it[0], it[1] or "", it[2] or 0)
        ):
            if file_path is not None and file_line is not None:
                lines.append(
                    f"- [{count}x] Location: `{file_path}:{file_line}` | Source: `{call}`"
                )
            else:
                lines.append(f"- [{count}x] Location: `unknown` | Source: `{call}`")
        lines.append("")

    return "\n".join(lines).rstrip() + "\n"


def main() -> None:
    parser = argparse.ArgumentParser(
        description=(
            "Parse pytest.log and write a Markdown report of unique scikit-learn calls "
            "that trigger hash-mismatch AssertionError failures."
        )
    )
    parser.add_argument(
        "--log",
        type=Path,
        default=Path("pytest.log"),
        help="Path to pytest log file (default: pytest.log)",
    )
    parser.add_argument(
        "--output",
        type=Path,
        default=Path("pytest_hash_mismatch_report.md"),
        help="Output Markdown report path (default: pytest_hash_mismatch_report.md)",
    )
    args = parser.parse_args()

    if not args.log.exists():
        raise SystemExit(f"Log file not found: {args.log}")

    clean_lines = read_clean_lines(args.log)
    records = parse_hash_mismatch_records(clean_lines)
    report = render_markdown(records, args.log)
    args.output.write_text(report, encoding="utf-8")

    print(f"Wrote {args.output} with {len(records)} matching failure blocks.")


if __name__ == "__main__":
    main()

There are also many AttributeError that I ignored for now.

I think that many of the problems in the report above still stem from the same root cause though.

@itamarst

Copy link
Copy Markdown
Contributor Author

Based on feedback above I filed issues #34071 and #34072, to continue the discussion.

@ogrisel ogrisel added the Parallelism and scalability All things related to efficient handling of cores via thread-based or process-based parallelism. label May 26, 2026
@itamarst

Copy link
Copy Markdown
Contributor Author

@ogrisel I have updated the prototype with some examples of annotating both inputs and classes for known thread safety (or bugginess). The annotations allow for quickly getting everything green in CI and then going item by item later to fix bugginess or document thread-safety if it's not immediately obvious how it's implemented.

@ogrisel

ogrisel commented May 28, 2026

Copy link
Copy Markdown
Member

Thanks, I will try to find the time to review this today or early next week.

@ogrisel ogrisel added this to Labs May 28, 2026
@ogrisel ogrisel moved this to In progress in Labs May 28, 2026
@itamarst

Copy link
Copy Markdown
Contributor Author

To take this from sketch to something potentially mergeable, I would want to do the following at minimum:

  • Revert changes to binary tree.
  • Unit tests for the new code.
  • CI job that runs with the new test mode.
  • Annotations for all newly failing tests, such that the new CI job is green. There may be follow up work for these, depending on whether it's a known bug (binary tree / kdtree), needs documentation, or where thread-safety is potentially wrong (e.g. the random state example in the current draft). The follow up work could be done in separate PRs, though.

@jeremiedbb jeremiedbb moved this from In progress to PR waiting for reviews in Labs Jun 29, 2026
@itamarst

Copy link
Copy Markdown
Contributor Author

As I'm starting to create PRs that turn on free-threading, testing for correctness is increasingly important. In order to make it easier to get this merged, I will likely refactor it to initially be a manual testing option one has to implement for specific classes, which means less noise and the ability to make its usage incremental. And then I can use it in PRs like #34659.

@itamarst

Copy link
Copy Markdown
Contributor Author

#32753 is an example of limits of this approach, since __setstate__ wipes out the shared-across-threads buffer, so a testing mechanism based on pickling won't work.

This branch has not been deployed

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

Labels

cython free-threading PRs and issues related to support for free-threaded CPython (a.k.a. nogil or no-GIL, PEP 703) module:neighbors module:utils Parallelism and scalability All things related to efficient handling of cores via thread-based or process-based parallelism.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants