Skip to content

fix(monitoring): exact Spark KS through SciPy's public ks_2samp - #207

Closed
flyingriverhorse wants to merge 1 commit into
masterfrom
fix/spark-ks-public-api
Closed

flyingriverhorse wants to merge 1 commit into
masterfrom
fix/spark-ks-public-api

Conversation

@flyingriverhorse

@flyingriverhorse flyingriverhorse commented Oct 24, 2026 •

Copy link
Copy Markdown
Owner

What and why

Fixes the CI failure in test_internal_api_boundary.py::test_integration_imports_do_not_borrow_private_symbols. Spark drift for 1,000–10,000 rows (added in 1a2a5ed) imported SciPy's private _attempt_exact_2kssamp.

The exact two-sample KS probability depends only on n, m and the statistic. _scipy_exact_probability now rebuilds two tied samples with that statistic (i zeros among n, j zeros among m, |i/n − j/m| = d) and calls public scipy.stats.ks_2samp(method="exact"), which runs the same exact count internally. Results don't change: healthy data is still judged like local ks_2samp and does not fall back to the DKW bound.

When SciPy can't finish the exact count, it warns and silently switches to the asymptotic method. That warning now returns None, so the existing DKW fallback applies, the same as the old success=False path. The boundary test is unchanged; no exception was added to it.

Type

  • Bug fix

How I checked it

  • Before the change, the boundary test failed locally the same way as in CI.
  • Compared the public route with the private helper on 18 cases: sizes 1600/2000, 2000/2000, 1999/2003, 1001/9999, 10000/10000 and 3000/7000, each with shifts 0, 0.05 and 0.2. The p-values were identical (maximum relative difference 0.0) and matched local ks_2samp.
  • New parametrized test test_middle_range_matches_local_exact_ks_for_any_sizes covers equal, coprime and uneven sizes.
  • pytest test_internal_api_boundary.py plus the KS tests in tests/spark/test_monitoring_drift.py: 24 passed.
  • ruff check, ruff format --check, the full CI ty check scope, and lizard -C 10 on the file: all clean.
  • Not re-run on Databricks, because the p-values come from the same SciPy routine as before.

Checklist

  • Tests added or updated (if code changed)
  • changelog/ and docs updated: not needed, no user-visible change
  • Commits signed off (git commit -s), no secrets committed

🤖 Generated with Claude Code

Summary by Sourcery

Use SciPy’s public two-sample KS API for exact Spark drift probabilities without changing monitoring outcomes.

Bug Fixes:

  • Replace SciPy’s private exact KS helper with the public ks_2samp API while preserving exact drift probabilities and applying the existing DKW fallback when exact evaluation cannot complete.

Enhancements:

  • Construct representative tied samples so the public SciPy implementation evaluates the requested statistic for arbitrary sample sizes.

Tests:

  • Add coverage for equal, coprime, and uneven sample sizes to verify exact KS results match local SciPy calculations.

The 1k-10k row KS path imported SciPy's private _attempt_exact_2kssamp,
which test_internal_api_boundary rejects. The exact probability depends
only on n, m and the statistic, so two tied samples with the same
statistic now go through public ks_2samp(method="exact"). It runs the
same exact count, so p-values are unchanged (identical on 18 checked
size/shift cases, including equal and coprime sizes). If SciPy cannot
finish the exact count it warns; that warning now returns None and the
existing DKW fallback applies, as before.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Signed-off-by: flyingriverhorse <buzzycarl@gmail.com>
Copilot AI balanced review requested due to automatic review settings October 24, 2026 15:50
@sourcery-ai

sourcery-ai Bot commented Oct 24, 2026 •

Copy link
Copy Markdown

Reviewer's Guide

The PR removes the forbidden SciPy private _attempt_exact_2kssamp dependency by reconstructing tied samples and routing exact probability calculation through public ks_2samp; failures still use the DKW fallback, with regression coverage confirming matching results for equal, coprime, and uneven sample sizes.

Sequence diagram for public exact KS probability with DKW fallback

sequenceDiagram
    participant Evidence as _ks_evidence
    participant Probability as _scipy_exact_probability
    participant SciPy as scipy.stats.ks_2samp
    participant DKW as DKW fallback

    Evidence->>Probability: _scipy_exact_probability(statistic, n, m)
    Probability->>Probability: math.gcd(n, m)
    Probability->>Probability: np.repeat(reference, current)
    Probability->>SciPy: ks_2samp(reference, current, method="exact")
    alt exact count succeeds
        SciPy-->>Probability: pvalue
        Probability-->>Evidence: probability
    else warning or invalid reconstruction
        SciPy-->>Probability: RuntimeWarning or error
        Probability-->>Evidence: None
        Evidence->>DKW: use DKW bound
    end
Loading

File-Level Changes

Change Details Files
Replace SciPy private exact KS helper usage with a public API reconstruction while preserving the existing DKW fallback behavior.
  • Construct tied binary samples whose sizes and empirical statistic match the requested KS statistic.
  • Call public scipy.stats.ks_2samp(method="exact") and convert exact-count runtime warnings into fallback results.
  • Retain validation of the returned probability and return None when no matching samples can be constructed or exact computation fails.
skyulf-core/skyulf/integrations/databricks/observability/monitoring/spark/spark_monitoring_drift.py
Expand regression coverage for exact KS probabilities across representative sample-size relationships.
  • Parameterize equal, coprime, and uneven sample sizes.
  • Compare Spark drift evidence p-values with local exact ks_2samp results to tight tolerance.
skyulf-core/tests/spark/test_monitoring_drift.py

Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copilot was unable to review this pull request because the user who requested the review has insufficient remaining quota.

@codacy-production

Copy link
Copy Markdown

Up to standards ✅

🟢 Issues 0 issues

Results:
0 new issues

View in Codacy

🟢 Metrics 0 complexity

Metric Results
Complexity 0

View in Codacy

NEW Get contextual insights on your PRs based on Codacy's metrics, along with PR and Jira context, without leaving GitHub. Enable AI reviewer
TIP This summary will be updated as you push new changes.

@sourcery-ai sourcery-ai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hey - I've found 3 issues

Prompt for AI Agents
Please address the comments from this code review:

## Individual Comments

### Comment 1
<location path="skyulf-core/skyulf/integrations/databricks/observability/monitoring/spark/spark_monitoring_drift.py" line_range="73" />
<code_context>
-    except (ImportError, TypeError, ValueError, ArithmeticError):
+        with warnings.catch_warnings():
+            # SciPy warns and silently switches to the asymptotic method on failure.
+            warnings.simplefilter("error", RuntimeWarning)
+            probability = float(ks_2samp(reference, current, method="exact").pvalue)
+    except (RuntimeWarning, ValueError, ArithmeticError):
</code_context>
<issue_to_address>
**Concurrent drift evidence is wrong**

When two monitoring calls overlap while SciPy emits its exact-count RuntimeWarning, `warnings.catch_warnings()` and `warnings.simplefilter()` modify process-wide warning filters, so one call can restore the filter before another call handles SciPy’s warning. The second call then accepts an asymptotic p-value as exact and can report incorrect drift evidence, while an unrelated thread’s RuntimeWarning can also be raised as an exception.

Handle the exact-count warning without changing process-wide warning filters.
</issue_to_address>

### Comment 2
<location path="skyulf-core/skyulf/integrations/databricks/observability/monitoring/spark/spark_monitoring_drift.py" line_range="74" />
<code_context>
+        with warnings.catch_warnings():
+            # SciPy warns and silently switches to the asymptotic method on failure.
+            warnings.simplefilter("error", RuntimeWarning)
+            probability = float(ks_2samp(reference, current, method="exact").pvalue)
+    except (RuntimeWarning, ValueError, ArithmeticError):
         return None
</code_context>
<issue_to_address>
**Databricks behavior unvalidated**

When this Spark drift behavior change is validated only in the local environment, the new `ks_2samp(..., method="exact")` path is compared only against local SciPy, leaving its execution in the Databricks runtime unverified and a runtime-specific drift regression undetected.

Run a focused validation of the changed KS path on Databricks.
</issue_to_address>

### Comment 3
<location path="skyulf-core/tests/spark/test_monitoring_drift.py" line_range="180" />
<code_context>

+@pytest.mark.parametrize(("n", "m"), [(2000, 2000), (1999, 2003), (1001, 9999)])
+def test_middle_range_matches_local_exact_ks_for_any_sizes(n, m):
+    """Equal, coprime and uneven sizes take other exact-count paths; all must match local."""
+    from skyulf.integrations.databricks.observability.monitoring.spark.spark_monitoring_drift import (
+        _ks_evidence,
</code_context>
<issue_to_address>
**Drift impact left unclear**

When the new parametrized test is added, the docstring says the results must match local but not what breaks if they do not, leaving the significance of divergent Spark drift evidence for these sample sizes unstated.

State in the docstring that mismatches would make Spark drift evidence differ from local KS results for these sample sizes.
</issue_to_address>

Sourcery assessment

Approval pending. 2 findings to address first.

Blocking findings: skyulf-core/skyulf/integrations/databricks/observability/monitoring/spark/spark_monitoring_drift.py:73, skyulf-core/skyulf/integrations/databricks/observability/monitoring/spark/spark_monitoring_drift.py:74


Sourcery is free for open source - if you like our reviews please consider sharing them ✨

except (ImportError, TypeError, ValueError, ArithmeticError):
with warnings.catch_warnings():
# SciPy warns and silently switches to the asymptotic method on failure.
warnings.simplefilter("error", RuntimeWarning)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Medium · Concurrent drift evidence is wrong

When two monitoring calls overlap while SciPy emits its exact-count RuntimeWarning, warnings.catch_warnings() and warnings.simplefilter() modify process-wide warning filters, so one call can restore the filter before another call handles SciPy’s warning. The second call then accepts an asymptotic p-value as exact and can report incorrect drift evidence, while an unrelated thread’s RuntimeWarning can also be raised as an exception.

Handle the exact-count warning without changing process-wide warning filters.

Prompt for AI agents
In `skyulf-core/skyulf/integrations/databricks/observability/monitoring/spark/spark_monitoring_drift.py` at line 73:

**Concurrent drift evidence is wrong**

When two monitoring calls overlap while SciPy emits its exact-count RuntimeWarning, `warnings.catch_warnings()` and `warnings.simplefilter()` modify process-wide warning filters, so one call can restore the filter before another call handles SciPy’s warning. The second call then accepts an asymptotic p-value as exact and can report incorrect drift evidence, while an unrelated thread’s RuntimeWarning can also be raised as an exception.

Handle the exact-count warning without changing process-wide warning filters.

with warnings.catch_warnings():
# SciPy warns and silently switches to the asymptotic method on failure.
warnings.simplefilter("error", RuntimeWarning)
probability = float(ks_2samp(reference, current, method="exact").pvalue)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Medium · Databricks behavior unvalidated

When this Spark drift behavior change is validated only in the local environment, the new ks_2samp(..., method="exact") path is compared only against local SciPy, leaving its execution in the Databricks runtime unverified and a runtime-specific drift regression undetected.

Run a focused validation of the changed KS path on Databricks.

Prompt for AI agents
In `skyulf-core/skyulf/integrations/databricks/observability/monitoring/spark/spark_monitoring_drift.py` at line 74:

**Databricks behavior unvalidated**

When this Spark drift behavior change is validated only in the local environment, the new `ks_2samp(..., method="exact")` path is compared only against local SciPy, leaving its execution in the Databricks runtime unverified and a runtime-specific drift regression undetected.

Run a focused validation of the changed KS path on Databricks.

From AGENTS.md L122-124:

- Keep Ruff, full CI Ty scope, applicable complexity checks and pre-commit hooks.
  For Databricks behavior changes, retain focused validation on Databricks itself.
  Do not reduce CI coverage or skip relevant tests to shorten local feedback.


@pytest.mark.parametrize(("n", "m"), [(2000, 2000), (1999, 2003), (1001, 9999)])
def test_middle_range_matches_local_exact_ks_for_any_sizes(n, m):
"""Equal, coprime and uneven sizes take other exact-count paths; all must match local."""

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚪ Low · Drift impact left unclear

When the new parametrized test is added, the docstring says the results must match local but not what breaks if they do not, leaving the significance of divergent Spark drift evidence for these sample sizes unstated.

State in the docstring that mismatches would make Spark drift evidence differ from local KS results for these sample sizes.

Prompt for AI agents
In `skyulf-core/tests/spark/test_monitoring_drift.py` at line 180:

**Drift impact left unclear**

When the new parametrized test is added, the docstring says the results must match local but not what breaks if they do not, leaving the significance of divergent Spark drift evidence for these sample sizes unstated.

State in the docstring that mismatches would make Spark drift evidence differ from local KS results for these sample sizes.

From AGENTS.md L143-145:

- **New tests still get a one-line docstring** stating the behaviour being
  pinned — what would break if the test failed. The test name carries the *what*,
  the docstring carries the *why it matters*.

@codecov

codecov Bot commented Oct 24, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 81.25000% with 3 lines in your changes missing coverage. Please review.

Files with missing lines Patch % Lines
...ability/monitoring/spark/spark_monitoring_drift.py 81.25% 2 Missing and 1 partial ⚠️

📢 Thoughts on this report? Let us know!

@sonarqubecloud

Copy link
Copy Markdown

@flyingriverhorse
flyingriverhorse deleted the fix/spark-ks-public-api branch November 6, 2026 13:04
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants